/tools/Ruby/lib/ruby/1.8/webrick/utils.rb

http://github.com/agross/netopenspace · Ruby · 100 lines · 87 code · 4 blank · 9 comment · 3 complexity · 8ca03cc6df3069fba976cf72c1ae9624 MD5 · raw file

  1. #
  2. # utils.rb -- Miscellaneous utilities
  3. #
  4. # Author: IPR -- Internet Programming with Ruby -- writers
  5. # Copyright (c) 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou
  6. # Copyright (c) 2002 Internet Programming with Ruby writers. All rights
  7. # reserved.
  8. #
  9. # $IPR: utils.rb,v 1.10 2003/02/16 22:22:54 gotoyuzo Exp $
  10. require 'socket'
  11. require 'fcntl'
  12. begin
  13. require 'etc'
  14. rescue LoadError
  15. nil
  16. end
  17. module WEBrick
  18. module Utils
  19. def set_non_blocking(io)
  20. flag = File::NONBLOCK
  21. if defined?(Fcntl::F_GETFL)
  22. flag |= io.fcntl(Fcntl::F_GETFL)
  23. end
  24. io.fcntl(Fcntl::F_SETFL, flag)
  25. end
  26. module_function :set_non_blocking
  27. def set_close_on_exec(io)
  28. if defined?(Fcntl::FD_CLOEXEC)
  29. io.fcntl(Fcntl::FD_CLOEXEC, 1)
  30. end
  31. end
  32. module_function :set_close_on_exec
  33. def su(user)
  34. if defined?(Etc)
  35. pw = Etc.getpwnam(user)
  36. Process::initgroups(user, pw.gid)
  37. Process::Sys::setgid(pw.gid)
  38. Process::Sys::setuid(pw.uid)
  39. else
  40. warn("WEBrick::Utils::su doesn't work on this platform")
  41. end
  42. end
  43. module_function :su
  44. def getservername
  45. host = Socket::gethostname
  46. begin
  47. Socket::gethostbyname(host)[0]
  48. rescue
  49. host
  50. end
  51. end
  52. module_function :getservername
  53. def create_listeners(address, port, logger=nil)
  54. unless port
  55. raise ArgumentError, "must specify port"
  56. end
  57. res = Socket::getaddrinfo(address, port,
  58. Socket::AF_UNSPEC, # address family
  59. Socket::SOCK_STREAM, # socket type
  60. 0, # protocol
  61. Socket::AI_PASSIVE) # flag
  62. last_error = nil
  63. sockets = []
  64. res.each{|ai|
  65. begin
  66. logger.debug("TCPServer.new(#{ai[3]}, #{port})") if logger
  67. sock = TCPServer.new(ai[3], port)
  68. port = sock.addr[1] if port == 0
  69. Utils::set_close_on_exec(sock)
  70. sockets << sock
  71. rescue => ex
  72. logger.warn("TCPServer Error: #{ex}") if logger
  73. last_error = ex
  74. end
  75. }
  76. raise last_error if sockets.empty?
  77. return sockets
  78. end
  79. module_function :create_listeners
  80. RAND_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
  81. "0123456789" +
  82. "abcdefghijklmnopqrstuvwxyz"
  83. def random_string(len)
  84. rand_max = RAND_CHARS.size
  85. ret = ""
  86. len.times{ ret << RAND_CHARS[rand(rand_max)] }
  87. ret
  88. end
  89. module_function :random_string
  90. end
  91. end