r_proxy 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 5839c4652d9988cb964b5c26a98d942940b40ca752dd93d6771418dcd3c0edb2
4
+ data.tar.gz: 15244457f3886e601b65c9ede7aa42ff7e185a61262e3403fa44a7bbdc3c0e63
5
+ SHA512:
6
+ metadata.gz: f9881daa03f08e974a1b64a08123a24598092f50422c357028b23b09500dcaf052411b8ec5d6679bd2b52697d62cdb6c00856b42e309b4473d475deb03c5c4ef
7
+ data.tar.gz: 2a7af84937c888473343c9f88a2f1b86068637b29ee3011e26d17633212cca70b19f4b761fe224586c2073d963c73a6f9322d40a828c392ecb6ae3f9301e8b51
data/.gitignore ADDED
@@ -0,0 +1,13 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ .idea
10
+ server_cert.txt
11
+ server_key.txt
12
+ debug.log
13
+ test_server.rb
data/.travis.yml ADDED
@@ -0,0 +1,6 @@
1
+ ---
2
+ language: ruby
3
+ cache: bundler
4
+ rvm:
5
+ - 2.5.3
6
+ before_install: gem install bundler -v 2.1.4
data/Gemfile ADDED
@@ -0,0 +1,9 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in r_proxy.gemspec
4
+ gemspec
5
+
6
+ gem "rake", "~> 12.0"
7
+ gem "minitest", "~> 5.0"
8
+ gem 'eventmachine', '~> 1.2', '>= 1.2.7'
9
+ gem 'redis', '~> 4.1', '>= 4.1.4'
data/Gemfile.lock ADDED
@@ -0,0 +1,27 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ r_proxy (0.1.0)
5
+ eventmachine (~> 1.2, >= 1.2.7)
6
+ redis (~> 4.1, >= 4.1.4)
7
+
8
+ GEM
9
+ remote: https://rubygems.org/
10
+ specs:
11
+ eventmachine (1.2.7)
12
+ minitest (5.14.0)
13
+ rake (12.3.3)
14
+ redis (4.1.4)
15
+
16
+ PLATFORMS
17
+ ruby
18
+
19
+ DEPENDENCIES
20
+ eventmachine (~> 1.2, >= 1.2.7)
21
+ minitest (~> 5.0)
22
+ r_proxy!
23
+ rake (~> 12.0)
24
+ redis (~> 4.1, >= 4.1.4)
25
+
26
+ BUNDLED WITH
27
+ 2.1.4
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2020 Ning An
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,76 @@
1
+ # RProxy
2
+
3
+ ruby http proxy server, base on eventmachine
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'r_proxy'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle install
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install r_proxy
20
+
21
+ ## Usage
22
+
23
+ Http and Https proxy server
24
+
25
+ integrated with Redis, if you enable auth then you must provide redis url
26
+ to let server connect to redis.
27
+
28
+ e.g: `server.set(:redis_url, "redis://@localhost:6379/1")`
29
+
30
+ redis key rule: `proxy:username-password`
31
+
32
+ redis value rule: `integer string` e.g: `1234567`
33
+
34
+ the value describe how many bytes that user can use.
35
+
36
+ `unit: bytes`
37
+
38
+ ```ruby
39
+ require 'r_proxy'
40
+
41
+ server = RProxy::MasterProcess.new
42
+
43
+ server.set(:host, '127.0.0.1')
44
+ server.set(:port, 8080)
45
+
46
+ # if disable_auth is true
47
+ # then server will not auth user and password
48
+ # server.set(:disable_auth, true)
49
+
50
+ # if disable unbind cb, then it mean
51
+ # server will not decrby usage for user
52
+ # server.set(:disable_unbind_cb, true)
53
+
54
+ # default is true
55
+ server.set(:enable_ssl, true)
56
+
57
+ server.set(:callback_url,'http://127.0.0.1:1234')
58
+
59
+ server.set(:redis_url, "redis://@localhost:6379/1")
60
+
61
+ server.set(:ssl_private_key, './server_key.txt')
62
+ server.set(:ssl_cert, './server_cert.txt')
63
+
64
+ server.set(:logger, Logger.new(STDOUT))
65
+ # logger output like:
66
+ # I, [2020-05-08T21:04:00.492477 #86348] INFO -- : r_proxy @1588935840 process start....
67
+ # I, [2020-05-08T21:04:21.534989 #87168] INFO -- : r_proxy rebuild new instance replace @1588935861....
68
+
69
+ # call run to start server
70
+ server.run!
71
+ ```
72
+
73
+ ## Contributing
74
+
75
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/r_proxy.
76
+
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 "r_proxy"
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/example.rb ADDED
@@ -0,0 +1,21 @@
1
+ require 'r_proxy'
2
+
3
+ server = RProxy::MasterProcess.new
4
+
5
+ server.set(:host, '127.0.0.1')
6
+ server.set(:port, 8080)
7
+
8
+
9
+ server.set(:disable_auth, true)
10
+ # server.set(:disable_unbind_cb, true)
11
+ server.set(:enable_ssl, false)
12
+
13
+ server.set(:callback_url,'http://127.0.0.1:1234')
14
+
15
+ server.set(:redis_url, "redis://@localhost:6379/1")
16
+
17
+ server.set(:ssl_private_key, './server_key.txt')
18
+ server.set(:ssl_cert, './server_cert.txt')
19
+
20
+ server.set(:logger, Logger.new(STDOUT))
21
+ server.run!
@@ -0,0 +1,36 @@
1
+ module RProxy
2
+ class CallbackConnection < EM::Connection
3
+ def initialize(uri, user, pass, value, tls)
4
+ @uri = uri
5
+ @path = uri.path.empty? ? '/' : uri.path
6
+ @http_request = RProxy::HttpPostTemplate.
7
+ new(@path).
8
+ create(user, pass, value)
9
+ @response = ''
10
+ @need_tls = tls
11
+ end
12
+
13
+ def assign_logger(logger)
14
+ @logger = logger
15
+ end
16
+
17
+ def connection_completed
18
+ start_tls if @need_tls
19
+ set_comm_inactivity_timeout(20)
20
+ send_data(@http_request)
21
+ end
22
+
23
+ def receive_data(data)
24
+ @response = data.split("\r\n")[0]
25
+ close_connection
26
+ end
27
+
28
+ def ssl_handshake_completed
29
+ send_data(@http_request)
30
+ end
31
+
32
+ def unbind
33
+ @logger.info("#{@uri.host}#{@path} response status: #{@response}") if @logger
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,19 @@
1
+ module RProxy
2
+ class CallbackService
3
+ def self.call(url, user, pass, value)
4
+ uri = URI(url)
5
+ tls = uri.scheme == 'https'
6
+
7
+ EventMachine.connect(
8
+ uri.host,
9
+ uri.port,
10
+ RProxy::CallbackConnection,
11
+ uri,
12
+ user,
13
+ pass,
14
+ value,
15
+ tls
16
+ )
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,30 @@
1
+ module RProxy
2
+ class CheckSnapshotService
3
+
4
+ def initialize(redis, config)
5
+ @redis = redis
6
+ @snapshot_expire_in = 15 * 60
7
+ @usage_threshold = config.usage_threshold
8
+ @cb_url = config.callback_url
9
+ @logger = config.logger
10
+ end
11
+
12
+ def call(user, pass, result)
13
+
14
+ s_key = "proxy:#{user}-#{pass}:snapshot"
15
+ snapshot_value = @redis.get(s_key)
16
+
17
+ if snapshot_value.nil? || snapshot_value.empty?
18
+ @redis.setex(s_key, @snapshot_expire_in, result)
19
+ else
20
+ tmp = snapshot_value.to_i - result.to_i
21
+
22
+ if tmp >= @usage_threshold
23
+ connection = RProxy::CallbackService.call(@cb_url, user, pass, tmp)
24
+ connection.assign_logger(@logger)
25
+ @redis.setex(s_key, @snapshot_expire_in, result)
26
+ end
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,57 @@
1
+ module RProxy
2
+ class Config
3
+ class << self
4
+ def add_config(name, default_value = nil)
5
+ self.define_method("#{name}") do
6
+ store = instance_variable_get('@store')
7
+ store["#{name}"].nil? ? default_value : store["#{name}"]
8
+ end
9
+
10
+ define_set_config_value_method(name)
11
+ end
12
+
13
+ def add_exception_config(name)
14
+ self.define_method("#{name}") do
15
+ store = instance_variable_get('@store')
16
+ val = store["#{name}"]
17
+ raise RProxy::EmptyConfigError,
18
+ "#{name} cannot set as empty or nil" if val.nil?
19
+ val
20
+ end
21
+
22
+ define_set_config_value_method(name)
23
+ end
24
+
25
+ def define_set_config_value_method(name)
26
+ self.define_method("#{name}=") do |value|
27
+ store = instance_variable_get('@store')
28
+ store["#{name}"] = value
29
+ end
30
+ end
31
+ end
32
+
33
+ add_config(:instances, 1)
34
+ add_config(:host, '0.0.0.0')
35
+ add_config(:port, 8081)
36
+
37
+ add_config(:logger)
38
+
39
+ add_config(:callback_url)
40
+ add_config(:usage_threshold, 1 * 1024 * 1024 * 1024)
41
+ add_config(:proxy_buffer, 1024 * 1024 * 10) # default is 10M
42
+
43
+ add_config(:disable_auth, false)
44
+ add_config(:disable_unbind_cb, false)
45
+
46
+ # e.g "redis://:p4ssw0rd@10.0.1.1:6380/15"
47
+ add_exception_config(:redis_url)
48
+
49
+ add_config(:enable_ssl, true)
50
+ add_exception_config(:ssl_private_key)
51
+ add_exception_config(:ssl_cert)
52
+
53
+ def initialize
54
+ @store = {}
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,86 @@
1
+ module RProxy
2
+ class ConnectionHandler < EM::Connection
3
+ def initialize(config)
4
+ @config = config
5
+ @logger = @config.logger
6
+ @redis = RProxy::RedisService.instance(@config.redis_url)
7
+ @http_parser = HttpProxyParser.new(@redis)
8
+ @disable_auth = @config.disable_auth
9
+ @disable_unbind_cb = @config.disable_unbind_cb
10
+ @buffer_size = @config.proxy_buffer
11
+ @callback_url = @config.callback_url
12
+ @username = nil
13
+ @password = nil
14
+ @target_connection = nil
15
+
16
+ @unbind_service = UnbindService.new(config, @redis)
17
+ @snapshot_service = RProxy::CheckSnapshotService.new(@redis, @config)
18
+ end
19
+
20
+ def post_init
21
+ begin
22
+ if @config.enable_ssl
23
+ start_tls(
24
+ private_key_file: @config.ssl_private_key,
25
+ cert_chain_file: @config.ssl_cert
26
+ )
27
+ end
28
+ @port, @ip = Socket.unpack_sockaddr_in(get_peername)
29
+
30
+ @timer = EventMachine.add_timer(20) do
31
+ self.close_connection(false)
32
+ @timer = nil
33
+ end
34
+ rescue => e
35
+ if @logger
36
+ @logger.error("id:#{@ip}, #{e.message}")
37
+ end
38
+ close_connection
39
+ end
40
+ end
41
+
42
+ def receive_data(data)
43
+ begin
44
+ target_host, target_port, remain = @http_parser.parse(data, !@disable_auth)
45
+
46
+ @target_connection = EventMachine.
47
+ connect(target_host,
48
+ target_port,
49
+ RProxy::TargetConnection,
50
+ self,
51
+ @disable_unbind_cb,
52
+ @buffer_size,
53
+ @unbind_service)
54
+ @target_connection.assign_logger(@logger)
55
+ if !@disable_auth
56
+ @username = @http_parser.username
57
+ @password = @http_parser.password
58
+ @target_connection.assign_user_and_password(@username, @password)
59
+
60
+ # check snapshot
61
+ @snapshot_service.call(@username, @password, remain)
62
+ end
63
+ rescue RProxy::HTTPAuthFailed
64
+ send_data(RProxy::Constants::HTTP_FAILED_AUTH)
65
+ close_connection_after_writing
66
+ rescue RProxy::HTTPNotSupport
67
+ send_data(RProxy::Constants::HTTP_BAD_REQUEST)
68
+ close_connection_after_writing
69
+ rescue => e
70
+ if @logger
71
+ @logger.error("client: id:#{@ip}, #{e.message}, #{e.backtrace}")
72
+ end
73
+ close_connection
74
+ end
75
+ end
76
+
77
+ def proxy_target_unbound
78
+ close_connection
79
+ end
80
+
81
+ def unbind
82
+ return if @disable_unbind_cb
83
+ @unbind_service.call(@username, @password, get_proxied_bytes)
84
+ end
85
+ end
86
+ end
@@ -0,0 +1,9 @@
1
+ module RProxy
2
+ module Constants
3
+ HTTP_SUCCESS = "HTTP/1.1 200 OK\r\n\r\n"
4
+ HTTP_FAILED_AUTH = "HTTP/1.1 401 Unauthorized\r\n\r\n"
5
+ HTTP_BAD_REQUEST = "HTTP/1.1 400 Bad Request\r\n\r\n"
6
+
7
+ HTTP_CONNECT_TITLE = "CONNECT\s"
8
+ end
9
+ end
@@ -0,0 +1,44 @@
1
+ require 'json'
2
+
3
+ module RProxy
4
+ class HttpPostTemplate
5
+
6
+ def initialize(route)
7
+ @route = route
8
+ @headers = init_headers
9
+ @protocol = "POST #{route} HTTP/1.1"
10
+ end
11
+
12
+ def create(user, pass, value)
13
+ body = {
14
+ user: user,
15
+ pass: pass,
16
+ value: value,
17
+ timestamp: Time.now.getutc.to_i
18
+ }.to_json
19
+
20
+ @headers['Content-Length'] = body.bytesize
21
+
22
+ headers_str = header_to_s
23
+
24
+ "#{@protocol}\r\n#{headers_str}\r\n#{body}"
25
+ end
26
+
27
+ private
28
+
29
+ def header_to_s
30
+ tmp = ''
31
+ @headers.each do |k, v|
32
+ tmp += "#{k}: #{v}\r\n"
33
+ end
34
+ tmp
35
+ end
36
+
37
+ def init_headers
38
+ {
39
+ 'User-Agent' => "RSocks/#{RProxy::VERSION}",
40
+ 'Content-Type' => 'application/json',
41
+ }
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,71 @@
1
+ require 'base64'
2
+
3
+ module RProxy
4
+ class HttpProxyParser
5
+
6
+ attr_reader :username, :password
7
+
8
+ def initialize(redis)
9
+ @redis = redis
10
+ @max_connection_size = 4 * 1024
11
+ end
12
+
13
+ def parse(data, need_auth)
14
+ parse_connect_request(data)
15
+ remain = 0
16
+ remain = auth_user if need_auth
17
+
18
+ [@schema.host, @schema.port, remain]
19
+ end
20
+
21
+ private
22
+
23
+ def auth_user
24
+ begin
25
+ temp = @headers['proxy-authorization']
26
+ raise RProxy::HTTPNotSupport if temp.nil?
27
+ pattern = /^Basic /
28
+ token = temp.gsub(pattern, '')
29
+ str = Base64.decode64(token)
30
+ @username, @password = str.split(':')
31
+ rescue
32
+ raise RProxy::HTTPNotSupport, "token parse failed #{token}"
33
+ end
34
+ key = "proxy:#{@username}-#{@password}"
35
+ value = @redis.get(key)
36
+
37
+ raise RProxy::HTTPAuthFailed if value.nil?
38
+ value
39
+ end
40
+
41
+ def parse_connect_request(data)
42
+ size_of_data = data.bytesize
43
+ raise RProxy::HTTPNotSupport unless
44
+ size_of_data <= @max_connection_size && check_is_valid_request(data[0...8])
45
+ temp = data.split("\r\n")
46
+ @schema = parse_connect_target(temp.shift)
47
+ @headers = parse_header(temp)
48
+ end
49
+
50
+ def parse_header(arr)
51
+ headers = {}
52
+ arr.each do |val|
53
+ name, value = val.split(':')
54
+ next if name.nil?
55
+ headers[name.strip.downcase] = value&.strip
56
+ end
57
+ headers
58
+ end
59
+
60
+ def parse_connect_target(data)
61
+ temp = data.split("\s")
62
+ URI("tcp://#{temp[1]}/")
63
+ end
64
+
65
+ def check_is_valid_request(s)
66
+ # hold for heath check, if needed.
67
+ # s[0...4] == "GET\s"
68
+ s == RProxy::Constants::HTTP_CONNECT_TITLE
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,76 @@
1
+ require 'socket'
2
+
3
+ module RProxy
4
+ class MasterProcess
5
+
6
+ attr_reader :config
7
+
8
+ def initialize
9
+ @config = RProxy::Config.new
10
+ @pids = []
11
+ end
12
+
13
+ def set(name, value)
14
+ @config.send("#{name}=", value)
15
+ end
16
+
17
+ def run!
18
+ @logger = @config.logger
19
+ begin
20
+ start_r_proxy
21
+ rescue Interrupt
22
+ @logger.info('existing all process....') if @logger
23
+ EventMachine.stop_event_loop if EventMachine.reactor_running?
24
+ rescue => e
25
+ @logger.info("master process exit with #{e.message}, #{e.backtrace}") if @logger
26
+ EventMachine.stop_event_loop if EventMachine.reactor_running?
27
+ end
28
+
29
+ at_exit { stop_all_process }
30
+ end
31
+
32
+ private
33
+
34
+ def stop_all_process
35
+ @pids.each do |pid|
36
+ next unless pid
37
+ Process.kill("TERM", pid)
38
+ end
39
+ end
40
+
41
+ def start_r_proxy
42
+
43
+ instance_amount = @config.instances
44
+ server = TCPServer.new(@config.host, @config.port)
45
+ instance_amount.times do
46
+ timestamp = Time.now.to_i
47
+ pid = Process.fork do
48
+ begin
49
+ @logger.info("r_proxy @#{timestamp} process start....") if @logger
50
+ RProxy::ProxyServer.new(server, @config).run!
51
+ rescue Interrupt
52
+ @logger.info("r_proxy TPC server instance @#{timestamp} closed now....") if @logger
53
+ rescue => e
54
+ @logger.error("instance @#{timestamp}, error: #{e.message}, #{e.backtrace}") if @logger
55
+ exit!(false)
56
+ end
57
+ end
58
+
59
+ Process.detach(pid)
60
+ @pids << pid
61
+ end
62
+
63
+ EventMachine.kqueue=(true)
64
+ EventMachine.run do
65
+ @pids.each do |pid|
66
+ EventMachine.watch_process(pid,
67
+ RProxy::ProcessHandler,
68
+ @pids,
69
+ @config,
70
+ server,
71
+ pid)
72
+ end
73
+ end
74
+ end
75
+ end
76
+ end
@@ -0,0 +1,40 @@
1
+ module RProxy
2
+ class ProcessHandler < EventMachine::ProcessWatch
3
+
4
+ def initialize(pids, config, socket, pid)
5
+ @pids = pids
6
+ @id = pid
7
+ @config = config
8
+ @socket = socket
9
+ @logger = config.logger
10
+ end
11
+
12
+ def process_exited
13
+
14
+ @pids.delete(@id)
15
+ timestamp = Time.now.to_i
16
+
17
+ pid = Process.fork do
18
+ begin
19
+ @logger.info("r_proxy rebuild new instance replace @#{timestamp}....") if @logger
20
+ RProxy::ProxyServer.new(@socket, @config).run!
21
+ rescue Interrupt
22
+ @logger.info("r_proxy TPC server instance @#{timestamp} closed now....") if @logger
23
+ rescue => e
24
+ @logger.error("instance @#{timestamp}, error: #{e.message}, #{e.backtrace}") if @logger
25
+ exit(false)
26
+ end
27
+ end
28
+
29
+ Process.detach(pid)
30
+ @pids << pid
31
+
32
+ EventMachine.watch_process(pid, RProxy::ProcessHandler,
33
+ @pids,
34
+ @config,
35
+ @socket,
36
+ pid)
37
+ close_connection
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,15 @@
1
+ module RProxy
2
+ class ProxyServer
3
+ def initialize(sock, config)
4
+ @sock = sock
5
+ @config = config
6
+ end
7
+
8
+ def run!
9
+ Signal.trap("TERM") { exit! }
10
+ EventMachine.run do
11
+ EventMachine.attach_server(@sock, RProxy::ConnectionHandler, @config)
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,7 @@
1
+ module RProxy
2
+ class RedisService
3
+ def self.instance(url)
4
+ Redis.new(url: url)
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,46 @@
1
+ module RProxy
2
+ class TargetConnection < EM::Connection
3
+
4
+ def initialize(client, disable_cb, buffer_size, unbind)
5
+ @disable_unbind_callback = disable_cb
6
+ @client_connection = client
7
+ @buffer_size = buffer_size
8
+ @unbind_service = unbind
9
+ end
10
+
11
+ def assign_logger(logger)
12
+ @logger = logger
13
+ end
14
+
15
+ def assign_user_and_password(username, password)
16
+ @username = username
17
+ @password = password
18
+ end
19
+
20
+ def connection_completed
21
+ response_proxy_connect_ready
22
+ end
23
+
24
+ def proxy_target_unbound
25
+ close_connection
26
+ end
27
+
28
+ def unbind
29
+ return if @disable_unbind_callback
30
+ @unbind_service.call(@username, @password, get_proxied_bytes)
31
+ end
32
+
33
+ private
34
+
35
+ def response_proxy_connect_ready
36
+ begin
37
+ @client_connection.send_data(RProxy::Constants::HTTP_SUCCESS)
38
+ @client_connection.proxy_incoming_to(self, @buffer_size)
39
+ proxy_incoming_to(@client_connection, @buffer_size)
40
+ rescue => e
41
+ port, ip = Socket.unpack_sockaddr_in(get_peername)
42
+ @logger.error("target ip: #{ip}, port: #{port}, #{e.message}") if @logger
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,24 @@
1
+ module RProxy
2
+ class UnbindService
3
+
4
+ def initialize(config, redis)
5
+ @config = config
6
+ @cb_url = config.callback_url
7
+ @redis = redis
8
+ @usage_threshold = @config.usage_threshold
9
+ @snapshot_expire_in = 15 * 60 # 15 min
10
+ end
11
+
12
+ def call(user, pass, usage)
13
+
14
+ return if user.nil? || pass.nil? || usage.nil?
15
+
16
+ key = proxy_key(user, pass)
17
+ @redis.decrby(key, usage)
18
+ end
19
+
20
+ def proxy_key(user, pass)
21
+ "proxy:#{user}-#{pass}"
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,3 @@
1
+ module RProxy
2
+ VERSION = "0.1.0"
3
+ end
data/lib/r_proxy.rb ADDED
@@ -0,0 +1,31 @@
1
+ require 'logger'
2
+ require 'r_proxy/version'
3
+ require 'eventmachine'
4
+ require 'redis'
5
+ require 'r_proxy/config'
6
+ require 'r_proxy/constants'
7
+ require 'r_proxy/check_snapshot_service'
8
+ require 'r_proxy/http_proxy_parser'
9
+ require 'r_proxy/redis_service'
10
+
11
+ require 'r_proxy/master_process'
12
+ require 'r_proxy/process_handler'
13
+
14
+ require 'r_proxy/target_connection'
15
+ require 'r_proxy/connection_handler'
16
+ require 'r_proxy/unbind_service'
17
+
18
+ require 'r_proxy/callback_connection'
19
+ require 'r_proxy/http_post_template'
20
+ require 'r_proxy/callback_service'
21
+
22
+ require 'r_proxy/proxy_server'
23
+ require 'r_proxy/master_process'
24
+
25
+ module RProxy
26
+ class Error < StandardError; end
27
+ class EmptyConfigError < Error; end
28
+
29
+ class HTTPNotSupport < Error; end
30
+ class HTTPAuthFailed < Error; end
31
+ end
data/r_proxy.gemspec ADDED
@@ -0,0 +1,31 @@
1
+ require_relative 'lib/r_proxy/version'
2
+
3
+ Gem::Specification.new do |spec|
4
+ spec.name = "r_proxy"
5
+ spec.version = RProxy::VERSION
6
+ spec.authors = ["Nick An"]
7
+ spec.email = ["anning0322@gmail.com"]
8
+ spec.licenses = ['Apache-2.0']
9
+
10
+ spec.summary = %q{http https proxy}
11
+ spec.description = %q{ruby http and https proxy server}
12
+ spec.homepage = "https://github.com/nickoan/r_proxy"
13
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.5.0")
14
+
15
+ # spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
16
+
17
+ spec.metadata["homepage_uri"] = spec.homepage
18
+ spec.metadata["source_code_uri"] = "https://github.com/nickoan/r_proxy"
19
+
20
+ # Specify which files should be added to the gem when it is released.
21
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
22
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
23
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
24
+ end
25
+ spec.bindir = "exe"
26
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
27
+ spec.require_paths = ["lib"]
28
+
29
+ spec.add_runtime_dependency 'eventmachine', '~> 1.2', '>= 1.2.7'
30
+ spec.add_runtime_dependency 'redis', '~> 4.1', '>= 4.1.4'
31
+ end
metadata ADDED
@@ -0,0 +1,113 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: r_proxy
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Nick An
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2020-05-08 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: eventmachine
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.2'
20
+ - - ">="
21
+ - !ruby/object:Gem::Version
22
+ version: 1.2.7
23
+ type: :runtime
24
+ prerelease: false
25
+ version_requirements: !ruby/object:Gem::Requirement
26
+ requirements:
27
+ - - "~>"
28
+ - !ruby/object:Gem::Version
29
+ version: '1.2'
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: 1.2.7
33
+ - !ruby/object:Gem::Dependency
34
+ name: redis
35
+ requirement: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - "~>"
38
+ - !ruby/object:Gem::Version
39
+ version: '4.1'
40
+ - - ">="
41
+ - !ruby/object:Gem::Version
42
+ version: 4.1.4
43
+ type: :runtime
44
+ prerelease: false
45
+ version_requirements: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - "~>"
48
+ - !ruby/object:Gem::Version
49
+ version: '4.1'
50
+ - - ">="
51
+ - !ruby/object:Gem::Version
52
+ version: 4.1.4
53
+ description: ruby http and https proxy server
54
+ email:
55
+ - anning0322@gmail.com
56
+ executables: []
57
+ extensions: []
58
+ extra_rdoc_files: []
59
+ files:
60
+ - ".gitignore"
61
+ - ".travis.yml"
62
+ - Gemfile
63
+ - Gemfile.lock
64
+ - LICENSE
65
+ - README.md
66
+ - Rakefile
67
+ - bin/console
68
+ - bin/setup
69
+ - example.rb
70
+ - lib/r_proxy.rb
71
+ - lib/r_proxy/callback_connection.rb
72
+ - lib/r_proxy/callback_service.rb
73
+ - lib/r_proxy/check_snapshot_service.rb
74
+ - lib/r_proxy/config.rb
75
+ - lib/r_proxy/connection_handler.rb
76
+ - lib/r_proxy/constants.rb
77
+ - lib/r_proxy/http_post_template.rb
78
+ - lib/r_proxy/http_proxy_parser.rb
79
+ - lib/r_proxy/master_process.rb
80
+ - lib/r_proxy/process_handler.rb
81
+ - lib/r_proxy/proxy_server.rb
82
+ - lib/r_proxy/redis_service.rb
83
+ - lib/r_proxy/target_connection.rb
84
+ - lib/r_proxy/unbind_service.rb
85
+ - lib/r_proxy/version.rb
86
+ - r_proxy.gemspec
87
+ homepage: https://github.com/nickoan/r_proxy
88
+ licenses:
89
+ - Apache-2.0
90
+ metadata:
91
+ homepage_uri: https://github.com/nickoan/r_proxy
92
+ source_code_uri: https://github.com/nickoan/r_proxy
93
+ post_install_message:
94
+ rdoc_options: []
95
+ require_paths:
96
+ - lib
97
+ required_ruby_version: !ruby/object:Gem::Requirement
98
+ requirements:
99
+ - - ">="
100
+ - !ruby/object:Gem::Version
101
+ version: 2.5.0
102
+ required_rubygems_version: !ruby/object:Gem::Requirement
103
+ requirements:
104
+ - - ">="
105
+ - !ruby/object:Gem::Version
106
+ version: '0'
107
+ requirements: []
108
+ rubyforge_project:
109
+ rubygems_version: 2.7.6
110
+ signing_key:
111
+ specification_version: 4
112
+ summary: http https proxy
113
+ test_files: []