public
Created

file_saving_proxy_server.rb

  • Download Gist
file_saving_proxy_server.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
#!/usr/bin/env ruby
 
require 'webrick'
require 'webrick/httpproxy'
require "pathname"
 
class Dumper
def initialize(dir)
@dir = dir
end
 
class FileDumper
attr_reader :dir, :time
def initialize(dir, time)
@dir = Pathname(dir)
@time = time
end
 
def dirname
dir + [(time.to_i/1000).to_s, time.to_f.to_s ].join('/')
end
 
def mkdir
FileUtils.mkdir_p(dirname)
end
 
def record(name, &block)
open(dirname + name, 'w') {|f| block.call(f) }
end
 
def touch(name)
open(dirname + name, 'w') {|f| f.print "" }
end
 
def url_to_filename(url)
url = url.dup
url.query = '' if url.query
url.to_s.gsub(/[^0-9a-z%_-]+/i, '_')
end
 
def save_req(req)
url = req.request_uri
touch(url_to_filename(url))
method = req.request_method
touch(method)
record("URL") {|f| f.puts url.to_s }
record("request-header.txt"){|f| f.print req.raw_header.join }
record("request-body"){|f| f.print req.body } if ["POST","PUT"].include?(method)
end
 
def save_res(res)
record("#{res.status}"){|f| f.puts res.status }
record("response-header.txt"){|f| res.each{|k,v| f.puts "#{k}: #{v}" }}
record("response-body"){|f| f.print res.body }
end
end
 
def save(req, res)
d = FileDumper.new(@dir, Time.now)
d.mkdir
d.save_req(req)
d.save_res(res)
end
end
 
class DumpProxy < WEBrick::HTTPProxyServer
class << self
def handler(dumper)
proc{|req,res|
# FILTER!
#if req.host =~ /mydomain.example.jp/
dumper.save(req, res)
#end
}
end
def create(dir)
dumper = Dumper.new(dir)
new(
:Port => 3234,
:Logger => WEBrick::Log.new($stderr, WEBrick::Log::DEBUG),
:ProxyVia => false,
:ProxyContentHandler => handler(dumper)
)
end
end
end
 
s = DumpProxy.create("/tmp/pathto/proxydata")
Signal.trap('INT') do
s.shutdown
end
s.start

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.