Class: ForwardProxy::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/forward_proxy/server.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(bind_address: "127.0.0.1", bind_port: 9292, threads: 128, timeout: 300, logger: default_logger) ⇒ Server

Returns a new instance of Server.



15
16
17
18
19
20
21
# File 'lib/forward_proxy/server.rb', line 15

def initialize(bind_address: "127.0.0.1", bind_port: 9292, threads: 128, timeout: 300, logger: default_logger)
  @bind_address = bind_address
  @bind_port = bind_port
  @logger = logger
  @thread_pool = ThreadPool.new(threads)
  @timeout = timeout
end

Instance Attribute Details

#bind_addressObject (readonly)

Returns the value of attribute bind_address.



13
14
15
# File 'lib/forward_proxy/server.rb', line 13

def bind_address
  @bind_address
end

#bind_portObject (readonly)

Returns the value of attribute bind_port.



13
14
15
# File 'lib/forward_proxy/server.rb', line 13

def bind_port
  @bind_port
end

#loggerObject (readonly)

Returns the value of attribute logger.



13
14
15
# File 'lib/forward_proxy/server.rb', line 13

def logger
  @logger
end

#timeoutObject (readonly)

Returns the value of attribute timeout.



13
14
15
# File 'lib/forward_proxy/server.rb', line 13

def timeout
  @timeout
end

Instance Method Details

#shutdownObject



58
59
60
61
62
63
64
# File 'lib/forward_proxy/server.rb', line 58

def shutdown
  if socket
    logger.info("Shutting down")

    socket.close
  end
end

#startObject



23
24
25
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
# File 'lib/forward_proxy/server.rb', line 23

def start
  thread_pool.start

  @socket = TCPServer.new(bind_address, bind_port)

  logger.info("Listening #{bind_address}:#{bind_port}")

  loop do
    thread_pool.schedule(socket.accept) do |client_conn|
      begin
        Timeout::timeout(timeout, Errors::ConnectionTimeoutError, "connection exceeded #{timeout} seconds") do
          req = parse_req(client_conn)

          logger.info(req.request_line.strip)

          case req.request_method
          when METHOD_CONNECT then handle_tunnel(client_conn, req)
          when METHOD_GET, METHOD_HEAD, METHOD_POST then handle(client_conn, req)
          else
            raise Errors::HTTPMethodNotImplemented
          end
        end
      rescue => e
        handle_error(client_conn, e)
      ensure
        client_conn.close
      end
    end
  end
rescue Interrupt
  shutdown
rescue IOError, Errno::EBADF => e
  logger.error(e.message)
end