Module: RubyProxyHeaders::NetHTTP

Defined in:
lib/ruby_proxy_headers/net_http.rb

Overview

Patches Net::HTTP so an HTTPS request through a proxy can send extra CONNECT headers and keep the proxy's CONNECT response.

The patch does not copy Net::HTTP#connect. The installed net-http still owns the socket, timeouted_connect, and HTTPS-to-proxy (+proxy_use_ssl+). A prepend validates the target, then rewrites the CONNECT bytes that upstream writes and records the CONNECT response.

Examples:

require 'ruby_proxy_headers/net_http'
RubyProxyHeaders::NetHTTP.patch!

http = Net::HTTP.new(uri.host, uri.port, proxy.host, proxy.port, proxy.user, proxy.password)
http.use_ssl = true
http.proxy_connect_request_headers = { 'X-ProxyMesh-IP' => '203.0.113.1' }
res = http.request(Net::HTTP::Get.new(uri))
p http.last_proxy_connect_response_headers['X-ProxyMesh-IP']

Defined Under Namespace

Modules: ConnectRequestWrite, ConnectResponseRead, Extension

Class Method Summary collapse

Class Method Details

.inject_connect_headers(buf, headers) ⇒ Object

Inserts headers before the blank line that ends a CONNECT request.



30
31
32
33
34
35
36
37
38
# File 'lib/ruby_proxy_headers/net_http.rb', line 30

def self.inject_connect_headers(buf, headers)
  return buf if headers.nil? || headers.empty?

  extra = String.new(encoding: buf.encoding)
  headers.each do |key, value|
    extra << "#{key}: #{value}\r\n".encode(buf.encoding)
  end
  "#{buf.sub(/\r\n\r\n\z/, "\r\n")}#{extra}\r\n"
end

.patch! ⇒ Object



103
104
105
106
107
108
109
110
111
# File 'lib/ruby_proxy_headers/net_http.rb', line 103

def patch!
  ::Net::HTTP.prepend(Extension) unless ::Net::HTTP.ancestors.include?(Extension)
  io_hooked = ::Net::BufferedIO.ancestors.include?(ConnectRequestWrite)
  ::Net::BufferedIO.prepend(ConnectRequestWrite) unless io_hooked
  response_class = ::Net::HTTPResponse.singleton_class
  response_hooked = response_class.ancestors.include?(ConnectResponseRead)
  response_class.prepend(ConnectResponseRead) unless response_hooked
  @patched = true
end

.patched? ⇒ Boolean

Returns:

  • (Boolean)


113
114
115
# File 'lib/ruby_proxy_headers/net_http.rb', line 113

def patched?
  @patched == true
end