-
Notifications
You must be signed in to change notification settings - Fork 21
/
proxy.py
executable file
·150 lines (118 loc) · 4.7 KB
/
proxy.py
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
#!/usr/bin/python
"""A basic transparent HTTP proxy"""
__author__ = "Erik Johansson"
__email__ = "[email protected]"
__license__= """
Copyright (c) 2012 Erik Johansson <[email protected]>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
USA
"""
from twisted.web import http
from twisted.internet import reactor, protocol
from twisted.python import log
import re
import sys
log.startLogging(sys.stdout)
class ProxyClient(http.HTTPClient):
""" The proxy client connects to the real server, fetches the resource and
sends it back to the original client, possibly in a slightly different
form.
"""
def __init__(self, method, uri, postData, headers, originalRequest):
self.method = method
self.uri = uri
self.postData = postData
self.headers = headers
self.originalRequest = originalRequest
self.contentLength = None
def sendRequest(self):
log.msg("Sending request: %s %s" % (self.method, self.uri))
self.sendCommand(self.method, self.uri)
def sendHeaders(self):
for key, values in self.headers:
if key.lower() == 'connection':
values = ['close']
elif key.lower() == 'keep-alive':
next
for value in values:
self.sendHeader(key, value)
self.endHeaders()
def sendPostData(self):
log.msg("Sending POST data")
self.transport.write(self.postData)
def connectionMade(self):
log.msg("HTTP connection made")
self.sendRequest()
self.sendHeaders()
if self.method == 'POST':
self.sendPostData()
def handleStatus(self, version, code, message):
log.msg("Got server response: %s %s %s" % (version, code, message))
self.originalRequest.setResponseCode(int(code), message)
def handleHeader(self, key, value):
if key.lower() == 'content-length':
self.contentLength = value
else:
self.originalRequest.responseHeaders.addRawHeader(key, value)
def handleResponse(self, data):
data = self.originalRequest.processResponse(data)
if self.contentLength != None:
self.originalRequest.setHeader('Content-Length', len(data))
self.originalRequest.write(data)
self.originalRequest.finish()
self.transport.loseConnection()
class ProxyClientFactory(protocol.ClientFactory):
def __init__(self, method, uri, postData, headers, originalRequest):
self.protocol = ProxyClient
self.method = method
self.uri = uri
self.postData = postData
self.headers = headers
self.originalRequest = originalRequest
def buildProtocol(self, addr):
return self.protocol(self.method, self.uri, self.postData,
self.headers, self.originalRequest)
def clientConnectionFailed(self, connector, reason):
log.err("Server connection failed: %s" % reason)
self.originalRequest.setResponseCode(504)
self.originalRequest.finish()
class ProxyRequest(http.Request):
def __init__(self, channel, queued, reactor=reactor):
http.Request.__init__(self, channel, queued)
self.reactor = reactor
def process(self):
host = self.getHeader('host')
if not host:
log.err("No host header given")
self.setResponseCode(400)
self.finish()
return
port = 80
if ':' in host:
host, port = host.split(':')
port = int(port)
self.setHost(host, port)
self.content.seek(0, 0)
postData = self.content.read()
factory = ProxyClientFactory(self.method, self.uri, postData,
self.requestHeaders.getAllRawHeaders(),
self)
self.reactor.connectTCP(host, port, factory)
def processResponse(self, data):
return data
class TransparentProxy(http.HTTPChannel):
requestFactory = ProxyRequest
class ProxyFactory(http.HTTPFactory):
protocol = TransparentProxy
reactor.listenTCP(8080, ProxyFactory())
reactor.run()