]> code.delx.au - cgiproxy/blob - ruby/proxy.rb
Make it clear that ruby1.8 is required
[cgiproxy] / ruby / proxy.rb
1 #!/usr/bin/env ruby
2
3 require 'net/http'
4 require 'net/https'
5 require 'uri'
6
7 class NilClass
8 # Make it easier to check for empty string or nil
9 def empty?; true; end
10 def to_s; ""; end
11 end
12
13
14 def get_params(url)
15 if !ENV["PATH_INFO"].empty?
16 url += ENV["PATH_INFO"]
17 end
18
19 url = URI.parse(url);
20 if !["http", "https"].include? url.scheme
21 raise RuntimeError, "Unsupported scheme: #{url.scheme}"
22 end
23
24 use_ssl = url.scheme == 'https'
25
26 filename = url.path.split("/")[-1]
27 path = url.path
28 if !ENV["QUERY_STRING"].empty?
29 path += "?" + ENV["QUERY_STRING"]
30 end
31
32 return url.host, url.port, use_ssl, filename, path
33 end
34
35 def create_request(method, path, ff_header)
36 if method == "GET"
37 req = Net::HTTP::Get.new(path)
38 elsif method == "POST"
39 req = Net::HTTP::Post.new(path)
40 req.body = $stdin.read()
41 else
42 raise RuntimeError, "No support for method: #{method}"
43 end
44
45 if ff_header
46 req["X-Forwarded-For"] = ENV["REMOTE_ADDR"]
47 end
48 req["Host"] = ENV["HTTP_HOST"]
49 req["Cookie"] = ENV["HTTP_COOKIE"]
50 req["Referer"] = ENV["HTTP_REFERER"]
51 req["Content-Length"] = ENV["CONTENT_LENGTH"]
52 req["Content-Type"] = ENV["CONTENT_TYPE"]
53 req["User-Agent"] = ENV["HTTP_USER_AGENT"]
54 req["Cache-Control"] = ENV["HTTP_CACHE_CONTROL"]
55 req["Authorization"] = ENV["HTTP_AUTHORIZATION"]
56 req["Accept"] = ENV["HTTP_ACCEPT"]
57 req["Accept-Charset"] = ENV["HTTP_ACCEPT_CHARSET"]
58 req["Accept-Encoding"] = ENV["HTTP_ACCEPT_ENCODING"]
59 req["Accept-Language"] = ENV["HTTP_ACCEPT_LANGUAGE"]
60
61 return req
62 end
63
64 def do_proxy(req, host, port, use_ssl, filename, output_dir)
65 # Make the request
66 http = Net::HTTP.new(host, port)
67 http.use_ssl = use_ssl
68 res = http.request req do |res|
69
70 # Tweak the headers a little
71 res.delete("transfer-encoding")
72 res.delete("transfer-length")
73 res["connection"] = "close"
74
75 if res.code != "200"
76 res["Status"] = "#{res.code} #{res.message}"
77 end
78 res.each_capitalized_name do |key|
79 res.get_fields(key).each do |value|
80 print "#{key}: #{value}\r\n"
81 end
82 end
83 print "\r\n"
84
85 out = nil
86 if output_dir
87 out = File.open("#{output_dir}/#{filename}", 'w')
88 end
89 res.read_body do |chunk|
90 print chunk
91 if out
92 out.write chunk
93 end
94 end
95 end
96 end
97
98 def debug(msg)
99 File.open("/tmp/debuglog.txt", "a") { |f|
100 f << Time.new.to_s + " " + msg + "\n"
101 }
102 end
103
104 def proxy_to(base_path, ff_header=True, output_dir=nil)
105 host, port, use_ssl, filename, path = get_params(base_path)
106 req = create_request(ENV["REQUEST_METHOD"], path, ff_header)
107 do_proxy(req, host, port, use_ssl, filename, output_dir)
108 end
109