Class: ProxyDaemon::Worker

Inherits:
Object
  • Object
show all
Defined in:
lib/proxy_daemon/worker.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeWorker

Returns a new instance of Worker.



10
11
12
13
# File 'lib/proxy_daemon/worker.rb', line 10

def initialize
  @client = Net::HTTP.Proxy(nil, nil)
  @url = ''
end

Instance Attribute Details

#urlObject

Returns the value of attribute url.



8
9
10
# File 'lib/proxy_daemon/worker.rb', line 8

def url
  @url
end

Instance Method Details

#answer(command) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
# File 'lib/proxy_daemon/worker.rb', line 34

def answer(command)
  begin
    $stdout.puts "#{command}"
    $stdout.flush
  rescue Errno::EPIPE => e
    log 'Broken pipe with daemon, exiting...'.yellow
    Kernel.exit!
  rescue => e
    log e.inspect.red
  end
end

#call(&block) ⇒ Object



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'lib/proxy_daemon/worker.rb', line 106

def call(&block)
  @block = block if block_given?
  proxy = nil

  loop do
    begin
      task = listen
      case task
      when /^proxy/
        proxy = task.match(/^proxy\s*(.*)$/)[1]
        changeProxy(proxy)
      when /^url/
        @url = task.match(/^url\s+(.+)$/)[1]
        process(@url)
      when /^exit/
        exit!
      end

      #$stderr.puts "[child #{Process.pid}]".magenta + ' Task: ' + task.to_s.yellow
    rescue => e
      log "rescue in #{'call'.yellow}: #{e.inspect.red}"
      answer 'error'
    end
  end
end

#changeProxy(proxy) ⇒ Object



91
92
93
94
95
96
97
# File 'lib/proxy_daemon/worker.rb', line 91

def changeProxy(proxy)
  if proxy == 'localhost' || proxy.nil? || (proxy = proxy.split(/\s+/)).length < 2
    ENV['http_proxy'] = nil
  else
    ENV['http_proxy'] = "http://#{proxy[0]}:#{proxy[1]}"
  end
end

#listenObject



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/proxy_daemon/worker.rb', line 15

def listen
  begin
    command = ''
    Timeout::timeout(6) {
      command = ($stdin.gets || String.new).strip
      
      if command.empty?
        log "Got empty answer from daemon, exiting...".yellow
        raise Timeout::Error
      end
    }
  rescue Timeout::Error
    answer 'timeout'
    Kernel.exit!
  end
  
  command
end

#log(msg) ⇒ Object



132
133
134
# File 'lib/proxy_daemon/worker.rb', line 132

def log(msg)
  $stderr.puts "[child #{Process.pid}]".magenta + " #{msg}"
end

#parse(body) ⇒ Object

Raises:

  • (NotImplementedError)


99
100
101
102
103
104
# File 'lib/proxy_daemon/worker.rb', line 99

def parse(body)
  raise NotImplementedError if @block.nil?
  
  @block.call(self, body)
#      instance_exec body, &@block
end

#process(url) ⇒ Object



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
89
# File 'lib/proxy_daemon/worker.rb', line 46

def process(url)
  begin
    uri = URI(url)
    Timeout::timeout(15) {
      @client = Net::HTTP.new(uri.host, uri.port)
      @client.use_ssl = (uri.scheme == 'https')
      @client.verify_mode = OpenSSL::SSL::VERIFY_NONE if uri.scheme == 'https'
      #@client.set_debug_output($stderr)

      @client.start { |http|
        req = Net::HTTP::Get.new(uri,
          'Connection' => 'keep-alive',
          'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
          'Upgrade-Insecure-Requests' => '1',
          'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.13 Safari/537.36',
          'Accept-Language' => 'en-US,en;q=0.8,ru;q=0.6'
        )
        @page = http.request(req)
      }
    }
  
    if (!@page.is_a?(Net::HTTPOK) || @page.body.empty?)
      log @page
      raise Net::HTTPBadResponse
    end
  
    res = parse(@page.body)
    
    if !!res == res || res.nil?; answer(res ? 'ok' : 'error')
    elsif res.is_a? Array; answer("set #{res[0]}:#{res[1]}")
    else; answer('error') end
  rescue Timeout::Error, Errno::ETIMEDOUT, Errno::ECONNREFUSED,
  Errno::EINVAL, Errno::ECONNRESET, Errno::ENETUNREACH, SocketError, EOFError,
  TypeError, Net::HTTPExceptions, Net::HTTPBadResponse, OpenSSL::SSL::SSLError => e
    log "proxy".red + " in #{'process'.yellow}: #{e.inspect.red}"
    answer 'proxy'
  rescue Interrupt => e
    log 'Interrupted by user, exiting...'.yellow
    Kernel.exit!
  rescue Exception => e
    log "rescue in #{'process'.yellow}: #{e.inspect},\n#{e.backtrace.reverse.join("\n").red}"
    answer 'error'
  end
end