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

http://github.com/agross/netopenspace · Ruby · 254 lines · 199 code · 28 blank · 27 comment · 27 complexity · e49ef18a3ba4c11878620ee77ae7963c MD5 · raw file

  1. #
  2. # httpproxy.rb -- HTTPProxy Class
  3. #
  4. # Author: IPR -- Internet Programming with Ruby -- writers
  5. # Copyright (c) 2002 GOTO Kentaro
  6. # Copyright (c) 2002 Internet Programming with Ruby writers. All rights
  7. # reserved.
  8. #
  9. # $IPR: httpproxy.rb,v 1.18 2003/03/08 18:58:10 gotoyuzo Exp $
  10. # $kNotwork: straw.rb,v 1.3 2002/02/12 15:13:07 gotoken Exp $
  11. require "webrick/httpserver"
  12. require "net/http"
  13. Net::HTTP::version_1_2 if RUBY_VERSION < "1.7"
  14. module WEBrick
  15. NullReader = Object.new
  16. class << NullReader
  17. def read(*args)
  18. nil
  19. end
  20. alias gets read
  21. end
  22. class HTTPProxyServer < HTTPServer
  23. def initialize(config)
  24. super
  25. c = @config
  26. @via = "#{c[:HTTPVersion]} #{c[:ServerName]}:#{c[:Port]}"
  27. end
  28. def service(req, res)
  29. if req.request_method == "CONNECT"
  30. proxy_connect(req, res)
  31. elsif req.unparsed_uri =~ %r!^http://!
  32. proxy_service(req, res)
  33. else
  34. super(req, res)
  35. end
  36. end
  37. def proxy_auth(req, res)
  38. if proc = @config[:ProxyAuthProc]
  39. proc.call(req, res)
  40. end
  41. req.header.delete("proxy-authorization")
  42. end
  43. # Some header fields should not be transferred.
  44. HopByHop = %w( connection keep-alive proxy-authenticate upgrade
  45. proxy-authorization te trailers transfer-encoding )
  46. ShouldNotTransfer = %w( set-cookie proxy-connection )
  47. def split_field(f) f ? f.split(/,\s+/).collect{|i| i.downcase } : [] end
  48. def choose_header(src, dst)
  49. connections = split_field(src['connection'])
  50. src.each{|key, value|
  51. key = key.downcase
  52. if HopByHop.member?(key) || # RFC2616: 13.5.1
  53. connections.member?(key) || # RFC2616: 14.10
  54. ShouldNotTransfer.member?(key) # pragmatics
  55. @logger.debug("choose_header: `#{key}: #{value}'")
  56. next
  57. end
  58. dst[key] = value
  59. }
  60. end
  61. # Net::HTTP is stupid about the multiple header fields.
  62. # Here is workaround:
  63. def set_cookie(src, dst)
  64. if str = src['set-cookie']
  65. cookies = []
  66. str.split(/,\s*/).each{|token|
  67. if /^[^=]+;/o =~ token
  68. cookies[-1] << ", " << token
  69. elsif /=/o =~ token
  70. cookies << token
  71. else
  72. cookies[-1] << ", " << token
  73. end
  74. }
  75. dst.cookies.replace(cookies)
  76. end
  77. end
  78. def set_via(h)
  79. if @config[:ProxyVia]
  80. if h['via']
  81. h['via'] << ", " << @via
  82. else
  83. h['via'] = @via
  84. end
  85. end
  86. end
  87. def proxy_uri(req, res)
  88. @config[:ProxyURI]
  89. end
  90. def proxy_service(req, res)
  91. # Proxy Authentication
  92. proxy_auth(req, res)
  93. # Create Request-URI to send to the origin server
  94. uri = req.request_uri
  95. path = uri.path.dup
  96. path << "?" << uri.query if uri.query
  97. # Choose header fields to transfer
  98. header = Hash.new
  99. choose_header(req, header)
  100. set_via(header)
  101. # select upstream proxy server
  102. if proxy = proxy_uri(req, res)
  103. proxy_host = proxy.host
  104. proxy_port = proxy.port
  105. if proxy.userinfo
  106. credentials = "Basic " + [proxy.userinfo].pack("m*")
  107. credentials.chomp!
  108. header['proxy-authorization'] = credentials
  109. end
  110. end
  111. response = nil
  112. begin
  113. http = Net::HTTP.new(uri.host, uri.port, proxy_host, proxy_port)
  114. http.start{
  115. if @config[:ProxyTimeout]
  116. ################################## these issues are
  117. http.open_timeout = 30 # secs # necessary (maybe bacause
  118. http.read_timeout = 60 # secs # Ruby's bug, but why?)
  119. ##################################
  120. end
  121. case req.request_method
  122. when "GET" then response = http.get(path, header)
  123. when "POST" then response = http.post(path, req.body || "", header)
  124. when "HEAD" then response = http.head(path, header)
  125. else
  126. raise HTTPStatus::MethodNotAllowed,
  127. "unsupported method `#{req.request_method}'."
  128. end
  129. }
  130. rescue => err
  131. logger.debug("#{err.class}: #{err.message}")
  132. raise HTTPStatus::ServiceUnavailable, err.message
  133. end
  134. # Persistent connction requirements are mysterious for me.
  135. # So I will close the connection in every response.
  136. res['proxy-connection'] = "close"
  137. res['connection'] = "close"
  138. # Convert Net::HTTP::HTTPResponse to WEBrick::HTTPProxy
  139. res.status = response.code.to_i
  140. choose_header(response, res)
  141. set_cookie(response, res)
  142. set_via(res)
  143. res.body = response.body
  144. # Process contents
  145. if handler = @config[:ProxyContentHandler]
  146. handler.call(req, res)
  147. end
  148. end
  149. def proxy_connect(req, res)
  150. # Proxy Authentication
  151. proxy_auth(req, res)
  152. ua = Thread.current[:WEBrickSocket] # User-Agent
  153. raise HTTPStatus::InternalServerError,
  154. "[BUG] cannot get socket" unless ua
  155. host, port = req.unparsed_uri.split(":", 2)
  156. # Proxy authentication for upstream proxy server
  157. if proxy = proxy_uri(req, res)
  158. proxy_request_line = "CONNECT #{host}:#{port} HTTP/1.0"
  159. if proxy.userinfo
  160. credentials = "Basic " + [proxy.userinfo].pack("m*")
  161. credentials.chomp!
  162. end
  163. host, port = proxy.host, proxy.port
  164. end
  165. begin
  166. @logger.debug("CONNECT: upstream proxy is `#{host}:#{port}'.")
  167. os = TCPSocket.new(host, port) # origin server
  168. if proxy
  169. @logger.debug("CONNECT: sending a Request-Line")
  170. os << proxy_request_line << CRLF
  171. @logger.debug("CONNECT: > #{proxy_request_line}")
  172. if credentials
  173. @logger.debug("CONNECT: sending a credentials")
  174. os << "Proxy-Authorization: " << credentials << CRLF
  175. end
  176. os << CRLF
  177. proxy_status_line = os.gets(LF)
  178. @logger.debug("CONNECT: read a Status-Line form the upstream server")
  179. @logger.debug("CONNECT: < #{proxy_status_line}")
  180. if %r{^HTTP/\d+\.\d+\s+200\s*} =~ proxy_status_line
  181. while line = os.gets(LF)
  182. break if /\A(#{CRLF}|#{LF})\z/om =~ line
  183. end
  184. else
  185. raise HTTPStatus::BadGateway
  186. end
  187. end
  188. @logger.debug("CONNECT #{host}:#{port}: succeeded")
  189. res.status = HTTPStatus::RC_OK
  190. rescue => ex
  191. @logger.debug("CONNECT #{host}:#{port}: failed `#{ex.message}'")
  192. res.set_error(ex)
  193. raise HTTPStatus::EOFError
  194. ensure
  195. if handler = @config[:ProxyContentHandler]
  196. handler.call(req, res)
  197. end
  198. res.send_response(ua)
  199. access_log(@config, req, res)
  200. # Should clear request-line not to send the sesponse twice.
  201. # see: HTTPServer#run
  202. req.parse(NullReader) rescue nil
  203. end
  204. begin
  205. while fds = IO::select([ua, os])
  206. if fds[0].member?(ua)
  207. buf = ua.sysread(1024);
  208. @logger.debug("CONNECT: #{buf.size} byte from User-Agent")
  209. os.syswrite(buf)
  210. elsif fds[0].member?(os)
  211. buf = os.sysread(1024);
  212. @logger.debug("CONNECT: #{buf.size} byte from #{host}:#{port}")
  213. ua.syswrite(buf)
  214. end
  215. end
  216. rescue => ex
  217. os.close
  218. @logger.debug("CONNECT #{host}:#{port}: closed")
  219. end
  220. raise HTTPStatus::EOFError
  221. end
  222. def do_OPTIONS(req, res)
  223. res['allow'] = "GET,HEAD,POST,OPTIONS,CONNECT"
  224. end
  225. end
  226. end