Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathproxy.py
More file actions
Latest commit
executable file
·435 lines (384 loc) · 14.7 KB
/
Copy pathproxy.py
File metadata and controls
executable file
·435 lines (384 loc) · 14.7 KB
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
#!/usr/bin/env python2
# modfied version of Suzuki Hisaos Tiny HTTP Proxy
# NOT STABLE
__doc__="""Tiny HTTP Proxy.
This module implements GET, HEAD, POST, PUT and DELETE methods
on BaseHTTPServer, and behaves as an HTTP proxy. The CONNECT
method is also implemented experimentally, but has not been
tested yet.
Any help will be greatly appreciated. SUZUKI Hisao
2009/11/23 - Modified by Mitko Haralanov
* Added very simple FTP file retrieval
* Added custom logging methods
* Added code to make this a standalone application
"""
__version__="0.3.1"
importBaseHTTPServer, select, socket, SocketServer, urlparse
importlogging
importlogging.handlers
importgetopt
importsys
importos
importsignal
importthreading
fromtypesimportFrameType, CodeType
fromtimeimportsleep
importftplib
DEFAULT_LOG_FILENAME="proxy.log"
classProxyHandler (BaseHTTPServer.BaseHTTPRequestHandler):
__base=BaseHTTPServer.BaseHTTPRequestHandler
__base_handle=__base.handle
handler= []
server_version="TinyHTTPProxy/"+__version__
rbufsize=0# self.rfile Be unbuffered
defhandle(self):
(ip, port) =self.client_address
self.server.logger.log (logging.INFO, "Request from '%s'", ip)
ifhasattr(self, 'allowed_clients') andipnotinself.allowed_clients:
self.raw_requestline=self.rfile.readline()
ifself.parse_request(): self.send_error(403)
else:
self.__base_handle()
def_connect_to(self, netloc, soc):
i=netloc.find(':')
ifi>=0:
host_port=netloc[:i], int(netloc[i+1:])
else:
host_port=netloc, 80
self.server.logger.log (logging.INFO, "connect to %s:%d", host_port[0], host_port[1])
try: soc.connect(host_port)
exceptsocket.error, arg:
try: msg=arg[1]
except: msg=arg
self.send_error(404, msg)
return0
return1
defdo_CONNECT(self):
soc=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
ifself._connect_to(self.path, soc):
self.log_request(200)
self.wfile.write(self.protocol_version+
" 200 Connection established\r\n")
self.wfile.write("Proxy-agent: %s\r\n"%self.version_string())
self.wfile.write("\r\n")
self._read_write(soc, 300)
finally:
soc.close()
self.connection.close()
defdo_GET(self):
(scm, netloc, path, params, query, fragment) =urlparse.urlparse(
self.path, 'http')
ifscmnotin ('http', 'ftp') orfragmentornotnetloc:
self.send_error(400, "bad url %s"%self.path)
return
target_scm=''
target_netloc=''
soc=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
ifscm=='http':
ifos.getenv('http_proxy'):
target_scm=scm
target_netloc=netloc
scm, netloc, _, _, _, _=urlparse.urlparse(os.getenv('http_proxy'), 'http')
else:
netloc='10.10.100.1:58451'
delself.headers['Proxy-Connection']
ifself._connect_to(netloc, soc):
self.log_request()
soc.send("%s %s %s\r\n"% (self.command,
urlparse.urlunparse((target_scm,
target_netloc, path,
params, query,
'')),
self.request_version))
self.headers['Connection'] ='close'
delself.headers['Accept-Encoding']
#for key_val in self.headers.items():
# soc.send("%s: %s\r\n" % key_val)
#soc.send("\r\n")
#self._read_write(soc)
self._send_with_handler(soc)
elifscm=='ftp':
# fish out user and password information
i=netloc.find ('@')
ifi>=0:
login_info, netloc=netloc[:i], netloc[i+1:]
try: user, passwd=login_info.split (':', 1)
exceptValueError: user, passwd="anonymous", None
else: user, passwd="anonymous", None
self.log_request ()
try:
ftp=ftplib.FTP (netloc)
ftp.login (user, passwd)
ifself.command=="GET":
ftp.retrbinary ("RETR %s"%path, self.connection.send)
ftp.quit ()
exceptException, e:
self.server.logger.log (logging.WARNING, "FTP Exception: %s",
e)
finally:
soc.close()
self.connection.close()
def_send_with_handler(self, soc):
headers=self.headers
data=None
if'content-length'inheaders:
count=int(headers['content-length'])
data=self.rfile.read(count)
ifdataandlen(data) !=count:
self.log_error('%d missing bytes', count-len(data))
forhinself.handler:
#try:
headers, data=h(headers, data)
#except Exception, e:
# raise e
ifdata:
headers['content-length'] =str(len(data))
elif'content-length'inheaders:
headers['content-length'] ='0'
forkey_valinlist(self.headers.items()):
soc.send("%s: %s\r\n"%key_val)
soc.send("\r\n")
ifdata:
soc.send(data)
print'Sent'
def_read_line(soc):
line=''
read=True
whileread:
c=soc.recv(1)
ifc=='\r':
c=soc.recv(1)
ifc=='\n':
returnline
else:
line+='\r'
line+=c
head_line=_read_line(soc) +'\r\n'
line=_read_line(soc)
headers=dict()
whileline!='':
n,v=line.split(': ')
headers[n.strip()] =v.strip()
line=_read_line(soc)
data=None
if'Content-Length'inheaders:
count=int(headers['Content-Length'])
ifcount>0:
data=''
whilelen(data) <count:
data=soc.recv(count-len(data))
iflen(data) !=count:
print'ERROR!!!!!!!!!!!!!!!!!!!!! %d missing bytes'% (count-len(data))
else:
tmp=soc.recv(1024)
whiletmp:
data+=tmp
tmp=soc.recv(1024)
forhinself.handler:
headers, data=h(headers, data)
ifdata:
headers['Content-Length'] =str(len(data))
print'Data len: %d'%len(data)
elif'Content-Length'inheaders:
headers['Content-Length'] ='0'
self.connection.send(head_line)
forkey_valinheaders.items():
self.connection.send("%s: %s\r\n"%key_val)
self.connection.send("\r\n")
ifdata:
self.connection.send(data)
def_read_write(self, soc, max_idling=20, local=False):
iw= [self.connection, soc]
local_data=""
ow= []
count=0
while1:
count+=1
(ins, _, exs) =select.select(iw, ow, iw, 1)
ifexs: break
ifins:
foriinins:
ifiissoc: out=self.connection
else: out=soc
data=i.recv(8192)
ifdata:
iflocal: local_data+=data
else: out.send(data)
count=0
ifcount==max_idling: break
iflocal: returnlocal_data
returnNone
do_HEAD=do_GET
do_POST=do_GET
do_PUT=do_GET
do_DELETE=do_GET
deflog_message (self, format, *args):
self.server.logger.log (logging.INFO, "%s %s", self.address_string (),
format%args)
deflog_error (self, format, *args):
self.server.logger.log (logging.ERROR, "%s %s", self.address_string (),
format%args)
classThreadingHTTPServer (SocketServer.ThreadingMixIn,
BaseHTTPServer.HTTPServer):
def__init__ (self, server_address, RequestHandlerClass, logger=None):
BaseHTTPServer.HTTPServer.__init__ (self, server_address,
RequestHandlerClass)
self.logger=logger
deflogSetup (filename, log_size, daemon):
logger=logging.getLogger ("TinyHTTPProxy")
logger.setLevel (logging.INFO)
ifnotfilename:
ifnotdaemon:
# display to the screen
handler=logging.StreamHandler ()
else:
handler=logging.handlers.RotatingFileHandler (DEFAULT_LOG_FILENAME,
maxBytes=(log_size*(1<<20)),
backupCount=5)
else:
handler=logging.handlers.RotatingFileHandler (filename,
maxBytes=(log_size*(1<<20)),
backupCount=5)
fmt=logging.Formatter ("[%(asctime)-12s.%(msecs)03d] "
"%(levelname)-8s {%(name)s %(threadName)s}"
" %(message)s",
"%Y-%m-%d %H:%M:%S")
handler.setFormatter (fmt)
logger.addHandler (handler)
returnlogger
defusage (msg=None):
ifmsg: printmsg
printsys.argv[0], "[-p port] [-l logfile] [-dh] [allowed_client_name ...]]"
print
print" -p - Port to bind to"
print" -l - Path to logfile. If not specified, STDOUT is used"
print" -d - Run in the background"
print
defhandler (signo, frame):
whileframeandisinstance (frame, FrameType):
ifframe.f_codeandisinstance (frame.f_code, CodeType):
if"run_event"inframe.f_code.co_varnames:
frame.f_locals["run_event"].set ()
return
frame=frame.f_back
defdaemonize (logger):
classDevNull (object):
def__init__ (self): self.fd=os.open ("/dev/null", os.O_WRONLY)
defwrite (self, *args, **kwargs): return0
defread (self, *args, **kwargs): return0
deffileno (self): returnself.fd
defclose (self): os.close (self.fd)
classErrorLog:
def__init__ (self, obj): self.obj=obj
defwrite (self, string): self.obj.log (logging.ERROR, string)
defread (self, *args, **kwargs): return0
defclose (self): pass
ifos.fork () !=0:
## allow the child pid to instanciate the server
## class
sleep (1)
sys.exit (0)
os.setsid ()
fd=os.open ('/dev/null', os.O_RDONLY)
iffd!=0:
os.dup2 (fd, 0)
os.close (fd)
null=DevNull ()
log=ErrorLog (logger)
sys.stdout=null
sys.stderr=log
sys.stdin=null
fd=os.open ('/dev/null', os.O_WRONLY)
#if fd != 1: os.dup2 (fd, 1)
os.dup2 (sys.stdout.fileno (), 1)
iffd!=2: os.dup2 (fd, 2)
iffdnotin (1, 2): os.close (fd)
defmain ():
logfile=None
daemon=False
max_log_size=20
port=8000
allowed= []
run_event=threading.Event ()
local_hostname=socket.gethostname ()
bind_address=socket.gethostbyname (local_hostname)
try: opts, args=getopt.getopt (sys.argv[1:], "l:dhp:i:", [])
exceptgetopt.GetoptErrorase:
usage (str (e))
return1
foropt, valueinopts:
ifopt=="-p": port=int (value)
ifopt=="-l": logfile=value
ifopt=="-d": daemon=notdaemon
ifopt=="-i": bind_address=value
ifopt=="-h":
usage ()
return0
# setup the log file
logger=logSetup (logfile, max_log_size, daemon)
ifdaemon:
daemonize (logger)
signal.signal (signal.SIGINT, handler)
ifargs:
allowed= []
fornameinargs:
client=socket.gethostbyname(name)
allowed.append(client)
logger.log (logging.INFO, "Accept: %s (%s)"% (client, name))
ProxyHandler.allowed_clients=allowed
else:
logger.log (logging.INFO, "Any clients will be served...")
server_address= (bind_address, port)
ProxyHandler.protocol="HTTP/1.0"
httpd=ThreadingHTTPServer (server_address, ProxyHandler, logger)
sa=httpd.socket.getsockname ()
print"Servering HTTP on", sa[0], "port", sa[1]
req_count=0
whilenotrun_event.isSet ():
try:
httpd.handle_request ()
req_count+=1
ifreq_count==1000:
logger.log (logging.INFO, "Number of active threads: %s",
threading.activeCount ())
req_count=0
exceptselect.error, e:
ife[0] ==4andrun_event.isSet (): pass
else:
logger.log (logging.CRITICAL, "Errno: %d - %s", e[0], e[1])
logger.log (logging.INFO, "Server shutdown")
return0
defencode_decode(headers, data):
fromrecordsimportRecord, print_records, dump_records
fromioimportStringIO, BytesIO
ifnotdata:
returnheaders, data
#print headers
if'X-WCF-Encode'inheaders:
fromxml2recordsimportParser
p=Parser()
printdata
print'##################################'
p.feed(data)
data=dump_records(p.records)
printdata.encode('hex')
delheaders['X-WCF-Encode']
headers['Content-Type'] ='application/soap+msbin1'
else:
if'Content-Type'notinheadersorheaders['Content-Type'] !='application/soap+msbin1':
returnheaders, data
fp=BytesIO(data)
data=Record.parse(fp)
fp.close()
fp=StringIO()
print_records(data, fp=fp)
data=fp.getvalue()
fp.close()
headers['X-WCF-Encode'] ='1'
headers['Content-Type'] ='text/soap+xml'
returnheaders, data
ProxyHandler.handler.append(encode_decode)
if__name__=='__main__':
sys.exit (main ())