forked from jerryma119/goagent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy.py
executable file
·1667 lines (1553 loc) · 81.4 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
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding:utf-8
# Based on GAppProxy 2.0.0 by Du XiaoGang <dugang.2008@gmail.com>
# Based on WallProxy 0.4.0 by Hust Moon <www.ehust@gmail.com>
# Contributor:
# Phus Lu <phus.lu@gmail.com>
# Hewig Xu <hewigovens@gmail.com>
# Ayanamist Yang <ayanamist@gmail.com>
# V.E.O <V.E.O@tom.com>
# Max Lv <max.c.lv@gmail.com>
# AlsoTang <alsotang@gmail.com>
# Christopher Meng <i@cicku.me>
# Yonsm Guo <YonsmGuo@gmail.com>
# Parkman <cseparkman@gmail.com>
# Ming Bai <mbbill@gmail.com>
# Bin Yu <yubinlove1991@gmail.com>
# lileixuan <lileixuan@gmail.com>
# Cong Ding <cong@cding.org>
# Zhang Youfu <zhangyoufu@gmail.com>
# Lu Wei <luwei@barfoo>
# Harmony Meow <harmony.meow@gmail.com>
# logostream <logostream@gmail.com>
# Rui Wang <isnowfy@gmail.com>
# Wang Wei Qiang <wwqgtxx@gmail.com>
# Felix Yan <felixonmars@gmail.com>
# Sui Feng <suifeng.me@qq.com>
# QXO <qxodream@gmail.com>
# Geek An <geekan@foxmail.com>
# Poly Rabbit <mcx_221@foxmail.com>
# oxnz <yunxinyi@gmail.com>
# Shusen Liu <liushusen.smart@gmail.com>
# Yad Smood <y.s.inside@gmail.com>
# Chen Shuang <cs0x7f@gmail.com>
# cnfuyu <cnfuyu@gmail.com>
# cuixin <steven.cuixin@gmail.com>
# s2marine0 <s2marine0@gmail.com>
# Toshio Xiang <snachx@gmail.com>
# Bo Tian <dxmtb@163.com>
# Virgil <variousvirgil@gmail.com>
# hub01 <miaojiabumiao@yeah.net>
# v3aqb <sgzz.cj@gmail.com>
# Oling Cat <olingcat@gmail.com>
# Meng Zhuo <mengzhuo1203@gmail.com>
# zwhfly <zwhfly@163.com>
# Hubertzhang <hubert.zyk@gmail.com>
# arrix <arrixzhou@gmail.com>
# gwjwin <gwjwin@sina.com>
# Jobin <1149225004@qq.com>
# Zhuhao Wang <zhuhaow@gmail.com>
# YFdyh000 <yfdyh000@gmail.com>
# zzq1015 <zzq1015@users.noreply.github.com>
# Zhengfa Dang <zfdang@users.noreply.github.com>
# haosdent <haosdent@gmail.com>
# xk liu <lxk1012@gmail.com>
__version__ = '3.2.3'
import os
import sys
import sysconfig
reload(sys).setdefaultencoding('UTF-8')
sys.dont_write_bytecode = True
sys.path = [(os.path.dirname(__file__) or '.') + '/packages.egg/noarch'] + sys.path + [(os.path.dirname(__file__) or '.') + '/packages.egg/' + sysconfig.get_platform().split('-')[0]]
try:
__import__('gevent.monkey', fromlist=['.']).patch_all()
except (ImportError, SystemError):
sys.exit(sys.stderr.write('please install python-gevent\n'))
import base64
import collections
import ConfigParser
import errno
import httplib
import io
import Queue
import random
import re
import socket
import ssl
import struct
import thread
import threading
import time
import traceback
import urllib2
import urlparse
import zlib
import select
import gevent
import gevent.server
import OpenSSL
NetWorkIOError = (socket.error, ssl.SSLError, OpenSSL.SSL.Error, OSError)
class Logging(type(sys)):
CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0
def __init__(self, *args, **kwargs):
self.level = self.__class__.INFO
self.__set_error_color = lambda: None
self.__set_warning_color = lambda: None
self.__set_debug_color = lambda: None
self.__reset_color = lambda: None
if hasattr(sys.stderr, 'isatty') and sys.stderr.isatty():
if os.name == 'nt':
import ctypes
SetConsoleTextAttribute = ctypes.windll.kernel32.SetConsoleTextAttribute
GetStdHandle = ctypes.windll.kernel32.GetStdHandle
self.__set_error_color = lambda: SetConsoleTextAttribute(GetStdHandle(-11), 0x04)
self.__set_warning_color = lambda: SetConsoleTextAttribute(GetStdHandle(-11), 0x06)
self.__set_debug_color = lambda: SetConsoleTextAttribute(GetStdHandle(-11), 0x002)
self.__reset_color = lambda: SetConsoleTextAttribute(GetStdHandle(-11), 0x07)
elif os.name == 'posix':
self.__set_error_color = lambda: sys.stderr.write('\033[31m')
self.__set_warning_color = lambda: sys.stderr.write('\033[33m')
self.__set_debug_color = lambda: sys.stderr.write('\033[32m')
self.__reset_color = lambda: sys.stderr.write('\033[0m')
@classmethod
def getLogger(cls, *args, **kwargs):
return cls(*args, **kwargs)
def basicConfig(self, *args, **kwargs):
self.level = int(kwargs.get('level', self.__class__.INFO))
if self.level > self.__class__.DEBUG:
self.debug = self.dummy
def log(self, level, fmt, *args, **kwargs):
sys.stderr.write('%s - [%s] %s\n' % (level, time.ctime()[4:-5], fmt % args))
def dummy(self, *args, **kwargs):
pass
def debug(self, fmt, *args, **kwargs):
self.__set_debug_color()
self.log('DEBUG', fmt, *args, **kwargs)
self.__reset_color()
def info(self, fmt, *args, **kwargs):
self.log('INFO', fmt, *args)
def warning(self, fmt, *args, **kwargs):
self.__set_warning_color()
self.log('WARNING', fmt, *args, **kwargs)
self.__reset_color()
def warn(self, fmt, *args, **kwargs):
self.warning(fmt, *args, **kwargs)
def error(self, fmt, *args, **kwargs):
self.__set_error_color()
self.log('ERROR', fmt, *args, **kwargs)
self.__reset_color()
def exception(self, fmt, *args, **kwargs):
self.error(fmt, *args, **kwargs)
sys.stderr.write(traceback.format_exc() + '\n')
def critical(self, fmt, *args, **kwargs):
self.__set_error_color()
self.log('CRITICAL', fmt, *args, **kwargs)
self.__reset_color()
logging = sys.modules['logging'] = Logging('logging')
from proxylib import AuthFilter
from proxylib import AutoRangeFilter
from proxylib import BaseFetchPlugin
from proxylib import BaseProxyHandlerFilter
from proxylib import BlackholeFilter
from proxylib import CertUtil
from proxylib import CipherFileObject
from proxylib import deflate
from proxylib import DirectFetchPlugin
from proxylib import DirectRegionFilter
from proxylib import dnslib_record2iplist
from proxylib import dnslib_resolve_over_tcp
from proxylib import dnslib_resolve_over_udp
from proxylib import FakeHttpsFilter
from proxylib import ForceHttpsFilter
from proxylib import CRLFSitesFilter
from proxylib import get_dnsserver_list
from proxylib import get_process_list
from proxylib import get_uptime
from proxylib import inflate
from proxylib import LocalProxyServer
from proxylib import message_html
from proxylib import MockFetchPlugin
from proxylib import AdvancedNet2
from proxylib import Net2
from proxylib import ProxyNet2
from proxylib import ProxyUtil
from proxylib import RC4Cipher
from proxylib import SimpleProxyHandler
from proxylib import spawn_later
from proxylib import StaticFileFilter
from proxylib import StripPlugin
from proxylib import StripPluginEx
from proxylib import URLRewriteFilter
from proxylib import UserAgentFilter
from proxylib import XORCipher
from proxylib import forward_socket
def is_google_ip(ipaddr):
if ipaddr in ('74.125.127.102', '74.125.155.102', '74.125.39.102', '74.125.39.113', '209.85.229.138'):
return False
if ipaddr.startswith(('173.194.', '207.126.', '209.85.', '216.239.', '64.18.', '64.233.', '66.102.', '66.249.', '72.14.', '74.125.')):
return True
return False
class RangeFetch(object):
"""Range Fetch Class"""
threads = 2
maxsize = 1024*1024*4
bufsize = 8192
waitsize = 1024*512
def __init__(self, handler, plugin, response, fetchservers, **kwargs):
assert isinstance(plugin, BaseFetchPlugin) and hasattr(plugin, 'fetch')
self.handler = handler
self.url = handler.path
self.plugin = plugin
self.response = response
self.fetchservers = fetchservers
self.kwargs = kwargs
self._stopped = None
self._last_app_status = {}
self.expect_begin = 0
def fetch(self):
response_status = self.response.status
response_headers = dict((k.title(), v) for k, v in self.response.getheaders())
content_range = response_headers['Content-Range']
#content_length = response_headers['Content-Length']
start, end, length = tuple(int(x) for x in re.search(r'bytes (\d+)-(\d+)/(\d+)', content_range).group(1, 2, 3))
if start == 0:
response_status = 200
response_headers['Content-Length'] = str(length)
del response_headers['Content-Range']
else:
response_headers['Content-Range'] = 'bytes %s-%s/%s' % (start, end, length)
response_headers['Content-Length'] = str(length-start)
logging.info('>>>>>>>>>>>>>>> RangeFetch started(%r) %d-%d', self.url, start, end)
self.handler.send_response(response_status)
for key, value in response_headers.items():
self.handler.send_header(key, value)
self.handler.end_headers()
data_queue = Queue.PriorityQueue()
range_queue = Queue.PriorityQueue()
range_queue.put((start, end, self.response))
self.expect_begin = start
for begin in range(end+1, length, self.maxsize):
range_queue.put((begin, min(begin+self.maxsize-1, length-1), None))
for i in xrange(0, self.threads):
range_delay_size = i * self.maxsize
spawn_later(float(range_delay_size)/self.waitsize, self.__fetchlet, range_queue, data_queue, range_delay_size)
has_peek = hasattr(data_queue, 'peek')
peek_timeout = 120
while self.expect_begin < length - 1:
try:
if has_peek:
begin, data = data_queue.peek(timeout=peek_timeout)
if self.expect_begin == begin:
data_queue.get()
elif self.expect_begin < begin:
time.sleep(0.1)
continue
else:
logging.error('RangeFetch Error: begin(%r) < expect_begin(%r), quit.', begin, self.expect_begin)
break
else:
begin, data = data_queue.get(timeout=peek_timeout)
if self.expect_begin == begin:
pass
elif self.expect_begin < begin:
data_queue.put((begin, data))
time.sleep(0.1)
continue
else:
logging.error('RangeFetch Error: begin(%r) < expect_begin(%r), quit.', begin, self.expect_begin)
break
except Queue.Empty:
logging.error('data_queue peek timeout, break')
break
try:
self.handler.wfile.write(data)
self.expect_begin += len(data)
del data
except Exception as e:
logging.info('RangeFetch client connection aborted(%s).', e)
break
self._stopped = True
def __fetchlet(self, range_queue, data_queue, range_delay_size):
headers = dict((k.title(), v) for k, v in self.handler.headers.items())
headers['Connection'] = 'close'
while 1:
try:
if self._stopped:
return
try:
start, end, response = range_queue.get(timeout=1)
if self.expect_begin < start and data_queue.qsize() * self.bufsize + range_delay_size > 30*1024*1024:
range_queue.put((start, end, response))
time.sleep(10)
continue
headers['Range'] = 'bytes=%d-%d' % (start, end)
fetchserver = ''
if not response:
fetchserver = random.choice(self.fetchservers)
if self._last_app_status.get(fetchserver, 200) >= 500:
time.sleep(5)
response = self.plugin.fetch(self.handler, self.handler.command, self.url, headers, self.handler.body, timeout=self.handler.net2.connect_timeout, fetchserver=fetchserver, **self.kwargs)
except Queue.Empty:
continue
except Exception as e:
logging.warning("RangeFetch fetch response %r in __fetchlet", e)
range_queue.put((start, end, None))
continue
if not response:
logging.warning('RangeFetch %s return %r', headers['Range'], response)
range_queue.put((start, end, None))
continue
if fetchserver:
self._last_app_status[fetchserver] = response.app_status
if response.app_status != 200:
logging.warning('Range Fetch "%s %s" %s return %s', self.handler.command, self.url, headers['Range'], response.app_status)
response.close()
range_queue.put((start, end, None))
continue
if response.getheader('Location'):
self.url = urlparse.urljoin(self.url, response.getheader('Location'))
logging.info('RangeFetch Redirect(%r)', self.url)
response.close()
range_queue.put((start, end, None))
continue
if 200 <= response.status < 300:
content_range = response.getheader('Content-Range')
if not content_range:
logging.warning('RangeFetch "%s %s" return Content-Range=%r: response headers=%r, retry %s-%s', self.handler.command, self.url, content_range, response.getheaders(), start, end)
response.close()
range_queue.put((start, end, None))
continue
content_length = int(response.getheader('Content-Length', 0))
logging.info('>>>>>>>>>>>>>>> [thread %s] %s %s', threading.currentThread().ident, content_length, content_range)
while 1:
try:
if self._stopped:
response.close()
return
data = None
with gevent.Timeout(max(1, self.bufsize//8192), False):
data = response.read(self.bufsize)
if not data:
break
data_queue.put((start, data))
start += len(data)
except Exception as e:
logging.warning('RangeFetch "%s %s" %s failed: %s', self.handler.command, self.url, headers['Range'], e)
break
if start < end + 1:
logging.warning('RangeFetch "%s %s" retry %s-%s', self.handler.command, self.url, start, end)
response.close()
range_queue.put((start, end, None))
continue
logging.info('>>>>>>>>>>>>>>> Successfully reached %d bytes.', start - 1)
else:
logging.error('RangeFetch %r return %s', self.url, response.status)
response.close()
range_queue.put((start, end, None))
continue
except StandardError as e:
logging.exception('RangeFetch._fetchlet error:%s', e)
raise
class GAEFetchPlugin(BaseFetchPlugin):
"""gae fetch plugin"""
max_retry = 2
def __init__(self, appids, password, path, mode, cachesock, keepalive, obfuscate, pagespeed, validate, options):
BaseFetchPlugin.__init__(self)
self.appids = appids
self.password = password
self.path = path
self.mode = mode
self.cachesock = cachesock
self.keepalive = keepalive
self.obfuscate = obfuscate
self.pagespeed = pagespeed
self.validate = validate
self.options = options
def handle(self, handler, **kwargs):
assert handler.command != 'CONNECT'
rescue_bytes = int(kwargs.pop('rescue_bytes', 0))
method = handler.command
headers = dict((k.title(), v) for k, v in handler.headers.items())
body = handler.body
if handler.path[0] == '/':
url = '%s://%s%s' % (handler.scheme, handler.headers['Host'], handler.path)
elif handler.path.lower().startswith(('http://', 'https://', 'ftp://')):
url = handler.path
else:
raise ValueError('URLFETCH %r is not a valid url' % handler.path)
errors = []
response = None
for i in xrange(self.max_retry):
try:
if rescue_bytes:
headers['Range'] = 'bytes=%d-' % rescue_bytes
response = self.fetch(handler, method, url, headers, body, handler.net2.connect_timeout)
if response.app_status < 500:
break
else:
if response.app_status == 503:
# appid over qouta, switch to next appid
if len(self.appids) > 1:
self.appids.append(self.appids.pop(0))
logging.info('gae over qouta, switch next appid=%r', self.appids[0])
elif i < self.max_retry - 1 and len(self.appids) > 1:
self.appids.append(self.appids.pop(0))
logging.info('URLFETCH return %d, trying next appid=%r', response.app_status, self.appids[0])
response.close()
except Exception as e:
errors.append(e)
logging.info('GAE "%s %s" appid=%r %r, retry...', handler.command, handler.path, self.appids[0], e)
if len(errors) == self.max_retry:
if response and response.app_status >= 500:
status = response.app_status
headers = dict(response.getheaders())
content = response.read()
response.close()
else:
status = 502
headers = {'Content-Type': 'text/html'}
content = message_html('502 URLFetch failed', 'Local URLFetch %r failed' % handler.path, '<br>'.join(repr(x) for x in errors))
return handler.handler_plugins['mock'].handle(handler, status, headers, content)
logging.info('%s "GAE %s %s %s" %s %s', handler.address_string(), handler.command, handler.path, handler.protocol_version, response.status, response.getheader('Content-Length', '-'))
try:
if response.status == 206 and not rescue_bytes:
fetchservers = ['%s://%s.appspot.com%s' % (self.mode, x, self.path) for x in self.appids]
return RangeFetch(handler, self, response, fetchservers).fetch()
handler.close_connection = not response.getheader('Content-Length')
if not rescue_bytes:
handler.send_response(response.status)
for key, value in response.getheaders():
if key.title() == 'Transfer-Encoding':
continue
handler.send_header(key, value)
handler.end_headers()
bufsize = 8192
written = rescue_bytes
while True:
data = None
with gevent.Timeout(handler.net2.connect_timeout, False):
data = response.read(bufsize)
if data is None:
logging.warning('GAE response.read(%r) %r timeout', bufsize, url)
if response.getheader('Accept-Ranges', '') == 'bytes' and not urlparse.urlparse(url).query:
return self.handle(handler, rescue_bytes=written)
handler.close_connection = True
break
if data:
handler.wfile.write(data)
written += len(data)
if not data:
cache_sock = getattr(response, 'cache_sock', None)
if cache_sock:
cache_sock.close()
del response.cache_sock
response.close()
break
del data
except NetWorkIOError as e:
if e[0] in (errno.ECONNABORTED, errno.EPIPE) or 'bad write retry' in repr(e):
return
def fetch(self, handler, method, url, headers, body, timeout, **kwargs):
if isinstance(body, basestring) and body:
if len(body) < 10 * 1024 * 1024 and 'Content-Encoding' not in headers:
zbody = deflate(body)
if len(zbody) < len(body):
body = zbody
headers['Content-Encoding'] = 'deflate'
headers['Content-Length'] = str(len(body))
# GAE donot allow set `Host` header
if 'Host' in headers:
del headers['Host']
kwargs = {}
if self.password:
kwargs['password'] = self.password
if self.options:
kwargs['options'] = self.options
if self.validate:
kwargs['validate'] = self.validate
payload = '%s %s %s\r\n' % (method, url, handler.request_version)
payload += ''.join('%s: %s\r\n' % (k, v) for k, v in headers.items() if k not in handler.net2.skip_headers)
payload += ''.join('X-URLFETCH-%s: %s\r\n' % (k, v) for k, v in kwargs.items() if v)
# prepare GAE request
request_method = 'POST'
fetchserver_index = random.randint(0, len(self.appids)-1) if 'Range' in headers else 0
fetchserver = kwargs.get('fetchserver') or '%s://%s.appspot.com%s' % (self.mode, self.appids[fetchserver_index], self.path)
request_headers = {}
if common.GAE_OBFUSCATE:
request_method = 'GET'
fetchserver += 'ps/%d%s.gif' % (int(time.time()*1000), random.random())
request_headers['X-URLFETCH-PS1'] = base64.b64encode(deflate(payload)).strip()
if body:
request_headers['X-URLFETCH-PS2'] = base64.b64encode(deflate(body)).strip()
body = ''
if common.GAE_PAGESPEED:
fetchserver = re.sub(r'^(\w+://)', r'\g<1>1-ps.googleusercontent.com/h/', fetchserver)
else:
payload = deflate(payload)
body = '%s%s%s' % (struct.pack('!h', len(payload)), payload, body)
if 'rc4' in common.GAE_OPTIONS:
request_headers['X-URLFETCH-Options'] = 'rc4'
body = RC4Cipher(kwargs.get('password')).encrypt(body)
request_headers['Content-Length'] = str(len(body))
# post data
need_crlf = 0 if common.GAE_MODE == 'https' else 1
need_validate = common.GAE_VALIDATE
cache_key = '%s:%d' % (handler.net2.host_postfix_map['.appspot.com'], 443 if common.GAE_MODE == 'https' else 80)
headfirst = bool(common.GAE_HEADFIRST)
response = handler.net2.create_http_request(request_method, fetchserver, request_headers, body, timeout, crlf=need_crlf, validate=need_validate, cache_key=cache_key, headfirst=headfirst)
response.app_status = response.status
if response.app_status != 200:
return response
if 'rc4' in request_headers.get('X-URLFETCH-Options', ''):
response.fp = CipherFileObject(response.fp, RC4Cipher(kwargs['password']))
data = response.read(2)
if len(data) < 2:
response.status = 502
response.fp = io.BytesIO(b'connection aborted. too short leadbyte data=' + data)
response.read = response.fp.read
return response
headers_length, = struct.unpack('!h', data)
data = response.read(headers_length)
if len(data) < headers_length:
response.status = 502
response.fp = io.BytesIO(b'connection aborted. too short headers data=' + data)
response.read = response.fp.read
return response
raw_response_line, headers_data = inflate(data).split('\r\n', 1)
_, response.status, response.reason = raw_response_line.split(None, 2)
response.status = int(response.status)
response.reason = response.reason.strip()
response.msg = httplib.HTTPMessage(io.BytesIO(headers_data))
return response
class PHPFetchPlugin(BaseFetchPlugin):
"""php fetch plugin"""
def __init__(self, fetchserver, password, validate):
BaseFetchPlugin.__init__(self)
self.fetchservers = [fetchserver]
self.password = password
self.validate = validate
def handle(self, handler, **kwargs):
method = handler.command
url = handler.path
headers = dict((k.title(), v) for k, v in handler.headers.items())
body = handler.body
if body:
if len(body) < 10 * 1024 * 1024 and 'Content-Encoding' not in headers:
zbody = deflate(body)
if len(zbody) < len(body):
body = zbody
headers['Content-Encoding'] = 'deflate'
headers['Content-Length'] = str(len(body))
skip_headers = handler.net2.skip_headers
if self.password:
kwargs['password'] = self.password
if self.validate:
kwargs['validate'] = self.validate
payload = '%s %s %s\r\n' % (method, url, handler.request_version)
payload += ''.join('%s: %s\r\n' % (k, v) for k, v in headers.items() if k not in handler.net2.skip_headers)
payload += ''.join('X-URLFETCH-%s: %s\r\n' % (k, v) for k, v in kwargs.items() if v)
payload = deflate(payload)
body = '%s%s%s' % ((struct.pack('!h', len(payload)), payload, body))
request_headers = {'Content-Length': len(body), 'Content-Type': 'application/octet-stream'}
fetchserver_index = 0 if 'Range' not in headers else random.randint(0, len(self.fetchservers)-1)
fetchserver = '%s?%s' % (self.fetchservers[fetchserver_index], random.random())
crlf = 0
cache_key = '%s//:%s' % urlparse.urlsplit(fetchserver)[:2]
try:
response = handler.net2.create_http_request('POST', fetchserver, request_headers, body, handler.net2.connect_timeout, crlf=crlf, cache_key=cache_key)
except Exception as e:
logging.warning('%s "%s" failed %r', method, url, e)
return
response.app_status = response.status
need_decrypt = self.password and response.app_status == 200 and response.getheader('Content-Type', '') == 'image/gif' and response.fp
if need_decrypt:
response.fp = CipherFileObject(response.fp, XORCipher(self.password[0]))
logging.info('%s "PHP %s %s %s" %s %s', handler.address_string(), handler.command, url, handler.protocol_version, response.status, response.getheader('Content-Length', '-'))
handler.close_connection = bool(response.getheader('Transfer-Encoding'))
while True:
data = response.read(8192)
if not data:
break
handler.wfile.write(data)
del data
class VPSServer(gevent.server.StreamServer):
"""vps server"""
net2 = Net2()
def __init__(self, *args, **kwargs):
self.fetchservers = kwargs.pop('fetchservers')
gevent.server.StreamServer.__init__(self, *args, **kwargs)
self.remote_cache = {}
def forward_socket(self, local, remote, timeout, bufsize):
"""forward socket"""
tick = 1
count = timeout
while 1:
count -= tick
if count <= 0:
break
ins, _, errors = select.select([local, remote], [], [local, remote], tick)
if remote in errors:
local.close()
remote.close()
return
if local in errors:
local.close()
remote.close()
return
if remote in ins:
data = remote.recv(bufsize)
if not data:
remote.close()
local.close()
return
local.sendall(data)
if local in ins:
data = local.recv(bufsize)
if not data:
remote.close()
local.close()
return
remote.sendall(data)
if ins:
count = timeout
def handle(self, sock, addr):
request_data = data = ''
while True:
data = sock.recv(8192)
request_data += data
if '\r\n' in data:
break
if data == '':
return
request_line, _, header_data = request_data.partition('\r\n')
logging.info('%s:%d "VPS %s" - -', addr[0], addr[1], request_line)
fetchserver = self.fetchservers[0]
scheme, username, password, netloc = ProxyUtil.parse_proxy(fetchserver)
if scheme != 'https':
raise ValueError('VPSServer current only support https protocol')
if netloc.rfind(':') <= netloc.rfind(']'):
# no port number
host = netloc
port = 443 if scheme == 'https' else 80
else:
host, _, port = netloc.rpartition(':')
port = int(port)
remote = self.net2.create_ssl_connection(host, port, 8, cache_key=netloc)
request_data = '%s\r\nProxy-Authorization: Baisic %s\r\n%s' % (request_line, base64.b64encode('%s:%s' % (username, password)).strip(), header_data)
remote.sendall(request_data)
try:
self.forward_socket(sock, remote, 60, bufsize=256*1024)
except (socket.error, ssl.SSLError, OpenSSL.SSL.Error) as e:
if e.args[0] not in (errno.ECONNABORTED, errno.ECONNRESET, errno.ENOTCONN, errno.EPIPE):
raise
if e.args[0] in (errno.EBADF,):
return
class GAEFetchFilter(BaseProxyHandlerFilter):
"""gae fetch filter"""
#https://github.com/AppScale/gae_sdk/blob/master/google/appengine/api/taskqueue/taskqueue.py#L241
MAX_URL_LENGTH = 2083
def filter(self, handler):
"""https://developers.google.com/appengine/docs/python/urlfetch/"""
if handler.command == 'CONNECT':
do_ssl_handshake = 440 <= handler.port <= 450 or 1024 <= handler.port <= 65535
alias = handler.net2.getaliasbyname(handler.path)
if alias:
return 'direct', {'cache_key': '%s:%d' % (alias, handler.port), 'headfirst': '.google' in handler.host}
else:
return 'strip', {'do_ssl_handshake': do_ssl_handshake}
elif handler.command in ('GET', 'POST', 'HEAD', 'PUT', 'DELETE', 'PATCH'):
alias = handler.net2.getaliasbyname(handler.path)
if alias:
return 'direct', {'cache_key': '%s:%d' % (alias, handler.port), 'headfirst': '.google' in handler.host}
else:
return 'gae', {}
else:
if 'php' in handler.handler_plugins:
return 'php', {}
else:
logging.warning('"%s %s" not supported by GAE, please enable PHP mode!', handler.command, handler.path)
return 'direct', {}
class WithGAEFilter(BaseProxyHandlerFilter):
"""withgae/withphp filter"""
def __init__(self, withgae_sites, withphp_sites):
self.withgae_sites = set(x for x in withgae_sites if not x.startswith('.'))
self.withgae_sites_postfix = tuple(x for x in withgae_sites if x.startswith('.'))
self.withphp_sites = set(x for x in withphp_sites if not x.startswith('.'))
self.withphp_sites_postfix = tuple(x for x in withphp_sites if x.startswith('.'))
def filter(self, handler):
plugin = ''
if handler.host in self.withgae_sites or handler.host.endswith(self.withgae_sites_postfix):
plugin = 'gae'
elif handler.host in self.withphp_sites or handler.host.endswith(self.withphp_sites_postfix):
if 'php' not in handler.handler_plugins:
logging.warning('handler=%s does not contains php plugin, fallback to gae plugin!', handler)
plugin = 'gae'
else:
plugin = 'php'
if plugin:
if handler.command == 'CONNECT':
do_ssl_handshake = 440 <= handler.port <= 450 or 1024 <= handler.port <= 65535
return 'strip', {'do_ssl_handshake': do_ssl_handshake}
else:
return plugin, {}
class GAEProxyHandler(SimpleProxyHandler):
"""GAE Proxy Handler"""
handler_filters = [GAEFetchFilter()]
handler_plugins = {'direct': DirectFetchPlugin(),
'mock': MockFetchPlugin(),
'strip': StripPlugin(),}
def __init__(self, *args, **kwargs):
SimpleProxyHandler.__init__(self, *args, **kwargs)
def first_run(self):
"""GAEProxyHandler setup, init domain/iplist map"""
if not common.PROXY_ENABLE:
logging.info('resolve common.IPLIST_ALIAS names=%s to iplist', list(common.IPLIST_ALIAS))
common.resolve_iplist()
random.shuffle(common.GAE_APPIDS)
self.__class__.handler_plugins['gae'] = GAEFetchPlugin(common.GAE_APPIDS, common.GAE_PASSWORD, common.GAE_PATH, common.GAE_MODE, common.GAE_CACHESOCK, common.GAE_KEEPALIVE, common.GAE_OBFUSCATE, common.GAE_PAGESPEED, common.GAE_VALIDATE, common.GAE_OPTIONS)
if not common.PROXY_ENABLE:
net2 = AdvancedNet2(window=common.GAE_WINDOW, ssl_version=common.GAE_SSLVERSION, dns_servers=common.DNS_SERVERS, dns_blacklist=common.DNS_BLACKLIST)
for name, iplist in common.IPLIST_ALIAS.items():
net2.add_iplist_alias(name, iplist)
if name == 'google_hk':
for delay in (30, 60, 150, 240, 300, 450, 600, 900):
spawn_later(delay, self.extend_iplist, name)
net2.add_fixed_iplist(common.IPLIST_PREDEFINED)
for pattern, hosts in common.RULE_MAP.items():
net2.add_rule(pattern, hosts)
if common.GAE_CACHESOCK:
net2.enable_connection_cache()
if common.GAE_KEEPALIVE:
net2.enable_connection_keepalive()
net2.enable_openssl_session_cache()
self.__class__.net2 = net2
def extend_iplist(self, iplist_name):
hosts = [x for x in common.CONFIG.get('iplist', iplist_name).split('|') if not re.match(r'^\d+\.\d+\.\d+\.\d+$', x) and ':' not in x]
logging.info('extend_iplist start for hosts=%s', hosts)
new_iplist = []
def do_remote_resolve(host, dnsserver, queue):
assert isinstance(dnsserver, basestring)
for dnslib_resolve in (dnslib_resolve_over_udp, dnslib_resolve_over_tcp):
try:
time.sleep(random.random())
iplist = dnslib_record2iplist(dnslib_resolve(host, [dnsserver], timeout=4, blacklist=common.DNS_BLACKLIST))
queue.put((host, dnsserver, iplist))
except (socket.error, OSError) as e:
logging.info('%s remote host=%r failed: %s', str(dnslib_resolve).split()[1], host, e)
time.sleep(1)
result_queue = Queue.Queue()
pool = __import__('gevent.pool', fromlist=['.']).Pool(8) if sys.modules.get('gevent') else None
for host in hosts:
for dnsserver in common.DNS_SERVERS:
logging.debug('remote resolve host=%r from dnsserver=%r', host, dnsserver)
if pool:
pool.spawn(do_remote_resolve, host, dnsserver, result_queue)
else:
thread.start_new_thread(do_remote_resolve, (host, dnsserver, result_queue))
for _ in xrange(len(common.DNS_SERVERS) * len(hosts) * 2):
try:
host, dnsserver, iplist = result_queue.get(timeout=16)
logging.debug('%r remote host=%r return %s', dnsserver, host, iplist)
if '.google' in host:
if common.GAE_IPV6:
iplist = [x for x in iplist if ':' in x]
else:
iplist = [x for x in iplist if is_google_ip(x)]
new_iplist += iplist
except Queue.Empty:
break
logging.info('extend_iplist finished, added %s', len(set(self.net2.iplist_alias[iplist_name])-set(new_iplist)))
self.net2.add_iplist_alias(iplist_name, new_iplist)
class PHPFetchFilter(BaseProxyHandlerFilter):
"""php fetch filter"""
def filter(self, handler):
if handler.net2.getaliasbyname(handler.path):
return 'direct', {}
if handler.command == 'CONNECT':
return 'strip', {}
else:
return 'php', {}
class PHPProxyHandler(SimpleProxyHandler):
"""PHP Proxy Handler"""
handler_filters = [PHPFetchFilter()]
handler_plugins = {'direct': DirectFetchPlugin(),
'mock': MockFetchPlugin(),
'strip': StripPlugin(),}
def __init__(self, *args, **kwargs):
SimpleProxyHandler.__init__(self, *args, **kwargs)
def first_run(self):
"""PHPProxyHandler setup, init domain/iplist map"""
if not common.PROXY_ENABLE:
hostname = urlparse.urlsplit(common.PHP_FETCHSERVER).hostname
net2 = AdvancedNet2(window=4, ssl_version='TLSv1', dns_servers=common.DNS_SERVERS, dns_blacklist=common.DNS_BLACKLIST)
if not common.PHP_HOSTS:
common.PHP_HOSTS = net2.gethostsbyname(hostname)
net2.add_iplist_alias('php_fetchserver', common.PHP_HOSTS)
net2.add_fixed_iplist(common.PHP_HOSTS)
net2.add_rule(hostname, 'php_fetchserver')
net2.enable_connection_cache()
if common.PHP_KEEPALIVE:
net2.enable_connection_keepalive()
net2.enable_openssl_session_cache()
self.__class__.net2 = net2
class PacUtil(object):
"""GoAgent Pac Util"""
@staticmethod
def urlread(url, proxy_address):
try:
conn = httplib.HTTPConnection(proxy_address)
conn.request('GET', url)
response = conn.getresponse()
return response.read()
finally:
conn.close()
@staticmethod
def update_pacfile(filename):
listen_ip = '127.0.0.1'
autoproxy = '%s:%s' % (listen_ip, common.LISTEN_PORT)
blackhole = '%s:%s' % (listen_ip, common.PAC_PORT)
default = 'PROXY %s:%s' % (common.PROXY_HOST, common.PROXY_PORT) if common.PROXY_ENABLE else 'DIRECT'
content = ''
need_update = True
with open(filename, 'rb') as fp:
content = fp.read()
try:
placeholder = '// AUTO-GENERATED RULES, DO NOT MODIFY!'
content = content[:content.index(placeholder)+len(placeholder)]
content = re.sub(r'''blackhole\s*=\s*['"]PROXY [\.\w:]+['"]''', 'blackhole = \'PROXY %s\'' % blackhole, content)
content = re.sub(r'''autoproxy\s*=\s*['"]PROXY [\.\w:]+['"]''', 'autoproxy = \'PROXY %s\'' % autoproxy, content)
content = re.sub(r'''defaultproxy\s*=\s*['"](DIRECT|PROXY [\.\w:]+)['"]''', 'defaultproxy = \'%s\'' % default, content)
content = re.sub(r'''host\s*==\s*['"][\.\w:]+['"]\s*\|\|\s*isPlainHostName''', 'host == \'%s\' || isPlainHostName' % listen_ip, content)
if content.startswith('//'):
line = '// Proxy Auto-Config file generated by autoproxy2pac, %s\r\n' % time.strftime('%Y-%m-%d %H:%M:%S')
content = line + '\r\n'.join(content.splitlines()[1:])
except ValueError:
need_update = False
try:
if common.PAC_ADBLOCK:
admode = common.PAC_ADMODE
logging.info('try download %r to update_pacfile(%r)', common.PAC_ADBLOCK, filename)
adblock_content = PacUtil.urlread(common.PAC_ADBLOCK, autoproxy)
logging.info('%r downloaded, try convert it with adblock2pac', common.PAC_ADBLOCK)
if 'gevent' in sys.modules and time.sleep is getattr(sys.modules['gevent'], 'sleep', None) and hasattr(gevent.get_hub(), 'threadpool'):
jsrule = gevent.get_hub().threadpool.apply_e(Exception, PacUtil.adblock2pac, (adblock_content, 'FindProxyForURLByAdblock', blackhole, default, admode))
else:
jsrule = PacUtil.adblock2pac(adblock_content, 'FindProxyForURLByAdblock', blackhole, default, admode)
content += '\r\n' + jsrule + '\r\n'
logging.info('%r downloaded and parsed', common.PAC_ADBLOCK)
else:
content += '\r\nfunction FindProxyForURLByAdblock(url, host) {return "DIRECT";}\r\n'
except StandardError as e:
need_update = False
logging.exception('update_pacfile failed: %r', e)
try:
autoproxy_content_list = []
for url in common.PAC_GFWLIST.split('|'):
logging.info('try download %r to update_pacfile(%r)', url, filename)
if url.startswith('file://'):
try:
with open(url[len('file://'):], 'rb') as fp:
autoproxy_content_list.append(fp.read())
except IOError as e:
logging.warning('PacUtil load %r failed: %r', url, e)
else:
url_content = PacUtil.urlread(url, autoproxy)
if not any(x in url_content for x in '!-@|'):
url_content = base64.b64decode(url_content)
autoproxy_content_list.append(url_content)
autoproxy_content = '\n'.join(autoproxy_content_list)
logging.info('%r downloaded, try convert it with autoproxy2pac_lite', common.PAC_GFWLIST)
if 'gevent' in sys.modules and time.sleep is getattr(sys.modules['gevent'], 'sleep', None) and hasattr(gevent.get_hub(), 'threadpool'):
jsrule = gevent.get_hub().threadpool.apply_e(Exception, PacUtil.autoproxy2pac_lite, (autoproxy_content, 'FindProxyForURLByAutoProxy', autoproxy, default))
else:
jsrule = PacUtil.autoproxy2pac_lite(autoproxy_content, 'FindProxyForURLByAutoProxy', autoproxy, default)
content += '\r\n' + jsrule + '\r\n'
logging.info('%r downloaded and parsed', common.PAC_GFWLIST)
except StandardError as e:
need_update = False
logging.exception('update_pacfile failed: %r', e)
if need_update:
with open(filename, 'wb') as fp:
fp.write(content)
logging.info('%r successfully updated', filename)
@staticmethod
def autoproxy2pac(content, func_name='FindProxyForURLByAutoProxy', proxy='127.0.0.1:8087', default='DIRECT', indent=4):
"""Autoproxy to Pac, based on https://github.com/iamamac/autoproxy2pac"""
jsLines = []
for line in content.splitlines()[1:]:
if line and not line.startswith("!"):
use_proxy = True
if line.startswith("@@"):
line = line[2:]
use_proxy = False
return_proxy = 'PROXY %s' % proxy if use_proxy else default
if line.startswith('/') and line.endswith('/'):
jsLine = 'if (/%s/i.test(url)) return "%s";' % (line[1:-1], return_proxy)
elif line.startswith('||'):
domain = line[2:].lstrip('.')
if len(jsLines) > 0 and ('host.indexOf(".%s") >= 0' % domain in jsLines[-1] or 'host.indexOf("%s") >= 0' % domain in jsLines[-1]):
jsLines.pop()
jsLine = 'if (dnsDomainIs(host, ".%s") || host == "%s") return "%s";' % (domain, domain, return_proxy)
elif line.startswith('|'):
jsLine = 'if (url.indexOf("%s") == 0) return "%s";' % (line[1:], return_proxy)
elif '*' in line:
jsLine = 'if (shExpMatch(url, "*%s*")) return "%s";' % (line.strip('*'), return_proxy)
elif '/' not in line:
jsLine = 'if (host.indexOf("%s") >= 0) return "%s";' % (line, return_proxy)
else:
jsLine = 'if (url.indexOf("%s") >= 0) return "%s";' % (line, return_proxy)
jsLine = ' ' * indent + jsLine
if use_proxy:
jsLines.append(jsLine)
else:
jsLines.insert(0, jsLine)
function = 'function %s(url, host) {\r\n%s\r\n%sreturn "%s";\r\n}' % (func_name, '\n'.join(jsLines), ' '*indent, default)
return function
@staticmethod
def autoproxy2pac_lite(content, func_name='FindProxyForURLByAutoProxy', proxy='127.0.0.1:8087', default='DIRECT', indent=4):
"""Autoproxy to Pac, based on https://github.com/iamamac/autoproxy2pac"""
direct_domain_set = set([])
proxy_domain_set = set([])
for line in content.splitlines()[1:]:
if line and not line.startswith(('!', '|!', '||!')):
use_proxy = True
if line.startswith("@@"):
line = line[2:]
use_proxy = False
domain = ''
if line.startswith('/') and line.endswith('/'):
line = line[1:-1]
if line.startswith('^https?:\\/\\/[^\\/]+') and re.match(r'^(\w|\\\-|\\\.)+$', line[18:]):
domain = line[18:].replace(r'\.', '.')
else:
logging.warning('unsupport gfwlist regex: %r', line)
elif line.startswith('||'):
domain = line[2:].lstrip('*').rstrip('/')