Class: WEBrick::AsyncHTTPProxyServer

Inherits:
HTTPProxyServer
  • Object
show all
Defined in:
lib/jscmd/asynchttpproxy.rb

Direct Known Subclasses

JSCommander::ProxyServer

Defined Under Namespace

Classes: QueueInput

Instance Method Summary collapse

Instance Method Details

#proxy_service(req, res) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/jscmd/asynchttpproxy.rb', line 26

def proxy_service(req, res)
  # Proxy Authentication
  proxy_auth(req, res)      
  
  # Create Request-URI to send to the origin server
  uri  = req.request_uri
  path = uri.path.dup
  path << "?" << uri.query if uri.query
  
  # Choose header fields to transfer
  header = Hash.new
  choose_header(req, header)
  set_via(header)
  
  # select upstream proxy server
  if proxy = proxy_uri(req, res)
    proxy_host = proxy.host
    proxy_port = proxy.port
    if proxy.userinfo
      credentials = "Basic " + [proxy.userinfo].pack("m*")
      credentials.chomp!
      header['proxy-authorization'] = credentials
    end
  end
  

  response = nil
  q = Queue.new
  data_queue = Queue.new
  # p_reader, p_writer = IO.pipe
  thread = Thread.start do
    begin
      @logger.debug "downloading #{uri}"
      http = Net::HTTP.new(uri.host, uri.port, proxy_host, proxy_port)
      http.start{
        if @config[:ProxyTimeout]
          ##################################   these issues are 
          http.open_timeout = 30   # secs  #   necessary (maybe bacause
          http.read_timeout = 60   # secs  #   Ruby's bug, but why?)
          ##################################
        end
        http_req = nil
        http_req_body = nil
        case req.request_method
        when "GET"
          http_req = Net::HTTP::Get.new(path, header)
        when "POST"
          http_req = Net::HTTP::Post.new(path, header)
          http_req_body = req.body || ""
        when "HEAD"
          http_req = Net::HTTP::Head.new(path, header)
        else
          raise HTTPStatus::MethodNotAllowed,
          "unsupported method `#{req.request_method}'."
        end
        http.request(http_req, http_req_body) do |response|
          q.push response
          size = 0
          last_size = 0
          response.read_body do |str|
            last_size = size
            size += str.size
            if last_size / 500000 != size / 500000
              @logger.debug "downloading #{uri}: size=#{size}"
            end
            # p_writer.write str
            data_queue.push str
          end
          @logger.debug "finished downloading #{uri}: size=#{size}"
          # p_writer.close
          data_queue.push nil
        end
      }
    rescue Exception => err
      logger.debug("#{err.class}: #{err.message}")
      q.push err
      # raise HTTPStatus::ServiceUnavailable, err.message
    end
  end
  response = q.pop
  if response.is_a?(Exception)
    @logger.debug "failed to download #{uri}"
    raise HTTPStatus::ServiceUnavailable, response.message
  end
  
  # Persistent connction requirements are mysterious for me.
  # So I will close the connection in every response.
  res['proxy-connection'] = "close"
  res['connection'] = "close"
  
  # Convert Net::HTTP::HTTPResponse to WEBrick::HTTPProxy
  res.status = response.code.to_i
  choose_header(response, res)
  set_cookie(response, res)
  set_via(res)
  res.body = QueueInput.new(data_queue) # p_reader
  def res.flush_body
    if @body.is_a?(IO)
      begin
        str_body = @body.read
      ensure
        @body.close
      end
      @body = str_body
    end
    @body
  end
  
  @logger.debug "downloading #{uri}: content-length=#{res.header['content-length']}"
  
  # Process contents
  if handler = @config[:ProxyContentHandler]
    handler.call(req, res)
  end
end