Class: ChefZeroHttpProxy

Inherits:
Object
  • Object
show all
Defined in:
lib/chef_metal_docker/chef_zero_http_proxy.rb

Instance Method Summary collapse

Constructor Details

#initialize(local_address, local_port, remote_address, remote_port) ⇒ ChefZeroHttpProxy

Returns a new instance of ChefZeroHttpProxy.



6
7
8
9
10
11
# File 'lib/chef_metal_docker/chef_zero_http_proxy.rb', line 6

def initialize(local_address, local_port, remote_address, remote_port)
  @local_address = local_address
  @local_port = local_port
  @remote_address = remote_address
  @remote_port = remote_port
end

Instance Method Details

#handle_request(to_client) ⇒ Object



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
# File 'lib/chef_metal_docker/chef_zero_http_proxy.rb', line 31

def handle_request(to_client)
  request_line = to_client.readline

  verb = request_line[/^\w+/]
  url = request_line[/^\w+\s+(\S+)/, 1]
  version = request_line[/HTTP\/(1\.\d)\s*$/, 1]
  uri = URI::parse url

  # Show what got requested
  Chef::Log.debug("[C->S]: #{verb} ->  #{url}")

  querystr = if uri.query
               "#{uri.path}?#{uri.query}"
             else
               uri.path
             end

  to_server = TCPSocket.new(@remote_address, @remote_port)

  to_server.write("#{verb} #{querystr} HTTP/#{version}\r\n")

  content_len = 0

  loop do
    line = to_client.readline

    if line =~ /^Content-Length:\s+(\d+)\s*$/
      content_len = $1.to_i
    end

    # Strip proxy headers
    if line =~ /^proxy/i
      next
    elsif line.strip.empty?
      to_server.write("Connection: close\r\n\r\n")

      if content_len >= 0
        to_server.write(to_client.read(content_len))
        Chef::Log.debug("[C->S]: Wrote #{content_len} bytes")
      end

      break
    else
      to_server.write(line)
    end
  end

  buff = ''
  loop do
    to_server.read(8192, buff)
    to_client.write(buff)
    break if buff.size < 8192
  end

  # Close the sockets
  to_client.close
  to_server.close
end

#runObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/chef_metal_docker/chef_zero_http_proxy.rb', line 13

def run
  begin
    Chef::Log.debug("Running proxy main loop on #{@local_address}:#{@local_port}!")

    # Start our server to handle connections (will raise things on errors)
    @socket = TCPServer.new @local_address, @local_port
    
    # Handle every request in another thread
    loop do
      s = @socket.accept
      Thread.new s, &method(:handle_request)
    end
    
  ensure
    @socket.close if @socket
  end
end