PageRenderTime 44ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/local/proxy.py

https://github.com/v3aqb/goagent
Python | 3290 lines | 3167 code | 64 blank | 59 comment | 190 complexity | e68c15ee85b15756e066815556593a70 MD5 | raw file
  1. #!/usr/bin/env python
  2. # coding:utf-8
  3. # Based on GAppProxy 2.0.0 by Du XiaoGang <dugang.2008@gmail.com>
  4. # Based on WallProxy 0.4.0 by Hust Moon <www.ehust@gmail.com>
  5. # Contributor:
  6. # Phus Lu <phus.lu@gmail.com>
  7. # Hewig Xu <hewigovens@gmail.com>
  8. # Ayanamist Yang <ayanamist@gmail.com>
  9. # V.E.O <V.E.O@tom.com>
  10. # Max Lv <max.c.lv@gmail.com>
  11. # AlsoTang <alsotang@gmail.com>
  12. # Christopher Meng <i@cicku.me>
  13. # Yonsm Guo <YonsmGuo@gmail.com>
  14. # Parkman <cseparkman@gmail.com>
  15. # Ming Bai <mbbill@gmail.com>
  16. # Bin Yu <yubinlove1991@gmail.com>
  17. # lileixuan <lileixuan@gmail.com>
  18. # Cong Ding <cong@cding.org>
  19. # Zhang Youfu <zhangyoufu@gmail.com>
  20. # Lu Wei <luwei@barfoo>
  21. # Harmony Meow <harmony.meow@gmail.com>
  22. # logostream <logostream@gmail.com>
  23. # Rui Wang <isnowfy@gmail.com>
  24. # Wang Wei Qiang <wwqgtxx@gmail.com>
  25. # Felix Yan <felixonmars@gmail.com>
  26. # Sui Feng <suifeng.me@qq.com>
  27. # QXO <qxodream@gmail.com>
  28. # Geek An <geekan@foxmail.com>
  29. # Poly Rabbit <mcx_221@foxmail.com>
  30. # oxnz <yunxinyi@gmail.com>
  31. # Shusen Liu <liushusen.smart@gmail.com>
  32. # Yad Smood <y.s.inside@gmail.com>
  33. # Chen Shuang <cs0x7f@gmail.com>
  34. # cnfuyu <cnfuyu@gmail.com>
  35. # cuixin <steven.cuixin@gmail.com>
  36. # s2marine0 <s2marine0@gmail.com>
  37. # Toshio Xiang <snachx@gmail.com>
  38. # Bo Tian <dxmtb@163.com>
  39. # Virgil <variousvirgil@gmail.com>
  40. # hub01 <miaojiabumiao@yeah.net>
  41. # v3aqb <sgzz.cj@gmail.com>
  42. # Oling Cat <olingcat@gmail.com>
  43. __version__ = '3.1.18'
  44. import sys
  45. import os
  46. import glob
  47. reload(sys).setdefaultencoding('UTF-8')
  48. sys.dont_write_bytecode = True
  49. sys.path += glob.glob('%s/*.egg' % os.path.dirname(os.path.abspath(__file__)))
  50. try:
  51. import gevent
  52. import gevent.socket
  53. import gevent.server
  54. import gevent.queue
  55. import gevent.monkey
  56. gevent.monkey.patch_all(subprocess=True)
  57. except ImportError:
  58. gevent = None
  59. except TypeError:
  60. gevent.monkey.patch_all()
  61. sys.stderr.write('\033[31m Warning: Please update gevent to the latest 1.0 version!\033[0m\n')
  62. import errno
  63. import time
  64. import struct
  65. import collections
  66. import binascii
  67. import zlib
  68. import itertools
  69. import re
  70. import io
  71. import fnmatch
  72. import traceback
  73. import random
  74. import base64
  75. import string
  76. import hashlib
  77. import uuid
  78. import threading
  79. import thread
  80. import socket
  81. import ssl
  82. import select
  83. import Queue
  84. import SocketServer
  85. import ConfigParser
  86. import BaseHTTPServer
  87. import httplib
  88. import urllib
  89. import urllib2
  90. import urlparse
  91. try:
  92. import dnslib
  93. except ImportError:
  94. dnslib = None
  95. try:
  96. import OpenSSL
  97. except ImportError:
  98. OpenSSL = None
  99. try:
  100. import pygeoip
  101. except ImportError:
  102. pygeoip = None
  103. HAS_PYPY = hasattr(sys, 'pypy_version_info')
  104. NetWorkIOError = (socket.error, ssl.SSLError, OSError) if not OpenSSL else (socket.error, ssl.SSLError, OpenSSL.SSL.Error, OSError)
  105. class Logging(type(sys)):
  106. CRITICAL = 50
  107. FATAL = CRITICAL
  108. ERROR = 40
  109. WARNING = 30
  110. WARN = WARNING
  111. INFO = 20
  112. DEBUG = 10
  113. NOTSET = 0
  114. def __init__(self, *args, **kwargs):
  115. self.level = self.__class__.INFO
  116. self.__set_error_color = lambda: None
  117. self.__set_warning_color = lambda: None
  118. self.__set_debug_color = lambda: None
  119. self.__reset_color = lambda: None
  120. if hasattr(sys.stderr, 'isatty') and sys.stderr.isatty():
  121. if os.name == 'nt':
  122. import ctypes
  123. SetConsoleTextAttribute = ctypes.windll.kernel32.SetConsoleTextAttribute
  124. GetStdHandle = ctypes.windll.kernel32.GetStdHandle
  125. self.__set_error_color = lambda: SetConsoleTextAttribute(GetStdHandle(-11), 0x04)
  126. self.__set_warning_color = lambda: SetConsoleTextAttribute(GetStdHandle(-11), 0x06)
  127. self.__set_debug_color = lambda: SetConsoleTextAttribute(GetStdHandle(-11), 0x002)
  128. self.__reset_color = lambda: SetConsoleTextAttribute(GetStdHandle(-11), 0x07)
  129. elif os.name == 'posix':
  130. self.__set_error_color = lambda: sys.stderr.write('\033[31m')
  131. self.__set_warning_color = lambda: sys.stderr.write('\033[33m')
  132. self.__set_debug_color = lambda: sys.stderr.write('\033[32m')
  133. self.__reset_color = lambda: sys.stderr.write('\033[0m')
  134. @classmethod
  135. def getLogger(cls, *args, **kwargs):
  136. return cls(*args, **kwargs)
  137. def basicConfig(self, *args, **kwargs):
  138. self.level = int(kwargs.get('level', self.__class__.INFO))
  139. if self.level > self.__class__.DEBUG:
  140. self.debug = self.dummy
  141. def log(self, level, fmt, *args, **kwargs):
  142. sys.stderr.write('%s - [%s] %s\n' % (level, time.ctime()[4:-5], fmt % args))
  143. def dummy(self, *args, **kwargs):
  144. pass
  145. def debug(self, fmt, *args, **kwargs):
  146. self.__set_debug_color()
  147. self.log('DEBUG', fmt, *args, **kwargs)
  148. self.__reset_color()
  149. def info(self, fmt, *args, **kwargs):
  150. self.log('INFO', fmt, *args)
  151. def warning(self, fmt, *args, **kwargs):
  152. self.__set_warning_color()
  153. self.log('WARNING', fmt, *args, **kwargs)
  154. self.__reset_color()
  155. def warn(self, fmt, *args, **kwargs):
  156. self.warning(fmt, *args, **kwargs)
  157. def error(self, fmt, *args, **kwargs):
  158. self.__set_error_color()
  159. self.log('ERROR', fmt, *args, **kwargs)
  160. self.__reset_color()
  161. def exception(self, fmt, *args, **kwargs):
  162. self.error(fmt, *args, **kwargs)
  163. sys.stderr.write(traceback.format_exc() + '\n')
  164. def critical(self, fmt, *args, **kwargs):
  165. self.__set_error_color()
  166. self.log('CRITICAL', fmt, *args, **kwargs)
  167. self.__reset_color()
  168. logging = sys.modules['logging'] = Logging('logging')
  169. class LRUCache(object):
  170. """http://pypi.python.org/pypi/lru/"""
  171. def __init__(self, max_items=100):
  172. self.cache = {}
  173. self.key_order = []
  174. self.max_items = max_items
  175. def __setitem__(self, key, value):
  176. self.cache[key] = value
  177. self._mark(key)
  178. def __getitem__(self, key):
  179. value = self.cache[key]
  180. self._mark(key)
  181. return value
  182. def __contains__(self, key):
  183. return key in self.cache
  184. def _mark(self, key):
  185. if key in self.key_order:
  186. self.key_order.remove(key)
  187. self.key_order.insert(0, key)
  188. if len(self.key_order) > self.max_items:
  189. index = self.max_items // 2
  190. delitem = self.cache.__delitem__
  191. key_order = self.key_order
  192. any(delitem(key_order[x]) for x in xrange(index, len(key_order)))
  193. self.key_order = self.key_order[:index]
  194. def clear(self):
  195. self.cache = {}
  196. self.key_order = []
  197. class CertUtil(object):
  198. """CertUtil module, based on mitmproxy"""
  199. ca_vendor = 'GoAgent'
  200. ca_keyfile = 'CA.crt'
  201. ca_certdir = 'certs'
  202. ca_lock = threading.Lock()
  203. @staticmethod
  204. def create_ca():
  205. key = OpenSSL.crypto.PKey()
  206. key.generate_key(OpenSSL.crypto.TYPE_RSA, 2048)
  207. ca = OpenSSL.crypto.X509()
  208. ca.set_serial_number(0)
  209. ca.set_version(2)
  210. subj = ca.get_subject()
  211. subj.countryName = 'CN'
  212. subj.stateOrProvinceName = 'Internet'
  213. subj.localityName = 'Cernet'
  214. subj.organizationName = CertUtil.ca_vendor
  215. subj.organizationalUnitName = '%s Root' % CertUtil.ca_vendor
  216. subj.commonName = '%s CA' % CertUtil.ca_vendor
  217. ca.gmtime_adj_notBefore(0)
  218. ca.gmtime_adj_notAfter(24 * 60 * 60 * 3652)
  219. ca.set_issuer(ca.get_subject())
  220. ca.set_pubkey(key)
  221. ca.add_extensions([
  222. OpenSSL.crypto.X509Extension(b'basicConstraints', True, b'CA:TRUE'),
  223. # OpenSSL.crypto.X509Extension(b'nsCertType', True, b'sslCA'),
  224. OpenSSL.crypto.X509Extension(b'extendedKeyUsage', True, b'serverAuth,clientAuth,emailProtection,timeStamping,msCodeInd,msCodeCom,msCTLSign,msSGC,msEFS,nsSGC'),
  225. OpenSSL.crypto.X509Extension(b'keyUsage', False, b'keyCertSign, cRLSign'),
  226. OpenSSL.crypto.X509Extension(b'subjectKeyIdentifier', False, b'hash', subject=ca), ])
  227. ca.sign(key, 'sha1')
  228. return key, ca
  229. @staticmethod
  230. def dump_ca():
  231. key, ca = CertUtil.create_ca()
  232. with open(CertUtil.ca_keyfile, 'wb') as fp:
  233. fp.write(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, ca))
  234. fp.write(OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, key))
  235. @staticmethod
  236. def _get_cert(commonname, sans=()):
  237. with open(CertUtil.ca_keyfile, 'rb') as fp:
  238. content = fp.read()
  239. key = OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, content)
  240. ca = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, content)
  241. pkey = OpenSSL.crypto.PKey()
  242. pkey.generate_key(OpenSSL.crypto.TYPE_RSA, 2048)
  243. req = OpenSSL.crypto.X509Req()
  244. subj = req.get_subject()
  245. subj.countryName = 'CN'
  246. subj.stateOrProvinceName = 'Internet'
  247. subj.localityName = 'Cernet'
  248. subj.organizationalUnitName = '%s Branch' % CertUtil.ca_vendor
  249. if commonname[0] == '.':
  250. subj.commonName = '*' + commonname
  251. subj.organizationName = '*' + commonname
  252. sans = ['*'+commonname] + [x for x in sans if x != '*'+commonname]
  253. else:
  254. subj.commonName = commonname
  255. subj.organizationName = commonname
  256. sans = [commonname] + [x for x in sans if x != commonname]
  257. #req.add_extensions([OpenSSL.crypto.X509Extension(b'subjectAltName', True, ', '.join('DNS: %s' % x for x in sans)).encode()])
  258. req.set_pubkey(pkey)
  259. req.sign(pkey, 'sha1')
  260. cert = OpenSSL.crypto.X509()
  261. cert.set_version(2)
  262. try:
  263. cert.set_serial_number(int(hashlib.md5(commonname.encode('utf-8')).hexdigest(), 16))
  264. except OpenSSL.SSL.Error:
  265. cert.set_serial_number(int(time.time()*1000))
  266. cert.gmtime_adj_notBefore(0)
  267. cert.gmtime_adj_notAfter(60 * 60 * 24 * 3652)
  268. cert.set_issuer(ca.get_subject())
  269. cert.set_subject(req.get_subject())
  270. cert.set_pubkey(req.get_pubkey())
  271. if commonname[0] == '.':
  272. sans = ['*'+commonname] + [s for s in sans if s != '*'+commonname]
  273. else:
  274. sans = [commonname] + [s for s in sans if s != commonname]
  275. #cert.add_extensions([OpenSSL.crypto.X509Extension(b'subjectAltName', True, ', '.join('DNS: %s' % x for x in sans))])
  276. cert.sign(key, 'sha1')
  277. certfile = os.path.join(CertUtil.ca_certdir, commonname + '.crt')
  278. with open(certfile, 'wb') as fp:
  279. fp.write(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, cert))
  280. fp.write(OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, pkey))
  281. return certfile
  282. @staticmethod
  283. def get_cert(commonname, sans=()):
  284. if commonname.count('.') >= 2 and [len(x) for x in reversed(commonname.split('.'))] > [2, 4]:
  285. commonname = '.'+commonname.partition('.')[-1]
  286. certfile = os.path.join(CertUtil.ca_certdir, commonname + '.crt')
  287. if os.path.exists(certfile):
  288. return certfile
  289. elif OpenSSL is None:
  290. return CertUtil.ca_keyfile
  291. else:
  292. with CertUtil.ca_lock:
  293. if os.path.exists(certfile):
  294. return certfile
  295. return CertUtil._get_cert(commonname, sans)
  296. @staticmethod
  297. def import_ca(certfile):
  298. commonname = os.path.splitext(os.path.basename(certfile))[0]
  299. sha1digest = 'AB:70:2C:DF:18:EB:E8:B4:38:C5:28:69:CD:4A:5D:EF:48:B4:0E:33'
  300. if OpenSSL:
  301. try:
  302. with open(certfile, 'rb') as fp:
  303. x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, fp.read())
  304. commonname = next(v.decode() for k, v in x509.get_subject().get_components() if k == b'O')
  305. sha1digest = x509.digest('sha1')
  306. except StandardError as e:
  307. logging.error('load_certificate(certfile=%r) failed:%s', certfile, e)
  308. if sys.platform.startswith('win'):
  309. import ctypes
  310. with open(certfile, 'rb') as fp:
  311. certdata = fp.read()
  312. if certdata.startswith(b'-----'):
  313. begin = b'-----BEGIN CERTIFICATE-----'
  314. end = b'-----END CERTIFICATE-----'
  315. certdata = base64.b64decode(b''.join(certdata[certdata.find(begin)+len(begin):certdata.find(end)].strip().splitlines()))
  316. crypt32 = ctypes.WinDLL(b'crypt32.dll'.decode())
  317. store_handle = crypt32.CertOpenStore(10, 0, 0, 0x4000 | 0x20000, b'ROOT'.decode())
  318. if not store_handle:
  319. return -1
  320. X509_ASN_ENCODING = 0x00000001
  321. CERT_FIND_HASH = 0x10000
  322. class CRYPT_HASH_BLOB(ctypes.Structure):
  323. _fields_ = [('cbData', ctypes.c_ulong), ('pbData', ctypes.c_char_p)]
  324. crypt_hash = CRYPT_HASH_BLOB(20, binascii.a2b_hex(sha1digest.replace(':', '')))
  325. crypt_handle = crypt32.CertFindCertificateInStore(store_handle, X509_ASN_ENCODING, 0, CERT_FIND_HASH, ctypes.byref(crypt_hash), None)
  326. if crypt_handle:
  327. crypt32.CertFreeCertificateContext(crypt_handle)
  328. return 0
  329. ret = crypt32.CertAddEncodedCertificateToStore(store_handle, 0x1, certdata, len(certdata), 4, None)
  330. crypt32.CertCloseStore(store_handle, 0)
  331. del crypt32
  332. return 0 if ret else -1
  333. elif sys.platform == 'darwin':
  334. return os.system(('security find-certificate -a -c "%s" | grep "%s" >/dev/null || security add-trusted-cert -d -r trustRoot -k "/Library/Keychains/System.keychain" "%s"' % (commonname, commonname, certfile.decode('utf-8'))).encode('utf-8'))
  335. elif sys.platform.startswith('linux'):
  336. import platform
  337. platform_distname = platform.dist()[0]
  338. if platform_distname == 'Ubuntu':
  339. pemfile = "/etc/ssl/certs/%s.pem" % commonname
  340. new_certfile = "/usr/local/share/ca-certificates/%s.crt" % commonname
  341. if not os.path.exists(pemfile):
  342. return os.system('cp "%s" "%s" && update-ca-certificates' % (certfile, new_certfile))
  343. elif any(os.path.isfile('%s/certutil' % x) for x in os.environ['PATH'].split(os.pathsep)):
  344. return os.system('certutil -L -d sql:$HOME/.pki/nssdb | grep "%s" || certutil -d sql:$HOME/.pki/nssdb -A -t "C,," -n "%s" -i "%s"' % (commonname, commonname, certfile))
  345. else:
  346. logging.warning('please install *libnss3-tools* package to import GoAgent root ca')
  347. return 0
  348. @staticmethod
  349. def check_ca():
  350. #Check CA exists
  351. capath = os.path.join(os.path.dirname(os.path.abspath(__file__)), CertUtil.ca_keyfile)
  352. certdir = os.path.join(os.path.dirname(os.path.abspath(__file__)), CertUtil.ca_certdir)
  353. if not os.path.exists(capath):
  354. if not OpenSSL:
  355. logging.critical('CA.key is not exist and OpenSSL is disabled, ABORT!')
  356. sys.exit(-1)
  357. if os.path.exists(certdir):
  358. if os.path.isdir(certdir):
  359. any(os.remove(x) for x in glob.glob(certdir+'/*.crt')+glob.glob(certdir+'/.*.crt'))
  360. else:
  361. os.remove(certdir)
  362. os.mkdir(certdir)
  363. CertUtil.dump_ca()
  364. if glob.glob('%s/*.key' % CertUtil.ca_certdir):
  365. for filename in glob.glob('%s/*.key' % CertUtil.ca_certdir):
  366. try:
  367. os.remove(filename)
  368. os.remove(os.path.splitext(filename)[0]+'.crt')
  369. except EnvironmentError:
  370. pass
  371. #Check CA imported
  372. if CertUtil.import_ca(capath) != 0:
  373. logging.warning('install root certificate failed, Please run as administrator/root/sudo')
  374. #Check Certs Dir
  375. if not os.path.exists(certdir):
  376. os.makedirs(certdir)
  377. class DetectMobileBrowser:
  378. """detect mobile function from http://detectmobilebrowsers.com"""
  379. regex_match_a = re.compile(r"(android|bb\\d+|meego).+mobile|avantgo|bada\\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino", re.I|re.M).search
  380. regex_match_b = re.compile(r"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\\-(n|u)|c55\\/|capi|ccwa|cdm\\-|cell|chtm|cldc|cmd\\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\\-s|devi|dica|dmob|do(c|p)o|ds(12|\\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\\-|_)|g1 u|g560|gene|gf\\-5|g\\-mo|go(\\.w|od)|gr(ad|un)|haie|hcit|hd\\-(m|p|t)|hei\\-|hi(pt|ta)|hp( i|ip)|hs\\-c|ht(c(\\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\\-(20|go|ma)|i230|iac( |\\-|\\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\\/)|klon|kpt |kwc\\-|kyo(c|k)|le(no|xi)|lg( g|\\/(k|l|u)|50|54|\\-[a-w])|libw|lynx|m1\\-w|m3ga|m50\\/|ma(te|ui|xo)|mc(01|21|ca)|m\\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\\-2|po(ck|rt|se)|prox|psio|pt\\-g|qa\\-a|qc(07|12|21|32|60|\\-[2-7]|i\\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\\-|oo|p\\-)|sdk\\/|se(c(\\-|0|1)|47|mc|nd|ri)|sgh\\-|shar|sie(\\-|m)|sk\\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\\-|v\\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\\-|tdg\\-|tel(i|m)|tim\\-|t\\-mo|to(pl|sh)|ts(70|m\\-|m3|m5)|tx\\-9|up(\\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\\-|your|zeto|zte\\-", re.I|re.M).search
  381. @staticmethod
  382. def detect(user_agent):
  383. return DetectMobileBrowser.regex_match_a(user_agent) or DetectMobileBrowser.regex_match_b(user_agent)
  384. class SSLConnection(object):
  385. """OpenSSL Connection Wapper"""
  386. def __init__(self, context, sock):
  387. self._context = context
  388. self._sock = sock
  389. self._connection = OpenSSL.SSL.Connection(context, sock)
  390. self._makefile_refs = 0
  391. def __getattr__(self, attr):
  392. if attr not in ('_context', '_sock', '_connection', '_makefile_refs'):
  393. return getattr(self._connection, attr)
  394. def __wait_sock_io(self, io_func, *args, **kwargs):
  395. timeout = self._sock.gettimeout() or 0.1
  396. fd = self._sock.fileno()
  397. while True:
  398. try:
  399. return io_func(*args, **kwargs)
  400. except (OpenSSL.SSL.WantReadError, OpenSSL.SSL.WantX509LookupError):
  401. sys.exc_clear()
  402. _, _, errors = select.select([fd], [], [fd], timeout)
  403. if errors:
  404. break
  405. except OpenSSL.SSL.WantWriteError:
  406. sys.exc_clear()
  407. _, _, errors = select.select([], [fd], [fd], timeout)
  408. if errors:
  409. break
  410. def accept(self):
  411. sock, addr = self._sock.accept()
  412. client = OpenSSL.SSL.Connection(sock._context, sock)
  413. return client, addr
  414. def do_handshake(self):
  415. return self.__wait_sock_io(self._connection.do_handshake)
  416. def connect(self, *args, **kwargs):
  417. return self.__wait_sock_io(self._connection.connect, *args, **kwargs)
  418. def send(self, data, flags=0):
  419. try:
  420. return self.__wait_sock_io(self._connection.send, data, flags)
  421. except OpenSSL.SSL.SysCallError as e:
  422. if e[0] == -1 and not data:
  423. # errors when writing empty strings are expected and can be ignored
  424. return 0
  425. raise
  426. def recv(self, bufsiz, flags=0):
  427. pending = self._connection.pending()
  428. if pending:
  429. return self._connection.recv(min(pending, bufsiz))
  430. try:
  431. return self.__wait_sock_io(self._connection.recv, bufsiz, flags)
  432. except OpenSSL.SSL.ZeroReturnError:
  433. return ''
  434. def read(self, bufsiz, flags=0):
  435. return self.recv(bufsiz, flags)
  436. def write(self, buf, flags=0):
  437. return self.sendall(buf, flags)
  438. def close(self):
  439. if self._makefile_refs < 1:
  440. self._connection = None
  441. if self._sock:
  442. socket.socket.close(self._sock)
  443. else:
  444. self._makefile_refs -= 1
  445. def makefile(self, mode='r', bufsize=-1):
  446. self._makefile_refs += 1
  447. return socket._fileobject(self, mode, bufsize, close=True)
  448. @staticmethod
  449. def context_builder(ssl_version='SSLv23', ca_certs=None, cipher_suites=('ALL', '!aNULL', '!eNULL')):
  450. protocol_version = getattr(OpenSSL.SSL, '%s_METHOD' % ssl_version)
  451. ssl_context = OpenSSL.SSL.Context(protocol_version)
  452. if ca_certs:
  453. ssl_context.load_verify_locations(os.path.abspath(ca_certs))
  454. ssl_context.set_verify(OpenSSL.SSL.VERIFY_PEER, lambda c, x, e, d, ok: ok)
  455. else:
  456. ssl_context.set_verify(OpenSSL.SSL.VERIFY_NONE, lambda c, x, e, d, ok: ok)
  457. ssl_context.set_cipher_list(':'.join(cipher_suites))
  458. if hasattr(OpenSSL.SSL, 'SESS_CACHE_BOTH'):
  459. ssl_context.set_session_cache_mode(OpenSSL.SSL.SESS_CACHE_BOTH)
  460. return ssl_context
  461. class ProxyUtil(object):
  462. """ProxyUtil module, based on urllib2"""
  463. @staticmethod
  464. def parse_proxy(proxy):
  465. return urllib2._parse_proxy(proxy)
  466. @staticmethod
  467. def get_system_proxy():
  468. proxies = urllib2.getproxies()
  469. return proxies.get('https') or proxies.get('http') or {}
  470. @staticmethod
  471. def get_listen_ip():
  472. listen_ip = '127.0.0.1'
  473. sock = None
  474. try:
  475. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  476. sock.connect(('8.8.8.8', 53))
  477. listen_ip = sock.getsockname()[0]
  478. except socket.error:
  479. pass
  480. finally:
  481. if sock:
  482. sock.close()
  483. return listen_ip
  484. def inflate(data):
  485. return zlib.decompress(data, -zlib.MAX_WBITS)
  486. def deflate(data):
  487. return zlib.compress(data)[2:-4]
  488. def parse_hostport(host, default_port=80):
  489. m = re.match(r'(.+)[#](\d+)$', host)
  490. if m:
  491. return m.group(1).strip('[]'), int(m.group(2))
  492. else:
  493. return host.strip('[]'), default_port
  494. def dnslib_resolve_over_udp(query, dnsservers, timeout, **kwargs):
  495. """
  496. http://gfwrev.blogspot.com/2009/11/gfwdns.html
  497. http://zh.wikipedia.org/wiki/%E5%9F%9F%E5%90%8D%E6%9C%8D%E5%8A%A1%E5%99%A8%E7%BC%93%E5%AD%98%E6%B1%A1%E6%9F%93
  498. http://support.microsoft.com/kb/241352
  499. """
  500. if not isinstance(query, (basestring, dnslib.DNSRecord)):
  501. raise TypeError('query argument requires string/DNSRecord')
  502. blacklist = kwargs.get('blacklist', ())
  503. turstservers = kwargs.get('turstservers', ())
  504. dns_v4_servers = [x for x in dnsservers if ':' not in x]
  505. dns_v6_servers = [x for x in dnsservers if ':' in x]
  506. sock_v4 = sock_v6 = None
  507. socks = []
  508. if dns_v4_servers:
  509. sock_v4 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  510. socks.append(sock_v4)
  511. if dns_v6_servers:
  512. sock_v6 = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
  513. socks.append(sock_v6)
  514. timeout_at = time.time() + timeout
  515. try:
  516. for _ in xrange(4):
  517. try:
  518. for dnsserver in dns_v4_servers:
  519. if isinstance(query, basestring):
  520. query = dnslib.DNSRecord(q=dnslib.DNSQuestion(query))
  521. query_data = query.pack()
  522. sock_v4.sendto(query_data, parse_hostport(dnsserver, 53))
  523. for dnsserver in dns_v6_servers:
  524. if isinstance(query, basestring):
  525. query = dnslib.DNSRecord(q=dnslib.DNSQuestion(query, qtype=dnslib.QTYPE.AAAA))
  526. query_data = query.pack()
  527. sock_v6.sendto(query_data, parse_hostport(dnsserver, 53))
  528. while time.time() < timeout_at:
  529. ins, _, _ = select.select(socks, [], [], 0.1)
  530. for sock in ins:
  531. reply_data, reply_address = sock.recvfrom(512)
  532. reply_server = reply_address[0]
  533. record = dnslib.DNSRecord.parse(reply_data)
  534. iplist = [str(x.rdata) for x in record.rr if x.rtype in (1, 28, 255)]
  535. if any(x in blacklist for x in iplist):
  536. logging.warning('query=%r dnsservers=%r record bad iplist=%r', query, dnsservers, iplist)
  537. elif record.header.rcode and not iplist and reply_server in turstservers:
  538. logging.info('query=%r trust reply_server=%r record rcode=%s', query, reply_server, record.header.rcode)
  539. return record
  540. elif iplist:
  541. logging.debug('query=%r reply_server=%r record iplist=%s', query, reply_server, iplist)
  542. return record
  543. else:
  544. logging.debug('query=%r reply_server=%r record null iplist=%s', query, reply_server, iplist)
  545. continue
  546. except socket.error as e:
  547. logging.warning('handle dns query=%s socket: %r', query, e)
  548. raise socket.gaierror(11004, 'getaddrinfo %r from %r failed' % (query, dnsservers))
  549. finally:
  550. for sock in socks:
  551. sock.close()
  552. def dnslib_resolve_over_tcp(query, dnsservers, timeout, **kwargs):
  553. """dns query over tcp"""
  554. if not isinstance(query, (basestring, dnslib.DNSRecord)):
  555. raise TypeError('query argument requires string/DNSRecord')
  556. blacklist = kwargs.get('blacklist', ())
  557. def do_resolve(query, dnsserver, timeout, queobj):
  558. if isinstance(query, basestring):
  559. qtype = dnslib.QTYPE.AAAA if ':' in dnsserver else dnslib.QTYPE.A
  560. query = dnslib.DNSRecord(q=dnslib.DNSQuestion(query, qtype=qtype))
  561. query_data = query.pack()
  562. sock_family = socket.AF_INET6 if ':' in dnsserver else socket.AF_INET
  563. sock = socket.socket(sock_family)
  564. rfile = None
  565. try:
  566. sock.settimeout(timeout or None)
  567. sock.connect(parse_hostport(dnsserver, 53))
  568. sock.send(struct.pack('>h', len(query_data)) + query_data)
  569. rfile = sock.makefile('r', 1024)
  570. reply_data_length = rfile.read(2)
  571. if len(reply_data_length) < 2:
  572. raise socket.gaierror(11004, 'getaddrinfo %r from %r failed' % (query, dnsserver))
  573. reply_data = rfile.read(struct.unpack('>h', reply_data_length)[0])
  574. record = dnslib.DNSRecord.parse(reply_data)
  575. iplist = [str(x.rdata) for x in record.rr if x.rtype in (1, 28, 255)]
  576. if any(x in blacklist for x in iplist):
  577. logging.debug('query=%r dnsserver=%r record bad iplist=%r', query, dnsserver, iplist)
  578. raise socket.gaierror(11004, 'getaddrinfo %r from %r failed' % (query, dnsserver))
  579. else:
  580. logging.debug('query=%r dnsserver=%r record iplist=%s', query, dnsserver, iplist)
  581. queobj.put(record)
  582. except socket.error as e:
  583. logging.debug('query=%r dnsserver=%r failed %r', query, dnsserver, e)
  584. queobj.put(e)
  585. finally:
  586. if rfile:
  587. rfile.close()
  588. sock.close()
  589. queobj = Queue.Queue()
  590. for dnsserver in dnsservers:
  591. thread.start_new_thread(do_resolve, (query, dnsserver, timeout, queobj))
  592. for i in range(len(dnsservers)):
  593. try:
  594. result = queobj.get(timeout)
  595. except Queue.Empty:
  596. raise socket.gaierror(11004, 'getaddrinfo %r from %r failed' % (query, dnsservers))
  597. if result and not isinstance(result, Exception):
  598. return result
  599. elif i == len(dnsservers) - 1:
  600. logging.warning('dnslib_resolve_over_tcp %r with %s return %r', query, dnsservers, result)
  601. raise socket.gaierror(11004, 'getaddrinfo %r from %r failed' % (query, dnsservers))
  602. def dnslib_record2iplist(record):
  603. """convert dnslib.DNSRecord to iplist"""
  604. assert isinstance(record, dnslib.DNSRecord)
  605. iplist = [x for x in (str(r.rdata) for r in record.rr) if re.match(r'^\d+\.\d+\.\d+\.\d+$', x) or ':' in x]
  606. return iplist
  607. def get_dnsserver_list():
  608. if os.name == 'nt':
  609. import ctypes, ctypes.wintypes, struct, socket
  610. DNS_CONFIG_DNS_SERVER_LIST = 6
  611. buf = ctypes.create_string_buffer(2048)
  612. ctypes.windll.dnsapi.DnsQueryConfig(DNS_CONFIG_DNS_SERVER_LIST, 0, None, None, ctypes.byref(buf), ctypes.byref(ctypes.wintypes.DWORD(len(buf))))
  613. ipcount = struct.unpack('I', buf[0:4])[0]
  614. iplist = [socket.inet_ntoa(buf[i:i+4]) for i in xrange(4, ipcount*4+4, 4)]
  615. return iplist
  616. elif os.path.isfile('/etc/resolv.conf'):
  617. with open('/etc/resolv.conf', 'rb') as fp:
  618. return re.findall(r'(?m)^nameserver\s+(\S+)', fp.read())
  619. else:
  620. logging.warning("get_dnsserver_list failed: unsupport platform '%s-%s'", sys.platform, os.name)
  621. return []
  622. def spawn_later(seconds, target, *args, **kwargs):
  623. def wrap(*args, **kwargs):
  624. time.sleep(seconds)
  625. return target(*args, **kwargs)
  626. return thread.start_new_thread(wrap, args, kwargs)
  627. def spawn_period(seconds, target, *args, **kwargs):
  628. def wrap(*args, **kwargs):
  629. try:
  630. time.sleep(seconds)
  631. target(*args, **kwargs)
  632. except StandardError as e:
  633. logging.warning('%r(%s, %s) error: %r', target, args, kwargs, e)
  634. return thread.start_new_thread(wrap, args, kwargs)
  635. def is_clienthello(data):
  636. if len(data) < 20:
  637. return False
  638. if data.startswith('\x16\x03'):
  639. # TLSv12/TLSv11/TLSv1/SSLv3
  640. length, = struct.unpack('>h', data[3:5])
  641. return len(data) == 5 + length
  642. elif data[0] == '\x80' and data[2:4] == '\x01\x03':
  643. # SSLv23
  644. return len(data) == 2 + ord(data[1])
  645. else:
  646. return False
  647. def is_google_ip(ipaddr):
  648. return ipaddr.startswith(('173.194.', '207.126.', '209.85.', '216.239.', '64.18.', '64.233.', '66.102.', '66.249.', '72.14.', '74.125.'))
  649. def extract_sni_name(packet):
  650. if packet.startswith('\x16\x03'):
  651. stream = io.BytesIO(packet)
  652. stream.read(0x2b)
  653. session_id_length = ord(stream.read(1))
  654. stream.read(session_id_length)
  655. cipher_suites_length, = struct.unpack('>h', stream.read(2))
  656. stream.read(cipher_suites_length+2)
  657. extensions_length, = struct.unpack('>h', stream.read(2))
  658. # extensions = {}
  659. while True:
  660. data = stream.read(2)
  661. if not data:
  662. break
  663. etype, = struct.unpack('>h', data)
  664. elen, = struct.unpack('>h', stream.read(2))
  665. edata = stream.read(elen)
  666. if etype == 0:
  667. server_name = edata[5:]
  668. return server_name
  669. class URLFetch(object):
  670. """URLFetch for gae/php fetchservers"""
  671. skip_headers = frozenset(['Vary', 'Via', 'X-Forwarded-For', 'Proxy-Authorization', 'Proxy-Connection', 'Upgrade', 'X-Chrome-Variations', 'Connection', 'Cache-Control'])
  672. def __init__(self, fetchserver, create_http_request):
  673. assert isinstance(fetchserver, basestring) and callable(create_http_request)
  674. self.fetchserver = fetchserver
  675. self.create_http_request = create_http_request
  676. def fetch(self, method, url, headers, body, timeout, **kwargs):
  677. if '.appspot.com/' in self.fetchserver:
  678. response = self.__gae_fetch(method, url, headers, body, timeout, **kwargs)
  679. response.app_header_parsed = True
  680. else:
  681. response = self.__php_fetch(method, url, headers, body, timeout, **kwargs)
  682. response.app_header_parsed = False
  683. return response
  684. def __gae_fetch(self, method, url, headers, body, timeout, **kwargs):
  685. rc4crypt = lambda s, k: RC4Cipher(k).encrypt(s) if k else s
  686. if isinstance(body, basestring) and body:
  687. if len(body) < 10 * 1024 * 1024 and 'Content-Encoding' not in headers:
  688. zbody = deflate(body)
  689. if len(zbody) < len(body):
  690. body = zbody
  691. headers['Content-Encoding'] = 'deflate'
  692. headers['Content-Length'] = str(len(body))
  693. # GAE donot allow set `Host` header
  694. if 'Host' in headers:
  695. del headers['Host']
  696. metadata = 'G-Method:%s\nG-Url:%s\n%s' % (method, url, ''.join('G-%s:%s\n' % (k, v) for k, v in kwargs.items() if v))
  697. skip_headers = self.skip_headers
  698. metadata += ''.join('%s:%s\n' % (k.title(), v) for k, v in headers.items() if k not in skip_headers)
  699. # prepare GAE request
  700. request_fetchserver = self.fetchserver
  701. request_method = 'POST'
  702. request_headers = {}
  703. if common.GAE_OBFUSCATE:
  704. request_method = 'GET'
  705. request_fetchserver += '/ps/%s.gif' % uuid.uuid1()
  706. request_headers['X-GOA-PS1'] = base64.b64encode(deflate(metadata)).strip()
  707. if body:
  708. request_headers['X-GOA-PS2'] = base64.b64encode(deflate(body)).strip()
  709. body = ''
  710. if common.GAE_PAGESPEED:
  711. request_fetchserver = re.sub(r'^(\w+://)', r'\g<1>1-ps.googleusercontent.com/h/', request_fetchserver)
  712. else:
  713. metadata = deflate(metadata)
  714. body = '%s%s%s' % (struct.pack('!h', len(metadata)), metadata, body)
  715. if 'rc4' in common.GAE_OPTIONS:
  716. request_headers['X-GOA-Options'] = 'rc4'
  717. body = rc4crypt(body, kwargs.get('password'))
  718. request_headers['Content-Length'] = str(len(body))
  719. # post data
  720. need_crlf = 0 if common.GAE_MODE == 'https' else 1
  721. need_validate = common.GAE_VALIDATE
  722. cache_key = '%s:%d' % (common.HOST_POSTFIX_MAP['.appspot.com'], 443 if common.GAE_MODE == 'https' else 80)
  723. response = self.create_http_request(request_method, request_fetchserver, request_headers, body, timeout, crlf=need_crlf, validate=need_validate, cache_key=cache_key)
  724. response.app_status = response.status
  725. response.app_options = response.getheader('X-GOA-Options', '')
  726. if response.status != 200:
  727. return response
  728. data = response.read(4)
  729. if len(data) < 4:
  730. response.status = 502
  731. response.fp = io.BytesIO(b'connection aborted. too short leadbyte data=' + data)
  732. response.read = response.fp.read
  733. return response
  734. response.status, headers_length = struct.unpack('!hh', data)
  735. data = response.read(headers_length)
  736. if len(data) < headers_length:
  737. response.status = 502
  738. response.fp = io.BytesIO(b'connection aborted. too short headers data=' + data)
  739. response.read = response.fp.read
  740. return response
  741. if 'rc4' not in response.app_options:
  742. response.msg = httplib.HTTPMessage(io.BytesIO(inflate(data)))
  743. else:
  744. response.msg = httplib.HTTPMessage(io.BytesIO(inflate(rc4crypt(data, kwargs.get('password')))))
  745. if kwargs.get('password') and response.fp:
  746. response.fp = CipherFileObject(response.fp, RC4Cipher(kwargs['password']))
  747. return response
  748. def __php_fetch(self, method, url, headers, body, timeout, **kwargs):
  749. if body:
  750. if len(body) < 10 * 1024 * 1024 and 'Content-Encoding' not in headers:
  751. zbody = deflate(body)
  752. if len(zbody) < len(body):
  753. body = zbody
  754. headers['Content-Encoding'] = 'deflate'
  755. headers['Content-Length'] = str(len(body))
  756. skip_headers = self.skip_headers
  757. metadata = 'G-Method:%s\nG-Url:%s\n%s%s' % (method, url, ''.join('G-%s:%s\n' % (k, v) for k, v in kwargs.items() if v), ''.join('%s:%s\n' % (k, v) for k, v in headers.items() if k not in skip_headers))
  758. metadata = deflate(metadata)
  759. app_body = b''.join((struct.pack('!h', len(metadata)), metadata, body))
  760. app_headers = {'Content-Length': len(app_body), 'Content-Type': 'application/octet-stream'}
  761. fetchserver = '%s?%s' % (self.fetchserver, random.random())
  762. crlf = 0
  763. cache_key = '%s//:%s' % urlparse.urlsplit(fetchserver)[:2]
  764. response = self.create_http_request('POST', fetchserver, app_headers, app_body, timeout, crlf=crlf, cache_key=cache_key)
  765. if not response:
  766. raise socket.error(errno.ECONNRESET, 'urlfetch %r return None' % url)
  767. if response.status >= 400:
  768. return response
  769. response.app_status = response.status
  770. need_decrypt = kwargs.get('password') and response.app_status == 200 and response.getheader('Content-Type', '') == 'image/gif' and response.fp
  771. if need_decrypt:
  772. response.fp = CipherFileObject(response.fp, XORCipher(kwargs['password'][0]))
  773. return response
  774. class BaseProxyHandlerFilter(object):
  775. """base proxy handler filter"""
  776. def filter(self, handler):
  777. raise NotImplementedError
  778. class SimpleProxyHandlerFilter(BaseProxyHandlerFilter):
  779. """simple proxy handler filter"""
  780. def filter(self, handler):
  781. if handler.command == 'CONNECT':
  782. return [handler.FORWARD, handler.host, handler.port, handler.connect_timeout]
  783. else:
  784. return [handler.DIRECT, {}]
  785. class AuthFilter(BaseProxyHandlerFilter):
  786. """authorization filter"""
  787. auth_info = "Proxy authentication required"""
  788. white_list = set(['127.0.0.1'])
  789. def __init__(self, username, password):
  790. self.username = username
  791. self.password = password
  792. def check_auth_header(self, auth_header):
  793. method, _, auth_data = auth_header.partition(' ')
  794. if method == 'Basic':
  795. username, _, password = base64.b64decode(auth_data).partition(':')
  796. if username == self.username and password == self.password:
  797. return True
  798. return False
  799. def filter(self, handler):
  800. if self.white_list and handler.client_address[0] in self.white_list:
  801. return None
  802. auth_header = handler.headers.get('Proxy-Authorization') or getattr(handler, 'auth_header', None)
  803. if auth_header and self.check_auth_header(auth_header):
  804. handler.auth_header = auth_header
  805. else:
  806. headers = {'Access-Control-Allow-Origin': '*',
  807. 'Proxy-Authenticate': 'Basic realm="%s"' % self.auth_info,
  808. 'Content-Length': '0',
  809. 'Connection': 'keep-alive'}
  810. return [handler.MOCK, 407, headers, '']
  811. class SimpleProxyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  812. """SimpleProxyHandler for GoAgent 3.x"""
  813. protocol_version = 'HTTP/1.1'
  814. ssl_version = ssl.PROTOCOL_SSLv23
  815. disable_transport_ssl = True
  816. scheme = 'http'
  817. skip_headers = frozenset(['Vary', 'Via', 'X-Forwarded-For', 'Proxy-Authorization', 'Proxy-Connection', 'Upgrade', 'X-Chrome-Variations', 'Connection', 'Cache-Control'])
  818. bufsize = 256 * 1024
  819. max_timeout = 4
  820. connect_timeout = 2
  821. first_run_lock = threading.Lock()
  822. handler_filters = [SimpleProxyHandlerFilter()]
  823. sticky_filter = None
  824. def finish(self):
  825. """make python2 BaseHTTPRequestHandler happy"""
  826. try:
  827. BaseHTTPServer.BaseHTTPRequestHandler.finish(self)
  828. except NetWorkIOError as e:
  829. if e[0] not in (errno.ECONNABORTED, errno.ECONNRESET, errno.EPIPE):
  830. raise
  831. def address_string(self):
  832. return '%s:%s' % self.client_address[:2]
  833. def send_response(self, code, message=None):
  834. if message is None:
  835. if code in self.responses:
  836. message = self.responses[code][0]
  837. else:
  838. message = ''
  839. if self.request_version != 'HTTP/0.9':
  840. self.wfile.write('%s %d %s\r\n' % (self.protocol_version, code, message))
  841. def send_header(self, keyword, value):
  842. """Send a MIME header."""
  843. base_send_header = BaseHTTPServer.BaseHTTPRequestHandler.send_header
  844. keyword = keyword.title()
  845. if keyword == 'Set-Cookie':
  846. for cookie in re.split(r', (?=[^ =]+(?:=|$))', value):
  847. base_send_header(self, keyword, cookie)
  848. elif keyword == 'Content-Disposition' and '"' not in value:
  849. value = re.sub(r'filename=([^"\']+)', 'filename="\\1"', value)
  850. base_send_header(self, keyword, value)
  851. else:
  852. base_send_header(self, keyword, value)
  853. def setup(self):
  854. if isinstance(self.__class__.first_run, collections.Callable):
  855. try:
  856. with self.__class__.first_run_lock:
  857. if isinstance(self.__class__.first_run, collections.Callable):
  858. self.first_run()
  859. self.__class__.first_run = None
  860. except StandardError as e:
  861. logging.exception('%s.first_run() return %r', self.__class__, e)
  862. self.__class__.setup = BaseHTTPServer.BaseHTTPRequestHandler.setup
  863. self.__class__.do_CONNECT = self.__class__.do_METHOD
  864. self.__class__.do_GET = self.__class__.do_METHOD
  865. self.__class__.do_PUT = self.__class__.do_METHOD
  866. self.__class__.do_POST = self.__class__.do_METHOD
  867. self.__class__.do_HEAD = self.__class__.do_METHOD
  868. self.__class__.do_DELETE = self.__class__.do_METHOD
  869. self.__class__.do_OPTIONS = self.__class__.do_METHOD
  870. self.setup()
  871. def handle_one_request(self):
  872. if not self.disable_transport_ssl and self.scheme == 'http':
  873. leadbyte = self.connection.recv(1, socket.MSG_PEEK)
  874. if leadbyte in ('\x80', '\x16'):
  875. server_name = ''
  876. if leadbyte == '\x16':
  877. for _ in xrange(2):
  878. leaddata = self.connection.recv(1024, socket.MSG_PEEK)
  879. if is_clienthello(leaddata):
  880. try:
  881. server_name = extract_sni_name(leaddata)
  882. finally:
  883. break
  884. try:
  885. certfile = CertUtil.get_cert(server_name or 'www.google.com')
  886. ssl_sock = ssl.wrap_socket(self.connection, ssl_version=self.ssl_version, keyfile=certfile, certfile=certfile, server_side=True)
  887. except StandardError as e:
  888. if e.args[0] not in (errno.ECONNABORTED, errno.ECONNRESET):
  889. logging.exception('ssl.wrap_socket(self.connection=%r) failed: %s', self.connection, e)
  890. return
  891. self.connection = ssl_sock
  892. self.rfile = self.connection.makefile('rb', self.bufsize)
  893. self.wfile = self.connection.makefile('wb', 0)
  894. self.scheme = 'https'
  895. return BaseHTTPServer.BaseHTTPRequestHandler.handle_one_request(self)
  896. def first_run(self):
  897. pass
  898. def gethostbyname2(self, hostname):
  899. return socket.gethostbyname_ex(hostname)[-1]
  900. def create_tcp_connection(self, hostname, port, timeout, **kwargs):
  901. return socket.create_connection((hostname, port), timeout)
  902. def create_ssl_connection(self, hostname, port, timeout, **kwargs):
  903. sock = self.create_tcp_connection(hostname, port, timeout, **kwargs)
  904. ssl_sock = ssl.wrap_socket(sock, ssl_version=self.ssl_version)
  905. return ssl_sock
  906. def create_http_request(self, method, url, headers, body, timeout, **kwargs):
  907. scheme, netloc, path, query, _ = urlparse.urlsplit(url)
  908. if netloc.rfind(':') <= netloc.rfind(']'):
  909. # no port number
  910. host = netloc
  911. port = 443 if scheme == 'https' else 80
  912. else:
  913. host, _, port = netloc.rpartition(':')
  914. port = int(port)
  915. if query:
  916. path += '?' + query
  917. if 'Host' not in headers:
  918. headers['Host'] = host
  919. if body and 'Content-Length' not in headers:
  920. headers['Content-Length'] = str(len(body))
  921. ConnectionType = httplib.HTTPSConnection if scheme == 'https' else httplib.HTTPConnection
  922. connection = ConnectionType(netloc, timeout=timeout)
  923. connection.request(method, path, body=body, headers=headers)
  924. response = connection.getresponse()
  925. return response
  926. def create_http_request_withserver(self, fetchserver, method, url, headers, body, timeout, **kwargs):
  927. return URLFetch(fetchserver, self.create_http_request).fetch(method, url, headers, body, timeout, **kwargs)
  928. def handle_urlfetch_error(self, fetchserver, response):
  929. pass
  930. def handle_urlfetch_response_close(self, fetchserver, response):
  931. pass
  932. def parse_header(self):
  933. if self.command == 'CONNECT':
  934. netloc = self.path
  935. elif self.path[0] == '/':
  936. netloc = self.headers.get('Host', 'localhost')
  937. self.path = '%s://%s%s' % (self.scheme, netloc, self.path)
  938. else:
  939. netloc = urlparse.urlsplit(self.path).netloc
  940. m = re.match(r'^(.+):(\d+)$', netloc)
  941. if m:
  942. self.host = m.group(1).strip('[]')
  943. self.port = int(m.group(2))
  944. else:
  945. self.host = netloc
  946. self.port = 443 if self.scheme == 'https' else 80
  947. def forward_socket(self, local, remote, timeout):
  948. try:
  949. tick = 1
  950. bufsize = self.bufsize
  951. timecount = timeout
  952. while 1:
  953. timecount -= tick
  954. if timecount <= 0:
  955. break
  956. (ins, _, errors) = select.select([local, remote], [], [local, remote], tick)
  957. if errors:
  958. break
  959. for sock in ins:
  960. data = sock.recv(bufsize)
  961. if not data:
  962. break
  963. if sock is remote:
  964. local.sendall(data)
  965. timecount = timeout
  966. else:
  967. remote.sendall(data)
  968. timecount = timeout
  969. except socket.timeout:
  970. pass
  971. except NetWorkIOError as e:
  972. if e.args[0] not in (errno.ECONNABORTED, errno.ECONNRESET, errno.ENOTCONN, errno.EPIPE):
  973. raise
  974. if e.args[0] in (errno.EBADF,):
  975. return
  976. finally:
  977. for sock in (remote, local):
  978. try:
  979. sock.close()
  980. except StandardError:
  981. pass
  982. def MOCK(self, status, headers, content):
  983. """mock response"""
  984. logging.info('%s "MOCK %s %s %s" %d %d', self.address_string(), self.command, self.path, self.protocol_version, status, len(content))
  985. headers = dict((k.title(), v) for k, v in headers.items())
  986. if 'Transfer-Encoding' in headers:
  987. del headers['Transfer-Encoding']
  988. if 'Content-Length' not in headers:
  989. headers['Content-Length'] = len(content)
  990. if 'Connection' not in headers:
  991. headers['Connection'] = 'close'
  992. self.send_response(status)
  993. for key, value in headers.items():
  994. self.send_header(key, value)
  995. self.end_headers()
  996. self.wfile.write(content)
  997. def STRIP(self, do_ssl_handshake=True, sticky_filter=None):
  998. """strip connect"""
  999. certfile = CertUtil.get_cert(self.host)
  1000. logging.info('%s "STRIP %s %s:%d %s" - -', self.address_string(), self.command, self.host, self.port, self.protocol_version)
  1001. self.send_response(200)
  1002. self.end_headers()
  1003. if do_ssl_handshake:
  1004. try:
  1005. # ssl_sock = ssl.wrap_socket(self.connection, ssl_version=self.ssl_version, keyfile=certfile, certfile=certfile, server_side=True)
  1006. # bugfix for youtube-dl
  1007. ssl_sock = ssl.wrap_socket(self.connection, keyfile=certfile, certfile=certfile, server_side=True)
  1008. except StandardError as e:
  1009. if e.args[0] not in (errno.ECONNABORTED, errno.ECONNRESET):
  1010. logging.exception('ssl.wrap_socket(self.connection=%r) failed: %s', self.connection, e)
  1011. return
  1012. self.connection = ssl_sock
  1013. self.rfile = self.connection.makefile('rb', self.bufsize)
  1014. self.wfile = self.connection.makefile('wb', 0)
  1015. self.scheme = 'https'
  1016. try:
  1017. self.raw_requestline = self.rfile.readline(65537)
  1018. if len(self.raw_requestline) > 65536:
  1019. self.requestline = ''
  1020. self.request_version = ''
  1021. self.command = ''
  1022. self.send_error(414)
  1023. return
  1024. if not self.raw_requestline:
  1025. self.close_connection = 1
  1026. return
  1027. if not self.parse_request():
  1028. return
  1029. except NetWorkIOError as e:
  1030. if e.args[0] not in (errno.ECONNABORTED, errno.ECONNRESET, errno.EPIPE):
  1031. raise
  1032. self.sticky_filter = sticky_filter
  1033. try:
  1034. self.do_METHOD()
  1035. except NetWorkIOError as e:
  1036. if e.args[0] not in (errno.ECONNABORTED, errno.ETIMEDOUT, errno.EPIPE):
  1037. raise
  1038. def FORWARD(self, hostname, port, timeout, kwargs={}):
  1039. """forward socket"""
  1040. do_ssl_handshake = kwargs.pop('do_ssl_handshake', False)
  1041. local = self.connection
  1042. remote = None
  1043. self.send_response(200)
  1044. self.end_headers()
  1045. self.close_connection = 1
  1046. data = local.recv(1024)
  1047. if not data:
  1048. local.close()
  1049. return
  1050. data_is_clienthello = is_clienthello(data)
  1051. if data_is_clienthello:
  1052. kwargs['client_hello'] = data
  1053. max_retry = kwargs.get('max_retry', 3)
  1054. for i in xrange(max_retry):
  1055. try:
  1056. if do_ssl_handshake:
  1057. remote = self.create_ssl_connection(hostname, port, timeout, **kwargs)
  1058. else:
  1059. remote = self.create_tcp_connection(hostname, port, timeout, **kwargs)
  1060. if not data_is_clienthello and remote and not isinstance(remote, Exception):
  1061. remote.sendall(data)
  1062. break
  1063. except StandardError as e:
  1064. logging.exception('%s "FWD %s %s:%d %s" %r', self.address_string(), self.command, hostname, port, self.protocol_version, e)
  1065. if hasattr(remote, 'close'):
  1066. remote.close()
  1067. if i == max_retry - 1:
  1068. raise
  1069. logging.info('%s "FWD %s %s:%d %s" - -', self.address_string(), self.command, hostname, port, self.protocol_version)
  1070. if hasattr(remote, 'fileno'):
  1071. # reset timeout default to avoid long http upload failure, but it will delay timeout retry :(
  1072. remote.settimeout(None)
  1073. del kwargs
  1074. data = data_is_clienthello and getattr(remote, 'data', None)
  1075. if data:
  1076. del remote.data
  1077. local.sendall(data)
  1078. self.forward_socket(local, remote, self.max_timeout)
  1079. def DIRECT(self, kwargs):
  1080. method = self.command
  1081. if 'url' in kwargs:
  1082. url = kwargs.pop('url')
  1083. elif self.path.lower().startswith(('http://', 'https://', 'ftp://')):
  1084. url = self.path
  1085. else:
  1086. url = 'http://%s%s' % (self.headers['Host'], self.path)
  1087. headers = dict((k.title(), v) for k, v in self.headers.items())
  1088. body = self.body
  1089. response = None
  1090. try:
  1091. response = self.create_http_request(method, url, headers, body, timeout=self.connect_timeout, **kwargs)
  1092. logging.info('%s "DIRECT %s %s %s" %s %s', self.address_string(), self.command, url, self.protocol_version, response.status, response.getheader('Content-Length', '-'))
  1093. response_headers = dict((k.title(), v) for k, v in response.getheaders())
  1094. self.send_response(response.status)
  1095. for key, value in response.getheaders():
  1096. self.send_header(key, value)
  1097. self.end_headers()
  1098. if self.command == 'HEAD' or response.status in (204, 304):
  1099. response.close()
  1100. return
  1101. need_chunked = 'Transfer-Encoding' in response_headers
  1102. while True:
  1103. data = response.read(8192)
  1104. if not data:
  1105. if need_chunked:
  1106. self.wfile.write('0\r\n\r\n')
  1107. break
  1108. if need_chunked:
  1109. self.wfile.write('%x\r\n' % len(data))
  1110. self.wfile.write(data)
  1111. if need_chunked:
  1112. self.wfile.write('\r\n')
  1113. del data
  1114. except (ssl.SSLError, socket.timeout, socket.error):
  1115. if response:
  1116. if response.fp and response.fp._sock:
  1117. response.fp._sock.close()
  1118. response.close()
  1119. finally:
  1120. if response:
  1121. response.close()
  1122. def URLFETCH(self, fetchservers, max_retry=2, kwargs={}):
  1123. """urlfetch from fetchserver"""
  1124. method = self.command
  1125. if self.path[0] == '/':
  1126. url = '%s://%s%s' % (self.scheme, self.headers['Host'], self.path)
  1127. elif self.path.lower().startswith(('http://', 'https://', 'ftp://')):
  1128. url = self.path
  1129. else:
  1130. raise ValueError('URLFETCH %r is not a valid url' % self.path)
  1131. headers = dict((k.title(), v) for k, v in self.headers.items())
  1132. body = self.body
  1133. response = None
  1134. errors = []
  1135. fetchserver = fetchservers[0]
  1136. for i in xrange(max_retry):
  1137. try:
  1138. response = self.create_http_request_withserver(fetchserver, method, url, headers, body, timeout=60, **kwargs)
  1139. if response.app_status < 400:
  1140. break
  1141. else:
  1142. self.handle_urlfetch_error(fetchserver, response)
  1143. if i < max_retry - 1:
  1144. if len(fetchservers) > 1:
  1145. fetchserver = random.choice(fetchservers[1:])
  1146. logging.info('URLFETCH return %d, trying fetchserver=%r', response.app_status, fetchserver)
  1147. response.close()
  1148. except StandardError as e:
  1149. errors.append(e)
  1150. logging.info('URLFETCH "%s %s" fetchserver=%r %r, retry...', method, url, fetchserver, e)
  1151. if len(errors) == max_retry:
  1152. if response and response.app_status >= 500:
  1153. status = response.app_status
  1154. headers = dict(response.getheaders())
  1155. content = response.read()
  1156. response.close()
  1157. else:
  1158. status = 502
  1159. headers = {'Content-Type': 'text/html'}
  1160. content = message_html('502 URLFetch failed', 'Local URLFetch %r failed' % url, '<br>'.join(repr(x) for x in errors))
  1161. return self.MOCK(status, headers, content)
  1162. logging.info('%s "URL %s %s %s" %s %s', self.address_string(), method, url, self.protocol_version, response.status, response.getheader('Content-Length', '-'))
  1163. try:
  1164. if response.status == 206:
  1165. return RangeFetch(self, response, fetchservers, **kwargs).fetch()
  1166. if response.app_header_parsed:
  1167. self.close_connection = not response.getheader('Content-Length')
  1168. self.send_response(response.status)
  1169. for key, value in response.getheaders():
  1170. if key.title() == 'Transfer-Encoding':
  1171. continue
  1172. self.send_header(key, value)
  1173. self.end_headers()
  1174. bufsize = 8192
  1175. while True:
  1176. data = response.read(bufsize)
  1177. if data:
  1178. self.wfile.write(data)
  1179. if not data:
  1180. self.handle_urlfetch_response_close(fetchserver, response)
  1181. response.close()
  1182. break
  1183. del data
  1184. except NetWorkIOError as e:
  1185. if e[0] in (errno.ECONNABORTED, errno.EPIPE) or 'bad write retry' in repr(e):
  1186. return
  1187. def do_METHOD(self):
  1188. self.parse_header()
  1189. self.body = self.rfile.read(int(self.headers['Content-Length'])) if 'Content-Length' in self.headers else ''
  1190. if self.sticky_filter:
  1191. action = self.sticky_filter.filter(self)
  1192. if action:
  1193. return action.pop(0)(*action)
  1194. for handler_filter in self.handler_filters:
  1195. action = handler_filter.filter(self)
  1196. if action:
  1197. return action.pop(0)(*action)
  1198. class RangeFetch(object):
  1199. """Range Fetch Class"""
  1200. threads = 2
  1201. maxsize = 1024*1024*4
  1202. bufsize = 8192
  1203. waitsize = 1024*512
  1204. def __init__(self, handler, response, fetchservers, **kwargs):
  1205. self.handler = handler
  1206. self.url = handler.path
  1207. self.response = response
  1208. self.fetchservers = fetchservers
  1209. self.kwargs = kwargs
  1210. self._stopped = None
  1211. self._last_app_status = {}
  1212. self.expect_begin = 0
  1213. def fetch(self):
  1214. response_status = self.response.status
  1215. response_headers = dict((k.title(), v) for k, v in self.response.getheaders())
  1216. content_range = response_headers['Content-Range']
  1217. #content_length = response_headers['Content-Length']
  1218. start, end, length = tuple(int(x) for x in re.search(r'bytes (\d+)-(\d+)/(\d+)', content_range).group(1, 2, 3))
  1219. if start == 0:
  1220. response_status = 200
  1221. response_headers['Content-Length'] = str(length)
  1222. del response_headers['Content-Range']
  1223. else:
  1224. response_headers['Content-Range'] = 'bytes %s-%s/%s' % (start, end, length)
  1225. response_headers['Content-Length'] = str(length-start)
  1226. logging.info('>>>>>>>>>>>>>>> RangeFetch started(%r) %d-%d', self.url, start, end)
  1227. self.handler.send_response(response_status)
  1228. for key, value in response_headers.items():
  1229. self.handler.send_header(key, value)
  1230. self.handler.end_headers()
  1231. data_queue = Queue.PriorityQueue()
  1232. range_queue = Queue.PriorityQueue()
  1233. range_queue.put((start, end, self.response))
  1234. self.expect_begin = start
  1235. for begin in range(end+1, length, self.maxsize):
  1236. range_queue.put((begin, min(begin+self.maxsize-1, length-1), None))
  1237. for i in xrange(0, self.threads):
  1238. range_delay_size = i * self.maxsize
  1239. spawn_later(float(range_delay_size)/self.waitsize, self.__fetchlet, range_queue, data_queue, range_delay_size)
  1240. has_peek = hasattr(data_queue, 'peek')
  1241. peek_timeout = 120
  1242. while self.expect_begin < length - 1:
  1243. try:
  1244. if has_peek:
  1245. begin, data = data_queue.peek(timeout=peek_timeout)
  1246. if self.expect_begin == begin:
  1247. data_queue.get()
  1248. elif self.expect_begin < begin:
  1249. time.sleep(0.1)
  1250. continue
  1251. else:
  1252. logging.error('RangeFetch Error: begin(%r) < expect_begin(%r), quit.', begin, self.expect_begin)
  1253. break
  1254. else:
  1255. begin, data = data_queue.get(timeout=peek_timeout)
  1256. if self.expect_begin == begin:
  1257. pass
  1258. elif self.expect_begin < begin:
  1259. data_queue.put((begin, data))
  1260. time.sleep(0.1)
  1261. continue
  1262. else:
  1263. logging.error('RangeFetch Error: begin(%r) < expect_begin(%r), quit.', begin, self.expect_begin)
  1264. break
  1265. except Queue.Empty:
  1266. logging.error('data_queue peek timeout, break')
  1267. break
  1268. try:
  1269. self.handler.wfile.write(data)
  1270. self.expect_begin += len(data)
  1271. del data
  1272. except StandardError as e:
  1273. logging.info('RangeFetch client connection aborted(%s).', e)
  1274. break
  1275. self._stopped = True
  1276. def __fetchlet(self, range_queue, data_queue, range_delay_size):
  1277. headers = dict((k.title(), v) for k, v in self.handler.headers.items())
  1278. headers['Connection'] = 'close'
  1279. while 1:
  1280. try:
  1281. if self._stopped:
  1282. return
  1283. try:
  1284. start, end, response = range_queue.get(timeout=1)
  1285. if self.expect_begin < start and data_queue.qsize() * self.bufsize + range_delay_size > 30*1024*1024:
  1286. range_queue.put((start, end, response))
  1287. time.sleep(10)
  1288. continue
  1289. headers['Range'] = 'bytes=%d-%d' % (start, end)
  1290. fetchserver = ''
  1291. if not response:
  1292. fetchserver = random.choice(self.fetchservers)
  1293. if self._last_app_status.get(fetchserver, 200) >= 500:
  1294. time.sleep(5)
  1295. response = self.handler.create_http_request_withserver(fetchserver, self.handler.command, self.url, headers, self.handler.body, timeout=self.handler.connect_timeout, **self.kwargs)
  1296. except Queue.Empty:
  1297. continue
  1298. except StandardError as e:
  1299. logging.warning("Response %r in __fetchlet", e)
  1300. range_queue.put((start, end, None))
  1301. continue
  1302. if not response:
  1303. logging.warning('RangeFetch %s return %r', headers['Range'], response)
  1304. range_queue.put((start, end, None))
  1305. continue
  1306. if fetchserver:
  1307. self._last_app_status[fetchserver] = response.app_status
  1308. if response.app_status != 200:
  1309. logging.warning('Range Fetch "%s %s" %s return %s', self.handler.command, self.url, headers['Range'], response.app_status)
  1310. response.close()
  1311. range_queue.put((start, end, None))
  1312. continue
  1313. if response.getheader('Location'):
  1314. self.url = urlparse.urljoin(self.url, response.getheader('Location'))
  1315. logging.info('RangeFetch Redirect(%r)', self.url)
  1316. response.close()
  1317. range_queue.put((start, end, None))
  1318. continue
  1319. if 200 <= response.status < 300:
  1320. content_range = response.getheader('Content-Range')
  1321. if not content_range:
  1322. logging.warning('RangeFetch "%s %s" return Content-Range=%r: response headers=%r', self.handler.command, self.url, content_range, response.getheaders())
  1323. response.close()
  1324. range_queue.put((start, end, None))
  1325. continue
  1326. content_length = int(response.getheader('Content-Length', 0))
  1327. logging.info('>>>>>>>>>>>>>>> [thread %s] %s %s', threading.currentThread().ident, content_length, content_range)
  1328. while 1:
  1329. try:
  1330. if self._stopped:
  1331. response.close()
  1332. return
  1333. data = response.read(self.bufsize)
  1334. if not data:
  1335. break
  1336. data_queue.put((start, data))
  1337. start += len(data)
  1338. except StandardError as e:
  1339. logging.warning('RangeFetch "%s %s" %s failed: %s', self.handler.command, self.url, headers['Range'], e)
  1340. break
  1341. if start < end + 1:
  1342. logging.warning('RangeFetch "%s %s" retry %s-%s', self.handler.command, self.url, start, end)
  1343. response.close()
  1344. range_queue.put((start, end, None))
  1345. continue
  1346. logging.info('>>>>>>>>>>>>>>> Successfully reached %d bytes.', start - 1)
  1347. else:
  1348. logging.error('RangeFetch %r return %s', self.url, response.status)
  1349. response.close()
  1350. range_queue.put((start, end, None))
  1351. continue
  1352. except StandardError as e:
  1353. logging.exception('RangeFetch._fetchlet error:%s', e)
  1354. raise
  1355. class AdvancedProxyHandler(SimpleProxyHandler):
  1356. """Advanced Proxy Handler"""
  1357. dns_cache = LRUCache(64*1024)
  1358. dns_servers = []
  1359. dns_blacklist = []
  1360. tcp_connection_time = collections.defaultdict(float)
  1361. tcp_connection_time_with_clienthello = collections.defaultdict(float)
  1362. tcp_connection_cache = collections.defaultdict(Queue.PriorityQueue)
  1363. ssl_connection_time = collections.defaultdict(float)
  1364. ssl_connection_cache = collections.defaultdict(Queue.PriorityQueue)
  1365. ssl_connection_good_ipaddrs = {}
  1366. ssl_connection_bad_ipaddrs = {}
  1367. ssl_connection_unknown_ipaddrs = {}
  1368. ssl_connection_keepalive = False
  1369. max_window = 4
  1370. openssl_context = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_METHOD)
  1371. def gethostbyname2(self, hostname):
  1372. try:
  1373. iplist = self.dns_cache[hostname]
  1374. except KeyError:
  1375. if re.match(r'^\d+\.\d+\.\d+\.\d+$', hostname) or ':' in hostname:
  1376. iplist = [hostname]
  1377. elif self.dns_servers:
  1378. try:
  1379. record = dnslib_resolve_over_udp(hostname, self.dns_servers, timeout=2, blacklist=self.dns_blacklist)
  1380. except socket.gaierror:
  1381. record = dnslib_resolve_over_tcp(hostname, self.dns_servers, timeout=2, blacklist=self.dns_blacklist)
  1382. iplist = dnslib_record2iplist(record)
  1383. else:
  1384. iplist = socket.gethostbyname_ex(hostname)[-1]
  1385. self.dns_cache[hostname] = iplist
  1386. return iplist
  1387. def create_tcp_connection(self, hostname, port, timeout, **kwargs):
  1388. client_hello = kwargs.get('client_hello', None)
  1389. cache_key = kwargs.get('cache_key') if not client_hello else None
  1390. def create_connection(ipaddr, timeout, queobj):
  1391. sock = None
  1392. try:
  1393. # create a ipv4/ipv6 socket object
  1394. sock = socket.socket(socket.AF_INET if ':' not in ipaddr[0] else socket.AF_INET6)
  1395. # set reuseaddr option to avoid 10048 socket error
  1396. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  1397. # resize socket recv buffer 8K->32K to improve browser releated application performance
  1398. sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 32*1024)
  1399. # disable nagle algorithm to send http request quickly.
  1400. sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, True)
  1401. # set a short timeout to trigger timeout retry more quickly.
  1402. sock.settimeout(min(self.connect_timeout, timeout))
  1403. # start connection time record
  1404. start_time = time.time()
  1405. # TCP connect
  1406. sock.connect(ipaddr)
  1407. # record TCP connection time
  1408. self.tcp_connection_time[ipaddr] = time.time() - start_time
  1409. # send client hello and peek server hello
  1410. if client_hello:
  1411. sock.sendall(client_hello)
  1412. if gevent and isinstance(sock, gevent.socket.socket):
  1413. sock.data = data = sock.recv(4096)
  1414. else:
  1415. data = sock.recv(4096, socket.MSG_PEEK)
  1416. if not data:
  1417. logging.debug('create_tcp_connection %r with client_hello return NULL byte, continue %r', ipaddr, time.time()-start_time)
  1418. raise socket.timeout('timed out')
  1419. # record TCP connection time with client hello
  1420. self.tcp_connection_time_with_clienthello[ipaddr] = time.time() - start_time
  1421. # set timeout
  1422. sock.settimeout(timeout)
  1423. # put tcp socket object to output queobj
  1424. queobj.put(sock)
  1425. except (socket.error, OSError) as e:
  1426. # any socket.error, put Excpetions to output queobj.
  1427. queobj.put(e)
  1428. # reset a large and random timeout to the ipaddr
  1429. self.tcp_connection_time[ipaddr] = self.connect_timeout+random.random()
  1430. # close tcp socket
  1431. if sock:
  1432. sock.close()
  1433. def close_connection(count, queobj, first_tcp_time):
  1434. for _ in range(count):
  1435. sock = queobj.get()
  1436. tcp_time_threshold = min(1, 1.3 * first_tcp_time)
  1437. if sock and not isinstance(sock, Exception):
  1438. ipaddr = sock.getpeername()
  1439. if cache_key and self.tcp_connection_time[ipaddr] < tcp_time_threshold:
  1440. cache_queue = self.tcp_connection_cache[cache_key]
  1441. if cache_queue.qsize() < 8:
  1442. try:
  1443. _, old_sock = cache_queue.get_nowait()
  1444. old_sock.close()
  1445. except Queue.Empty:
  1446. pass
  1447. cache_queue.put((time.time(), sock))
  1448. else:
  1449. sock.close()
  1450. try:
  1451. while cache_key:
  1452. ctime, sock = self.tcp_connection_cache[cache_key].get_nowait()
  1453. if time.time() - ctime < 30:
  1454. return sock
  1455. else:
  1456. sock.close()
  1457. except Queue.Empty:
  1458. pass
  1459. addresses = [(x, port) for x in self.gethostbyname2(hostname)]
  1460. sock = None
  1461. for _ in range(kwargs.get('max_retry', 3)):
  1462. window = min((self.max_window+1)//2, len(addresses))
  1463. if client_hello:
  1464. addresses.sort(key=self.tcp_connection_time_with_clienthello.__getitem__)
  1465. else:
  1466. addresses.sort(key=self.tcp_connection_time.__getitem__)
  1467. addrs = addresses[:window] + random.sample(addresses, window)
  1468. queobj = gevent.queue.Queue() if gevent else Queue.Queue()
  1469. for addr in addrs:
  1470. thread.start_new_thread(create_connection, (addr, timeout, queobj))
  1471. for i in range(len(addrs)):
  1472. sock = queobj.get()
  1473. if not isinstance(sock, Exception):
  1474. first_tcp_time = self.tcp_connection_time[sock.getpeername()] if not cache_key else 0
  1475. thread.start_new_thread(close_connection, (len(addrs)-i-1, queobj, first_tcp_time))
  1476. return sock
  1477. elif i == 0:
  1478. # only output first error
  1479. logging.warning('create_tcp_connection to %r with %s return %r, try again.', hostname, addrs, sock)
  1480. if isinstance(sock, Exception):
  1481. raise sock
  1482. def create_ssl_connection(self, hostname, port, timeout, **kwargs):
  1483. cache_key = kwargs.get('cache_key')
  1484. validate = kwargs.get('validate')
  1485. def create_connection(ipaddr, timeout, queobj):
  1486. sock = None
  1487. ssl_sock = None
  1488. try:
  1489. # create a ipv4/ipv6 socket object
  1490. sock = socket.socket(socket.AF_INET if ':' not in ipaddr[0] else socket.AF_INET6)
  1491. # set reuseaddr option to avoid 10048 socket error
  1492. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  1493. # resize socket recv buffer 8K->32K to improve browser releated application performance
  1494. sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 32*1024)
  1495. # disable negal algorithm to send http request quickly.
  1496. sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, True)
  1497. # set a short timeout to trigger timeout retry more quickly.
  1498. sock.settimeout(min(self.connect_timeout, timeout))
  1499. # pick up the certificate
  1500. if not validate:
  1501. ssl_sock = ssl.wrap_socket(sock, ssl_version=self.ssl_version, do_handshake_on_connect=False)
  1502. else:
  1503. ssl_sock = ssl.wrap_socket(sock, ssl_version=self.ssl_version, cert_reqs=ssl.CERT_REQUIRED, ca_certs=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'cacert.pem'), do_handshake_on_connect=False)
  1504. ssl_sock.settimeout(min(self.connect_timeout, timeout))
  1505. # start connection time record
  1506. start_time = time.time()
  1507. # TCP connect
  1508. ssl_sock.connect(ipaddr)
  1509. connected_time = time.time()
  1510. # SSL handshake
  1511. ssl_sock.do_handshake()
  1512. handshaked_time = time.time()
  1513. # record TCP connection time
  1514. self.tcp_connection_time[ipaddr] = ssl_sock.tcp_time = connected_time - start_time
  1515. # record SSL connection time
  1516. self.ssl_connection_time[ipaddr] = ssl_sock.ssl_time = handshaked_time - start_time
  1517. ssl_sock.ssl_time = connected_time - start_time
  1518. # sometimes, we want to use raw tcp socket directly(select/epoll), so setattr it to ssl socket.
  1519. ssl_sock.sock = sock
  1520. # remove from bad/unknown ipaddrs dict
  1521. self.ssl_connection_bad_ipaddrs.pop(ipaddr, None)
  1522. self.ssl_connection_unknown_ipaddrs.pop(ipaddr, None)
  1523. # add to good ipaddrs dict
  1524. if ipaddr not in self.ssl_connection_good_ipaddrs:
  1525. self.ssl_connection_good_ipaddrs[ipaddr] = handshaked_time
  1526. # verify SSL certificate.
  1527. if validate and hostname.endswith('.appspot.com'):
  1528. cert = ssl_sock.getpeercert()
  1529. orgname = next((v for ((k, v),) in cert['subject'] if k == 'organizationName'))
  1530. if not orgname.lower().startswith('google '):
  1531. raise ssl.SSLError("%r certificate organizationName(%r) not startswith 'Google'" % (hostname, orgname))
  1532. # set timeout
  1533. ssl_sock.settimeout(timeout)
  1534. # put ssl socket object to output queobj
  1535. queobj.put(ssl_sock)
  1536. except (socket.error, ssl.SSLError, OSError) as e:
  1537. # any socket.error, put Excpetions to output queobj.
  1538. queobj.put(e)
  1539. # reset a large and random timeout to the ipaddr
  1540. self.ssl_connection_time[ipaddr] = self.connect_timeout + random.random()
  1541. # add to bad ipaddrs dict
  1542. if ipaddr not in self.ssl_connection_bad_ipaddrs:
  1543. self.ssl_connection_bad_ipaddrs[ipaddr] = time.time()
  1544. # remove from good/unknown ipaddrs dict
  1545. self.ssl_connection_good_ipaddrs.pop(ipaddr, None)
  1546. self.ssl_connection_unknown_ipaddrs.pop(ipaddr, None)
  1547. # close ssl socket
  1548. if ssl_sock:
  1549. ssl_sock.close()
  1550. # close tcp socket
  1551. if sock:
  1552. sock.close()
  1553. def create_connection_withopenssl(ipaddr, timeout, queobj):
  1554. sock = None
  1555. ssl_sock = None
  1556. try:
  1557. # create a ipv4/ipv6 socket object
  1558. sock = socket.socket(socket.AF_INET if ':' not in ipaddr[0] else socket.AF_INET6)
  1559. # set reuseaddr option to avoid 10048 socket error
  1560. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  1561. # resize socket recv buffer 8K->32K to improve browser releated application performance
  1562. sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 32*1024)
  1563. # disable negal algorithm to send http request quickly.
  1564. sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, True)
  1565. # set a short timeout to trigger timeout retry more quickly.
  1566. sock.settimeout(timeout or self.connect_timeout)
  1567. # pick up the certificate
  1568. server_hostname = b'www.googleapis.com' if cache_key.startswith('google_') or hostname.endswith('.appspot.com') else None
  1569. ssl_sock = SSLConnection(self.openssl_context, sock)
  1570. ssl_sock.set_connect_state()
  1571. if server_hostname and hasattr(ssl_sock, 'set_tlsext_host_name'):
  1572. ssl_sock.set_tlsext_host_name(server_hostname)
  1573. # start connection time record
  1574. start_time = time.time()
  1575. # TCP connect
  1576. ssl_sock.connect(ipaddr)
  1577. connected_time = time.time()
  1578. # SSL handshake
  1579. ssl_sock.do_handshake()
  1580. handshaked_time = time.time()
  1581. # record TCP connection time
  1582. self.tcp_connection_time[ipaddr] = ssl_sock.tcp_time = connected_time - start_time
  1583. # record SSL connection time
  1584. self.ssl_connection_time[ipaddr] = ssl_sock.ssl_time = handshaked_time - start_time
  1585. # sometimes, we want to use raw tcp socket directly(select/epoll), so setattr it to ssl socket.
  1586. ssl_sock.sock = sock
  1587. # remove from bad/unknown ipaddrs dict
  1588. self.ssl_connection_bad_ipaddrs.pop(ipaddr, None)
  1589. self.ssl_connection_unknown_ipaddrs.pop(ipaddr, None)
  1590. # add to good ipaddrs dict
  1591. if ipaddr not in self.ssl_connection_good_ipaddrs:
  1592. self.ssl_connection_good_ipaddrs[ipaddr] = handshaked_time
  1593. # verify SSL certificate.
  1594. if validate and hostname.endswith('.appspot.com'):
  1595. cert = ssl_sock.get_peer_certificate()
  1596. commonname = next((v for k, v in cert.get_subject().get_components() if k == 'CN'))
  1597. if '.google' not in commonname and not commonname.endswith('.appspot.com'):
  1598. raise socket.error("Host name '%s' doesn't match certificate host '%s'" % (hostname, commonname))
  1599. # put ssl socket object to output queobj
  1600. queobj.put(ssl_sock)
  1601. except (socket.error, OpenSSL.SSL.Error, OSError) as e:
  1602. # any socket.error, put Excpetions to output queobj.
  1603. queobj.put(e)
  1604. # reset a large and random timeout to the ipaddr
  1605. self.ssl_connection_time[ipaddr] = self.connect_timeout + random.random()
  1606. # add to bad ipaddrs dict
  1607. if ipaddr not in self.ssl_connection_bad_ipaddrs:
  1608. self.ssl_connection_bad_ipaddrs[ipaddr] = time.time()
  1609. # remove from good/unknown ipaddrs dict
  1610. self.ssl_connection_good_ipaddrs.pop(ipaddr, None)
  1611. self.ssl_connection_unknown_ipaddrs.pop(ipaddr, None)
  1612. # close ssl socket
  1613. if ssl_sock:
  1614. ssl_sock.close()
  1615. # close tcp socket
  1616. if sock:
  1617. sock.close()
  1618. def close_connection(count, queobj, first_tcp_time, first_ssl_time):
  1619. for _ in range(count):
  1620. sock = queobj.get()
  1621. ssl_time_threshold = min(1, 1.3 * first_ssl_time)
  1622. if sock and not isinstance(sock, Exception):
  1623. if cache_key and sock.ssl_time < ssl_time_threshold:
  1624. cache_queue = self.ssl_connection_cache[cache_key]
  1625. if cache_queue.qsize() < 8:
  1626. try:
  1627. _, old_sock = cache_queue.get_nowait()
  1628. old_sock.close()
  1629. except Queue.Empty:
  1630. pass
  1631. cache_queue.put((time.time(), sock))
  1632. else:
  1633. sock.close()
  1634. def reorg_ipaddrs():
  1635. current_time = time.time()
  1636. for ipaddr, ctime in self.ssl_connection_good_ipaddrs.items():
  1637. if current_time - ctime > 4 * 60:
  1638. self.ssl_connection_good_ipaddrs.pop(ipaddr, None)
  1639. self.ssl_connection_unknown_ipaddrs[ipaddr] = ctime
  1640. for ipaddr, ctime in self.ssl_connection_bad_ipaddrs.items():
  1641. if current_time - ctime > 6 * 60:
  1642. self.ssl_connection_bad_ipaddrs.pop(ipaddr, None)
  1643. self.ssl_connection_unknown_ipaddrs[ipaddr] = ctime
  1644. logging.info("good_ipaddrs=%d, bad_ipaddrs=%d, unkown_ipaddrs=%d", len(self.ssl_connection_good_ipaddrs), len(self.ssl_connection_bad_ipaddrs), len(self.ssl_connection_unknown_ipaddrs))
  1645. try:
  1646. while cache_key:
  1647. ctime, sock = self.ssl_connection_cache[cache_key].get_nowait()
  1648. if time.time() - ctime < 30:
  1649. return sock
  1650. else:
  1651. sock.close()
  1652. except Queue.Empty:
  1653. pass
  1654. addresses = [(x, port) for x in self.gethostbyname2(hostname)]
  1655. sock = None
  1656. for i in range(kwargs.get('max_retry', 5)):
  1657. reorg_ipaddrs()
  1658. window = self.max_window + i
  1659. good_ipaddrs = [x for x in addresses if x in self.ssl_connection_good_ipaddrs]
  1660. good_ipaddrs = sorted(good_ipaddrs, key=self.ssl_connection_time.get)[:window]
  1661. unkown_ipaddrs = [x for x in addresses if x not in self.ssl_connection_good_ipaddrs and x not in self.ssl_connection_bad_ipaddrs]
  1662. random.shuffle(unkown_ipaddrs)
  1663. unkown_ipaddrs = unkown_ipaddrs[:window]
  1664. bad_ipaddrs = [x for x in addresses if x in self.ssl_connection_bad_ipaddrs]
  1665. bad_ipaddrs = sorted(bad_ipaddrs, key=self.ssl_connection_bad_ipaddrs.get)[:window]
  1666. addrs = good_ipaddrs + unkown_ipaddrs + bad_ipaddrs
  1667. remain_window = 3 * window - len(addrs)
  1668. if 0 < remain_window <= len(addresses):
  1669. addrs += random.sample(addresses, remain_window)
  1670. logging.debug('%s good_ipaddrs=%d, unkown_ipaddrs=%r, bad_ipaddrs=%r', cache_key, len(good_ipaddrs), len(unkown_ipaddrs), len(bad_ipaddrs))
  1671. queobj = gevent.queue.Queue() if gevent else Queue.Queue()
  1672. for addr in addrs:
  1673. thread.start_new_thread(create_connection_withopenssl, (addr, timeout, queobj))
  1674. for i in range(len(addrs)):
  1675. sock = queobj.get()
  1676. if not isinstance(sock, Exception):
  1677. thread.start_new_thread(close_connection, (len(addrs)-i-1, queobj, sock.tcp_time, sock.ssl_time))
  1678. return sock
  1679. elif i == 0:
  1680. # only output first error
  1681. logging.warning('create_ssl_connection to %r with %s return %r, try again.', hostname, addrs, sock)
  1682. if isinstance(sock, Exception):
  1683. raise sock
  1684. def create_http_request(self, method, url, headers, body, timeout, max_retry=2, bufsize=8192, crlf=None, validate=None, cache_key=None):
  1685. scheme, netloc, path, query, _ = urlparse.urlsplit(url)
  1686. if netloc.rfind(':') <= netloc.rfind(']'):
  1687. # no port number
  1688. host = netloc
  1689. port = 443 if scheme == 'https' else 80
  1690. else:
  1691. host, _, port = netloc.rpartition(':')
  1692. port = int(port)
  1693. if query:
  1694. path += '?' + query
  1695. if 'Host' not in headers:
  1696. headers['Host'] = host
  1697. if body and 'Content-Length' not in headers:
  1698. headers['Content-Length'] = str(len(body))
  1699. sock = None
  1700. for i in range(max_retry):
  1701. try:
  1702. create_connection = self.create_ssl_connection if scheme == 'https' else self.create_tcp_connection
  1703. sock = create_connection(host, port, timeout, validate=validate, cache_key=cache_key)
  1704. break
  1705. except StandardError as e:
  1706. logging.exception('create_http_request "%s %s" failed:%s', method, url, e)
  1707. if sock:
  1708. sock.close()
  1709. if i == max_retry - 1:
  1710. raise
  1711. request_data = ''
  1712. crlf_counter = 0
  1713. if scheme != 'https' and crlf:
  1714. fakeheaders = dict((k.title(), v) for k, v in headers.items())
  1715. fakeheaders.pop('Content-Length', None)
  1716. fakeheaders.pop('Cookie', None)
  1717. fakeheaders.pop('Host', None)
  1718. if 'User-Agent' not in fakeheaders:
  1719. fakeheaders['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1878.0 Safari/537.36'
  1720. if 'Accept-Language' not in fakeheaders:
  1721. fakeheaders['Accept-Language'] = 'zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4'
  1722. if 'Accept' not in fakeheaders:
  1723. fakeheaders['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
  1724. fakeheaders_data = ''.join('%s: %s\r\n' % (k, v) for k, v in fakeheaders.items() if k not in self.skip_headers)
  1725. while crlf_counter < 5 or len(request_data) < 1500 * 2:
  1726. request_data += 'GET / HTTP/1.1\r\n%s\r\n' % fakeheaders_data
  1727. crlf_counter += 1
  1728. request_data += '\r\n\r\n\r\n'
  1729. request_data += '%s %s %s\r\n' % (method, path, self.protocol_version)
  1730. request_data += ''.join('%s: %s\r\n' % (k.title(), v) for k, v in headers.items() if k.title() not in self.skip_headers)
  1731. request_data += '\r\n'
  1732. if isinstance(body, bytes):
  1733. sock.sendall(request_data.encode() + body)
  1734. elif hasattr(body, 'read'):
  1735. sock.sendall(request_data)
  1736. while 1:
  1737. data = body.read(bufsize)
  1738. if not data:
  1739. break
  1740. sock.sendall(data)
  1741. else:
  1742. raise TypeError('create_http_request(body) must be a string or buffer, not %r' % type(body))
  1743. response = None
  1744. try:
  1745. while crlf_counter:
  1746. if sys.version[:3] == '2.7':
  1747. response = httplib.HTTPResponse(sock, buffering=False)
  1748. else:
  1749. response = httplib.HTTPResponse(sock)
  1750. response.fp.close()
  1751. response.fp = sock.makefile('rb', 0)
  1752. response.begin()
  1753. response.read()
  1754. response.close()
  1755. crlf_counter -= 1
  1756. except StandardError as e:
  1757. logging.exception('crlf skip read host=%r path=%r error: %r', headers.get('Host'), path, e)
  1758. if response:
  1759. if response.fp and response.fp._sock:
  1760. response.fp._sock.close()
  1761. response.close()
  1762. if sock:
  1763. sock.close()
  1764. return None
  1765. if sys.version[:3] == '2.7':
  1766. response = httplib.HTTPResponse(sock, buffering=True)
  1767. else:
  1768. response = httplib.HTTPResponse(sock)
  1769. response.fp.close()
  1770. response.fp = sock.makefile('rb')
  1771. response.begin()
  1772. if self.ssl_connection_keepalive and scheme == 'https' and cache_key:
  1773. response.cache_key = cache_key
  1774. response.cache_sock = response.fp._sock
  1775. return response
  1776. def handle_urlfetch_response_close(self, fetchserver, response):
  1777. cache_sock = getattr(response, 'cache_sock', None)
  1778. if cache_sock:
  1779. if self.scheme == 'https':
  1780. self.ssl_connection_cache[response.cache_key].put((time.time(), cache_sock))
  1781. else:
  1782. cache_sock.close()
  1783. del response.cache_sock
  1784. def handle_urlfetch_error(self, fetchserver, response):
  1785. pass
  1786. class Common(object):
  1787. """Global Config Object"""
  1788. ENV_CONFIG_PREFIX = 'GOAGENT_'
  1789. def __init__(self):
  1790. """load config from proxy.ini"""
  1791. ConfigParser.RawConfigParser.OPTCRE = re.compile(r'(?P<option>[^=\s][^=]*)\s*(?P<vi>[=])\s*(?P<value>.*)$')
  1792. self.CONFIG = ConfigParser.ConfigParser()
  1793. self.CONFIG_FILENAME = os.path.splitext(os.path.abspath(__file__))[0]+'.ini'
  1794. self.CONFIG_USER_FILENAME = re.sub(r'\.ini$', '.user.ini', self.CONFIG_FILENAME)
  1795. self.CONFIG.read([self.CONFIG_FILENAME, self.CONFIG_USER_FILENAME])
  1796. for key, value in os.environ.items():
  1797. m = re.match(r'^%s([A-Z]+)_([A-Z\_\-]+)$' % self.ENV_CONFIG_PREFIX, key)
  1798. if m:
  1799. self.CONFIG.set(m.group(1).lower(), m.group(2).lower(), value)
  1800. self.LISTEN_IP = self.CONFIG.get('listen', 'ip')
  1801. self.LISTEN_PORT = self.CONFIG.getint('listen', 'port')
  1802. self.LISTEN_USERNAME = self.CONFIG.get('listen', 'username') if self.CONFIG.has_option('listen', 'username') else ''
  1803. self.LISTEN_PASSWORD = self.CONFIG.get('listen', 'password') if self.CONFIG.has_option('listen', 'password') else ''
  1804. self.LISTEN_VISIBLE = self.CONFIG.getint('listen', 'visible')
  1805. self.LISTEN_DEBUGINFO = self.CONFIG.getint('listen', 'debuginfo')
  1806. self.GAE_APPIDS = re.findall(r'[\w\-\.]+', self.CONFIG.get('gae', 'appid').replace('.appspot.com', ''))
  1807. self.GAE_PASSWORD = self.CONFIG.get('gae', 'password').strip()
  1808. self.GAE_PATH = self.CONFIG.get('gae', 'path')
  1809. self.GAE_MODE = self.CONFIG.get('gae', 'mode')
  1810. self.GAE_PROFILE = self.CONFIG.get('gae', 'profile').strip()
  1811. self.GAE_WINDOW = self.CONFIG.getint('gae', 'window')
  1812. self.GAE_KEEPALIVE = self.CONFIG.getint('gae', 'keepalive') if self.CONFIG.has_option('gae', 'keepalive') else 0
  1813. self.GAE_OBFUSCATE = self.CONFIG.getint('gae', 'obfuscate')
  1814. self.GAE_VALIDATE = self.CONFIG.getint('gae', 'validate')
  1815. self.GAE_TRANSPORT = self.CONFIG.getint('gae', 'transport') if self.CONFIG.has_option('gae', 'transport') else 0
  1816. self.GAE_OPTIONS = self.CONFIG.get('gae', 'options')
  1817. self.GAE_REGIONS = set(x.upper() for x in self.CONFIG.get('gae', 'regions').split('|') if x.strip())
  1818. self.GAE_SSLVERSION = self.CONFIG.get('gae', 'sslversion')
  1819. self.GAE_PAGESPEED = self.CONFIG.getint('gae', 'pagespeed') if self.CONFIG.has_option('gae', 'pagespeed') else 0
  1820. if self.GAE_PROFILE == 'auto':
  1821. try:
  1822. socket.create_connection(('2001:4860:4860::8888', 53), timeout=1).close()
  1823. logging.info('Use profile ipv6')
  1824. self.GAE_PROFILE = 'ipv6'
  1825. except socket.error as e:
  1826. logging.info('Fail try profile ipv6 %r, fallback ipv4', e)
  1827. self.GAE_PROFILE = 'ipv4'
  1828. hosts_section, http_section = '%s/hosts' % self.GAE_PROFILE, '%s/http' % self.GAE_PROFILE
  1829. if 'USERDNSDOMAIN' in os.environ and re.match(r'^\w+\.\w+$', os.environ['USERDNSDOMAIN']):
  1830. self.CONFIG.set(hosts_section, '.' + os.environ['USERDNSDOMAIN'], '')
  1831. self.HOST_MAP = collections.OrderedDict((k, v or k) for k, v in self.CONFIG.items(hosts_section) if '\\' not in k and ':' not in k and not k.startswith('.'))
  1832. self.HOST_POSTFIX_MAP = collections.OrderedDict((k, v) for k, v in self.CONFIG.items(hosts_section) if '\\' not in k and ':' not in k and k.startswith('.'))
  1833. self.HOST_POSTFIX_ENDSWITH = tuple(self.HOST_POSTFIX_MAP)
  1834. self.HOSTPORT_MAP = collections.OrderedDict((k, v) for k, v in self.CONFIG.items(hosts_section) if ':' in k and not k.startswith('.'))
  1835. self.HOSTPORT_POSTFIX_MAP = collections.OrderedDict((k, v) for k, v in self.CONFIG.items(hosts_section) if ':' in k and k.startswith('.'))
  1836. self.HOSTPORT_POSTFIX_ENDSWITH = tuple(self.HOSTPORT_POSTFIX_MAP)
  1837. self.URLRE_MAP = collections.OrderedDict((re.compile(k).match, v) for k, v in self.CONFIG.items(hosts_section) if '\\' in k)
  1838. self.HTTP_WITHGAE = set(self.CONFIG.get(http_section, 'withgae').split('|'))
  1839. self.HTTP_CRLFSITES = tuple(self.CONFIG.get(http_section, 'crlfsites').split('|'))
  1840. self.HTTP_FORCEHTTPS = tuple(self.CONFIG.get(http_section, 'forcehttps').split('|')) if self.CONFIG.get(http_section, 'forcehttps').strip() else tuple()
  1841. self.HTTP_NOFORCEHTTPS = set(self.CONFIG.get(http_section, 'noforcehttps').split('|')) if self.CONFIG.get(http_section, 'noforcehttps').strip() else set()
  1842. self.HTTP_FAKEHTTPS = tuple(self.CONFIG.get(http_section, 'fakehttps').split('|')) if self.CONFIG.get(http_section, 'fakehttps').strip() else tuple()
  1843. self.HTTP_NOFAKEHTTPS = set(self.CONFIG.get(http_section, 'nofakehttps').split('|')) if self.CONFIG.get(http_section, 'nofakehttps').strip() else set()
  1844. self.HTTP_DNS = self.CONFIG.get(http_section, 'dns').split('|') if self.CONFIG.has_option(http_section, 'dns') else []
  1845. self.IPLIST_MAP = collections.OrderedDict((k, v.split('|')) for k, v in self.CONFIG.items('iplist'))
  1846. self.IPLIST_MAP.update((k, [k]) for k, v in self.HOST_MAP.items() if k == v)
  1847. self.PAC_ENABLE = self.CONFIG.getint('pac', 'enable')
  1848. self.PAC_IP = self.CONFIG.get('pac', 'ip')
  1849. self.PAC_PORT = self.CONFIG.getint('pac', 'port')
  1850. self.PAC_FILE = self.CONFIG.get('pac', 'file').lstrip('/')
  1851. self.PAC_GFWLIST = self.CONFIG.get('pac', 'gfwlist')
  1852. self.PAC_ADBLOCK = self.CONFIG.get('pac', 'adblock')
  1853. self.PAC_ADMODE = self.CONFIG.getint('pac', 'admode')
  1854. self.PAC_EXPIRED = self.CONFIG.getint('pac', 'expired')
  1855. self.PHP_ENABLE = self.CONFIG.getint('php', 'enable')
  1856. self.PHP_LISTEN = self.CONFIG.get('php', 'listen')
  1857. self.PHP_PASSWORD = self.CONFIG.get('php', 'password') if self.CONFIG.has_option('php', 'password') else ''
  1858. self.PHP_CRLF = self.CONFIG.getint('php', 'crlf') if self.CONFIG.has_option('php', 'crlf') else 1
  1859. self.PHP_VALIDATE = self.CONFIG.getint('php', 'validate') if self.CONFIG.has_option('php', 'validate') else 0
  1860. self.PHP_FETCHSERVER = self.CONFIG.get('php', 'fetchserver')
  1861. self.PHP_USEHOSTS = self.CONFIG.getint('php', 'usehosts')
  1862. self.PROXY_ENABLE = self.CONFIG.getint('proxy', 'enable')
  1863. self.PROXY_AUTODETECT = self.CONFIG.getint('proxy', 'autodetect') if self.CONFIG.has_option('proxy', 'autodetect') else 0
  1864. self.PROXY_HOST = self.CONFIG.get('proxy', 'host')
  1865. self.PROXY_PORT = self.CONFIG.getint('proxy', 'port')
  1866. self.PROXY_USERNAME = self.CONFIG.get('proxy', 'username')
  1867. self.PROXY_PASSWROD = self.CONFIG.get('proxy', 'password')
  1868. if not self.PROXY_ENABLE and self.PROXY_AUTODETECT:
  1869. system_proxy = ProxyUtil.get_system_proxy()
  1870. if system_proxy and self.LISTEN_IP not in system_proxy:
  1871. _, username, password, address = ProxyUtil.parse_proxy(system_proxy)
  1872. proxyhost, _, proxyport = address.rpartition(':')
  1873. self.PROXY_ENABLE = 1
  1874. self.PROXY_USERNAME = username
  1875. self.PROXY_PASSWROD = password
  1876. self.PROXY_HOST = proxyhost
  1877. self.PROXY_PORT = int(proxyport)
  1878. if self.PROXY_ENABLE:
  1879. self.GAE_MODE = 'https'
  1880. self.AUTORANGE_HOSTS = self.CONFIG.get('autorange', 'hosts').split('|')
  1881. self.AUTORANGE_HOSTS_MATCH = [re.compile(fnmatch.translate(h)).match for h in self.AUTORANGE_HOSTS]
  1882. self.AUTORANGE_ENDSWITH = tuple(self.CONFIG.get('autorange', 'endswith').split('|'))
  1883. self.AUTORANGE_NOENDSWITH = tuple(self.CONFIG.get('autorange', 'noendswith').split('|'))
  1884. self.AUTORANGE_MAXSIZE = self.CONFIG.getint('autorange', 'maxsize')
  1885. self.AUTORANGE_WAITSIZE = self.CONFIG.getint('autorange', 'waitsize')
  1886. self.AUTORANGE_BUFSIZE = self.CONFIG.getint('autorange', 'bufsize')
  1887. self.AUTORANGE_THREADS = self.CONFIG.getint('autorange', 'threads')
  1888. self.FETCHMAX_LOCAL = self.CONFIG.getint('fetchmax', 'local') if self.CONFIG.get('fetchmax', 'local') else 3
  1889. self.FETCHMAX_SERVER = self.CONFIG.get('fetchmax', 'server')
  1890. self.DNS_ENABLE = self.CONFIG.getint('dns', 'enable')
  1891. self.DNS_LISTEN = self.CONFIG.get('dns', 'listen')
  1892. self.DNS_SERVERS = self.HTTP_DNS or self.CONFIG.get('dns', 'servers').split('|')
  1893. self.DNS_BLACKLIST = set(self.CONFIG.get('dns', 'blacklist').split('|'))
  1894. self.DNS_TCPOVER = tuple(self.CONFIG.get('dns', 'tcpover').split('|')) if self.CONFIG.get('dns', 'tcpover').strip() else tuple()
  1895. self.USERAGENT_ENABLE = self.CONFIG.getint('useragent', 'enable')
  1896. self.USERAGENT_STRING = self.CONFIG.get('useragent', 'string')
  1897. self.LOVE_ENABLE = self.CONFIG.getint('love', 'enable')
  1898. self.LOVE_TIP = self.CONFIG.get('love', 'tip').encode('utf8').decode('unicode-escape').split('|')
  1899. def extend_iplist(self, iplist_name, hosts):
  1900. logging.info('extend_iplist start for hosts=%s', hosts)
  1901. new_iplist = []
  1902. def do_remote_resolve(host, dnsserver, queue):
  1903. assert isinstance(dnsserver, basestring)
  1904. for dnslib_resolve in (dnslib_resolve_over_udp, dnslib_resolve_over_tcp):
  1905. try:
  1906. time.sleep(random.random())
  1907. iplist = dnslib_record2iplist(dnslib_resolve(host, [dnsserver], timeout=4, blacklist=self.DNS_BLACKLIST))
  1908. queue.put((host, dnsserver, iplist))
  1909. except (socket.error, OSError) as e:
  1910. logging.warning('%r remote host=%r failed: %s', dnslib_resolve, host, e)
  1911. time.sleep(1)
  1912. result_queue = Queue.Queue()
  1913. for host in hosts:
  1914. for dnsserver in self.DNS_SERVERS:
  1915. logging.debug('remote resolve host=%r from dnsserver=%r', host, dnsserver)
  1916. thread.start_new_thread(do_remote_resolve, (host, dnsserver, result_queue))
  1917. for _ in xrange(len(self.DNS_SERVERS) * len(hosts) * 2):
  1918. try:
  1919. host, dnsserver, iplist = result_queue.get(timeout=16)
  1920. logging.debug('%r remote host=%r return %s', dnsserver, host, iplist)
  1921. if host.endswith('.google.com'):
  1922. iplist = [x for x in iplist if is_google_ip(x)]
  1923. new_iplist += iplist
  1924. except Queue.Empty:
  1925. break
  1926. logging.info('extend_iplist finished, added %s', len(set(self.IPLIST_MAP[iplist_name])-set(new_iplist)))
  1927. self.IPLIST_MAP[iplist_name] = list(set(self.IPLIST_MAP[iplist_name] + new_iplist))
  1928. def resolve_iplist(self):
  1929. # https://support.google.com/websearch/answer/186669?hl=zh-Hans
  1930. def do_local_resolve(host, queue):
  1931. assert isinstance(host, basestring)
  1932. for _ in xrange(3):
  1933. try:
  1934. queue.put((host, socket.gethostbyname_ex(host)[-1]))
  1935. except (socket.error, OSError) as e:
  1936. logging.warning('socket.gethostbyname_ex host=%r failed: %s', host, e)
  1937. time.sleep(0.1)
  1938. google_blacklist = ['216.239.32.20'] + list(self.DNS_BLACKLIST)
  1939. for name, need_resolve_hosts in list(self.IPLIST_MAP.items()):
  1940. if all(re.match(r'\d+\.\d+\.\d+\.\d+', x) or ':' in x for x in need_resolve_hosts):
  1941. continue
  1942. need_resolve_remote = [x for x in need_resolve_hosts if ':' not in x and not re.match(r'\d+\.\d+\.\d+\.\d+', x)]
  1943. resolved_iplist = [x for x in need_resolve_hosts if x not in need_resolve_remote]
  1944. result_queue = Queue.Queue()
  1945. for host in need_resolve_remote:
  1946. logging.debug('local resolve host=%r', host)
  1947. thread.start_new_thread(do_local_resolve, (host, result_queue))
  1948. for _ in xrange(len(need_resolve_remote)):
  1949. try:
  1950. host, iplist = result_queue.get(timeout=8)
  1951. if host.endswith('.google.com'):
  1952. iplist = [x for x in iplist if is_google_ip(x)]
  1953. resolved_iplist += iplist
  1954. except Queue.Empty:
  1955. break
  1956. if name == 'google_hk':
  1957. for delay in (1, 60, 150, 240, 300, 450, 600, 900):
  1958. spawn_later(delay, self.extend_iplist, name, need_resolve_remote)
  1959. if name.startswith('google_') and name not in ('google_cn', 'google_hk') and resolved_iplist:
  1960. iplist_prefix = re.split(r'[\.:]', resolved_iplist[0])[0]
  1961. resolved_iplist = list(set(x for x in resolved_iplist if x.startswith(iplist_prefix)))
  1962. else:
  1963. resolved_iplist = list(set(resolved_iplist))
  1964. if name.startswith('google_'):
  1965. resolved_iplist = list(set(resolved_iplist) - set(google_blacklist))
  1966. if len(resolved_iplist) == 0:
  1967. logging.error('resolve %s host return empty! please retry!', name)
  1968. sys.exit(-1)
  1969. logging.info('resolve name=%s host to iplist=%r', name, resolved_iplist)
  1970. common.IPLIST_MAP[name] = resolved_iplist
  1971. def info(self):
  1972. info = ''
  1973. info += '------------------------------------------------------\n'
  1974. info += 'GoAgent Version : %s (python/%s %spyopenssl/%s)\n' % (__version__, sys.version[:5], gevent and 'gevent/%s ' % gevent.__version__ or '', getattr(OpenSSL, '__version__', 'Disabled'))
  1975. info += 'Uvent Version : %s (pyuv/%s libuv/%s)\n' % (__import__('uvent').__version__, __import__('pyuv').__version__, __import__('pyuv').LIBUV_VERSION) if all(x in sys.modules for x in ('pyuv', 'uvent')) else ''
  1976. info += 'Listen Address : %s:%d\n' % (self.LISTEN_IP, self.LISTEN_PORT)
  1977. info += 'Local Proxy : %s:%s\n' % (self.PROXY_HOST, self.PROXY_PORT) if self.PROXY_ENABLE else ''
  1978. info += 'Debug INFO : %s\n' % self.LISTEN_DEBUGINFO if self.LISTEN_DEBUGINFO else ''
  1979. info += 'GAE Mode : %s\n' % self.GAE_MODE
  1980. info += 'GAE Profile : %s\n' % self.GAE_PROFILE if self.GAE_PROFILE else ''
  1981. info += 'GAE APPID : %s\n' % '|'.join(self.GAE_APPIDS)
  1982. info += 'GAE Validate : %s\n' % self.GAE_VALIDATE if self.GAE_VALIDATE else ''
  1983. info += 'GAE Obfuscate : %s\n' % self.GAE_OBFUSCATE if self.GAE_OBFUSCATE else ''
  1984. if common.PAC_ENABLE:
  1985. info += 'Pac Server : http://%s:%d/%s\n' % (self.PAC_IP if self.PAC_IP and self.PAC_IP != '0.0.0.0' else ProxyUtil.get_listen_ip(), self.PAC_PORT, self.PAC_FILE)
  1986. info += 'Pac File : file://%s\n' % os.path.abspath(self.PAC_FILE)
  1987. if common.PHP_ENABLE:
  1988. info += 'PHP Listen : %s\n' % common.PHP_LISTEN
  1989. info += 'PHP FetchServer : %s\n' % common.PHP_FETCHSERVER
  1990. if common.DNS_ENABLE:
  1991. info += 'DNS Listen : %s\n' % common.DNS_LISTEN
  1992. info += 'DNS Servers : %s\n' % '|'.join(common.DNS_SERVERS)
  1993. info += '------------------------------------------------------\n'
  1994. return info
  1995. common = Common()
  1996. def message_html(title, banner, detail=''):
  1997. MESSAGE_TEMPLATE = '''
  1998. <html><head>
  1999. <meta http-equiv="content-type" content="text/html;charset=utf-8">
  2000. <title>$title</title>
  2001. <style><!--
  2002. body {font-family: arial,sans-serif}
  2003. div.nav {margin-top: 1ex}
  2004. div.nav A {font-size: 10pt; font-family: arial,sans-serif}
  2005. span.nav {font-size: 10pt; font-family: arial,sans-serif; font-weight: bold}
  2006. div.nav A,span.big {font-size: 12pt; color: #0000cc}
  2007. div.nav A {font-size: 10pt; color: black}
  2008. A.l:link {color: #6f6f6f}
  2009. A.u:link {color: green}
  2010. //--></style>
  2011. </head>
  2012. <body text=#000000 bgcolor=#ffffff>
  2013. <table border=0 cellpadding=2 cellspacing=0 width=100%>
  2014. <tr><td bgcolor=#3366cc><font face=arial,sans-serif color=#ffffff><b>Message From LocalProxy</b></td></tr>
  2015. <tr><td> </td></tr></table>
  2016. <blockquote>
  2017. <H1>$banner</H1>
  2018. $detail
  2019. <p>
  2020. </blockquote>
  2021. <table width=100% cellpadding=0 cellspacing=0><tr><td bgcolor=#3366cc><img alt="" width=1 height=4></td></tr></table>
  2022. </body></html>
  2023. '''
  2024. return string.Template(MESSAGE_TEMPLATE).substitute(title=title, banner=banner, detail=detail)
  2025. try:
  2026. from Crypto.Cipher.ARC4 import new as RC4Cipher
  2027. except ImportError:
  2028. logging.warn('Load Crypto.Cipher.ARC4 Failed, Use Pure Python Instead.')
  2029. class RC4Cipher(object):
  2030. def __init__(self, key):
  2031. x = 0
  2032. box = range(256)
  2033. for i, y in enumerate(box):
  2034. x = (x + y + ord(key[i % len(key)])) & 0xff
  2035. box[i], box[x] = box[x], y
  2036. self.__box = box
  2037. self.__x = 0
  2038. self.__y = 0
  2039. def encrypt(self, data):
  2040. out = []
  2041. out_append = out.append
  2042. x = self.__x
  2043. y = self.__y
  2044. box = self.__box
  2045. for char in data:
  2046. x = (x + 1) & 0xff
  2047. y = (y + box[x]) & 0xff
  2048. box[x], box[y] = box[y], box[x]
  2049. out_append(chr(ord(char) ^ box[(box[x] + box[y]) & 0xff]))
  2050. self.__x = x
  2051. self.__y = y
  2052. return ''.join(out)
  2053. class XORCipher(object):
  2054. """XOR Cipher Class"""
  2055. def __init__(self, key):
  2056. self.__key_gen = itertools.cycle([ord(x) for x in key]).next
  2057. self.__key_xor = lambda s: ''.join(chr(ord(x) ^ self.__key_gen()) for x in s)
  2058. if len(key) == 1:
  2059. try:
  2060. from Crypto.Util.strxor import strxor_c
  2061. c = ord(key)
  2062. self.__key_xor = lambda s: strxor_c(s, c)
  2063. except ImportError:
  2064. sys.stderr.write('Load Crypto.Util.strxor Failed, Use Pure Python Instead.\n')
  2065. def encrypt(self, data):
  2066. return self.__key_xor(data)
  2067. class CipherFileObject(object):
  2068. """fileobj wrapper for cipher"""
  2069. def __init__(self, fileobj, cipher):
  2070. self.__fileobj = fileobj
  2071. self.__cipher = cipher
  2072. def __getattr__(self, attr):
  2073. if attr not in ('__fileobj', '__cipher'):
  2074. return getattr(self.__fileobj, attr)
  2075. def read(self, size=-1):
  2076. return self.__cipher.encrypt(self.__fileobj.read(size))
  2077. class LocalProxyServer(SocketServer.ThreadingTCPServer):
  2078. """Local Proxy Server"""
  2079. allow_reuse_address = True
  2080. daemon_threads = True
  2081. def close_request(self, request):
  2082. try:
  2083. request.close()
  2084. except StandardError:
  2085. pass
  2086. def finish_request(self, request, client_address):
  2087. try:
  2088. self.RequestHandlerClass(request, client_address, self)
  2089. except NetWorkIOError as e:
  2090. if e[0] not in (errno.ECONNABORTED, errno.ECONNRESET, errno.EPIPE):
  2091. raise
  2092. def handle_error(self, *args):
  2093. """make ThreadingTCPServer happy"""
  2094. exc_info = sys.exc_info()
  2095. error = exc_info and len(exc_info) and exc_info[1]
  2096. if isinstance(error, NetWorkIOError) and len(error.args) > 1 and 'bad write retry' in error.args[1]:
  2097. exc_info = error = None
  2098. else:
  2099. del exc_info, error
  2100. SocketServer.ThreadingTCPServer.handle_error(self, *args)
  2101. class UserAgentFilter(BaseProxyHandlerFilter):
  2102. """user agent filter"""
  2103. def filter(self, handler):
  2104. if common.USERAGENT_ENABLE:
  2105. handler.headers['User-Agent'] = common.USERAGENT_STRING
  2106. class WithGAEFilter(BaseProxyHandlerFilter):
  2107. """with gae filter"""
  2108. def filter(self, handler):
  2109. if handler.host in common.HTTP_WITHGAE:
  2110. logging.debug('WithGAEFilter metched %r %r', handler.path, handler.headers)
  2111. # assume the last one handler is GAEFetchFilter
  2112. return handler.handler_filters[-1].filter(handler)
  2113. class ForceHttpsFilter(BaseProxyHandlerFilter):
  2114. """force https filter"""
  2115. def filter(self, handler):
  2116. if handler.command != 'CONNECT' and handler.host.endswith(common.HTTP_FORCEHTTPS) and handler.host not in common.HTTP_NOFORCEHTTPS:
  2117. if not handler.headers.get('Referer', '').startswith('https://') and not handler.path.startswith('https://'):
  2118. logging.debug('ForceHttpsFilter metched %r %r', handler.path, handler.headers)
  2119. headers = {'Location': handler.path.replace('http://', 'https://', 1), 'Connection': 'close'}
  2120. return [handler.MOCK, 301, headers, '']
  2121. class FakeHttpsFilter(BaseProxyHandlerFilter):
  2122. """fake https filter"""
  2123. def filter(self, handler):
  2124. if handler.command == 'CONNECT' and handler.host.endswith(common.HTTP_FAKEHTTPS) and handler.host not in common.HTTP_NOFAKEHTTPS:
  2125. logging.debug('FakeHttpsFilter metched %r %r', handler.path, handler.headers)
  2126. return [handler.STRIP, True, None]
  2127. class URLRewriteFilter(BaseProxyHandlerFilter):
  2128. """url rewrite filter"""
  2129. rules = {
  2130. 'www.google.com': (r'^https?://www\.google\.com/url\?.*url=([^&]+)', lambda m: urllib.unquote_plus(m.group(1))),
  2131. 'www.google.com.hk': (r'^https?://www\.google\.com\.hk/url\?.*url=([^&]+)', lambda m: urllib.unquote_plus(m.group(1))),
  2132. }
  2133. def filter(self, handler):
  2134. if handler.host in self.rules:
  2135. pattern, callback = self.rules[handler.host]
  2136. m = re.search(pattern, handler.path)
  2137. if m:
  2138. logging.debug('URLRewriteFilter metched %r', handler.path)
  2139. headers = {'Location': callback(m), 'Connection': 'close'}
  2140. return [handler.MOCK, 301, headers, '']
  2141. class HostsFilter(BaseProxyHandlerFilter):
  2142. """force https filter"""
  2143. def filter_localfile(self, handler, filename):
  2144. content_type = None
  2145. try:
  2146. import mimetypes
  2147. content_type = mimetypes.types_map.get(os.path.splitext(filename)[1])
  2148. except StandardError as e:
  2149. logging.error('import mimetypes failed: %r', e)
  2150. try:
  2151. with open(filename, 'rb') as fp:
  2152. data = fp.read()
  2153. headers = {'Connection': 'close', 'Content-Length': str(len(data))}
  2154. if content_type:
  2155. headers['Content-Type'] = content_type
  2156. return [handler.MOCK, 200, headers, data]
  2157. except StandardError as e:
  2158. return [handler.MOCK, 403, {'Connection': 'close'}, 'read %r %r' % (filename, e)]
  2159. def filter(self, handler):
  2160. host, port = handler.host, handler.port
  2161. hostport = handler.path if handler.command == 'CONNECT' else '%s:%d' % (host, port)
  2162. hostname = ''
  2163. if host in common.HOST_MAP:
  2164. hostname = common.HOST_MAP[host] or host
  2165. elif host.endswith(common.HOST_POSTFIX_ENDSWITH):
  2166. hostname = next(common.HOST_POSTFIX_MAP[x] for x in common.HOST_POSTFIX_MAP if host.endswith(x)) or host
  2167. common.HOST_MAP[host] = hostname
  2168. if hostport in common.HOSTPORT_MAP:
  2169. hostname = common.HOSTPORT_MAP[hostport] or host
  2170. elif hostport.endswith(common.HOSTPORT_POSTFIX_ENDSWITH):
  2171. hostname = next(common.HOSTPORT_POSTFIX_MAP[x] for x in common.HOSTPORT_POSTFIX_MAP if hostport.endswith(x)) or host
  2172. common.HOSTPORT_MAP[hostport] = hostname
  2173. if handler.command != 'CONNECT' and common.URLRE_MAP:
  2174. try:
  2175. hostname = next(common.URLRE_MAP[x] for x in common.URLRE_MAP if x(handler.path)) or host
  2176. except StopIteration:
  2177. pass
  2178. if not hostname:
  2179. return None
  2180. elif hostname in common.IPLIST_MAP:
  2181. handler.dns_cache[host] = common.IPLIST_MAP[hostname]
  2182. elif hostname == host and host.endswith(common.DNS_TCPOVER) and host not in handler.dns_cache:
  2183. try:
  2184. iplist = dnslib_record2iplist(dnslib_resolve_over_tcp(host, handler.dns_servers, timeout=4, blacklist=handler.dns_blacklist))
  2185. logging.info('HostsFilter dnslib_resolve_over_tcp %r with %r return %s', host, handler.dns_servers, iplist)
  2186. handler.dns_cache[host] = iplist
  2187. except socket.error as e:
  2188. logging.warning('HostsFilter dnslib_resolve_over_tcp %r with %r failed: %r', host, handler.dns_servers, e)
  2189. elif re.match(r'^\d+\.\d+\.\d+\.\d+$', hostname) or ':' in hostname:
  2190. handler.dns_cache[host] = [hostname]
  2191. elif hostname.startswith('file://'):
  2192. filename = hostname.lstrip('file://')
  2193. if os.name == 'nt':
  2194. filename = filename.lstrip('/')
  2195. return self.filter_localfile(handler, filename)
  2196. cache_key = '%s:%s' % (hostname, port)
  2197. if handler.command == 'CONNECT':
  2198. return [handler.FORWARD, host, port, handler.connect_timeout, {'cache_key': cache_key}]
  2199. else:
  2200. if host.endswith(common.HTTP_CRLFSITES):
  2201. handler.close_connection = True
  2202. return [handler.DIRECT, {'crlf': True}]
  2203. else:
  2204. return [handler.DIRECT, {'cache_key': cache_key}]
  2205. class DirectRegionFilter(BaseProxyHandlerFilter):
  2206. """direct region filter"""
  2207. geoip = pygeoip.GeoIP(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'GeoIP.dat')) if pygeoip and common.GAE_REGIONS else None
  2208. region_cache = LRUCache(16*1024)
  2209. def get_country_code(self, hostname, dnsservers):
  2210. """http://dev.maxmind.com/geoip/legacy/codes/iso3166/"""
  2211. try:
  2212. return self.region_cache[hostname]
  2213. except KeyError:
  2214. pass
  2215. try:
  2216. if re.match(r'^\d+\.\d+\.\d+\.\d+$', hostname) or ':' in hostname:
  2217. iplist = [hostname]
  2218. elif dnsservers:
  2219. iplist = dnslib_record2iplist(dnslib_resolve_over_udp(hostname, dnsservers, timeout=2))
  2220. else:
  2221. iplist = socket.gethostbyname_ex(hostname)[-1]
  2222. country_code = self.geoip.country_code_by_addr(iplist[0])
  2223. except StandardError as e:
  2224. logging.warning('DirectRegionFilter cannot determine region for hostname=%r %r', hostname, e)
  2225. country_code = ''
  2226. self.region_cache[hostname] = country_code
  2227. return country_code
  2228. def filter(self, handler):
  2229. if self.geoip:
  2230. country_code = self.get_country_code(handler.host, handler.dns_servers)
  2231. if country_code in common.GAE_REGIONS:
  2232. if handler.command == 'CONNECT':
  2233. return [handler.FORWARD, handler.host, handler.port, handler.connect_timeout]
  2234. else:
  2235. return [handler.DIRECT, {}]
  2236. class AutoRangeFilter(BaseProxyHandlerFilter):
  2237. """force https filter"""
  2238. def filter(self, handler):
  2239. path = urlparse.urlsplit(handler.path).path
  2240. need_autorange = any(x(handler.host) for x in common.AUTORANGE_HOSTS_MATCH) or path.endswith(common.AUTORANGE_ENDSWITH)
  2241. if path.endswith(common.AUTORANGE_NOENDSWITH) or 'range=' in urlparse.urlsplit(path).query or handler.command == 'HEAD':
  2242. need_autorange = False
  2243. if handler.command != 'HEAD' and handler.headers.get('Range'):
  2244. m = re.search(r'bytes=(\d+)-', handler.headers['Range'])
  2245. start = int(m.group(1) if m else 0)
  2246. handler.headers['Range'] = 'bytes=%d-%d' % (start, start+common.AUTORANGE_MAXSIZE-1)
  2247. logging.info('autorange range=%r match url=%r', handler.headers['Range'], handler.path)
  2248. elif need_autorange:
  2249. logging.info('Found [autorange]endswith match url=%r', handler.path)
  2250. m = re.search(r'bytes=(\d+)-', handler.headers.get('Range', ''))
  2251. start = int(m.group(1) if m else 0)
  2252. handler.headers['Range'] = 'bytes=%d-%d' % (start, start+common.AUTORANGE_MAXSIZE-1)
  2253. class GAEFetchFilter(BaseProxyHandlerFilter):
  2254. """force https filter"""
  2255. def filter(self, handler):
  2256. """https://developers.google.com/appengine/docs/python/urlfetch/"""
  2257. if handler.command == 'CONNECT':
  2258. do_ssl_handshake = 440 <= handler.port <= 450 or 1024 <= handler.port <= 65535
  2259. return [handler.STRIP, do_ssl_handshake, self if not common.URLRE_MAP else None]
  2260. elif handler.command in ('GET', 'POST', 'HEAD', 'PUT', 'DELETE', 'PATCH'):
  2261. kwargs = {}
  2262. if common.GAE_PASSWORD:
  2263. kwargs['password'] = common.GAE_PASSWORD
  2264. if common.GAE_VALIDATE:
  2265. kwargs['validate'] = 1
  2266. fetchservers = ['%s://%s.appspot.com%s' % (common.GAE_MODE, x, common.GAE_PATH) for x in common.GAE_APPIDS]
  2267. return [handler.URLFETCH, fetchservers, common.FETCHMAX_LOCAL, kwargs]
  2268. else:
  2269. if common.PHP_ENABLE:
  2270. return PHPProxyHandler.handler_filters[-1].filter(handler)
  2271. else:
  2272. logging.warning('"%s %s" not supported by GAE, please enable PHP mode!', handler.command, handler.host)
  2273. return [handler.DIRECT, {}]
  2274. class GAEProxyHandler(AdvancedProxyHandler):
  2275. """GAE Proxy Handler"""
  2276. handler_filters = [UserAgentFilter(), WithGAEFilter(), FakeHttpsFilter(), ForceHttpsFilter(), URLRewriteFilter(), HostsFilter(), DirectRegionFilter(), AutoRangeFilter(), GAEFetchFilter()]
  2277. def first_run(self):
  2278. """GAEProxyHandler setup, init domain/iplist map"""
  2279. if not common.PROXY_ENABLE:
  2280. logging.info('resolve common.IPLIST_MAP names=%s to iplist', list(common.IPLIST_MAP))
  2281. common.resolve_iplist()
  2282. random.shuffle(common.GAE_APPIDS)
  2283. def gethostbyname2(self, hostname):
  2284. for postfix in ('.appspot.com', '.googleusercontent.com'):
  2285. if hostname.endswith(postfix):
  2286. host = common.HOST_MAP.get(hostname) or common.HOST_POSTFIX_MAP[postfix]
  2287. return common.IPLIST_MAP.get(host) or host.split('|')
  2288. return AdvancedProxyHandler.gethostbyname2(self, hostname)
  2289. def handle_urlfetch_error(self, fetchserver, response):
  2290. gae_appid = urlparse.urlsplit(fetchserver).hostname.split('.')[-3]
  2291. if response.app_status == 503:
  2292. # appid over qouta, switch to next appid
  2293. if gae_appid == common.GAE_APPIDS[0] and len(common.GAE_APPIDS) > 1:
  2294. common.GAE_APPIDS.append(common.GAE_APPIDS.pop(0))
  2295. logging.info('gae_appid=%r over qouta, switch next appid=%r', gae_appid, common.GAE_APPIDS[0])
  2296. class PHPFetchFilter(BaseProxyHandlerFilter):
  2297. """force https filter"""
  2298. def filter(self, handler):
  2299. if handler.command == 'CONNECT':
  2300. return [handler.STRIP, True, self]
  2301. else:
  2302. kwargs = {}
  2303. if common.PHP_PASSWORD:
  2304. kwargs['password'] = common.PHP_PASSWORD
  2305. if common.PHP_VALIDATE:
  2306. kwargs['validate'] = 1
  2307. return [handler.URLFETCH, [common.PHP_FETCHSERVER], 1, kwargs]
  2308. class PHPProxyHandler(AdvancedProxyHandler):
  2309. """PHP Proxy Handler"""
  2310. first_run_lock = threading.Lock()
  2311. handler_filters = [UserAgentFilter(), FakeHttpsFilter(), ForceHttpsFilter(), PHPFetchFilter()]
  2312. def first_run(self):
  2313. if common.PHP_USEHOSTS:
  2314. self.handler_filters.insert(-1, HostsFilter())
  2315. if not common.PROXY_ENABLE:
  2316. common.resolve_iplist()
  2317. fetchhost = urlparse.urlsplit(common.PHP_FETCHSERVER).hostname
  2318. logging.info('resolve common.PHP_FETCHSERVER domain=%r to iplist', fetchhost)
  2319. if common.PHP_USEHOSTS and fetchhost in common.HOST_MAP:
  2320. hostname = common.HOST_MAP[fetchhost]
  2321. fetchhost_iplist = sum([socket.gethostbyname_ex(x)[-1] for x in common.IPLIST_MAP.get(hostname) or hostname.split('|')], [])
  2322. else:
  2323. fetchhost_iplist = self.gethostbyname2(fetchhost)
  2324. if len(fetchhost_iplist) == 0:
  2325. logging.error('resolve %r domain return empty! please use ip list to replace domain list!', fetchhost)
  2326. sys.exit(-1)
  2327. self.dns_cache[fetchhost] = list(set(fetchhost_iplist))
  2328. logging.info('resolve common.PHP_FETCHSERVER domain to iplist=%r', fetchhost_iplist)
  2329. return True
  2330. class ProxyChainMixin:
  2331. """proxy chain mixin"""
  2332. def gethostbyname2(self, hostname):
  2333. try:
  2334. return socket.gethostbyname_ex(hostname)[-1]
  2335. except socket.error:
  2336. return [hostname]
  2337. def create_tcp_connection(self, hostname, port, timeout, **kwargs):
  2338. sock = socket.create_connection((common.PROXY_HOST, int(common.PROXY_PORT)))
  2339. if hostname.endswith('.appspot.com'):
  2340. hostname = 'www.google.com'
  2341. request_data = 'CONNECT %s:%s HTTP/1.1\r\n' % (hostname, port)
  2342. if common.PROXY_USERNAME and common.PROXY_PASSWROD:
  2343. request_data += 'Proxy-Authorization: Basic %s\r\n' % base64.b64encode(('%s:%s' % (common.PROXY_USERNAME, common.PROXY_PASSWROD)).encode()).decode().strip()
  2344. request_data += '\r\n'
  2345. sock.sendall(request_data)
  2346. response = httplib.HTTPResponse(sock)
  2347. response.fp.close()
  2348. response.fp = sock.makefile('rb', 0)
  2349. response.begin()
  2350. if response.status >= 400:
  2351. raise httplib.BadStatusLine('%s %s %s' % (response.version, response.status, response.reason))
  2352. return sock
  2353. def create_ssl_connection(self, hostname, port, timeout, **kwargs):
  2354. sock = self.create_tcp_connection(hostname, port, timeout, **kwargs)
  2355. ssl_sock = ssl.wrap_socket(sock)
  2356. return ssl_sock
  2357. class GreenForwardMixin:
  2358. """green forward mixin"""
  2359. @staticmethod
  2360. def io_copy(dest, source, timeout, bufsize):
  2361. try:
  2362. dest.settimeout(timeout)
  2363. source.settimeout(timeout)
  2364. while 1:
  2365. data = source.recv(bufsize)
  2366. if not data:
  2367. break
  2368. dest.sendall(data)
  2369. except socket.timeout:
  2370. pass
  2371. except NetWorkIOError as e:
  2372. if e.args[0] not in (errno.ECONNABORTED, errno.ECONNRESET, errno.ENOTCONN, errno.EPIPE):
  2373. raise
  2374. if e.args[0] in (errno.EBADF,):
  2375. return
  2376. finally:
  2377. for sock in (dest, source):
  2378. try:
  2379. sock.close()
  2380. except StandardError:
  2381. pass
  2382. def forward_socket(self, local, remote, timeout):
  2383. """forward socket"""
  2384. bufsize = self.bufsize
  2385. thread.start_new_thread(GreenForwardMixin.io_copy, (remote.dup(), local.dup(), timeout, bufsize))
  2386. GreenForwardMixin.io_copy(local, remote, timeout, bufsize)
  2387. class ProxyChainGAEProxyHandler(ProxyChainMixin, GAEProxyHandler):
  2388. pass
  2389. class ProxyChainPHPProxyHandler(ProxyChainMixin, PHPProxyHandler):
  2390. pass
  2391. class GreenForwardGAEProxyHandler(GreenForwardMixin, GAEProxyHandler):
  2392. pass
  2393. class GreenForwardPHPProxyHandler(GreenForwardMixin, PHPProxyHandler):
  2394. pass
  2395. class ProxyChainGreenForwardGAEProxyHandler(ProxyChainMixin, GreenForwardGAEProxyHandler):
  2396. pass
  2397. class ProxyChainGreenForwardPHPProxyHandler(ProxyChainMixin, GreenForwardPHPProxyHandler):
  2398. pass
  2399. def get_uptime():
  2400. if os.name == 'nt':
  2401. import ctypes
  2402. try:
  2403. tick = ctypes.windll.kernel32.GetTickCount64()
  2404. except AttributeError:
  2405. tick = ctypes.windll.kernel32.GetTickCount()
  2406. return tick / 1000.0
  2407. elif os.path.isfile('/proc/uptime'):
  2408. with open('/proc/uptime', 'rb') as fp:
  2409. uptime = fp.readline().strip().split()[0].strip()
  2410. return float(uptime)
  2411. elif any(os.path.isfile(os.path.join(x, 'uptime')) for x in os.environ['PATH'].split(os.pathsep)):
  2412. # http://www.opensource.apple.com/source/lldb/lldb-69/test/pexpect-2.4/examples/uptime.py
  2413. pattern = r'up\s+(.*?),\s+([0-9]+) users?,\s+load averages?: ([0-9]+\.[0-9][0-9]),?\s+([0-9]+\.[0-9][0-9]),?\s+([0-9]+\.[0-9][0-9])'
  2414. output = os.popen('uptime').read()
  2415. duration, _, _, _, _ = re.search(pattern, output).groups()
  2416. days, hours, mins = 0, 0, 0
  2417. if 'day' in duration:
  2418. m = re.search(r'([0-9]+)\s+day', duration)
  2419. days = int(m.group(1))
  2420. if ':' in duration:
  2421. m = re.search(r'([0-9]+):([0-9]+)', duration)
  2422. hours = int(m.group(1))
  2423. mins = int(m.group(2))
  2424. if 'min' in duration:
  2425. m = re.search(r'([0-9]+)\s+min', duration)
  2426. mins = int(m.group(1))
  2427. return days * 86400 + hours * 3600 + mins * 60
  2428. else:
  2429. #TODO: support other platforms
  2430. return None
  2431. class PacUtil(object):
  2432. """GoAgent Pac Util"""
  2433. @staticmethod
  2434. def update_pacfile(filename):
  2435. listen_ip = '127.0.0.1'
  2436. autoproxy = '%s:%s' % (listen_ip, common.LISTEN_PORT)
  2437. blackhole = '%s:%s' % (listen_ip, common.PAC_PORT)
  2438. default = 'PROXY %s:%s' % (common.PROXY_HOST, common.PROXY_PORT) if common.PROXY_ENABLE else 'DIRECT'
  2439. opener = urllib2.build_opener(urllib2.ProxyHandler({'http': autoproxy, 'https': autoproxy}))
  2440. content = ''
  2441. need_update = True
  2442. with open(filename, 'rb') as fp:
  2443. content = fp.read()
  2444. try:
  2445. placeholder = '// AUTO-GENERATED RULES, DO NOT MODIFY!'
  2446. content = content[:content.index(placeholder)+len(placeholder)]
  2447. content = re.sub(r'''blackhole\s*=\s*['"]PROXY [\.\w:]+['"]''', 'blackhole = \'PROXY %s\'' % blackhole, content)
  2448. content = re.sub(r'''autoproxy\s*=\s*['"]PROXY [\.\w:]+['"]''', 'autoproxy = \'PROXY %s\'' % autoproxy, content)
  2449. content = re.sub(r'''defaultproxy\s*=\s*['"](DIRECT|PROXY [\.\w:]+)['"]''', 'defaultproxy = \'%s\'' % default, content)
  2450. content = re.sub(r'''host\s*==\s*['"][\.\w:]+['"]\s*\|\|\s*isPlainHostName''', 'host == \'%s\' || isPlainHostName' % listen_ip, content)
  2451. if content.startswith('//'):
  2452. line = '// Proxy Auto-Config file generated by autoproxy2pac, %s\r\n' % time.strftime('%Y-%m-%d %H:%M:%S')
  2453. content = line + '\r\n'.join(content.splitlines()[1:])
  2454. except ValueError:
  2455. need_update = False
  2456. try:
  2457. if common.PAC_ADBLOCK:
  2458. admode = common.PAC_ADMODE
  2459. logging.info('try download %r to update_pacfile(%r)', common.PAC_ADBLOCK, filename)
  2460. adblock_content = opener.open(common.PAC_ADBLOCK).read()
  2461. logging.info('%r downloaded, try convert it with adblock2pac', common.PAC_ADBLOCK)
  2462. if 'gevent' in sys.modules and time.sleep is getattr(sys.modules['gevent'], 'sleep', None) and hasattr(gevent.get_hub(), 'threadpool'):
  2463. jsrule = gevent.get_hub().threadpool.apply_e(Exception, PacUtil.adblock2pac, (adblock_content, 'FindProxyForURLByAdblock', blackhole, default, admode))
  2464. else:
  2465. jsrule = PacUtil.adblock2pac(adblock_content, 'FindProxyForURLByAdblock', blackhole, default, admode)
  2466. content += '\r\n' + jsrule + '\r\n'
  2467. logging.info('%r downloaded and parsed', common.PAC_ADBLOCK)
  2468. else:
  2469. content += '\r\nfunction FindProxyForURLByAdblock(url, host) {return "DIRECT";}\r\n'
  2470. except StandardError as e:
  2471. need_update = False
  2472. logging.exception('update_pacfile failed: %r', e)
  2473. try:
  2474. logging.info('try download %r to update_pacfile(%r)', common.PAC_GFWLIST, filename)
  2475. autoproxy_content = base64.b64decode(opener.open(common.PAC_GFWLIST).read())
  2476. logging.info('%r downloaded, try convert it with autoproxy2pac_lite', common.PAC_GFWLIST)
  2477. if 'gevent' in sys.modules and time.sleep is getattr(sys.modules['gevent'], 'sleep', None) and hasattr(gevent.get_hub(), 'threadpool'):
  2478. jsrule = gevent.get_hub().threadpool.apply_e(Exception, PacUtil.autoproxy2pac_lite, (autoproxy_content, 'FindProxyForURLByAutoProxy', autoproxy, default))
  2479. else:
  2480. jsrule = PacUtil.autoproxy2pac_lite(autoproxy_content, 'FindProxyForURLByAutoProxy', autoproxy, default)
  2481. content += '\r\n' + jsrule + '\r\n'
  2482. logging.info('%r downloaded and parsed', common.PAC_GFWLIST)
  2483. except StandardError as e:
  2484. need_update = False
  2485. logging.exception('update_pacfile failed: %r', e)
  2486. if need_update:
  2487. with open(filename, 'wb') as fp:
  2488. fp.write(content)
  2489. logging.info('%r successfully updated', filename)
  2490. @staticmethod
  2491. def autoproxy2pac(content, func_name='FindProxyForURLByAutoProxy', proxy='127.0.0.1:8087', default='DIRECT', indent=4):
  2492. """Autoproxy to Pac, based on https://github.com/iamamac/autoproxy2pac"""
  2493. jsLines = []
  2494. for line in content.splitlines()[1:]:
  2495. if line and not line.startswith("!"):
  2496. use_proxy = True
  2497. if line.startswith("@@"):
  2498. line = line[2:]
  2499. use_proxy = False
  2500. return_proxy = 'PROXY %s' % proxy if use_proxy else default
  2501. if line.startswith('/') and line.endswith('/'):
  2502. jsLine = 'if (/%s/i.test(url)) return "%s";' % (line[1:-1], return_proxy)
  2503. elif line.startswith('||'):
  2504. domain = line[2:].lstrip('.')
  2505. if len(jsLines) > 0 and ('host.indexOf(".%s") >= 0' % domain in jsLines[-1] or 'host.indexOf("%s") >= 0' % domain in jsLines[-1]):
  2506. jsLines.pop()
  2507. jsLine = 'if (dnsDomainIs(host, ".%s") || host == "%s") return "%s";' % (domain, domain, return_proxy)
  2508. elif line.startswith('|'):
  2509. jsLine = 'if (url.indexOf("%s") == 0) return "%s";' % (line[1:], return_proxy)
  2510. elif '*' in line:
  2511. jsLine = 'if (shExpMatch(url, "*%s*")) return "%s";' % (line.strip('*'), return_proxy)
  2512. elif '/' not in line:
  2513. jsLine = 'if (host.indexOf("%s") >= 0) return "%s";' % (line, return_proxy)
  2514. else:
  2515. jsLine = 'if (url.indexOf("%s") >= 0) return "%s";' % (line, return_proxy)
  2516. jsLine = ' ' * indent + jsLine
  2517. if use_proxy:
  2518. jsLines.append(jsLine)
  2519. else:
  2520. jsLines.insert(0, jsLine)
  2521. function = 'function %s(url, host) {\r\n%s\r\n%sreturn "%s";\r\n}' % (func_name, '\n'.join(jsLines), ' '*indent, default)
  2522. return function
  2523. @staticmethod
  2524. def autoproxy2pac_lite(content, func_name='FindProxyForURLByAutoProxy', proxy='127.0.0.1:8087', default='DIRECT', indent=4):
  2525. """Autoproxy to Pac, based on https://github.com/iamamac/autoproxy2pac"""
  2526. direct_domain_set = set([])
  2527. proxy_domain_set = set([])
  2528. for line in content.splitlines()[1:]:
  2529. if line and not line.startswith(('!', '|!', '||!')):
  2530. use_proxy = True
  2531. if line.startswith("@@"):
  2532. line = line[2:]
  2533. use_proxy = False
  2534. domain = ''
  2535. if line.startswith('/') and line.endswith('/'):
  2536. line = line[1:-1]
  2537. if line.startswith('^https?:\\/\\/[^\\/]+') and re.match(r'^(\w|\\\-|\\\.)+$', line[18:]):
  2538. domain = line[18:].replace(r'\.', '.')
  2539. else:
  2540. logging.warning('unsupport gfwlist regex: %r', line)
  2541. elif line.startswith('||'):
  2542. domain = line[2:].lstrip('*').rstrip('/')
  2543. elif line.startswith('|'):
  2544. domain = urlparse.urlsplit(line[1:]).hostname.lstrip('*')
  2545. elif line.startswith(('http://', 'https://')):
  2546. domain = urlparse.urlsplit(line).hostname.lstrip('*')
  2547. elif re.search(r'^([\w\-\_\.]+)([\*\/]|$)', line):
  2548. domain = re.split(r'[\*\/]', line)[0]
  2549. else:
  2550. pass
  2551. if '*' in domain:
  2552. domain = domain.split('*')[-1]
  2553. if not domain or re.match(r'^\w+$', domain):
  2554. logging.debug('unsupport gfwlist rule: %r', line)
  2555. continue
  2556. if use_proxy:
  2557. proxy_domain_set.add(domain)
  2558. else:
  2559. direct_domain_set.add(domain)
  2560. proxy_domain_list = sorted(set(x.lstrip('.') for x in proxy_domain_set))
  2561. autoproxy_host = ',\r\n'.join('%s"%s": 1' % (' '*indent, x) for x in proxy_domain_list)
  2562. template = '''\
  2563. var autoproxy_host = {
  2564. %(autoproxy_host)s
  2565. };
  2566. function %(func_name)s(url, host) {
  2567. var lastPos;
  2568. do {
  2569. if (autoproxy_host.hasOwnProperty(host)) {
  2570. return 'PROXY %(proxy)s';
  2571. }
  2572. lastPos = host.indexOf('.') + 1;
  2573. host = host.slice(lastPos);
  2574. } while (lastPos >= 1);
  2575. return '%(default)s';
  2576. }'''
  2577. template = re.sub(r'(?m)^\s{%d}' % min(len(re.search(r' +', x).group()) for x in template.splitlines()), '', template)
  2578. template_args = {'autoproxy_host': autoproxy_host,
  2579. 'func_name': func_name,
  2580. 'proxy': proxy,
  2581. 'default': default}
  2582. return template % template_args
  2583. @staticmethod
  2584. def urlfilter2pac(content, func_name='FindProxyForURLByUrlfilter', proxy='127.0.0.1:8086', default='DIRECT', indent=4):
  2585. """urlfilter.ini to Pac, based on https://github.com/iamamac/autoproxy2pac"""
  2586. jsLines = []
  2587. for line in content[content.index('[exclude]'):].splitlines()[1:]:
  2588. if line and not line.startswith(';'):
  2589. use_proxy = True
  2590. if line.startswith("@@"):
  2591. line = line[2:]
  2592. use_proxy = False
  2593. return_proxy = 'PROXY %s' % proxy if use_proxy else default
  2594. if '*' in line:
  2595. jsLine = 'if (shExpMatch(url, "%s")) return "%s";' % (line, return_proxy)
  2596. else:
  2597. jsLine = 'if (url == "%s") return "%s";' % (line, return_proxy)
  2598. jsLine = ' ' * indent + jsLine
  2599. if use_proxy:
  2600. jsLines.append(jsLine)
  2601. else:
  2602. jsLines.insert(0, jsLine)
  2603. function = 'function %s(url, host) {\r\n%s\r\n%sreturn "%s";\r\n}' % (func_name, '\n'.join(jsLines), ' '*indent, default)
  2604. return function
  2605. @staticmethod
  2606. def adblock2pac(content, func_name='FindProxyForURLByAdblock', proxy='127.0.0.1:8086', default='DIRECT', admode=1, indent=4):
  2607. """adblock list to Pac, based on https://github.com/iamamac/autoproxy2pac"""
  2608. white_conditions = {'host': [], 'url.indexOf': [], 'shExpMatch': []}
  2609. black_conditions = {'host': [], 'url.indexOf': [], 'shExpMatch': []}
  2610. for line in content.splitlines()[1:]:
  2611. if not line or line.startswith('!') or '##' in line or '#@#' in line:
  2612. continue
  2613. use_proxy = True
  2614. use_start = False
  2615. use_end = False
  2616. use_domain = False
  2617. use_postfix = []
  2618. if '$' in line:
  2619. posfixs = line.split('$')[-1].split(',')
  2620. if any('domain' in x for x in posfixs):
  2621. continue
  2622. if 'image' in posfixs:
  2623. use_postfix += ['.jpg', '.gif']
  2624. elif 'script' in posfixs:
  2625. use_postfix += ['.js']
  2626. else:
  2627. continue
  2628. line = line.split('$')[0]
  2629. if line.startswith("@@"):
  2630. line = line[2:]
  2631. use_proxy = False
  2632. if '||' == line[:2]:
  2633. line = line[2:]
  2634. if '/' not in line:
  2635. use_domain = True
  2636. else:
  2637. use_start = True
  2638. elif '|' == line[0]:
  2639. line = line[1:]
  2640. use_start = True
  2641. if line[-1] in ('^', '|'):
  2642. line = line[:-1]
  2643. if not use_postfix:
  2644. use_end = True
  2645. line = line.replace('^', '*').strip('*')
  2646. conditions = black_conditions if use_proxy else white_conditions
  2647. if use_start and use_end:
  2648. conditions['shExpMatch'] += ['*%s*' % line]
  2649. elif use_start:
  2650. if '*' in line:
  2651. if use_postfix:
  2652. conditions['shExpMatch'] += ['*%s*%s' % (line, x) for x in use_postfix]
  2653. else:
  2654. conditions['shExpMatch'] += ['*%s*' % line]
  2655. else:
  2656. conditions['url.indexOf'] += [line]
  2657. elif use_domain and use_end:
  2658. if '*' in line:
  2659. conditions['shExpMatch'] += ['%s*' % line]
  2660. else:
  2661. conditions['host'] += [line]
  2662. elif use_domain:
  2663. if line.split('/')[0].count('.') <= 1:
  2664. if use_postfix:
  2665. conditions['shExpMatch'] += ['*.%s*%s' % (line, x) for x in use_postfix]
  2666. else:
  2667. conditions['shExpMatch'] += ['*.%s*' % line]
  2668. else:
  2669. if '*' in line:
  2670. if use_postfix:
  2671. conditions['shExpMatch'] += ['*%s*%s' % (line, x) for x in use_postfix]
  2672. else:
  2673. conditions['shExpMatch'] += ['*%s*' % line]
  2674. else:
  2675. if use_postfix:
  2676. conditions['shExpMatch'] += ['*%s*%s' % (line, x) for x in use_postfix]
  2677. else:
  2678. conditions['url.indexOf'] += ['http://%s' % line]
  2679. else:
  2680. if use_postfix:
  2681. conditions['shExpMatch'] += ['*%s*%s' % (line, x) for x in use_postfix]
  2682. else:
  2683. conditions['shExpMatch'] += ['*%s*' % line]
  2684. templates = ['''\
  2685. function %(func_name)s(url, host) {
  2686. return '%(default)s';
  2687. }''',
  2688. '''\
  2689. var blackhole_host = {
  2690. %(blackhole_host)s
  2691. };
  2692. function %(func_name)s(url, host) {
  2693. // untrusted ablock plus list, disable whitelist until chinalist come back.
  2694. if (blackhole_host.hasOwnProperty(host)) {
  2695. return 'PROXY %(proxy)s';
  2696. }
  2697. return '%(default)s';
  2698. }''',
  2699. '''\
  2700. var blackhole_host = {
  2701. %(blackhole_host)s
  2702. };
  2703. var blackhole_url_indexOf = [
  2704. %(blackhole_url_indexOf)s
  2705. ];
  2706. function %s(url, host) {
  2707. // untrusted ablock plus list, disable whitelist until chinalist come back.
  2708. if (blackhole_host.hasOwnProperty(host)) {
  2709. return 'PROXY %(proxy)s';
  2710. }
  2711. for (i = 0; i < blackhole_url_indexOf.length; i++) {
  2712. if (url.indexOf(blackhole_url_indexOf[i]) >= 0) {
  2713. return 'PROXY %(proxy)s';
  2714. }
  2715. }
  2716. return '%(default)s';
  2717. }''',
  2718. '''\
  2719. var blackhole_host = {
  2720. %(blackhole_host)s
  2721. };
  2722. var blackhole_url_indexOf = [
  2723. %(blackhole_url_indexOf)s
  2724. ];
  2725. var blackhole_shExpMatch = [
  2726. %(blackhole_shExpMatch)s
  2727. ];
  2728. function %(func_name)s(url, host) {
  2729. // untrusted ablock plus list, disable whitelist until chinalist come back.
  2730. if (blackhole_host.hasOwnProperty(host)) {
  2731. return 'PROXY %(proxy)s';
  2732. }
  2733. for (i = 0; i < blackhole_url_indexOf.length; i++) {
  2734. if (url.indexOf(blackhole_url_indexOf[i]) >= 0) {
  2735. return 'PROXY %(proxy)s';
  2736. }
  2737. }
  2738. for (i = 0; i < blackhole_shExpMatch.length; i++) {
  2739. if (shExpMatch(url, blackhole_shExpMatch[i])) {
  2740. return 'PROXY %(proxy)s';
  2741. }
  2742. }
  2743. return '%(default)s';
  2744. }''']
  2745. template = re.sub(r'(?m)^\s{%d}' % min(len(re.search(r' +', x).group()) for x in templates[admode].splitlines()), '', templates[admode])
  2746. template_kwargs = {'blackhole_host': ',\r\n'.join("%s'%s': 1" % (' '*indent, x) for x in sorted(black_conditions['host'])),
  2747. 'blackhole_url_indexOf': ',\r\n'.join("%s'%s'" % (' '*indent, x) for x in sorted(black_conditions['url.indexOf'])),
  2748. 'blackhole_shExpMatch': ',\r\n'.join("%s'%s'" % (' '*indent, x) for x in sorted(black_conditions['shExpMatch'])),
  2749. 'func_name': func_name,
  2750. 'proxy': proxy,
  2751. 'default': default}
  2752. return template % template_kwargs
  2753. class PacFileFilter(BaseProxyHandlerFilter):
  2754. """pac file filter"""
  2755. def filter(self, handler):
  2756. is_local_client = handler.client_address[0] in ('127.0.0.1', '::1')
  2757. pacfile = os.path.join(os.path.dirname(os.path.abspath(__file__)), common.PAC_FILE)
  2758. urlparts = urlparse.urlsplit(handler.path)
  2759. if handler.command == 'GET' and urlparts.path.lstrip('/') == common.PAC_FILE:
  2760. if urlparts.query == 'flush':
  2761. if is_local_client:
  2762. thread.start_new_thread(PacUtil.update_pacfile, (pacfile,))
  2763. else:
  2764. return [handler.MOCK, 403, {'Content-Type': 'text/plain'}, 'client address %r not allowed' % handler.client_address[0]]
  2765. if time.time() - os.path.getmtime(pacfile) > common.PAC_EXPIRED:
  2766. # check system uptime > 30 minutes
  2767. uptime = get_uptime()
  2768. if uptime and uptime > 1800:
  2769. thread.start_new_thread(lambda: os.utime(pacfile, (time.time(), time.time())) or PacUtil.update_pacfile(pacfile), tuple())
  2770. with open(pacfile, 'rb') as fp:
  2771. content = fp.read()
  2772. if not is_local_client:
  2773. serving_addr = urlparts.hostname or ProxyUtil.get_listen_ip()
  2774. content = content.replace('127.0.0.1', serving_addr)
  2775. headers = {'Content-Type': 'text/plain'}
  2776. if 'gzip' in handler.headers.get('Accept-Encoding', ''):
  2777. headers['Content-Encoding'] = 'gzip'
  2778. compressobj = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS, zlib.DEF_MEM_LEVEL, 0)
  2779. dataio = io.BytesIO()
  2780. dataio.write('\x1f\x8b\x08\x00\x00\x00\x00\x00\x02\xff')
  2781. dataio.write(compressobj.compress(content))
  2782. dataio.write(compressobj.flush())
  2783. dataio.write(struct.pack('<LL', zlib.crc32(content) & 0xFFFFFFFFL, len(content) & 0xFFFFFFFFL))
  2784. content = dataio.getvalue()
  2785. return [handler.MOCK, 200, headers, content]
  2786. class StaticFileFilter(BaseProxyHandlerFilter):
  2787. """static file filter"""
  2788. index_file = 'index.html'
  2789. def format_index_html(self, dirname):
  2790. INDEX_TEMPLATE = u'''
  2791. <html>
  2792. <title>Directory listing for $dirname</title>
  2793. <body>
  2794. <h2>Directory listing for $dirname</h2>
  2795. <hr>
  2796. <ul>
  2797. $html
  2798. </ul>
  2799. <hr>
  2800. </body></html>
  2801. '''
  2802. html = ''
  2803. if not isinstance(dirname, unicode):
  2804. dirname = dirname.decode(sys.getfilesystemencoding())
  2805. for name in os.listdir(dirname):
  2806. fullname = os.path.join(dirname, name)
  2807. suffix = u'/' if os.path.isdir(fullname) else u''
  2808. html += u'<li><a href="%s%s">%s%s</a>\r\n' % (name, suffix, name, suffix)
  2809. return string.Template(INDEX_TEMPLATE).substitute(dirname=dirname, html=html)
  2810. def filter(self, handler):
  2811. path = urlparse.urlsplit(handler.path).path
  2812. if path.startswith('/'):
  2813. path = urllib.unquote_plus(path.lstrip('/') or '.').decode('utf8')
  2814. if os.path.isdir(path):
  2815. index_file = os.path.join(path, self.index_file)
  2816. if not os.path.isfile(index_file):
  2817. content = self.format_index_html(path).encode('UTF-8')
  2818. headers = {'Content-Type': 'text/html; charset=utf-8', 'Connection': 'close'}
  2819. return [handler.MOCK, 200, headers, content]
  2820. else:
  2821. path = index_file
  2822. if os.path.isfile(path):
  2823. content_type = 'application/octet-stream'
  2824. try:
  2825. import mimetypes
  2826. content_type = mimetypes.types_map.get(os.path.splitext(path)[1])
  2827. except StandardError as e:
  2828. logging.error('import mimetypes failed: %r', e)
  2829. with open(path, 'rb') as fp:
  2830. content = fp.read()
  2831. headers = {'Connection': 'close', 'Content-Type': content_type}
  2832. return [handler.MOCK, 200, headers, content]
  2833. class BlackholeFilter(BaseProxyHandlerFilter):
  2834. """blackhole filter"""
  2835. one_pixel_gif = 'GIF89a\x01\x00\x01\x00\x80\xff\x00\xc0\xc0\xc0\x00\x00\x00!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;'
  2836. def filter(self, handler):
  2837. if handler.command == 'CONNECT':
  2838. return [handler.STRIP, True, self]
  2839. elif handler.path.startswith(('http://', 'https://')):
  2840. headers = {'Cache-Control': 'max-age=86400',
  2841. 'Expires': 'Oct, 01 Aug 2100 00:00:00 GMT',
  2842. 'Connection': 'close'}
  2843. content = ''
  2844. if urlparse.urlsplit(handler.path).path.lower().endswith(('.jpg', '.gif', '.png','.jpeg', '.bmp')):
  2845. headers['Content-Type'] = 'image/gif'
  2846. content = self.one_pixel_gif
  2847. return [handler.MOCK, 200, headers, content]
  2848. else:
  2849. return [handler.MOCK, 404, {'Connection': 'close'}, '']
  2850. class PACProxyHandler(SimpleProxyHandler):
  2851. """pac proxy handler"""
  2852. handler_filters = [PacFileFilter(), StaticFileFilter(), BlackholeFilter()]
  2853. def get_process_list():
  2854. import os
  2855. import glob
  2856. import ctypes
  2857. import collections
  2858. Process = collections.namedtuple('Process', 'pid name exe')
  2859. process_list = []
  2860. if os.name == 'nt':
  2861. PROCESS_QUERY_INFORMATION = 0x0400
  2862. PROCESS_VM_READ = 0x0010
  2863. lpidProcess = (ctypes.c_ulong * 1024)()
  2864. cb = ctypes.sizeof(lpidProcess)
  2865. cbNeeded = ctypes.c_ulong()
  2866. ctypes.windll.psapi.EnumProcesses(ctypes.byref(lpidProcess), cb, ctypes.byref(cbNeeded))
  2867. nReturned = cbNeeded.value/ctypes.sizeof(ctypes.c_ulong())
  2868. pidProcess = [i for i in lpidProcess][:nReturned]
  2869. has_queryimage = hasattr(ctypes.windll.kernel32, 'QueryFullProcessImageNameA')
  2870. for pid in pidProcess:
  2871. hProcess = ctypes.windll.kernel32.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, 0, pid)
  2872. if hProcess:
  2873. modname = ctypes.create_string_buffer(2048)
  2874. count = ctypes.c_ulong(ctypes.sizeof(modname))
  2875. if has_queryimage:
  2876. ctypes.windll.kernel32.QueryFullProcessImageNameA(hProcess, 0, ctypes.byref(modname), ctypes.byref(count))
  2877. else:
  2878. ctypes.windll.psapi.GetModuleFileNameExA(hProcess, 0, ctypes.byref(modname), ctypes.byref(count))
  2879. exe = modname.value
  2880. name = os.path.basename(exe)
  2881. process_list.append(Process(pid=pid, name=name, exe=exe))
  2882. ctypes.windll.kernel32.CloseHandle(hProcess)
  2883. elif sys.platform.startswith('linux'):
  2884. for filename in glob.glob('/proc/[0-9]*/cmdline'):
  2885. pid = int(filename.split('/')[2])
  2886. exe_link = '/proc/%d/exe' % pid
  2887. if os.path.exists(exe_link):
  2888. exe = os.readlink(exe_link)
  2889. name = os.path.basename(exe)
  2890. process_list.append(Process(pid=pid, name=name, exe=exe))
  2891. else:
  2892. try:
  2893. import psutil
  2894. process_list = psutil.get_process_list()
  2895. except StandardError as e:
  2896. logging.exception('psutil.get_process_list() failed: %r', e)
  2897. return process_list
  2898. def pre_start():
  2899. if not OpenSSL:
  2900. logging.warning('python-openssl not found, please install it!')
  2901. if sys.platform == 'cygwin':
  2902. logging.info('cygwin is not officially supported, please continue at your own risk :)')
  2903. #sys.exit(-1)
  2904. elif os.name == 'posix':
  2905. try:
  2906. import resource
  2907. resource.setrlimit(resource.RLIMIT_NOFILE, (8192, -1))
  2908. except ValueError:
  2909. pass
  2910. elif os.name == 'nt':
  2911. import ctypes
  2912. ctypes.windll.kernel32.SetConsoleTitleW(u'GoAgent v%s' % __version__)
  2913. if not common.LISTEN_VISIBLE:
  2914. ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 0)
  2915. else:
  2916. ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 1)
  2917. if common.LOVE_ENABLE and random.randint(1, 100) <= 5:
  2918. title = ctypes.create_unicode_buffer(1024)
  2919. ctypes.windll.kernel32.GetConsoleTitleW(ctypes.byref(title), len(title)-1)
  2920. ctypes.windll.kernel32.SetConsoleTitleW('%s %s' % (title.value, random.choice(common.LOVE_TIP)))
  2921. blacklist = {'360safe': False,
  2922. 'QQProtect': False, }
  2923. softwares = [k for k, v in blacklist.items() if v]
  2924. if softwares:
  2925. tasklist = '\n'.join(x.name for x in get_process_list()).lower()
  2926. softwares = [x for x in softwares if x.lower() in tasklist]
  2927. if softwares:
  2928. title = u'GoAgent 建议'
  2929. error = u'某些安全软件(如 %s)可能和本软件存在冲突,造成 CPU 占用过高。\n如有此现象建议暂时退出此安全软件来继续运行GoAgent' % ','.join(softwares)
  2930. ctypes.windll.user32.MessageBoxW(None, error, title, 0)
  2931. #sys.exit(0)
  2932. if os.path.isfile('/proc/cpuinfo'):
  2933. with open('/proc/cpuinfo', 'rb') as fp:
  2934. m = re.search(r'(?im)(BogoMIPS|cpu MHz)\s+:\s+([\d\.]+)', fp.read())
  2935. if m and float(m.group(2)) < 1000:
  2936. logging.warning("*NOTE*, Please set [gae]window=2 [gae]keepalive=1")
  2937. if GAEProxyHandler.max_window != common.GAE_WINDOW:
  2938. GAEProxyHandler.max_window = common.GAE_WINDOW
  2939. if common.GAE_KEEPALIVE and common.GAE_MODE == 'https':
  2940. GAEProxyHandler.ssl_connection_keepalive = True
  2941. if common.GAE_PAGESPEED and not common.GAE_OBFUSCATE:
  2942. logging.critical("*NOTE*, [gae]pagespeed=1 requires [gae]obfuscate=1")
  2943. sys.exit(-1)
  2944. if common.GAE_SSLVERSION:
  2945. GAEProxyHandler.ssl_version = getattr(ssl, 'PROTOCOL_%s' % common.GAE_SSLVERSION)
  2946. GAEProxyHandler.openssl_context = SSLConnection.context_builder(common.GAE_SSLVERSION)
  2947. if common.GAE_APPIDS[0] == 'goagent':
  2948. logging.critical('please edit %s to add your appid to [gae] !', common.CONFIG_FILENAME)
  2949. sys.exit(-1)
  2950. if common.GAE_MODE == 'http' and common.GAE_PASSWORD == '':
  2951. logging.critical('to enable http mode, you should set %r [gae]password = <your_pass> and [gae]options = rc4', common.CONFIG_FILENAME)
  2952. sys.exit(-1)
  2953. if common.GAE_TRANSPORT:
  2954. GAEProxyHandler.disable_transport_ssl = False
  2955. if common.GAE_REGIONS and not pygeoip:
  2956. logging.critical('to enable [gae]regions mode, you should install pygeoip')
  2957. sys.exit(-1)
  2958. if common.PAC_ENABLE:
  2959. pac_ip = ProxyUtil.get_listen_ip() if common.PAC_IP in ('', '::', '0.0.0.0') else common.PAC_IP
  2960. url = 'http://%s:%d/%s' % (pac_ip, common.PAC_PORT, common.PAC_FILE)
  2961. spawn_later(600, urllib2.build_opener(urllib2.ProxyHandler({})).open, url)
  2962. if not dnslib:
  2963. logging.error('dnslib not found, please put dnslib-0.8.3.egg to %r!', os.path.dirname(os.path.abspath(__file__)))
  2964. sys.exit(-1)
  2965. if not common.DNS_ENABLE:
  2966. if not common.HTTP_DNS:
  2967. common.HTTP_DNS = common.DNS_SERVERS[:]
  2968. for dnsservers_ref in (common.HTTP_DNS, common.DNS_SERVERS):
  2969. any(dnsservers_ref.insert(0, x) for x in [y for y in get_dnsserver_list() if y not in dnsservers_ref])
  2970. AdvancedProxyHandler.dns_servers = common.HTTP_DNS
  2971. AdvancedProxyHandler.dns_blacklist = common.DNS_BLACKLIST
  2972. else:
  2973. AdvancedProxyHandler.dns_servers = common.HTTP_DNS or common.DNS_SERVERS
  2974. AdvancedProxyHandler.dns_blacklist = common.DNS_BLACKLIST
  2975. RangeFetch.threads = common.AUTORANGE_THREADS
  2976. RangeFetch.maxsize = common.AUTORANGE_MAXSIZE
  2977. RangeFetch.bufsize = common.AUTORANGE_BUFSIZE
  2978. RangeFetch.waitsize = common.AUTORANGE_WAITSIZE
  2979. if common.LISTEN_USERNAME and common.LISTEN_PASSWORD:
  2980. GAEProxyHandler.handler_filters.insert(0, AuthFilter(common.LISTEN_USERNAME, common.LISTEN_PASSWORD))
  2981. def main():
  2982. global __file__
  2983. __file__ = os.path.abspath(__file__)
  2984. if os.path.islink(__file__):
  2985. __file__ = getattr(os, 'readlink', lambda x: x)(__file__)
  2986. os.chdir(os.path.dirname(os.path.abspath(__file__)))
  2987. logging.basicConfig(level=logging.DEBUG if common.LISTEN_DEBUGINFO else logging.INFO, format='%(levelname)s - %(asctime)s %(message)s', datefmt='[%b %d %H:%M:%S]')
  2988. pre_start()
  2989. CertUtil.check_ca()
  2990. sys.stderr.write(common.info())
  2991. uvent_enabled = 'uvent.loop' in sys.modules and isinstance(gevent.get_hub().loop, __import__('uvent').loop.UVLoop)
  2992. if common.PHP_ENABLE:
  2993. host, port = common.PHP_LISTEN.split(':')
  2994. HandlerClass = ((PHPProxyHandler, GreenForwardPHPProxyHandler) if not common.PROXY_ENABLE else (ProxyChainPHPProxyHandler, ProxyChainGreenForwardPHPProxyHandler))[uvent_enabled]
  2995. server = LocalProxyServer((host, int(port)), HandlerClass)
  2996. thread.start_new_thread(server.serve_forever, tuple())
  2997. if common.PAC_ENABLE:
  2998. server = LocalProxyServer((common.PAC_IP, common.PAC_PORT), PACProxyHandler)
  2999. thread.start_new_thread(server.serve_forever, tuple())
  3000. if common.DNS_ENABLE:
  3001. try:
  3002. sys.path += ['.']
  3003. from dnsproxy import DNSServer
  3004. host, port = common.DNS_LISTEN.split(':')
  3005. server = DNSServer((host, int(port)), dns_servers=common.DNS_SERVERS, dns_blacklist=common.DNS_BLACKLIST, dns_tcpover=common.DNS_TCPOVER)
  3006. thread.start_new_thread(server.serve_forever, tuple())
  3007. except ImportError:
  3008. logging.exception('GoAgent DNSServer requires dnslib and gevent 1.0')
  3009. sys.exit(-1)
  3010. HandlerClass = ((GAEProxyHandler, GreenForwardGAEProxyHandler) if not common.PROXY_ENABLE else (ProxyChainGAEProxyHandler, ProxyChainGreenForwardGAEProxyHandler))[uvent_enabled]
  3011. server = LocalProxyServer((common.LISTEN_IP, common.LISTEN_PORT), HandlerClass)
  3012. try:
  3013. server.serve_forever()
  3014. except SystemError as e:
  3015. if '(libev) select: ' in repr(e):
  3016. logging.error('PLEASE START GOAGENT BY uvent.bat')
  3017. sys.exit(-1)
  3018. if __name__ == '__main__':
  3019. main()