Module: Tor

Extended by:
Tor, Lock
Included in:
Tor
Defined in:
lib/rest-tor.rb,
lib/rest_tor/tor.rb,
lib/rest_tor/lock.rb,
lib/rest_tor/utils.rb,
lib/rest_tor/version.rb,
lib/rest_tor/instance.rb,
lib/rest_tor/dispatcher.rb,
lib/rest_tor/strategy/restart.rb

Defined Under Namespace

Modules: Builder, Dispatcher, Lock, Strategy, Utils Classes: Counter, DiedPortError, Error, Instance, InvalidFormat, UnvaliablePort

Constant Summary collapse

USER_AGENT =
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'
MOBILE_AGENT =
'ANDROID_KFZ_COM_2.0.9_M6 Note_7.1.2'
TOR_COUNT =
10
TOR_PORT_START_WITH =
9000
VERSION =
"0.1.0"

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Lock

lock, locked?, unlock!

Class Method Details

.loggerObject



8
9
10
# File 'lib/rest-tor.rb', line 8

def self.logger
  Logger.new(STDOUT)
end

Instance Method Details

#clearObject



152
153
154
155
# File 'lib/rest_tor/tor.rb', line 152

def clear
  `ps aux | grep tor | grep RunAsDaemon|grep -v "ps aux" | awk '{print $2}' | xargs kill -9`
  store.clear
end

#countObject



157
158
159
# File 'lib/rest_tor/tor.rb', line 157

def count
  `ps aux | grep tor | grep RunAsDaemon|grep -v "ps aux"`.to_s.strip.split("\n").keep_if { |s| s.strip.present? }.count
end

#dir(port) ⇒ Object



132
133
134
135
136
# File 'lib/rest_tor/tor.rb', line 132

def dir(port)
  "/tmp/tor/#{port}".tap do |dir|
    FileUtils.mkpath(dir) if not Dir.exists?(dir)
  end
end

#hold_tor(mode: :default, &block) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/rest_tor/tor.rb', line 25

def hold_tor(mode: :default, &block)
  if tor=Thread.current[:tor]
    port = tor.port
  else
    port, tor = Dispatcher.take(mode: mode)
  end

  Thread.current[:tor] = tor

  if block_given?
    yield port, tor
  end
ensure
  Thread.current[:tor] = nil
  tor && tor.release!
end

#initObject



13
14
15
16
17
18
19
# File 'lib/rest_tor/tor.rb', line 13

def init
  lock("tor:init", expires: 1.minutes) do
    Parallel.each(0...TOR_COUNT, in_threads: 20, progress: 'Init Tor') do |i|
      listen(TOR_PORT_START_WITH + i)
    end
  end
end

#listen(port) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/rest_tor/tor.rb', line 95

def listen(port)
  return if port.blank? || !port.to_s.match(/^\d+$/)
  # if `lsof -i -P -n |grep -E :#{port}`.chomp.present?
  #   logger.error "Unavailable port:#{port}, it used!"
  #   return
  # end

  logger.info "Open tor with port:#{port}"

  control_port = 6000 + port.to_i

  tor = 'tor --RunAsDaemon 1 --CookieAuthentication 0 --HashedControlPassword ""'
  tor+= " --ControlPort #{ control_port } --PidFile tor#{port}.pid --SocksPort #{port} --DataDirectory #{dir(port)}"
  tor+= " --CircuitBuildTimeout 5 --KeepalivePeriod 60 --NewCircuitPeriod 15 --NumEntryGuards 8"# make tor faster
  tor+= " --quiet" # unless Rails.env.production?
  system tor
  sleep 5
  if ip=test(port)
    store.insert(port, ip)
  else
    tor = Tor.store[port]
    raise DiedPortError if tor&.died?
    raise UnvaliablePort if !tor
  end
rescue Error, RestClient::Exception => e
  stop(port)
  logger.info "#{e.class}:#{e.message}"
  retry
end

#request(options = {}, &block) ⇒ Object



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
# File 'lib/rest_tor/tor.rb', line 42

def request(options={}, &block)
  url     = options[:url]
  mode    = options[:mode] || :default
  raw     = options[:raw].nil? ? true : false
  method  = options[:method] || :get
  payload = options[:payload] || {}
  timeout = options[:timeout] || 10
  format  = options[:format] || (raw ? :html : :string)
  mobile  = options[:mobile]
  default_header = { 'User-Agent' => mobile ? MOBILE_AGENT : USER_AGENT }
  time, body = Time.now, nil

  hold_tor(mode: mode) do |port, tor|
    logger.info "Started #{method.to_s.upcase} #{url.inspect} (port:#{port} | mode:#{mode}"
    params = {
      method: method,
      url: url,
      payload: payload,
      proxy: "socks5://127.0.0.1:#{port}",
      timeout: timeout,
      headers: default_header.merge(options[:header] || {})
    }

    begin
      response = RestClient::Request.execute(params) do |res, req, headers|
         yield(res, req, headers ) if block_given?
         res
      end
      tor.success!
      body = response.body
      logger.info "Completed #{response.try(:code)} OK in #{(Time.now-time).round(1)}s (Size: #{Utils.number_to_human_size(body.bytesize)})"
    rescue Exception => e
      tor.fail!(e)
      logger.info "#{e.class}: #{e.message}, <Tor#(success: #{tor.counter.success}, fail: #{tor.counter.fail}, port: #{tor.port})>"
      raise e
    end
  end
  case format.to_s
    when "html"    then Nokogiri::HTML(Utils.encode_html(body))
    when "json"    then Utils.to_json(body)
    when "string"  then body
  else
    raise InvalidFormat, format.to_s
  end
end

#restart(port) ⇒ Object



125
126
127
128
129
130
# File 'lib/rest_tor/tor.rb', line 125

def restart(port)
  lock("tor:#{port}:restart", expires: 1.minutes) do
    stop(port)
    listen(port)
  end
end

#stop(port) ⇒ Object



88
89
90
91
92
93
# File 'lib/rest_tor/tor.rb', line 88

def stop(port)
  logger.info "Stop tor port:#{port}"
  Open3.pipeline("ps aux", "grep tor", "grep RunAsDaemon", "grep #{port}", "awk '{print $2}'", "xargs kill -9")
ensure
  store.delete(port)
end

#storeObject



21
22
23
# File 'lib/rest_tor/tor.rb', line 21

def store
  @store ||= Redis::HashKey.new('tor', marshal: true).tap { |s| s.send(:extend, Builder) }
end

#test(port) ⇒ Object



138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/rest_tor/tor.rb', line 138

def test(port)
  logger.info  "Testing tor #{port}"

  url = 'http://ip.plusor.cn/'

  req = RestClient::Request.execute({method: :get, url: url, proxy: "socks5://127.0.0.1:#{port}"})
  req.body.chomp.tap do |body|
    logger.info "  IP: #{body} "
  end
rescue Net::OpenTimeout, Net::ReadTimeout, Errno::ECONNREFUSED, SOCKSError, SOCKSError::TTLExpired, Errno::ECONNRESET => e
  logger.error "#{e.class}: #{e.message}"
  false
end

#unusedObject



161
162
163
# File 'lib/rest_tor/tor.rb', line 161

def unused
  store.select {|_, options| !options.using? }
end