Class: Ferrum::Proxy

Inherits:
Object
  • Object
show all
Defined in:
lib/ferrum/proxy.rb

Defined Under Namespace

Classes: HTTPProxyServer

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host: "127.0.0.1", port: 0, user: nil, password: nil) ⇒ Proxy

Returns a new instance of Proxy.



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

def initialize(host: "127.0.0.1", port: 0, user: nil, password: nil)
  @file = nil
  @host = host
  @port = port
  @user = user
  @password = password
end

Instance Attribute Details

#hostObject (readonly)

Returns the value of attribute host.



13
14
15
# File 'lib/ferrum/proxy.rb', line 13

def host
  @host
end

#passwordObject (readonly)

Returns the value of attribute password.



13
14
15
# File 'lib/ferrum/proxy.rb', line 13

def password
  @password
end

#portObject (readonly)

Returns the value of attribute port.



13
14
15
# File 'lib/ferrum/proxy.rb', line 13

def port
  @port
end

#userObject (readonly)

Returns the value of attribute user.



13
14
15
# File 'lib/ferrum/proxy.rb', line 13

def user
  @user
end

Class Method Details

.start(**args) ⇒ Object



9
10
11
# File 'lib/ferrum/proxy.rb', line 9

def self.start(**args)
  new(**args).tap(&:start)
end

Instance Method Details

#rotate(host:, port:, user: nil, password: nil) ⇒ Object



48
49
50
51
52
# File 'lib/ferrum/proxy.rb', line 48

def rotate(host:, port:, user: nil, password: nil)
  credentials = "#{user}:#{password}@" if user && password
  proxy_uri = "schema://#{credentials}#{host}:#{port}"
  @server.config[:ProxyURI] = URI.parse(proxy_uri)
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
# File 'lib/ferrum/proxy.rb', line 23

def start
  options = {
    ProxyURI: nil, ServerType: Thread,
    Logger: Logger.new(IO::NULL), AccessLog: [],
    BindAddress: host, Port: port
  }

  if user && password
    @file = Tempfile.new("htpasswd")
    htpasswd = WEBrick::HTTPAuth::Htpasswd.new(@file.path)
    htpasswd.set_passwd "Proxy Realm", user, password
    htpasswd.flush
    authenticator = WEBrick::HTTPAuth::ProxyBasicAuth.new(Realm: "Proxy Realm",
                                                          UserDB: htpasswd,
                                                          Logger: Logger.new(IO::NULL))
    options.merge!(ProxyAuthProc: authenticator.method(:authenticate).to_proc)
  end

  @server = HTTPProxyServer.new(**options)
  @server.start
  at_exit { stop }

  @port = @server.config[:Port]
end

#stopObject



54
55
56
57
# File 'lib/ferrum/proxy.rb', line 54

def stop
  @file&.close(true)
  @server.shutdown
end