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