Module: TunnelRb::Server::HttpRequest

Defined in:
lib/tunnel_rb/server/http_request.rb

Overview

Reads the request line and headers from a browser socket, injects X-Forwarded-* headers, and returns the parsed Host plus the raw bytes ready to forward to the tunneled backend.

Constant Summary collapse

Timeout =
Class.new(StandardError)
DEFAULT_TIMEOUT =
5

Class Method Summary collapse

Class Method Details

.read(socket, client_ip:, timeout: DEFAULT_TIMEOUT) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/tunnel_rb/server/http_request.rb', line 17

def read(socket, client_ip:, timeout: DEFAULT_TIMEOUT)
  buffer = +""
  host = nil

  ::Timeout.timeout(timeout) do
    while (line = socket.gets)
      if line.strip.empty?
        buffer << "X-Forwarded-For: #{client_ip}\r\n"
        buffer << "X-Forwarded-Proto: https\r\n"
        buffer << "\r\n"
        break
      end

      next if line.match?(/^X-Forwarded-/i)

      buffer << line
      if (match = line.match(/^Host:\s+([^\r\n]+)/i))
        host = match[1]
      end
    end
  end

  [host, buffer]
rescue ::Timeout::Error
  raise Timeout
end