rest-tor 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 69c56528e872195fddd3c14db1b661d03a8e9663
4
+ data.tar.gz: ab759079d8abf7e67b638f06fe158615620c2c1a
5
+ SHA512:
6
+ metadata.gz: 1949446855c7fb316d10440c14fc9652a9c730b78bcabd03e696fdf212781b7f5c72534008c8cb940037bf81cfba29bda8d1216924bc289e4a7f8067c55e5d53
7
+ data.tar.gz: 018d06c86ae6a813c3312e70ed06cb0f047994bd76c3499d606f1d26bb0ef1239462cd3db67c538ee14f9ba2a35957e9f45226b052018797b57f98c2dbfd9be5
data/.gitignore ADDED
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.3.0
5
+ before_install: gem install bundler -v 1.14.6
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at plusor@qq.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in rest-tor.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 plusor
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,65 @@
1
+ # Rest::Tor
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/rest/tor`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'rest-tor'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install rest-tor
22
+
23
+ ## Usage
24
+
25
+ Tor.request(url: 'http://ip.plusor.cn/')
26
+ => #<Nokogiri::HTML::Document:0x3fcd64ec6eb0 name="document" children=[#<Nokogiri::XML::DTD:0x3fcd64ec6af0 name="html">, #<Nokogiri::XML::Element:0x3fcd64ec67f8 name="html" children=[#<Nokogiri::XML::Element:0x3fcd64ec6618 name="body" children=[#<Nokogiri::XML::Element:0x3fcd64ec6438 name="p" children=[#<Nokogiri::XML::Text:0x3fcd64ec6258 "185.100.85.101\n">]>]>]>]>
27
+
28
+ Tor.request(url: 'http://ip.plusor.cn/', raw: false)
29
+ "64.113.32.29\n"
30
+
31
+ Tor.request(url: 'http://ip.plusor.cn/', mobile: true) # RestClient.get "http://ip.plusor.cn/", "", "Accept"=>"*/*", "Accept-Encoding"=>"gzip, deflate", "Content-Length"=>"0", "Content-Type"=>"application/x-www-form-urlencoded", "User-Agent"=>"ANDROID_KFZ_COM_2.0.9_M6 Note_7.1.2"
32
+ Tor.request(url: 'http://ip.plusor.cn/') # RestClient.get "http://ip.plusor.cn/", "", "Accept"=>"*/*", "Accept-Encoding"=>"gzip, deflate", "Content-Length"=>"0", "Content-Type"=>"application/x-www-form-urlencoded", "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"
33
+
34
+ Tor.request(method: :post, url: '...', format: :json, mobile: true)
35
+ => {'hello' => 'world'}
36
+
37
+ Tor.request(url: '...', timeout: 10)
38
+
39
+ Tor.request(url: '...', mode: :default) # Priority to use the highest number of successes, default is :default
40
+ Tor.request(url: '...', mode: :order) # in order
41
+
42
+
43
+ ## TODO
44
+
45
+ - Test
46
+ - Optimization code
47
+ - Add config
48
+ - Configurable restart strategy
49
+ - Configurable dispatcher
50
+
51
+ ## Development
52
+
53
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
54
+
55
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
56
+
57
+ ## Contributing
58
+
59
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/rest-tor. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
60
+
61
+
62
+ ## License
63
+
64
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
65
+
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ require "bundler/gem_tasks"
2
+ require "rake/testtask"
3
+
4
+ Rake::TestTask.new(:test) do |t|
5
+ t.libs << "test"
6
+ t.libs << "lib"
7
+ t.test_files = FileList['test/**/*_test.rb']
8
+ end
9
+
10
+ task :default => :test
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "rest-tor"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
data/lib/rest-tor.rb ADDED
@@ -0,0 +1,11 @@
1
+ require 'nokogiri'
2
+ require 'rest-client'
3
+ require 'redis-objects'
4
+ require 'active_support/all'
5
+ Dir.glob(File.expand_path('../rest_tor/**/*.rb', __FILE__)).each { |file| require file }
6
+
7
+ module Tor
8
+ def self.logger
9
+ Logger.new(STDOUT)
10
+ end
11
+ end
@@ -0,0 +1,40 @@
1
+ module Tor
2
+ module Dispatcher
3
+ def self.modes
4
+ @modes ||= {}
5
+ end
6
+
7
+ def self.register(name, &block)
8
+ modes[name] = block
9
+ end
10
+
11
+ def self.take(mode: :default)
12
+ Tor.lock("tor:pick", expires: 10) do
13
+ port, tor = run(mode)
14
+ if port.blank? || tor.blank?
15
+ port, _ = Tor.store.max {|a,b | a[0] <=> b[0] } || Tor::TOR_PORT_START_WITH
16
+ tor = Tor.listen(port=port.next)
17
+ end
18
+ return [port, tor]
19
+ end
20
+
21
+ return []
22
+ end
23
+
24
+ def self.run(name)
25
+ @modes[:"#{name}"].call
26
+ end
27
+
28
+ register :default do
29
+ Tor.store.all.sort_by do |(port, tor)|
30
+ tor.c_fail - tor.c_success
31
+ end.detect { |(port, tor)| !tor.using? && tor.use! }
32
+ end
33
+
34
+ register :order do
35
+ Tor.store.all.sort_by do |(port, tor)|
36
+ port
37
+ end.detect { |(port, tor)| !tor.using? && tor.use! }
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,132 @@
1
+ require 'rest_tor/strategy/restart'
2
+ module Tor
3
+ class Instance
4
+ include Strategy::Restart
5
+ extend Forwardable
6
+
7
+ ATTRS = %i(ip port using counter)
8
+
9
+ attr_accessor *ATTRS
10
+
11
+ def_delegators :@counter, :success!, :fail!
12
+ def_delegator :@counter, :success, :c_success
13
+ def_delegator :@counter, :fail, :c_fail
14
+
15
+ def initialize(port, ip: nil, using: nil, counter: nil)
16
+ @port = port
17
+ @ip = ip
18
+ @using = using
19
+ @counter= Counter.new(self, counter || {})
20
+ end
21
+
22
+ def attributes
23
+ { ip: @ip, port: @port, using: @using, counter: @counter.to_h }
24
+ end
25
+
26
+ ATTRS.each do |name|
27
+ define_method :"#{name}=" do |value|
28
+ apply do
29
+ instance_variable_set("@#{name}", value)
30
+ end
31
+ end
32
+ end
33
+
34
+ def last?
35
+ Tor.store.max_by {|(k, v)| k}.try(:first).to_s == port.to_s
36
+ end
37
+
38
+ def release!
39
+ self.using = nil
40
+
41
+ if Tor.locked?("#{port}:restart")
42
+ logger.info "The tor(#{port}) already processing!"
43
+ else
44
+ if error=died?
45
+ restart!("Died(#{error})")
46
+ end
47
+ end
48
+ true
49
+ end
50
+
51
+ def restart!(message="")
52
+ logger.info "#{message} Restart => #{ip}:#{port}"
53
+ Tor.restart(port)
54
+ end
55
+
56
+ def use!
57
+ self.using = Time.now
58
+ end
59
+
60
+ def using?
61
+ @using.present?
62
+ end
63
+
64
+ def stop
65
+ Tor.stop(port)
66
+ end
67
+
68
+ alias_method :destroy, :stop
69
+
70
+ def apply(&block)
71
+ Tor.lock("tor:#{port}:update", expires: 1.minutes) do
72
+ if not Tor.store.has_key?(port)
73
+ logger.info "Has been destroyed"
74
+ return
75
+ end
76
+ if block_given?
77
+ yield.tap do
78
+ Tor.store[port] = attributes
79
+ end
80
+ else
81
+ Tor.store[port] = attributes
82
+ end
83
+ end
84
+ end
85
+
86
+ def avaliable?
87
+ `ps aux | grep tor | grep RunAsDaemon | grep -v "ps aux" | grep #{port} | awk '{print $2}'`.to_s.strip.to_i > 0
88
+ end
89
+ end
90
+
91
+ class Counter < BasicObject
92
+ attr_accessor :success, :fail, :success_at, :fail_at, :errors
93
+ def initialize(tor, success: 0, fail: 0, success_at: nil, fail_at: nil, errors: {})
94
+ @tor = tor
95
+ @success = success
96
+ @fail = fail
97
+ @success_at = success_at
98
+ @fail_at = fail_at
99
+ @errors = errors.is_a?(::Hash) ? errors : {}
100
+ end
101
+
102
+ def inspect
103
+ "#<Counter success: #{@success}, fail: #{@fail}, succss_at: #{@success_at}, fail_at:#{@fail_at}>"
104
+ end
105
+
106
+ def to_h
107
+ { success: @success, fail: @fail, success_at: @success_at, fail_at: @fail_at, errors: @errors }
108
+ end
109
+
110
+ def success!
111
+ @tor.apply do
112
+ @success += 1
113
+ @success_at = ::Time.now
114
+ end
115
+ end
116
+
117
+ def fail!(e)
118
+ if e.is_a?(::Exception)
119
+ errors[e.class] ||= 0
120
+ errors[e.class] += 1
121
+ else
122
+ erros[e] ||= 0
123
+ erros[e] += 1
124
+ end
125
+
126
+ @tor.apply do
127
+ @fail += 1
128
+ @fail_at = ::Time.now
129
+ end
130
+ end
131
+ end
132
+ end
@@ -0,0 +1,15 @@
1
+ module Tor
2
+ module Lock
3
+ def lock(key, expires: 10*60, timeout: 1 * 60 * 0, &block)
4
+ Redis::Lock.new("tor:lock:#{key}", expiration: expires, timeout: timeout).lock { yield }
5
+ end
6
+
7
+ def locked?(key)
8
+ Redis.current.get("tor:lock:#{key}")
9
+ end
10
+
11
+ def unlock!(key)
12
+ Redis.current.del("tor:lock:#{key}")
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,18 @@
1
+ require 'socksify/http'
2
+ module RestClient
3
+ class Request
4
+
5
+ def net_http_object_with_socksify(hostname, port)
6
+ p_uri = proxy_uri
7
+ if p_uri && p_uri.scheme =~ /^socks5?$/i
8
+ return Net::HTTP.SOCKSProxy(p_uri.hostname, p_uri.port).new(hostname, port)
9
+ end
10
+
11
+ net_http_object_without_socksify(hostname, port)
12
+ end
13
+
14
+ alias_method :net_http_object_without_socksify, :net_http_object
15
+ alias_method :net_http_object, :net_http_object_with_socksify
16
+
17
+ end
18
+ end
@@ -0,0 +1,30 @@
1
+ module Tor
2
+ module Strategy
3
+ module Restart
4
+ DEFAULT_EXCEPTION_COUNT = 50
5
+ EXCEPTIONS = {
6
+ ::Net::OpenTimeout => 20,
7
+ ::Errno::ECONNREFUSED => 50,
8
+ ::RestClient::Exceptions::OpenTimeout => 20
9
+ }
10
+
11
+ def died?
12
+ message = nil
13
+ return message if counter.errors.any? do |k,v|
14
+ if EXCEPTIONS.key?(k)
15
+ message = "#{k} count >= #{EXCEPTIONS[k]}" if v.to_i >= (EXCEPTIONS[k] || DEFAULT_EXCEPTION_COUNT)
16
+ else
17
+ message = "#{k} count >= #{DEFAULT_EXCEPTION_COUNT}" if v.to_i >= DEFAULT_EXCEPTION_COUNT
18
+ end
19
+ end
20
+
21
+ if c_success > 0 && c_fail > (c_success << 5)
22
+ message = "fail > success << 5 & success > 0"
23
+ elsif c_success == 0 and c_fail > 50
24
+ message = "fail > 50 & success = 0"
25
+ end
26
+ message.presence
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,191 @@
1
+ require 'open3'
2
+ module Tor extend self
3
+ extend Lock
4
+ class Error < StandardError; end
5
+ class UnvaliablePort < Error; end
6
+ class DiedPortError < Error; end
7
+ class InvalidFormat < Error; end
8
+ 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'
9
+ MOBILE_AGENT = 'ANDROID_KFZ_COM_2.0.9_M6 Note_7.1.2'
10
+ TOR_COUNT = 10
11
+ TOR_PORT_START_WITH = 9000
12
+
13
+ def init
14
+ lock("tor:init", expires: 1.minutes) do
15
+ Parallel.each(0...TOR_COUNT, in_threads: 20, progress: 'Init Tor') do |i|
16
+ listen(TOR_PORT_START_WITH + i)
17
+ end
18
+ end
19
+ end
20
+
21
+ def store
22
+ @store ||= Redis::HashKey.new('tor', marshal: true).tap { |s| s.send(:extend, Builder) }
23
+ end
24
+
25
+ def hold_tor(mode: :default, &block)
26
+ if tor=Thread.current[:tor]
27
+ port = tor.port
28
+ else
29
+ port, tor = Dispatcher.take(mode: mode)
30
+ end
31
+
32
+ Thread.current[:tor] = tor
33
+
34
+ if block_given?
35
+ yield port, tor
36
+ end
37
+ ensure
38
+ Thread.current[:tor] = nil
39
+ tor && tor.release!
40
+ end
41
+
42
+ def request(options={}, &block)
43
+ url = options[:url]
44
+ mode = options[:mode] || :default
45
+ raw = options[:raw].nil? ? true : false
46
+ method = options[:method] || :get
47
+ payload = options[:payload] || {}
48
+ timeout = options[:timeout] || 10
49
+ format = options[:format] || (raw ? :html : :string)
50
+ mobile = options[:mobile]
51
+ default_header = { 'User-Agent' => mobile ? MOBILE_AGENT : USER_AGENT }
52
+ time, body = Time.now, nil
53
+
54
+ hold_tor(mode: mode) do |port, tor|
55
+ logger.info "Started #{method.to_s.upcase} #{url.inspect} (port:#{port} | mode:#{mode}"
56
+ params = {
57
+ method: method,
58
+ url: url,
59
+ payload: payload,
60
+ proxy: "socks5://127.0.0.1:#{port}",
61
+ timeout: timeout,
62
+ headers: default_header.merge(options[:header] || {})
63
+ }
64
+
65
+ begin
66
+ response = RestClient::Request.execute(params) do |res, req, headers|
67
+ yield(res, req, headers ) if block_given?
68
+ res
69
+ end
70
+ tor.success!
71
+ body = response.body
72
+ logger.info "Completed #{response.try(:code)} OK in #{(Time.now-time).round(1)}s (Size: #{Utils.number_to_human_size(body.bytesize)})"
73
+ rescue Exception => e
74
+ tor.fail!(e)
75
+ logger.info "#{e.class}: #{e.message}, <Tor#(success: #{tor.counter.success}, fail: #{tor.counter.fail}, port: #{tor.port})>"
76
+ raise e
77
+ end
78
+ end
79
+ case format.to_s
80
+ when "html" then Nokogiri::HTML(Utils.encode_html(body))
81
+ when "json" then Utils.to_json(body)
82
+ when "string" then body
83
+ else
84
+ raise InvalidFormat, format.to_s
85
+ end
86
+ end
87
+
88
+ def stop(port)
89
+ logger.info "Stop tor port:#{port}"
90
+ Open3.pipeline("ps aux", "grep tor", "grep RunAsDaemon", "grep #{port}", "awk '{print $2}'", "xargs kill -9")
91
+ ensure
92
+ store.delete(port)
93
+ end
94
+
95
+ def listen(port)
96
+ return if port.blank? || !port.to_s.match(/^\d+$/)
97
+ # if `lsof -i -P -n |grep -E :#{port}`.chomp.present?
98
+ # logger.error "Unavailable port:#{port}, it used!"
99
+ # return
100
+ # end
101
+
102
+ logger.info "Open tor with port:#{port}"
103
+
104
+ control_port = 6000 + port.to_i
105
+
106
+ tor = 'tor --RunAsDaemon 1 --CookieAuthentication 0 --HashedControlPassword ""'
107
+ tor+= " --ControlPort #{ control_port } --PidFile tor#{port}.pid --SocksPort #{port} --DataDirectory #{dir(port)}"
108
+ tor+= " --CircuitBuildTimeout 5 --KeepalivePeriod 60 --NewCircuitPeriod 15 --NumEntryGuards 8"# make tor faster
109
+ tor+= " --quiet" # unless Rails.env.production?
110
+ system tor
111
+ sleep 5
112
+ if ip=test(port)
113
+ store.insert(port, ip)
114
+ else
115
+ tor = Tor.store[port]
116
+ raise DiedPortError if tor&.died?
117
+ raise UnvaliablePort if !tor
118
+ end
119
+ rescue Error, RestClient::Exception => e
120
+ stop(port)
121
+ logger.info "#{e.class}:#{e.message}"
122
+ retry
123
+ end
124
+
125
+ def restart(port)
126
+ lock("tor:#{port}:restart", expires: 1.minutes) do
127
+ stop(port)
128
+ listen(port)
129
+ end
130
+ end
131
+
132
+ def dir(port)
133
+ "/tmp/tor/#{port}".tap do |dir|
134
+ FileUtils.mkpath(dir) if not Dir.exists?(dir)
135
+ end
136
+ end
137
+
138
+ def test(port)
139
+ logger.info "Testing tor #{port}"
140
+
141
+ url = 'http://ip.plusor.cn/'
142
+
143
+ req = RestClient::Request.execute({method: :get, url: url, proxy: "socks5://127.0.0.1:#{port}"})
144
+ req.body.chomp.tap do |body|
145
+ logger.info " IP: #{body} "
146
+ end
147
+ rescue Net::OpenTimeout, Net::ReadTimeout, Errno::ECONNREFUSED, SOCKSError, SOCKSError::TTLExpired, Errno::ECONNRESET => e
148
+ logger.error "#{e.class}: #{e.message}"
149
+ false
150
+ end
151
+
152
+ def clear
153
+ `ps aux | grep tor | grep RunAsDaemon|grep -v "ps aux" | awk '{print $2}' | xargs kill -9`
154
+ store.clear
155
+ end
156
+
157
+ def count
158
+ `ps aux | grep tor | grep RunAsDaemon|grep -v "ps aux"`.to_s.strip.split("\n").keep_if { |s| s.strip.present? }.count
159
+ end
160
+
161
+ def unused
162
+ store.select {|_, options| !options.using? }
163
+ end
164
+
165
+ module Builder
166
+ def [](key)
167
+ if value=super(key)
168
+ Instance.new key, safe_value(value)
169
+ end
170
+ end
171
+
172
+ def all
173
+ super.reduce({}) { |h, (k, v)| h[k] = Tor::Instance.new(k, safe_value(v)); h }
174
+ end
175
+
176
+ def insert(port, ip)
177
+ self[port] = { ip: ip }
178
+ self[port]
179
+ end
180
+
181
+ private
182
+ def safe_value(value)
183
+ counter = value.try(:[], :counter) || {}
184
+ value.slice(*[:ip, :using]).merge({
185
+ counter: counter.slice(*[:success, :fail, :success_at, :fail_at, :errors])
186
+ })
187
+ rescue NoMethodError => e
188
+ value
189
+ end
190
+ end
191
+ end
@@ -0,0 +1,40 @@
1
+ module Tor
2
+ module Utils extend self
3
+ def to_json(body)
4
+ JSON.parse(body)
5
+ rescue Exception => e
6
+ $Logger.tag("ERROR") { "#{e.class}:#{e.message}" }
7
+ {}
8
+ end
9
+
10
+ def number_to_human_size(num, options={})
11
+ ActiveSupport::NumberHelper::NumberToHumanSizeConverter.convert num, options
12
+ end
13
+
14
+ def encode_html(body)
15
+ if /<meta .*?content=".*?charset=(\w+)"/ =~ body.encode("UTF-16be", :invalid=>:replace, :replace=>"?").encode('UTF-8')
16
+ encode = $1
17
+ if /utf-8/i !~ encode
18
+ begin
19
+ body = body.dup.force_encoding(encode).encode("utf-8", invalid: :replace, under: :replace)
20
+ rescue Exception => e
21
+ $Logger.tag("ERROR") { "#{e.class}:#{e.message}(Tor.request)" }
22
+ end
23
+ end
24
+ end
25
+ body
26
+ end
27
+
28
+ def with_lock(key)
29
+ name = "utils:with_lock:#{key}"
30
+ pid = Redis.current.get(name)
31
+ begin
32
+ raise LockedError if pid.blank? or Process.getpgid(pid.to_i)
33
+ rescue Errno::ESRCH, LockedError
34
+ yield if Redis.current.setnx(name, Process.pid)
35
+ end
36
+ ensure
37
+ Redis.current.del(name)
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,3 @@
1
+ module Tor
2
+ VERSION = "0.1.0"
3
+ end
data/rest-tor.gemspec ADDED
@@ -0,0 +1,42 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'rest_tor/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "rest-tor"
8
+ spec.version = Tor::VERSION
9
+ spec.authors = ["plusor"]
10
+ spec.email = ["plusor@qq.com"]
11
+
12
+ spec.summary = "Tor for ruby"
13
+ spec.description = 'Tor for ruby'
14
+ spec.homepage = 'https://github.com/plusor'
15
+ spec.license = "MIT"
16
+
17
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
18
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
19
+ if spec.respond_to?(:metadata)
20
+ spec.metadata['allowed_push_host'] = "https://rubygems.org"
21
+ else
22
+ raise "RubyGems 2.0 or newer is required to protect against " \
23
+ "public gem pushes."
24
+ end
25
+
26
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
27
+ f.match(%r{^(test|spec|features)/})
28
+ end
29
+ spec.bindir = "exe"
30
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
31
+ spec.require_paths = ["lib"]
32
+
33
+ spec.add_dependency 'rest-client'
34
+ spec.add_dependency 'redis-objects'
35
+ spec.add_dependency 'socksify'
36
+ spec.add_dependency 'activesupport'
37
+ spec.add_dependency 'nokogiri'
38
+
39
+ spec.add_development_dependency "bundler", "~> 1.14"
40
+ spec.add_development_dependency "rake", "~> 10.0"
41
+ spec.add_development_dependency "minitest", "~> 5.0"
42
+ end
metadata ADDED
@@ -0,0 +1,176 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rest-tor
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - plusor
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2017-12-15 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rest-client
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: redis-objects
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: socksify
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: activesupport
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: nokogiri
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :runtime
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: bundler
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '1.14'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '1.14'
97
+ - !ruby/object:Gem::Dependency
98
+ name: rake
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - "~>"
102
+ - !ruby/object:Gem::Version
103
+ version: '10.0'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - "~>"
109
+ - !ruby/object:Gem::Version
110
+ version: '10.0'
111
+ - !ruby/object:Gem::Dependency
112
+ name: minitest
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - "~>"
116
+ - !ruby/object:Gem::Version
117
+ version: '5.0'
118
+ type: :development
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - "~>"
123
+ - !ruby/object:Gem::Version
124
+ version: '5.0'
125
+ description: Tor for ruby
126
+ email:
127
+ - plusor@qq.com
128
+ executables: []
129
+ extensions: []
130
+ extra_rdoc_files: []
131
+ files:
132
+ - ".gitignore"
133
+ - ".travis.yml"
134
+ - CODE_OF_CONDUCT.md
135
+ - Gemfile
136
+ - LICENSE.txt
137
+ - README.md
138
+ - Rakefile
139
+ - bin/console
140
+ - bin/setup
141
+ - lib/rest-tor.rb
142
+ - lib/rest_tor/dispatcher.rb
143
+ - lib/rest_tor/instance.rb
144
+ - lib/rest_tor/lock.rb
145
+ - lib/rest_tor/rest_client.rb
146
+ - lib/rest_tor/strategy/restart.rb
147
+ - lib/rest_tor/tor.rb
148
+ - lib/rest_tor/utils.rb
149
+ - lib/rest_tor/version.rb
150
+ - rest-tor.gemspec
151
+ homepage: https://github.com/plusor
152
+ licenses:
153
+ - MIT
154
+ metadata:
155
+ allowed_push_host: https://rubygems.org
156
+ post_install_message:
157
+ rdoc_options: []
158
+ require_paths:
159
+ - lib
160
+ required_ruby_version: !ruby/object:Gem::Requirement
161
+ requirements:
162
+ - - ">="
163
+ - !ruby/object:Gem::Version
164
+ version: '0'
165
+ required_rubygems_version: !ruby/object:Gem::Requirement
166
+ requirements:
167
+ - - ">="
168
+ - !ruby/object:Gem::Version
169
+ version: '0'
170
+ requirements: []
171
+ rubyforge_project:
172
+ rubygems_version: 2.5.1
173
+ signing_key:
174
+ specification_version: 4
175
+ summary: Tor for ruby
176
+ test_files: []