swdyh (owner)

Revisions

gist: 166421 Download_button fork
public
Public Clone URL: git://gist.github.com/166421.git
Embed All Files: show embed
em_glitch_proxy.rb #
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
require 'rubygems'
require 'thin'
require 'em-http'
 
USE_GLITCH = true
 
def glitch res, body
  case res['CONTENT_TYPE']
  when /jpeg/i
    body.gsub!(/0/m, rand(10).to_s)
  when /gif/i
    body.gsub!(/x/m, rand(10).to_s)
  when /png/i
  end
end
 
class HttpProxy
  def self.call env
    ip = env['REMOTE_ADDR']
    url = env['REQUEST_URI']
    head = request_head env
    uri = URI url
 
    case env['REQUEST_METHOD']
    when 'GET'
      p ['req:', url]
      http = EventMachine::HttpRequest.new(url).get :head => head,
        :query => uri.query
    when 'POST'
# http = EventMachine::HttpRequest.new(url).post :head => head,
# :query => env['rack.input'].read
      puts "#{env['REQUEST_METHOD']}: Not supported."
      return
    else
      puts "#{env['REQUEST_METHOD']}: Not supported."
      return
    end
 
    http.callback do
      p ['res:', url, http.response_header.status, ip]
      glitch(http.response_header, http.response) if USE_GLITCH
      result = [http.response_header.status,
                http.response_header, http.response]
      env['async.callback'].call(result)
    end
    return Thin::Connection::AsyncResponse
  end
 
  def self.request_head env
    head = {}
    re = /(^HTTP_PROXY_|^HTTP_)/
    env.each do |k, v|
      if k.match re
        kc = k.gsub(re, '').split('_').map { |i| i.capitalize }.join('-')
        head[kc] = v
      end
    end
    head
  end
end
 
Thin::Server.start 'localhost', 8080, HttpProxy