forward-proxy 0.1.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 6af22f5d41a5a3b702233f8a13b67533451a411b
4
+ data.tar.gz: 850669c9081a84975689e17d0e92b6b9adb5f29a
5
+ SHA512:
6
+ metadata.gz: 0eba287e90bd3369421aa16401b2958203058047900f1b496e5c690bb15b5b58c018340118a76d18a39c3dcb054f5b034b2a5c3c6a94bc1a95a71b1f5ace78fd
7
+ data.tar.gz: c71b4cb6d19cdf9e9bad3605b03d4a8d2cc73933bb3b575ddf3be75d4408d266627dc97421b50c71578ede837a24417d00f243e5ad05cabebbd1c21c2d3a2d4f
@@ -0,0 +1,19 @@
1
+ name: Continuous Integration
2
+
3
+ on: [push, pull_request]
4
+
5
+ jobs:
6
+ build:
7
+ runs-on: ubuntu-latest
8
+
9
+ strategy:
10
+ matrix:
11
+ ruby: [ '2.3', '2.7' ]
12
+
13
+ steps:
14
+ - uses: actions/checkout@v2
15
+ - uses: ruby/setup-ruby@v1
16
+ with:
17
+ ruby-version: ${{ matrix.ruby }}
18
+ bundler-cache: true
19
+ - run: bundle exec rake
@@ -0,0 +1,8 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
@@ -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 james.moriarty@innablr.com.au. 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 [https://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: https://contributor-covenant.org
74
+ [version]: https://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,9 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in forward-proxy.gemspec
4
+ gemspec
5
+
6
+ gem "rake", "~> 12.0"
7
+ gem "minitest", "~> 5.0"
8
+ gem "minitest-reporters", "~> 1.4"
9
+ gem "simplecov", "~> 0.17"
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 TODO: Write your name
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.
@@ -0,0 +1,72 @@
1
+ # ForwardProxy
2
+
3
+ Ruby Forward Proxy implemented with only standard libraries.
4
+
5
+ ```
6
+ $ forward-proxy --binding 0.0.0.0 --port 3182 --threads 2
7
+ [2021-01-14 19:37:47 +1100] INFO Listening 0.0.0.0:3182
8
+ [2021-01-14 19:38:24 +1100] INFO CONNECT raw.githubusercontent.com:443 HTTP/1.1
9
+ ```
10
+
11
+ ## Installation
12
+
13
+ Add this line to your application's Gemfile:
14
+
15
+ ```ruby
16
+ gem 'forward-proxy'
17
+ ```
18
+
19
+ And then execute:
20
+
21
+ $ bundle install
22
+
23
+ Or install it yourself as:
24
+
25
+ $ gem install forward-proxy
26
+
27
+ ## Usage
28
+
29
+ ### CLI
30
+
31
+ ```
32
+ forward-proxy
33
+ ```
34
+
35
+ ```
36
+ Usage: forward-proxy [options]
37
+ -p, --port=PORT Bind to specified port. Default: 9292
38
+ -b, --binding=BINDING Bind to the specified IP. Default: 127.0.0.1
39
+ -t, --threads=THREADS Specify the number of client threads. Default: 32
40
+ -h, --help Prints this help
41
+ ```
42
+
43
+ ### Library
44
+
45
+ ```ruby
46
+ require 'forward_proxy'
47
+
48
+ proxy = ForwardProxy::Server.new(
49
+ bind_address: "127.0.0.1",
50
+ bind_port: 3000
51
+ )
52
+
53
+ proxy.start
54
+ ```
55
+
56
+ ## Development
57
+
58
+ 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.
59
+
60
+ 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).
61
+
62
+ ## Contributing
63
+
64
+ Bug reports and pull requests are welcome on GitHub at https://github.com/jamesmoriarty/forward-proxy. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/jamesmoriarty/forward-proxy/blob/master/CODE_OF_CONDUCT.md).
65
+
66
+ ## License
67
+
68
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
69
+
70
+ ## Code of Conduct
71
+
72
+ Everyone interacting in the ForwardProxy project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/jamesmoriarty/forward-proxy/blob/master/CODE_OF_CONDUCT.md).
@@ -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
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "forward_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__)
@@ -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
@@ -0,0 +1,31 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'optparse'
4
+
5
+ options = {}
6
+
7
+ OptionParser.new do |parser|
8
+ parser.banner = "Usage: forward-proxy [options]"
9
+
10
+ parser.on("-pPORT", "--port=PORT", "Bind to specified port. Default: 9292", String) do |bind_port|
11
+ options[:bind_port] = bind_port
12
+ end
13
+
14
+ parser.on("-bBINDING", "--binding=BINDING", String, "Bind to the specified IP. Default: 127.0.0.1") do |bind_address|
15
+ options[:bind_address] = bind_address
16
+ end
17
+
18
+ parser.on("-tTHREADS", "--threads=THREADS", Integer, "Specify the number of client threads. Default: 32") do |threads|
19
+ options[:threads] = threads
20
+ end
21
+
22
+ parser.on("-h", "--help", "Prints this help") do
23
+ puts parser
24
+ exit
25
+ end
26
+ end.parse!
27
+
28
+ require_relative '../lib/forward_proxy'
29
+
30
+ server = ForwardProxy::Server.new(options)
31
+ server.start
@@ -0,0 +1,27 @@
1
+ require_relative 'lib/forward_proxy/version'
2
+
3
+ Gem::Specification.new do |spec|
4
+ spec.name = "forward-proxy"
5
+ spec.version = ForwardProxy::VERSION
6
+ spec.authors = ["James Moriarty"]
7
+ spec.email = ["jamespaulmoriarty@gmail.com"]
8
+
9
+ spec.summary = %q{Forward proxy.}
10
+ spec.description = %q{Forward proxy using just Ruby standard libraries.}
11
+ spec.homepage = "https://github.com/jamesmoriarty/forward-proxy"
12
+ spec.license = "MIT"
13
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0")
14
+
15
+ spec.metadata["homepage_uri"] = spec.homepage
16
+ spec.metadata["source_code_uri"] = "https://github.com/jamesmoriarty/forward-proxy"
17
+ spec.metadata["changelog_uri"] = "https://github.com/jamesmoriarty/forward-proxy/blob/main/CHANGELOG.md"
18
+
19
+ # Specify which files should be added to the gem when it is released.
20
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
21
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
22
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
23
+ end
24
+ spec.bindir = "exe"
25
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
26
+ spec.require_paths = ["lib"]
27
+ end
@@ -0,0 +1,4 @@
1
+ $:.unshift File.dirname(__FILE__)
2
+
3
+ require 'forward_proxy/version'
4
+ require 'forward_proxy/server'
@@ -0,0 +1,154 @@
1
+ require 'forward_proxy/thread_pool'
2
+ require 'socket'
3
+ require 'webrick'
4
+ require 'net/http'
5
+
6
+ module ForwardProxy
7
+ class HTTPMethodNotImplemented < StandardError; end
8
+
9
+ class Server
10
+ attr_reader :bind_address, :bind_port
11
+
12
+ def initialize(bind_address: "127.0.0.1", bind_port: 9292, threads: 32)
13
+ @thread_pool = ThreadPool.new(threads)
14
+ @bind_address = bind_address
15
+ @bind_port = bind_port
16
+ end
17
+
18
+ def start
19
+ @server = TCPServer.new(bind_address, bind_port)
20
+
21
+ thread_pool.start
22
+
23
+ log("Listening #{bind_address}:#{bind_port}")
24
+
25
+ loop do
26
+ client = server.accept
27
+
28
+ thread_pool.schedule(client) do |client_conn|
29
+ begin
30
+ req = parse_req(client_conn)
31
+
32
+ log(req.request_line)
33
+
34
+ case req.request_method
35
+ when METHOD_CONNECT then handle_tunnel(client_conn, req)
36
+ when METHOD_GET, METHOD_POST then handle(client_conn, req)
37
+ else
38
+ raise HTTPMethodNotImplemented
39
+ end
40
+ rescue => e
41
+ client_conn.puts <<~eos.chomp
42
+ HTTP/1.1 502
43
+ eos
44
+
45
+ puts e.message
46
+ puts e.backtrace.map { |line| " #{line}" }
47
+ ensure
48
+ client_conn.close
49
+ end
50
+ end
51
+ end
52
+ rescue Interrupt
53
+ end
54
+
55
+ def shutdown
56
+ log("Closing client connections...")
57
+ thread_pool.shutdown
58
+
59
+ log("Stoping server...")
60
+ server.close if server
61
+ end
62
+
63
+ private
64
+
65
+ attr_reader :server, :thread_pool
66
+
67
+ METHOD_CONNECT = "CONNECT"
68
+ METHOD_GET = "GET"
69
+ METHOD_POST = "POST"
70
+
71
+ def handle_tunnel(client_conn, req)
72
+ # The following comments are from the IETF document
73
+ # "Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content"
74
+ # https://tools.ietf.org/html/rfc7231#section-4.3.6
75
+
76
+ # A client sending a CONNECT request MUST send the authority form of
77
+ # request-target (Section 5.3 of [RFC7230]); i.e., the request-target
78
+ # consists of only the host name and port number of the tunnel
79
+ # destination, separated by a colon. For example,
80
+ #
81
+ # CONNECT server.example.com:80 HTTP/1.1
82
+ # Host: server.example.com:80
83
+ #
84
+ host, port = *req['Host'].split(':')
85
+ dest_conn = TCPSocket.new(host, port)
86
+
87
+ # Any 2xx (Successful) response indicates that the sender (and all
88
+ # inbound proxies) will switch to tunnel mode immediately after the
89
+ # blank line that concludes the successful response's header section;
90
+ # data received after that blank line is from the server identified by
91
+ # the request-target.
92
+ client_conn.write "HTTP/1.1 200 OK\n\n"
93
+
94
+ # The CONNECT method requests that the recipient establish a tunnel to
95
+ # the destination origin server identified by the request-target and,
96
+ # if successful, thereafter restrict its behavior to blind forwarding
97
+ # of packets, in both directions, until the tunnel is closed.
98
+ [
99
+ Thread.new { transfer(client_conn, dest_conn) },
100
+ Thread.new { transfer(dest_conn, client_conn) }
101
+ ].each(&:join)
102
+ ensure
103
+ dest_conn.close
104
+ end
105
+
106
+ def handle(client_conn, req)
107
+ resp = Net::HTTP.start(req.host, req.port) do |http|
108
+ http.request map_webrick_to_net_http_req(req)
109
+ end
110
+
111
+ # A proxy MUST send an appropriate Via header field, as described
112
+ # below, in each message that it forwards. An HTTP-to-HTTP gateway
113
+ # MUST send an appropriate Via header field in each inbound request
114
+ # message and MAY send a Via header field in forwarded response
115
+ # messages.
116
+ client_conn.puts <<~eos.chomp
117
+ HTTP/1.1 #{resp.code}
118
+ Via: #{["1.1 ForwardProxy", resp['Via']].compact.join(', ')}
119
+ #{resp.each.map { |header, value| "#{header}: #{value}" }.join("\n")}
120
+
121
+ #{resp.body}
122
+ eos
123
+ end
124
+
125
+ def map_webrick_to_net_http_req(req)
126
+ req_headers = Hash[req.header.map { |k, v| [k, v.first] }]
127
+
128
+ klass = case req.request_method
129
+ when METHOD_GET then Net::HTTP::Get
130
+ when METHOD_POST then Net::HTTP::Post
131
+ else
132
+ raise HTTPMethodNotImplemented
133
+ end
134
+
135
+ klass.new(req.path, req_headers)
136
+ end
137
+
138
+ def transfer(dest_conn, src_conn)
139
+ IO.copy_stream(src_conn, dest_conn)
140
+ rescue => e
141
+ log(e.message, "WARNING")
142
+ end
143
+
144
+ def parse_req(client_conn)
145
+ WEBrick::HTTPRequest.new(WEBrick::Config::HTTP).tap do |req|
146
+ req.parse(client_conn)
147
+ end
148
+ end
149
+
150
+ def log(str, level = 'INFO')
151
+ puts "[#{Time.now}] #{level} #{str}"
152
+ end
153
+ end
154
+ end
@@ -0,0 +1,34 @@
1
+ class ThreadPool
2
+ attr_reader :queue, :threads, :size
3
+
4
+ def initialize(size)
5
+ @size = size
6
+ @queue = Queue.new
7
+ @threads = []
8
+ end
9
+
10
+ def start
11
+ size.times do
12
+ threads << Thread.new do
13
+ catch(:exit) do
14
+ loop do
15
+ job, args = queue.pop
16
+ job.call(*args)
17
+ end
18
+ end
19
+ end
20
+ end
21
+ end
22
+
23
+ def schedule(*args, &block)
24
+ queue.push([block, args])
25
+ end
26
+
27
+ def shutdown
28
+ threads.each do
29
+ schedule { throw :exit }
30
+ end
31
+
32
+ threads.each(&:join)
33
+ end
34
+ end
@@ -0,0 +1,3 @@
1
+ module ForwardProxy
2
+ VERSION = "0.1.1"
3
+ end
metadata ADDED
@@ -0,0 +1,63 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: forward-proxy
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - James Moriarty
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2021-01-14 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Forward proxy using just Ruby standard libraries.
14
+ email:
15
+ - jamespaulmoriarty@gmail.com
16
+ executables:
17
+ - forward-proxy
18
+ extensions: []
19
+ extra_rdoc_files: []
20
+ files:
21
+ - ".github/workflows/ci.yaml"
22
+ - ".gitignore"
23
+ - CODE_OF_CONDUCT.md
24
+ - Gemfile
25
+ - LICENSE.txt
26
+ - README.md
27
+ - Rakefile
28
+ - bin/console
29
+ - bin/setup
30
+ - exe/forward-proxy
31
+ - forward-proxy.gemspec
32
+ - lib/forward_proxy.rb
33
+ - lib/forward_proxy/server.rb
34
+ - lib/forward_proxy/thread_pool.rb
35
+ - lib/forward_proxy/version.rb
36
+ homepage: https://github.com/jamesmoriarty/forward-proxy
37
+ licenses:
38
+ - MIT
39
+ metadata:
40
+ homepage_uri: https://github.com/jamesmoriarty/forward-proxy
41
+ source_code_uri: https://github.com/jamesmoriarty/forward-proxy
42
+ changelog_uri: https://github.com/jamesmoriarty/forward-proxy/blob/main/CHANGELOG.md
43
+ post_install_message:
44
+ rdoc_options: []
45
+ require_paths:
46
+ - lib
47
+ required_ruby_version: !ruby/object:Gem::Requirement
48
+ requirements:
49
+ - - ">="
50
+ - !ruby/object:Gem::Version
51
+ version: 2.3.0
52
+ required_rubygems_version: !ruby/object:Gem::Requirement
53
+ requirements:
54
+ - - ">="
55
+ - !ruby/object:Gem::Version
56
+ version: '0'
57
+ requirements: []
58
+ rubyforge_project:
59
+ rubygems_version: 2.5.2.3
60
+ signing_key:
61
+ specification_version: 4
62
+ summary: Forward proxy.
63
+ test_files: []