PageRenderTime 72ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/local/proxy.py

https://github.com/BabySnake/goagent
Python | 3252 lines | 3135 code | 60 blank | 57 comment | 188 complexity | d9596bc80b9969176f5d3f89133fc4b9 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, sock, 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._sock, self._connection.do_handshake)
  416. def connect(self, *args, **kwargs):
  417. return self.__wait_sock_io(self._sock, self._connection.connect, *args, **kwargs)
  418. def send(self, data, flags=0):
  419. try:
  420. return self.__wait_sock_io(self._sock, 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._sock, 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. __import__('time').sleep(seconds)
  625. return target(*args, **kwargs)
  626. return __import__('thread').start_new_thread(wrap, args, kwargs)
  627. def is_clienthello(data):
  628. if len(data) < 20:
  629. return False
  630. if data.startswith('\x16\x03'):
  631. # TLSv12/TLSv11/TLSv1/SSLv3
  632. length, = struct.unpack('>h', data[3:5])
  633. return len(data) == 5 + length
  634. elif data[0] == '\x80' and data[2:4] == '\x01\x03':
  635. # SSLv23
  636. return len(data) == 2 + ord(data[1])
  637. else:
  638. return False
  639. def extract_sni_name(packet):
  640. if packet.startswith('\x16\x03'):
  641. stream = io.BytesIO(packet)
  642. stream.read(0x2b)
  643. session_id_length = ord(stream.read(1))
  644. stream.read(session_id_length)
  645. cipher_suites_length, = struct.unpack('>h', stream.read(2))
  646. stream.read(cipher_suites_length+2)
  647. extensions_length, = struct.unpack('>h', stream.read(2))
  648. extensions = {}
  649. while True:
  650. data = stream.read(2)
  651. if not data:
  652. break
  653. etype, = struct.unpack('>h', data)
  654. elen, = struct.unpack('>h', stream.read(2))
  655. edata = stream.read(elen)
  656. if etype == 0:
  657. server_name = edata[5:]
  658. return server_name
  659. class URLFetch(object):
  660. """URLFetch for gae/php fetchservers"""
  661. skip_headers = frozenset(['Vary', 'Via', 'X-Forwarded-For', 'Proxy-Authorization', 'Proxy-Connection', 'Upgrade', 'X-Chrome-Variations', 'Connection', 'Cache-Control'])
  662. def __init__(self, fetchserver, create_http_request):
  663. assert isinstance(fetchserver, basestring) and callable(create_http_request)
  664. self.fetchserver = fetchserver
  665. self.create_http_request = create_http_request
  666. def fetch(self, method, url, headers, body, timeout, **kwargs):
  667. if '.appspot.com/' in self.fetchserver:
  668. response = self.__gae_fetch(method, url, headers, body, timeout, **kwargs)
  669. response.app_header_parsed = True
  670. else:
  671. response = self.__php_fetch(method, url, headers, body, timeout, **kwargs)
  672. response.app_header_parsed = False
  673. return response
  674. def __gae_fetch(self, method, url, headers, body, timeout, **kwargs):
  675. rc4crypt = lambda s, k: RC4Cipher(k).encrypt(s) if k else s
  676. if isinstance(body, basestring) and body:
  677. if len(body) < 10 * 1024 * 1024 and 'Content-Encoding' not in headers:
  678. zbody = deflate(body)
  679. if len(zbody) < len(body):
  680. body = zbody
  681. headers['Content-Encoding'] = 'deflate'
  682. headers['Content-Length'] = str(len(body))
  683. # GAE donot allow set `Host` header
  684. if 'Host' in headers:
  685. del headers['Host']
  686. 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))
  687. skip_headers = self.skip_headers
  688. metadata += ''.join('%s:%s\n' % (k.title(), v) for k, v in headers.items() if k not in skip_headers)
  689. # prepare GAE request
  690. request_fetchserver = self.fetchserver
  691. request_method = 'POST'
  692. request_headers = {}
  693. if common.GAE_OBFUSCATE:
  694. request_method = 'GET'
  695. request_fetchserver += '/ps/%s.gif' % uuid.uuid1()
  696. request_headers['X-GOA-PS1'] = base64.b64encode(deflate(metadata)).strip()
  697. if body:
  698. request_headers['X-GOA-PS2'] = base64.b64encode(deflate(body)).strip()
  699. body = ''
  700. if common.GAE_PAGESPEED:
  701. request_fetchserver = re.sub(r'^(\w+://)', r'\g<1>1-ps.googleusercontent.com/h/', request_fetchserver)
  702. else:
  703. metadata = deflate(metadata)
  704. body = '%s%s%s' % (struct.pack('!h', len(metadata)), metadata, body)
  705. if 'rc4' in common.GAE_OPTIONS:
  706. request_headers['X-GOA-Options'] = 'rc4'
  707. body = rc4crypt(body, kwargs.get('password'))
  708. request_headers['Content-Length'] = str(len(body))
  709. # post data
  710. need_crlf = 0 if common.GAE_MODE == 'https' else 1
  711. need_validate = common.GAE_VALIDATE
  712. cache_key = '%s:%d' % (common.HOST_POSTFIX_MAP['.appspot.com'], 443 if common.GAE_MODE == 'https' else 80)
  713. response = self.create_http_request(request_method, request_fetchserver, request_headers, body, timeout, crlf=need_crlf, validate=need_validate, cache_key=cache_key)
  714. response.app_status = response.status
  715. response.app_options = response.getheader('X-GOA-Options', '')
  716. if response.status != 200:
  717. return response
  718. data = response.read(4)
  719. if len(data) < 4:
  720. response.status = 502
  721. response.fp = io.BytesIO(b'connection aborted. too short leadbyte data=' + data)
  722. response.read = response.fp.read
  723. return response
  724. response.status, headers_length = struct.unpack('!hh', data)
  725. data = response.read(headers_length)
  726. if len(data) < headers_length:
  727. response.status = 502
  728. response.fp = io.BytesIO(b'connection aborted. too short headers data=' + data)
  729. response.read = response.fp.read
  730. return response
  731. if 'rc4' not in response.app_options:
  732. response.msg = httplib.HTTPMessage(io.BytesIO(inflate(data)))
  733. else:
  734. response.msg = httplib.HTTPMessage(io.BytesIO(inflate(rc4crypt(data, kwargs.get('password')))))
  735. if kwargs.get('password') and response.fp:
  736. response.fp = CipherFileObject(response.fp, RC4Cipher(kwargs['password']))
  737. return response
  738. def __php_fetch(self, method, url, headers, body, timeout, **kwargs):
  739. if body:
  740. if len(body) < 10 * 1024 * 1024 and 'Content-Encoding' not in headers:
  741. zbody = deflate(body)
  742. if len(zbody) < len(body):
  743. body = zbody
  744. headers['Content-Encoding'] = 'deflate'
  745. headers['Content-Length'] = str(len(body))
  746. skip_headers = self.skip_headers
  747. 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))
  748. metadata = deflate(metadata)
  749. app_body = b''.join((struct.pack('!h', len(metadata)), metadata, body))
  750. app_headers = {'Content-Length': len(app_body), 'Content-Type': 'application/octet-stream'}
  751. fetchserver = '%s?%s' % (self.fetchserver, random.random())
  752. crlf = 0
  753. cache_key = '%s//:%s' % urlparse.urlsplit(fetchserver)[:2]
  754. response = self.create_http_request('POST', fetchserver, app_headers, app_body, timeout, crlf=crlf, cache_key=cache_key)
  755. if not response:
  756. raise socket.error(errno.ECONNRESET, 'urlfetch %r return None' % url)
  757. if response.status >= 400:
  758. return response
  759. response.app_status = response.status
  760. need_decrypt = kwargs.get('password') and response.app_status == 200 and response.getheader('Content-Type', '') == 'image/gif' and response.fp
  761. if need_decrypt:
  762. response.fp = CipherFileObject(response.fp, XORCipher(kwargs['password'][0]))
  763. return response
  764. class BaseProxyHandlerFilter(object):
  765. """base proxy handler filter"""
  766. def filter(self, handler):
  767. raise NotImplementedError
  768. class SimpleProxyHandlerFilter(BaseProxyHandlerFilter):
  769. """simple proxy handler filter"""
  770. def filter(self, handler):
  771. if handler.command == 'CONNECT':
  772. return [handler.FORWARD, handler.host, handler.port, handler.connect_timeout]
  773. else:
  774. return [handler.DIRECT, {}]
  775. class AuthFilter(BaseProxyHandlerFilter):
  776. """authorization filter"""
  777. auth_info = "Proxy authentication required"""
  778. white_list = set(['127.0.0.1'])
  779. def __init__(self, username, password):
  780. self.username = username
  781. self.password = password
  782. def check_auth_header(self, auth_header):
  783. method, _, auth_data = auth_header.partition(' ')
  784. if method == 'Basic':
  785. username, _, password = base64.b64decode(auth_data).partition(':')
  786. if username == self.username and password == self.password:
  787. return True
  788. return False
  789. def filter(self, handler):
  790. if self.white_list and handler.client_address[0] in self.white_list:
  791. return None
  792. auth_header = handler.headers.get('Proxy-Authorization') or getattr(handler, 'auth_header', None)
  793. if auth_header and self.check_auth_header(auth_header):
  794. handler.auth_header = auth_header
  795. else:
  796. headers = {'Access-Control-Allow-Origin': '*',
  797. 'Proxy-Authenticate': 'Basic realm="%s"' % self.auth_info,
  798. 'Content-Length': '0',
  799. 'Connection': 'keep-alive'}
  800. return [handler.MOCK, 407, headers, '']
  801. class SimpleProxyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  802. """SimpleProxyHandler for GoAgent 3.x"""
  803. protocol_version = 'HTTP/1.1'
  804. ssl_version = ssl.PROTOCOL_SSLv23
  805. disable_transport_ssl = True
  806. scheme = 'http'
  807. skip_headers = frozenset(['Vary', 'Via', 'X-Forwarded-For', 'Proxy-Authorization', 'Proxy-Connection', 'Upgrade', 'X-Chrome-Variations', 'Connection', 'Cache-Control'])
  808. bufsize = 256 * 1024
  809. max_timeout = 4
  810. connect_timeout = 2
  811. first_run_lock = threading.Lock()
  812. handler_filters = [SimpleProxyHandlerFilter()]
  813. sticky_filter = None
  814. def finish(self):
  815. """make python2 BaseHTTPRequestHandler happy"""
  816. try:
  817. BaseHTTPServer.BaseHTTPRequestHandler.finish(self)
  818. except NetWorkIOError as e:
  819. if e[0] not in (errno.ECONNABORTED, errno.ECONNRESET, errno.EPIPE):
  820. raise
  821. def address_string(self):
  822. return '%s:%s' % self.client_address[:2]
  823. def send_response(self, code, message=None):
  824. if message is None:
  825. if code in self.responses:
  826. message = self.responses[code][0]
  827. else:
  828. message = ''
  829. if self.request_version != 'HTTP/0.9':
  830. self.wfile.write('%s %d %s\r\n' % (self.protocol_version, code, message))
  831. def send_header(self, keyword, value):
  832. """Send a MIME header."""
  833. base_send_header = BaseHTTPServer.BaseHTTPRequestHandler.send_header
  834. keyword = keyword.title()
  835. if keyword == 'Set-Cookie':
  836. for cookie in re.split(r', (?=[^ =]+(?:=|$))', value):
  837. base_send_header(self, keyword, cookie)
  838. elif keyword == 'Content-Disposition' and '"' not in value:
  839. value = re.sub(r'filename=([^"\']+)', 'filename="\\1"', value)
  840. base_send_header(self, keyword, value)
  841. else:
  842. base_send_header(self, keyword, value)
  843. def setup(self):
  844. if isinstance(self.__class__.first_run, collections.Callable):
  845. try:
  846. with self.__class__.first_run_lock:
  847. if isinstance(self.__class__.first_run, collections.Callable):
  848. self.first_run()
  849. self.__class__.first_run = None
  850. except StandardError as e:
  851. logging.exception('%s.first_run() return %r', self.__class__, e)
  852. self.__class__.setup = BaseHTTPServer.BaseHTTPRequestHandler.setup
  853. self.__class__.do_CONNECT = self.__class__.do_METHOD
  854. self.__class__.do_GET = self.__class__.do_METHOD
  855. self.__class__.do_PUT = self.__class__.do_METHOD
  856. self.__class__.do_POST = self.__class__.do_METHOD
  857. self.__class__.do_HEAD = self.__class__.do_METHOD
  858. self.__class__.do_DELETE = self.__class__.do_METHOD
  859. self.__class__.do_OPTIONS = self.__class__.do_METHOD
  860. self.setup()
  861. def handle_one_request(self):
  862. if not self.disable_transport_ssl and self.scheme == 'http':
  863. leadbyte = self.connection.recv(1, socket.MSG_PEEK)
  864. if leadbyte in ('\x80', '\x16'):
  865. server_name = ''
  866. if leadbyte == '\x16':
  867. for _ in xrange(2):
  868. leaddata = self.connection.recv(1024, socket.MSG_PEEK)
  869. if is_clienthello(leaddata):
  870. try:
  871. server_name = extract_sni_name(leaddata)
  872. finally:
  873. break
  874. try:
  875. certfile = CertUtil.get_cert(server_name or 'www.google.com')
  876. ssl_sock = ssl.wrap_socket(self.connection, ssl_version=self.ssl_version, keyfile=certfile, certfile=certfile, server_side=True)
  877. except StandardError as e:
  878. if e.args[0] not in (errno.ECONNABORTED, errno.ECONNRESET):
  879. logging.exception('ssl.wrap_socket(self.connection=%r) failed: %s', self.connection, e)
  880. return
  881. self.connection = ssl_sock
  882. self.rfile = self.connection.makefile('rb', self.bufsize)
  883. self.wfile = self.connection.makefile('wb', 0)
  884. self.scheme = 'https'
  885. return BaseHTTPServer.BaseHTTPRequestHandler.handle_one_request(self)
  886. def first_run(self):
  887. pass
  888. def gethostbyname2(self, hostname):
  889. return socket.gethostbyname_ex(hostname)[-1]
  890. def create_tcp_connection(self, hostname, port, timeout, **kwargs):
  891. return socket.create_connection((hostname, port), timeout)
  892. def create_ssl_connection(self, hostname, port, timeout, **kwargs):
  893. sock = self.create_tcp_connection(hostname, port, timeout, **kwargs)
  894. ssl_sock = ssl.wrap_socket(sock, ssl_version=self.ssl_version)
  895. return ssl_sock
  896. def create_http_request(self, method, url, headers, body, timeout, **kwargs):
  897. scheme, netloc, path, query, _ = urlparse.urlsplit(url)
  898. if netloc.rfind(':') <= netloc.rfind(']'):
  899. # no port number
  900. host = netloc
  901. port = 443 if scheme == 'https' else 80
  902. else:
  903. host, _, port = netloc.rpartition(':')
  904. port = int(port)
  905. if query:
  906. path += '?' + query
  907. if 'Host' not in headers:
  908. headers['Host'] = host
  909. if body and 'Content-Length' not in headers:
  910. headers['Content-Length'] = str(len(body))
  911. ConnectionType = httplib.HTTPSConnection if scheme == 'https' else httplib.HTTPConnection
  912. connection = ConnectionType(netloc, timeout=timeout)
  913. connection.request(method, path, body=body, headers=headers)
  914. response = connection.getresponse()
  915. return response
  916. def create_http_request_withserver(self, fetchserver, method, url, headers, body, timeout, **kwargs):
  917. return URLFetch(fetchserver, self.create_http_request).fetch(method, url, headers, body, timeout, **kwargs)
  918. def handle_urlfetch_error(self, fetchserver, response):
  919. pass
  920. def handle_urlfetch_response_close(self, fetchserver, response):
  921. pass
  922. def parse_header(self):
  923. if self.command == 'CONNECT':
  924. netloc = self.path
  925. elif self.path[0] == '/':
  926. netloc = self.headers.get('Host', 'localhost')
  927. self.path = '%s://%s%s' % (self.scheme, netloc, self.path)
  928. else:
  929. netloc = urlparse.urlsplit(self.path).netloc
  930. m = re.match(r'^(.+):(\d+)$', netloc)
  931. if m:
  932. self.host = m.group(1).strip('[]')
  933. self.port = int(m.group(2))
  934. else:
  935. self.host = netloc
  936. self.port = 443 if self.scheme == 'https' else 80
  937. def forward_socket(self, local, remote, timeout):
  938. try:
  939. tick = 1
  940. bufsize = self.bufsize
  941. timecount = timeout
  942. while 1:
  943. timecount -= tick
  944. if timecount <= 0:
  945. break
  946. (ins, _, errors) = select.select([local, remote], [], [local, remote], tick)
  947. if errors:
  948. break
  949. for sock in ins:
  950. data = sock.recv(bufsize)
  951. if not data:
  952. break
  953. if sock is remote:
  954. local.sendall(data)
  955. timecount = timeout
  956. else:
  957. remote.sendall(data)
  958. timecount = timeout
  959. except socket.timeout:
  960. pass
  961. except NetWorkIOError as e:
  962. if e.args[0] not in (errno.ECONNABORTED, errno.ECONNRESET, errno.ENOTCONN, errno.EPIPE):
  963. raise
  964. if e.args[0] in (errno.EBADF,):
  965. return
  966. finally:
  967. for sock in (remote, local):
  968. try:
  969. sock.close()
  970. except StandardError:
  971. pass
  972. def MOCK(self, status, headers, content):
  973. """mock response"""
  974. logging.info('%s "MOCK %s %s %s" %d %d', self.address_string(), self.command, self.path, self.protocol_version, status, len(content))
  975. headers = dict((k.title(), v) for k, v in headers.items())
  976. if 'Transfer-Encoding' in headers:
  977. del headers['Transfer-Encoding']
  978. if 'Content-Length' not in headers:
  979. headers['Content-Length'] = len(content)
  980. if 'Connection' not in headers:
  981. headers['Connection'] = 'close'
  982. self.send_response(status)
  983. for key, value in headers.items():
  984. self.send_header(key, value)
  985. self.end_headers()
  986. self.wfile.write(content)
  987. def STRIP(self, do_ssl_handshake=True, sticky_filter=None):
  988. """strip connect"""
  989. certfile = CertUtil.get_cert(self.host)
  990. logging.info('%s "STRIP %s %s:%d %s" - -', self.address_string(), self.command, self.host, self.port, self.protocol_version)
  991. self.send_response(200)
  992. self.end_headers()
  993. if do_ssl_handshake:
  994. try:
  995. # ssl_sock = ssl.wrap_socket(self.connection, ssl_version=self.ssl_version, keyfile=certfile, certfile=certfile, server_side=True)
  996. # bugfix for youtube-dl
  997. ssl_sock = ssl.wrap_socket(self.connection, keyfile=certfile, certfile=certfile, server_side=True)
  998. except StandardError as e:
  999. if e.args[0] not in (errno.ECONNABORTED, errno.ECONNRESET):
  1000. logging.exception('ssl.wrap_socket(self.connection=%r) failed: %s', self.connection, e)
  1001. return
  1002. self.connection = ssl_sock
  1003. self.rfile = self.connection.makefile('rb', self.bufsize)
  1004. self.wfile = self.connection.makefile('wb', 0)
  1005. self.scheme = 'https'
  1006. try:
  1007. self.raw_requestline = self.rfile.readline(65537)
  1008. if len(self.raw_requestline) > 65536:
  1009. self.requestline = ''
  1010. self.request_version = ''
  1011. self.command = ''
  1012. self.send_error(414)
  1013. return
  1014. if not self.raw_requestline:
  1015. self.close_connection = 1
  1016. return
  1017. if not self.parse_request():
  1018. return
  1019. except NetWorkIOError as e:
  1020. if e.args[0] not in (errno.ECONNABORTED, errno.ECONNRESET, errno.EPIPE):
  1021. raise
  1022. self.sticky_filter = sticky_filter
  1023. try:
  1024. self.do_METHOD()
  1025. except NetWorkIOError as e:
  1026. if e.args[0] not in (errno.ECONNABORTED, errno.ETIMEDOUT, errno.EPIPE):
  1027. raise
  1028. def FORWARD(self, hostname, port, timeout, kwargs={}):
  1029. """forward socket"""
  1030. do_ssl_handshake = kwargs.pop('do_ssl_handshake', False)
  1031. local = self.connection
  1032. remote = None
  1033. self.send_response(200)
  1034. self.end_headers()
  1035. self.close_connection = 1
  1036. data = local.recv(1024)
  1037. if not data:
  1038. local.close()
  1039. return
  1040. data_is_clienthello = is_clienthello(data)
  1041. if data_is_clienthello:
  1042. kwargs['client_hello'] = data
  1043. max_retry = kwargs.get('max_retry', 3)
  1044. for i in xrange(max_retry):
  1045. try:
  1046. if do_ssl_handshake:
  1047. remote = self.create_ssl_connection(hostname, port, timeout, **kwargs)
  1048. else:
  1049. remote = self.create_tcp_connection(hostname, port, timeout, **kwargs)
  1050. if not data_is_clienthello and remote and not isinstance(remote, Exception):
  1051. remote.sendall(data)
  1052. break
  1053. except StandardError as e:
  1054. logging.exception('%s "FWD %s %s:%d %s" %r', self.address_string(), self.command, hostname, port, self.protocol_version, e)
  1055. if hasattr(remote, 'close'):
  1056. remote.close()
  1057. if i == max_retry - 1:
  1058. raise
  1059. logging.info('%s "FWD %s %s:%d %s" - -', self.address_string(), self.command, hostname, port, self.protocol_version)
  1060. if hasattr(remote, 'fileno'):
  1061. # reset timeout default to avoid long http upload failure, but it will delay timeout retry :(
  1062. remote.settimeout(None)
  1063. del kwargs
  1064. data = data_is_clienthello and getattr(remote, 'data', None)
  1065. if data:
  1066. del remote.data
  1067. local.sendall(data)
  1068. self.forward_socket(local, remote, self.max_timeout)
  1069. def DIRECT(self, kwargs):
  1070. method = self.command
  1071. if 'url' in kwargs:
  1072. url = kwargs.pop('url')
  1073. elif self.path.lower().startswith(('http://', 'https://', 'ftp://')):
  1074. url = self.path
  1075. else:
  1076. url = 'http://%s%s' % (self.headers['Host'], self.path)
  1077. headers = dict((k.title(), v) for k, v in self.headers.items())
  1078. body = self.body
  1079. response = None
  1080. try:
  1081. response = self.create_http_request(method, url, headers, body, timeout=self.connect_timeout, **kwargs)
  1082. logging.info('%s "DIRECT %s %s %s" %s %s', self.address_string(), self.command, url, self.protocol_version, response.status, response.getheader('Content-Length', '-'))
  1083. response_headers = dict((k.title(), v) for k, v in response.getheaders())
  1084. self.send_response(response.status)
  1085. for key, value in response.getheaders():
  1086. self.send_header(key, value)
  1087. self.end_headers()
  1088. if self.command == 'HEAD' or response.status in (204, 304):
  1089. response.close()
  1090. return
  1091. need_chunked = 'Transfer-Encoding' in response_headers
  1092. while True:
  1093. data = response.read(8192)
  1094. if not data:
  1095. if need_chunked:
  1096. self.wfile.write('0\r\n\r\n')
  1097. break
  1098. if need_chunked:
  1099. self.wfile.write('%x\r\n' % len(data))
  1100. self.wfile.write(data)
  1101. if need_chunked:
  1102. self.wfile.write('\r\n')
  1103. del data
  1104. except (ssl.SSLError, socket.timeout, socket.error):
  1105. if response:
  1106. if response.fp and response.fp._sock:
  1107. response.fp._sock.close()
  1108. response.close()
  1109. finally:
  1110. if response:
  1111. response.close()
  1112. def URLFETCH(self, fetchservers, max_retry=2, kwargs={}):
  1113. """urlfetch from fetchserver"""
  1114. method = self.command
  1115. if self.path[0] == '/':
  1116. url = '%s://%s%s' % (self.scheme, self.headers['Host'], self.path)
  1117. elif self.path.lower().startswith(('http://', 'https://', 'ftp://')):
  1118. url = self.path
  1119. else:
  1120. raise ValueError('URLFETCH %r is not a valid url' % self.path)
  1121. headers = dict((k.title(), v) for k, v in self.headers.items())
  1122. body = self.body
  1123. response = None
  1124. errors = []
  1125. fetchserver = fetchservers[0]
  1126. for i in xrange(max_retry):
  1127. try:
  1128. response = self.create_http_request_withserver(fetchserver, method, url, headers, body, timeout=60, **kwargs)
  1129. if response.app_status < 400:
  1130. break
  1131. else:
  1132. self.handle_urlfetch_error(fetchserver, response)
  1133. if i < max_retry - 1:
  1134. if len(fetchservers) > 1:
  1135. fetchserver = random.choice(fetchservers[1:])
  1136. logging.info('URLFETCH return %d, trying fetchserver=%r', response.app_status, fetchserver)
  1137. response.close()
  1138. except StandardError as e:
  1139. errors.append(e)
  1140. logging.info('URLFETCH "%s %s" fetchserver=%r %r, retry...', method, url, fetchserver, e)
  1141. if len(errors) == max_retry:
  1142. if response and response.app_status >= 500:
  1143. status = response.app_status
  1144. headers = dict(response.getheaders())
  1145. content = response.read()
  1146. response.close()
  1147. else:
  1148. status = 502
  1149. headers = {'Content-Type': 'text/html'}
  1150. content = message_html('502 URLFetch failed', 'Local URLFetch %r failed' % url, '<br>'.join(repr(x) for x in errors))
  1151. return self.MOCK(status, headers, content)
  1152. logging.info('%s "URL %s %s %s" %s %s', self.address_string(), method, url, self.protocol_version, response.status, response.getheader('Content-Length', '-'))
  1153. try:
  1154. if response.status == 206:
  1155. return RangeFetch(self, response, fetchservers, **kwargs).fetch()
  1156. if response.app_header_parsed:
  1157. self.close_connection = not response.getheader('Content-Length')
  1158. self.send_response(response.status)
  1159. for key, value in response.getheaders():
  1160. if key.title() == 'Transfer-Encoding':
  1161. continue
  1162. self.send_header(key, value)
  1163. self.end_headers()
  1164. bufsize = 8192
  1165. while True:
  1166. data = response.read(bufsize)
  1167. if data:
  1168. self.wfile.write(data)
  1169. if not data:
  1170. self.handle_urlfetch_response_close(fetchserver, response)
  1171. response.close()
  1172. break
  1173. del data
  1174. except NetWorkIOError as e:
  1175. if e[0] in (errno.ECONNABORTED, errno.EPIPE) or 'bad write retry' in repr(e):
  1176. return
  1177. def do_METHOD(self):
  1178. self.parse_header()
  1179. self.body = self.rfile.read(int(self.headers['Content-Length'])) if 'Content-Length' in self.headers else ''
  1180. if self.sticky_filter:
  1181. action = self.sticky_filter.filter(self)
  1182. if action:
  1183. return action.pop(0)(*action)
  1184. for handler_filter in self.handler_filters:
  1185. action = handler_filter.filter(self)
  1186. if action:
  1187. return action.pop(0)(*action)
  1188. class RangeFetch(object):
  1189. """Range Fetch Class"""
  1190. threads = 2
  1191. maxsize = 1024*1024*4
  1192. bufsize = 8192
  1193. waitsize = 1024*512
  1194. def __init__(self, handler, response, fetchservers, **kwargs):
  1195. self.handler = handler
  1196. self.url = handler.path
  1197. self.response = response
  1198. self.fetchservers = fetchservers
  1199. self.kwargs = kwargs
  1200. self._stopped = None
  1201. self._last_app_status = {}
  1202. self.expect_begin = 0
  1203. def fetch(self):
  1204. response_status = self.response.status
  1205. response_headers = dict((k.title(), v) for k, v in self.response.getheaders())
  1206. content_range = response_headers['Content-Range']
  1207. #content_length = response_headers['Content-Length']
  1208. start, end, length = tuple(int(x) for x in re.search(r'bytes (\d+)-(\d+)/(\d+)', content_range).group(1, 2, 3))
  1209. if start == 0:
  1210. response_status = 200
  1211. response_headers['Content-Length'] = str(length)
  1212. del response_headers['Content-Range']
  1213. else:
  1214. response_headers['Content-Range'] = 'bytes %s-%s/%s' % (start, end, length)
  1215. response_headers['Content-Length'] = str(length-start)
  1216. logging.info('>>>>>>>>>>>>>>> RangeFetch started(%r) %d-%d', self.url, start, end)
  1217. self.handler.send_response(response_status)
  1218. for key, value in response_headers.items():
  1219. self.handler.send_header(key, value)
  1220. self.handler.end_headers()
  1221. data_queue = Queue.PriorityQueue()
  1222. range_queue = Queue.PriorityQueue()
  1223. range_queue.put((start, end, self.response))
  1224. self.expect_begin = start
  1225. for begin in range(end+1, length, self.maxsize):
  1226. range_queue.put((begin, min(begin+self.maxsize-1, length-1), None))
  1227. for i in xrange(0, self.threads):
  1228. range_delay_size = i * self.maxsize
  1229. spawn_later(float(range_delay_size)/self.waitsize, self.__fetchlet, range_queue, data_queue, range_delay_size)
  1230. has_peek = hasattr(data_queue, 'peek')
  1231. peek_timeout = 120
  1232. while self.expect_begin < length - 1:
  1233. try:
  1234. if has_peek:
  1235. begin, data = data_queue.peek(timeout=peek_timeout)
  1236. if self.expect_begin == begin:
  1237. data_queue.get()
  1238. elif self.expect_begin < begin:
  1239. time.sleep(0.1)
  1240. continue
  1241. else:
  1242. logging.error('RangeFetch Error: begin(%r) < expect_begin(%r), quit.', begin, self.expect_begin)
  1243. break
  1244. else:
  1245. begin, data = data_queue.get(timeout=peek_timeout)
  1246. if self.expect_begin == begin:
  1247. pass
  1248. elif self.expect_begin < begin:
  1249. data_queue.put((begin, data))
  1250. time.sleep(0.1)
  1251. continue
  1252. else:
  1253. logging.error('RangeFetch Error: begin(%r) < expect_begin(%r), quit.', begin, self.expect_begin)
  1254. break
  1255. except Queue.Empty:
  1256. logging.error('data_queue peek timeout, break')
  1257. break
  1258. try:
  1259. self.handler.wfile.write(data)
  1260. self.expect_begin += len(data)
  1261. del data
  1262. except StandardError as e:
  1263. logging.info('RangeFetch client connection aborted(%s).', e)
  1264. break
  1265. self._stopped = True
  1266. def __fetchlet(self, range_queue, data_queue, range_delay_size):
  1267. headers = dict((k.title(), v) for k, v in self.handler.headers.items())
  1268. headers['Connection'] = 'close'
  1269. while 1:
  1270. try:
  1271. if self._stopped:
  1272. return
  1273. try:
  1274. start, end, response = range_queue.get(timeout=1)
  1275. if self.expect_begin < start and data_queue.qsize() * self.bufsize + range_delay_size > 30*1024*1024:
  1276. range_queue.put((start, end, response))
  1277. time.sleep(10)
  1278. continue
  1279. headers['Range'] = 'bytes=%d-%d' % (start, end)
  1280. fetchserver = ''
  1281. if not response:
  1282. fetchserver = random.choice(self.fetchservers)
  1283. if self._last_app_status.get(fetchserver, 200) >= 500:
  1284. time.sleep(5)
  1285. response = self.handler.create_http_request_withserver(fetchserver, self.handler.command, self.url, headers, self.handler.body, timeout=self.handler.connect_timeout, **self.kwargs)
  1286. except Queue.Empty:
  1287. continue
  1288. except StandardError as e:
  1289. logging.warning("Response %r in __fetchlet", e)
  1290. range_queue.put((start, end, None))
  1291. continue
  1292. if not response:
  1293. logging.warning('RangeFetch %s return %r', headers['Range'], response)
  1294. range_queue.put((start, end, None))
  1295. continue
  1296. if fetchserver:
  1297. self._last_app_status[fetchserver] = response.app_status
  1298. if response.app_status != 200:
  1299. logging.warning('Range Fetch "%s %s" %s return %s', self.handler.command, self.url, headers['Range'], response.app_status)
  1300. response.close()
  1301. range_queue.put((start, end, None))
  1302. continue
  1303. if response.getheader('Location'):
  1304. self.url = urlparse.urljoin(self.url, response.getheader('Location'))
  1305. logging.info('RangeFetch Redirect(%r)', self.url)
  1306. response.close()
  1307. range_queue.put((start, end, None))
  1308. continue
  1309. if 200 <= response.status < 300:
  1310. content_range = response.getheader('Content-Range')
  1311. if not content_range:
  1312. logging.warning('RangeFetch "%s %s" return Content-Range=%r: response headers=%r', self.handler.command, self.url, content_range, response.getheaders())
  1313. response.close()
  1314. range_queue.put((start, end, None))
  1315. continue
  1316. content_length = int(response.getheader('Content-Length', 0))
  1317. logging.info('>>>>>>>>>>>>>>> [thread %s] %s %s', threading.currentThread().ident, content_length, content_range)
  1318. while 1:
  1319. try:
  1320. if self._stopped:
  1321. response.close()
  1322. return
  1323. data = response.read(self.bufsize)
  1324. if not data:
  1325. break
  1326. data_queue.put((start, data))
  1327. start += len(data)
  1328. except StandardError as e:
  1329. logging.warning('RangeFetch "%s %s" %s failed: %s', self.handler.command, self.url, headers['Range'], e)
  1330. break
  1331. if start < end + 1:
  1332. logging.warning('RangeFetch "%s %s" retry %s-%s', self.handler.command, self.url, start, end)
  1333. response.close()
  1334. range_queue.put((start, end, None))
  1335. continue
  1336. logging.info('>>>>>>>>>>>>>>> Successfully reached %d bytes.', start - 1)
  1337. else:
  1338. logging.error('RangeFetch %r return %s', self.url, response.status)
  1339. response.close()
  1340. range_queue.put((start, end, None))
  1341. continue
  1342. except StandardError as e:
  1343. logging.exception('RangeFetch._fetchlet error:%s', e)
  1344. raise
  1345. class AdvancedProxyHandler(SimpleProxyHandler):
  1346. """Advanced Proxy Handler"""
  1347. dns_cache = LRUCache(64*1024)
  1348. dns_servers = []
  1349. dns_blacklist = []
  1350. tcp_connection_time = collections.defaultdict(float)
  1351. tcp_connection_time_with_clienthello = collections.defaultdict(float)
  1352. tcp_connection_cache = collections.defaultdict(Queue.PriorityQueue)
  1353. ssl_connection_time = collections.defaultdict(float)
  1354. ssl_connection_cache = collections.defaultdict(Queue.PriorityQueue)
  1355. ssl_connection_good_ipaddrs = {}
  1356. ssl_connection_bad_ipaddrs = {}
  1357. ssl_connection_unknown_ipaddrs = {}
  1358. ssl_connection_keepalive = False
  1359. max_window = 4
  1360. openssl_context = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_METHOD)
  1361. def gethostbyname2(self, hostname):
  1362. try:
  1363. iplist = self.dns_cache[hostname]
  1364. except KeyError:
  1365. if re.match(r'^\d+\.\d+\.\d+\.\d+$', hostname) or ':' in hostname:
  1366. iplist = [hostname]
  1367. elif self.dns_servers:
  1368. try:
  1369. record = dnslib_resolve_over_udp(hostname, self.dns_servers, timeout=2, blacklist=self.dns_blacklist)
  1370. except socket.gaierror:
  1371. record = dnslib_resolve_over_tcp(hostname, self.dns_servers, timeout=2, blacklist=self.dns_blacklist)
  1372. iplist = dnslib_record2iplist(record)
  1373. else:
  1374. iplist = socket.gethostbyname_ex(hostname)[-1]
  1375. self.dns_cache[hostname] = iplist
  1376. return iplist
  1377. def create_tcp_connection(self, hostname, port, timeout, **kwargs):
  1378. client_hello = kwargs.get('client_hello', None)
  1379. cache_key = kwargs.get('cache_key') if not client_hello else None
  1380. def create_connection(ipaddr, timeout, queobj):
  1381. sock = None
  1382. try:
  1383. # create a ipv4/ipv6 socket object
  1384. sock = socket.socket(socket.AF_INET if ':' not in ipaddr[0] else socket.AF_INET6)
  1385. # set reuseaddr option to avoid 10048 socket error
  1386. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  1387. # resize socket recv buffer 8K->32K to improve browser releated application performance
  1388. sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 32*1024)
  1389. # disable nagle algorithm to send http request quickly.
  1390. sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, True)
  1391. # set a short timeout to trigger timeout retry more quickly.
  1392. sock.settimeout(min(self.connect_timeout, timeout))
  1393. # start connection time record
  1394. start_time = time.time()
  1395. # TCP connect
  1396. sock.connect(ipaddr)
  1397. # record TCP connection time
  1398. self.tcp_connection_time[ipaddr] = time.time() - start_time
  1399. # send client hello and peek server hello
  1400. if client_hello:
  1401. sock.sendall(client_hello)
  1402. if gevent and isinstance(sock, gevent.socket.socket):
  1403. sock.data = data = sock.recv(4096)
  1404. else:
  1405. data = sock.recv(4096, socket.MSG_PEEK)
  1406. if not data:
  1407. logging.debug('create_tcp_connection %r with client_hello return NULL byte, continue %r', ipaddr, time.time()-start_time)
  1408. raise socket.timeout('timed out')
  1409. # record TCP connection time with client hello
  1410. self.tcp_connection_time_with_clienthello[ipaddr] = time.time() - start_time
  1411. # set timeout
  1412. sock.settimeout(timeout)
  1413. # put tcp socket object to output queobj
  1414. queobj.put(sock)
  1415. except (socket.error, OSError) as e:
  1416. # any socket.error, put Excpetions to output queobj.
  1417. queobj.put(e)
  1418. # reset a large and random timeout to the ipaddr
  1419. self.tcp_connection_time[ipaddr] = self.connect_timeout+random.random()
  1420. # close tcp socket
  1421. if sock:
  1422. sock.close()
  1423. def close_connection(count, queobj, first_tcp_time):
  1424. for _ in range(count):
  1425. sock = queobj.get()
  1426. tcp_time_threshold = min(1, 1.3 * first_tcp_time)
  1427. if sock and not isinstance(sock, Exception):
  1428. ipaddr = sock.getpeername()
  1429. if cache_key and self.tcp_connection_time[ipaddr] < tcp_time_threshold:
  1430. cache_queue = self.tcp_connection_cache[cache_key]
  1431. if cache_queue.qsize() < 8:
  1432. try:
  1433. _, old_sock = cache_queue.get_nowait()
  1434. old_sock.close()
  1435. except Queue.Empty:
  1436. pass
  1437. cache_queue.put((time.time(), sock))
  1438. else:
  1439. sock.close()
  1440. try:
  1441. while cache_key:
  1442. ctime, sock = self.tcp_connection_cache[cache_key].get_nowait()
  1443. if time.time() - ctime < 30:
  1444. return sock
  1445. else:
  1446. sock.close()
  1447. except Queue.Empty:
  1448. pass
  1449. addresses = [(x, port) for x in self.gethostbyname2(hostname)]
  1450. sock = None
  1451. for _ in range(kwargs.get('max_retry', 3)):
  1452. window = min((self.max_window+1)//2, len(addresses))
  1453. if client_hello:
  1454. addresses.sort(key=self.tcp_connection_time_with_clienthello.__getitem__)
  1455. else:
  1456. addresses.sort(key=self.tcp_connection_time.__getitem__)
  1457. addrs = addresses[:window] + random.sample(addresses, window)
  1458. queobj = gevent.queue.Queue() if gevent else Queue.Queue()
  1459. for addr in addrs:
  1460. thread.start_new_thread(create_connection, (addr, timeout, queobj))
  1461. for i in range(len(addrs)):
  1462. sock = queobj.get()
  1463. if not isinstance(sock, Exception):
  1464. first_tcp_time = self.tcp_connection_time[sock.getpeername()] if not cache_key else 0
  1465. thread.start_new_thread(close_connection, (len(addrs)-i-1, queobj, first_tcp_time))
  1466. return sock
  1467. elif i == 0:
  1468. # only output first error
  1469. logging.warning('create_tcp_connection to %r with %s return %r, try again.', hostname, addrs, sock)
  1470. if isinstance(sock, Exception):
  1471. raise sock
  1472. def create_ssl_connection(self, hostname, port, timeout, **kwargs):
  1473. cache_key = kwargs.get('cache_key')
  1474. validate = kwargs.get('validate')
  1475. def create_connection(ipaddr, timeout, queobj):
  1476. sock = None
  1477. ssl_sock = None
  1478. try:
  1479. # create a ipv4/ipv6 socket object
  1480. sock = socket.socket(socket.AF_INET if ':' not in ipaddr[0] else socket.AF_INET6)
  1481. # set reuseaddr option to avoid 10048 socket error
  1482. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  1483. # resize socket recv buffer 8K->32K to improve browser releated application performance
  1484. sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 32*1024)
  1485. # disable negal algorithm to send http request quickly.
  1486. sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, True)
  1487. # set a short timeout to trigger timeout retry more quickly.
  1488. sock.settimeout(min(self.connect_timeout, timeout))
  1489. # pick up the certificate
  1490. if not validate:
  1491. ssl_sock = ssl.wrap_socket(sock, ssl_version=self.ssl_version, do_handshake_on_connect=False)
  1492. else:
  1493. 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)
  1494. ssl_sock.settimeout(min(self.connect_timeout, timeout))
  1495. # start connection time record
  1496. start_time = time.time()
  1497. # TCP connect
  1498. ssl_sock.connect(ipaddr)
  1499. connected_time = time.time()
  1500. # SSL handshake
  1501. ssl_sock.do_handshake()
  1502. handshaked_time = time.time()
  1503. # record TCP connection time
  1504. self.tcp_connection_time[ipaddr] = ssl_sock.tcp_time = connected_time - start_time
  1505. # record SSL connection time
  1506. self.ssl_connection_time[ipaddr] = ssl_sock.ssl_time = handshaked_time - start_time
  1507. ssl_sock.ssl_time = connected_time - start_time
  1508. # sometimes, we want to use raw tcp socket directly(select/epoll), so setattr it to ssl socket.
  1509. ssl_sock.sock = sock
  1510. # remove from bad/unknown ipaddrs dict
  1511. self.ssl_connection_bad_ipaddrs.pop(ipaddr, None)
  1512. self.ssl_connection_unknown_ipaddrs.pop(ipaddr, None)
  1513. # add to good ipaddrs dict
  1514. if ipaddr not in self.ssl_connection_good_ipaddrs:
  1515. self.ssl_connection_good_ipaddrs[ipaddr] = handshaked_time
  1516. # verify SSL certificate.
  1517. if validate and hostname.endswith('.appspot.com'):
  1518. cert = ssl_sock.getpeercert()
  1519. orgname = next((v for ((k, v),) in cert['subject'] if k == 'organizationName'))
  1520. if not orgname.lower().startswith('google '):
  1521. raise ssl.SSLError("%r certificate organizationName(%r) not startswith 'Google'" % (hostname, orgname))
  1522. # set timeout
  1523. ssl_sock.settimeout(timeout)
  1524. # put ssl socket object to output queobj
  1525. queobj.put(ssl_sock)
  1526. except (socket.error, ssl.SSLError, OSError) as e:
  1527. # any socket.error, put Excpetions to output queobj.
  1528. queobj.put(e)
  1529. # reset a large and random timeout to the ipaddr
  1530. self.ssl_connection_time[ipaddr] = self.connect_timeout + random.random()
  1531. # add to bad ipaddrs dict
  1532. if ipaddr not in self.ssl_connection_bad_ipaddrs:
  1533. self.ssl_connection_bad_ipaddrs[ipaddr] = time.time()
  1534. # remove from good/unknown ipaddrs dict
  1535. self.ssl_connection_good_ipaddrs.pop(ipaddr, None)
  1536. self.ssl_connection_unknown_ipaddrs.pop(ipaddr, None)
  1537. # close ssl socket
  1538. if ssl_sock:
  1539. ssl_sock.close()
  1540. # close tcp socket
  1541. if sock:
  1542. sock.close()
  1543. def create_connection_withopenssl(ipaddr, timeout, queobj):
  1544. sock = None
  1545. ssl_sock = None
  1546. try:
  1547. # create a ipv4/ipv6 socket object
  1548. sock = socket.socket(socket.AF_INET if ':' not in ipaddr[0] else socket.AF_INET6)
  1549. # set reuseaddr option to avoid 10048 socket error
  1550. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  1551. # resize socket recv buffer 8K->32K to improve browser releated application performance
  1552. sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 32*1024)
  1553. # disable negal algorithm to send http request quickly.
  1554. sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, True)
  1555. # set a short timeout to trigger timeout retry more quickly.
  1556. sock.settimeout(timeout or self.connect_timeout)
  1557. # pick up the certificate
  1558. server_hostname = b'mail.google.com' if cache_key.startswith('google_') or hostname.endswith('.appspot.com') else None
  1559. ssl_sock = SSLConnection(self.openssl_context, sock)
  1560. ssl_sock.set_connect_state()
  1561. if server_hostname and hasattr(ssl_sock, 'set_tlsext_host_name'):
  1562. ssl_sock.set_tlsext_host_name(server_hostname)
  1563. # start connection time record
  1564. start_time = time.time()
  1565. # TCP connect
  1566. ssl_sock.connect(ipaddr)
  1567. connected_time = time.time()
  1568. # SSL handshake
  1569. ssl_sock.do_handshake()
  1570. handshaked_time = time.time()
  1571. # record TCP connection time
  1572. self.tcp_connection_time[ipaddr] = ssl_sock.tcp_time = connected_time - start_time
  1573. # record SSL connection time
  1574. self.ssl_connection_time[ipaddr] = ssl_sock.ssl_time = handshaked_time - start_time
  1575. # sometimes, we want to use raw tcp socket directly(select/epoll), so setattr it to ssl socket.
  1576. ssl_sock.sock = sock
  1577. # remove from bad/unknown ipaddrs dict
  1578. self.ssl_connection_bad_ipaddrs.pop(ipaddr, None)
  1579. self.ssl_connection_unknown_ipaddrs.pop(ipaddr, None)
  1580. # add to good ipaddrs dict
  1581. if ipaddr not in self.ssl_connection_good_ipaddrs:
  1582. self.ssl_connection_good_ipaddrs[ipaddr] = handshaked_time
  1583. # verify SSL certificate.
  1584. if validate and hostname.endswith('.appspot.com'):
  1585. cert = ssl_sock.get_peer_certificate()
  1586. commonname = next((v for k, v in cert.get_subject().get_components() if k == 'CN'))
  1587. if '.google' not in commonname and not commonname.endswith('.appspot.com'):
  1588. raise socket.error("Host name '%s' doesn't match certificate host '%s'" % (hostname, commonname))
  1589. # put ssl socket object to output queobj
  1590. queobj.put(ssl_sock)
  1591. except (socket.error, OpenSSL.SSL.Error, OSError) as e:
  1592. # any socket.error, put Excpetions to output queobj.
  1593. queobj.put(e)
  1594. # reset a large and random timeout to the ipaddr
  1595. self.ssl_connection_time[ipaddr] = self.connect_timeout + random.random()
  1596. # add to bad ipaddrs dict
  1597. if ipaddr not in self.ssl_connection_bad_ipaddrs:
  1598. self.ssl_connection_bad_ipaddrs[ipaddr] = time.time()
  1599. # remove from good/unknown ipaddrs dict
  1600. self.ssl_connection_good_ipaddrs.pop(ipaddr, None)
  1601. self.ssl_connection_unknown_ipaddrs.pop(ipaddr, None)
  1602. # close ssl socket
  1603. if ssl_sock:
  1604. ssl_sock.close()
  1605. # close tcp socket
  1606. if sock:
  1607. sock.close()
  1608. def close_connection(count, queobj, first_tcp_time, first_ssl_time):
  1609. for _ in range(count):
  1610. sock = queobj.get()
  1611. ssl_time_threshold = min(1, 1.3 * first_ssl_time)
  1612. if sock and not isinstance(sock, Exception):
  1613. if cache_key and sock.ssl_time < ssl_time_threshold:
  1614. cache_queue = self.ssl_connection_cache[cache_key]
  1615. if cache_queue.qsize() < 8:
  1616. try:
  1617. _, old_sock = cache_queue.get_nowait()
  1618. old_sock.close()
  1619. except Queue.Empty:
  1620. pass
  1621. cache_queue.put((time.time(), sock))
  1622. else:
  1623. sock.close()
  1624. def reorg_ipaddrs():
  1625. current_time = time.time()
  1626. for ipaddr, ctime in self.ssl_connection_good_ipaddrs.items():
  1627. if current_time - ctime > 4 * 60:
  1628. self.ssl_connection_good_ipaddrs.pop(ipaddr, None)
  1629. self.ssl_connection_unknown_ipaddrs[ipaddr] = ctime
  1630. for ipaddr, ctime in self.ssl_connection_bad_ipaddrs.items():
  1631. if current_time - ctime > 6 * 60:
  1632. self.ssl_connection_bad_ipaddrs.pop(ipaddr, None)
  1633. self.ssl_connection_unknown_ipaddrs[ipaddr] = ctime
  1634. 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))
  1635. try:
  1636. while cache_key:
  1637. ctime, sock = self.ssl_connection_cache[cache_key].get_nowait()
  1638. if time.time() - ctime < 30:
  1639. return sock
  1640. else:
  1641. sock.close()
  1642. except Queue.Empty:
  1643. pass
  1644. addresses = [(x, port) for x in self.gethostbyname2(hostname)]
  1645. sock = None
  1646. for i in range(kwargs.get('max_retry', 5)):
  1647. reorg_ipaddrs()
  1648. window = self.max_window + i
  1649. good_ipaddrs = [x for x in addresses if x in self.ssl_connection_good_ipaddrs]
  1650. good_ipaddrs = sorted(good_ipaddrs, key=self.ssl_connection_time.get)[:window]
  1651. 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]
  1652. random.shuffle(unkown_ipaddrs)
  1653. unkown_ipaddrs = unkown_ipaddrs[:window]
  1654. bad_ipaddrs = [x for x in addresses if x in self.ssl_connection_bad_ipaddrs]
  1655. bad_ipaddrs = sorted(bad_ipaddrs, key=self.ssl_connection_bad_ipaddrs.get)[:window]
  1656. addrs = good_ipaddrs + unkown_ipaddrs + bad_ipaddrs
  1657. remain_window = 3 * window - len(addrs)
  1658. if 0 < remain_window <= len(addresses):
  1659. addrs += random.sample(addresses, remain_window)
  1660. logging.debug('%s good_ipaddrs=%d, unkown_ipaddrs=%r, bad_ipaddrs=%r', cache_key, len(good_ipaddrs), len(unkown_ipaddrs), len(bad_ipaddrs))
  1661. queobj = gevent.queue.Queue() if gevent else Queue.Queue()
  1662. for addr in addrs:
  1663. thread.start_new_thread(create_connection_withopenssl, (addr, timeout, queobj))
  1664. for i in range(len(addrs)):
  1665. sock = queobj.get()
  1666. if not isinstance(sock, Exception):
  1667. thread.start_new_thread(close_connection, (len(addrs)-i-1, queobj, sock.tcp_time, sock.ssl_time))
  1668. return sock
  1669. elif i == 0:
  1670. # only output first error
  1671. logging.warning('create_ssl_connection to %r with %s return %r, try again.', hostname, addrs, sock)
  1672. if isinstance(sock, Exception):
  1673. raise sock
  1674. def create_http_request(self, method, url, headers, body, timeout, max_retry=2, bufsize=8192, crlf=None, validate=None, cache_key=None):
  1675. scheme, netloc, path, query, _ = urlparse.urlsplit(url)
  1676. if netloc.rfind(':') <= netloc.rfind(']'):
  1677. # no port number
  1678. host = netloc
  1679. port = 443 if scheme == 'https' else 80
  1680. else:
  1681. host, _, port = netloc.rpartition(':')
  1682. port = int(port)
  1683. if query:
  1684. path += '?' + query
  1685. if 'Host' not in headers:
  1686. headers['Host'] = host
  1687. if body and 'Content-Length' not in headers:
  1688. headers['Content-Length'] = str(len(body))
  1689. sock = None
  1690. for i in range(max_retry):
  1691. try:
  1692. create_connection = self.create_ssl_connection if scheme == 'https' else self.create_tcp_connection
  1693. sock = create_connection(host, port, timeout, validate=validate, cache_key=cache_key)
  1694. break
  1695. except StandardError as e:
  1696. logging.exception('create_http_request "%s %s" failed:%s', method, url, e)
  1697. if sock:
  1698. sock.close()
  1699. if i == max_retry - 1:
  1700. raise
  1701. request_data = ''
  1702. crlf_counter = 0
  1703. if scheme != 'https' and crlf:
  1704. fakeheaders = dict((k.title(), v) for k, v in headers.items())
  1705. fakeheaders.pop('Content-Length', None)
  1706. fakeheaders.pop('Cookie', None)
  1707. fakeheaders.pop('Host', None)
  1708. if 'User-Agent' not in fakeheaders:
  1709. 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'
  1710. if 'Accept-Language' not in fakeheaders:
  1711. fakeheaders['Accept-Language'] = 'zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4'
  1712. if 'Accept' not in fakeheaders:
  1713. fakeheaders['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
  1714. fakeheaders_data = ''.join('%s: %s\r\n' % (k, v) for k, v in fakeheaders.items() if k not in self.skip_headers)
  1715. while crlf_counter < 5 or len(request_data) < 1500 * 2:
  1716. request_data += 'GET / HTTP/1.1\r\n%s\r\n' % fakeheaders_data
  1717. crlf_counter += 1
  1718. request_data += '\r\n\r\n\r\n'
  1719. request_data += '%s %s %s\r\n' % (method, path, self.protocol_version)
  1720. request_data += ''.join('%s: %s\r\n' % (k.title(), v) for k, v in headers.items() if k.title() not in self.skip_headers)
  1721. request_data += '\r\n'
  1722. if isinstance(body, bytes):
  1723. sock.sendall(request_data.encode() + body)
  1724. elif hasattr(body, 'read'):
  1725. sock.sendall(request_data)
  1726. while 1:
  1727. data = body.read(bufsize)
  1728. if not data:
  1729. break
  1730. sock.sendall(data)
  1731. else:
  1732. raise TypeError('create_http_request(body) must be a string or buffer, not %r' % type(body))
  1733. response = None
  1734. try:
  1735. while crlf_counter:
  1736. if sys.version[:3] == '2.7':
  1737. response = httplib.HTTPResponse(sock, buffering=False)
  1738. else:
  1739. response = httplib.HTTPResponse(sock)
  1740. response.fp.close()
  1741. response.fp = sock.makefile('rb', 0)
  1742. response.begin()
  1743. response.read()
  1744. response.close()
  1745. crlf_counter -= 1
  1746. except StandardError as e:
  1747. logging.exception('crlf skip read host=%r path=%r error: %r', headers.get('Host'), path, e)
  1748. if response:
  1749. if response.fp and response.fp._sock:
  1750. response.fp._sock.close()
  1751. response.close()
  1752. if sock:
  1753. sock.close()
  1754. return None
  1755. if sys.version[:3] == '2.7':
  1756. response = httplib.HTTPResponse(sock, buffering=True)
  1757. else:
  1758. response = httplib.HTTPResponse(sock)
  1759. response.fp.close()
  1760. response.fp = sock.makefile('rb')
  1761. response.begin()
  1762. if self.ssl_connection_keepalive and scheme == 'https' and cache_key:
  1763. response.cache_key = cache_key
  1764. response.cache_sock = response.fp._sock
  1765. return response
  1766. def handle_urlfetch_response_close(self, fetchserver, response):
  1767. cache_sock = getattr(response, 'cache_sock', None)
  1768. if cache_sock:
  1769. if self.scheme == 'https':
  1770. self.ssl_connection_cache[response.cache_key].put((time.time(), cache_sock))
  1771. else:
  1772. cache_sock.close()
  1773. del response.cache_sock
  1774. def handle_urlfetch_error(self, fetchserver, response):
  1775. pass
  1776. class Common(object):
  1777. """Global Config Object"""
  1778. ENV_CONFIG_PREFIX = 'GOAGENT_'
  1779. def __init__(self):
  1780. """load config from proxy.ini"""
  1781. ConfigParser.RawConfigParser.OPTCRE = re.compile(r'(?P<option>[^=\s][^=]*)\s*(?P<vi>[=])\s*(?P<value>.*)$')
  1782. self.CONFIG = ConfigParser.ConfigParser()
  1783. self.CONFIG_FILENAME = os.path.splitext(os.path.abspath(__file__))[0]+'.ini'
  1784. self.CONFIG_USER_FILENAME = re.sub(r'\.ini$', '.user.ini', self.CONFIG_FILENAME)
  1785. self.CONFIG.read([self.CONFIG_FILENAME, self.CONFIG_USER_FILENAME])
  1786. for key, value in os.environ.items():
  1787. m = re.match(r'^%s([A-Z]+)_([A-Z\_\-]+)$' % self.ENV_CONFIG_PREFIX, key)
  1788. if m:
  1789. self.CONFIG.set(m.group(1).lower(), m.group(2).lower(), value)
  1790. self.LISTEN_IP = self.CONFIG.get('listen', 'ip')
  1791. self.LISTEN_PORT = self.CONFIG.getint('listen', 'port')
  1792. self.LISTEN_USERNAME = self.CONFIG.get('listen', 'username') if self.CONFIG.has_option('listen', 'username') else ''
  1793. self.LISTEN_PASSWORD = self.CONFIG.get('listen', 'password') if self.CONFIG.has_option('listen', 'password') else ''
  1794. self.LISTEN_VISIBLE = self.CONFIG.getint('listen', 'visible')
  1795. self.LISTEN_DEBUGINFO = self.CONFIG.getint('listen', 'debuginfo')
  1796. self.GAE_APPIDS = re.findall(r'[\w\-\.]+', self.CONFIG.get('gae', 'appid').replace('.appspot.com', ''))
  1797. self.GAE_PASSWORD = self.CONFIG.get('gae', 'password').strip()
  1798. self.GAE_PATH = self.CONFIG.get('gae', 'path')
  1799. self.GAE_MODE = self.CONFIG.get('gae', 'mode')
  1800. self.GAE_PROFILE = self.CONFIG.get('gae', 'profile').strip()
  1801. self.GAE_WINDOW = self.CONFIG.getint('gae', 'window')
  1802. self.GAE_KEEPALIVE = self.CONFIG.getint('gae', 'keepalive') if self.CONFIG.has_option('gae', 'keepalive') else 0
  1803. self.GAE_OBFUSCATE = self.CONFIG.getint('gae', 'obfuscate')
  1804. self.GAE_VALIDATE = self.CONFIG.getint('gae', 'validate')
  1805. self.GAE_TRANSPORT = self.CONFIG.getint('gae', 'transport') if self.CONFIG.has_option('gae', 'transport') else 0
  1806. self.GAE_OPTIONS = self.CONFIG.get('gae', 'options')
  1807. self.GAE_REGIONS = set(x.upper() for x in self.CONFIG.get('gae', 'regions').split('|') if x.strip())
  1808. self.GAE_SSLVERSION = self.CONFIG.get('gae', 'sslversion')
  1809. self.GAE_PAGESPEED = self.CONFIG.getint('gae', 'pagespeed') if self.CONFIG.has_option('gae', 'pagespeed') else 0
  1810. if self.GAE_PROFILE == 'auto':
  1811. try:
  1812. socket.create_connection(('2001:4860:4860::8888', 53), timeout=1).close()
  1813. logging.info('Use profile ipv6')
  1814. self.GAE_PROFILE = 'ipv6'
  1815. except socket.error as e:
  1816. logging.info('Fail try profile ipv6 %r, fallback ipv4', e)
  1817. self.GAE_PROFILE = 'ipv4'
  1818. hosts_section, http_section = '%s/hosts' % self.GAE_PROFILE, '%s/http' % self.GAE_PROFILE
  1819. if 'USERDNSDOMAIN' in os.environ and re.match(r'^\w+\.\w+$', os.environ['USERDNSDOMAIN']):
  1820. self.CONFIG.set(hosts_section, '.' + os.environ['USERDNSDOMAIN'], '')
  1821. 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('.'))
  1822. 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('.'))
  1823. self.HOST_POSTFIX_ENDSWITH = tuple(self.HOST_POSTFIX_MAP)
  1824. self.HOSTPORT_MAP = collections.OrderedDict((k, v) for k, v in self.CONFIG.items(hosts_section) if ':' in k and not k.startswith('.'))
  1825. self.HOSTPORT_POSTFIX_MAP = collections.OrderedDict((k, v) for k, v in self.CONFIG.items(hosts_section) if ':' in k and k.startswith('.'))
  1826. self.HOSTPORT_POSTFIX_ENDSWITH = tuple(self.HOSTPORT_POSTFIX_MAP)
  1827. self.URLRE_MAP = collections.OrderedDict((re.compile(k).match, v) for k, v in self.CONFIG.items(hosts_section) if '\\' in k)
  1828. self.HTTP_WITHGAE = set(self.CONFIG.get(http_section, 'withgae').split('|'))
  1829. self.HTTP_CRLFSITES = tuple(self.CONFIG.get(http_section, 'crlfsites').split('|'))
  1830. self.HTTP_FORCEHTTPS = tuple(self.CONFIG.get(http_section, 'forcehttps').split('|')) if self.CONFIG.get(http_section, 'forcehttps').strip() else tuple()
  1831. self.HTTP_NOFORCEHTTPS = set(self.CONFIG.get(http_section, 'noforcehttps').split('|')) if self.CONFIG.get(http_section, 'noforcehttps').strip() else set()
  1832. self.HTTP_FAKEHTTPS = tuple(self.CONFIG.get(http_section, 'fakehttps').split('|')) if self.CONFIG.get(http_section, 'fakehttps').strip() else tuple()
  1833. self.HTTP_NOFAKEHTTPS = set(self.CONFIG.get(http_section, 'nofakehttps').split('|')) if self.CONFIG.get(http_section, 'nofakehttps').strip() else set()
  1834. self.HTTP_DNS = self.CONFIG.get(http_section, 'dns').split('|') if self.CONFIG.has_option(http_section, 'dns') else []
  1835. self.IPLIST_MAP = collections.OrderedDict((k, v.split('|')) for k, v in self.CONFIG.items('iplist'))
  1836. self.IPLIST_MAP.update((k, [k]) for k, v in self.HOST_MAP.items() if k == v)
  1837. self.PAC_ENABLE = self.CONFIG.getint('pac', 'enable')
  1838. self.PAC_IP = self.CONFIG.get('pac', 'ip')
  1839. self.PAC_PORT = self.CONFIG.getint('pac', 'port')
  1840. self.PAC_FILE = self.CONFIG.get('pac', 'file').lstrip('/')
  1841. self.PAC_GFWLIST = self.CONFIG.get('pac', 'gfwlist')
  1842. self.PAC_ADBLOCK = self.CONFIG.get('pac', 'adblock')
  1843. self.PAC_ADMODE = self.CONFIG.getint('pac', 'admode')
  1844. self.PAC_EXPIRED = self.CONFIG.getint('pac', 'expired')
  1845. self.PHP_ENABLE = self.CONFIG.getint('php', 'enable')
  1846. self.PHP_LISTEN = self.CONFIG.get('php', 'listen')
  1847. self.PHP_PASSWORD = self.CONFIG.get('php', 'password') if self.CONFIG.has_option('php', 'password') else ''
  1848. self.PHP_CRLF = self.CONFIG.getint('php', 'crlf') if self.CONFIG.has_option('php', 'crlf') else 1
  1849. self.PHP_VALIDATE = self.CONFIG.getint('php', 'validate') if self.CONFIG.has_option('php', 'validate') else 0
  1850. self.PHP_FETCHSERVER = self.CONFIG.get('php', 'fetchserver')
  1851. self.PHP_USEHOSTS = self.CONFIG.getint('php', 'usehosts')
  1852. self.PROXY_ENABLE = self.CONFIG.getint('proxy', 'enable')
  1853. self.PROXY_AUTODETECT = self.CONFIG.getint('proxy', 'autodetect') if self.CONFIG.has_option('proxy', 'autodetect') else 0
  1854. self.PROXY_HOST = self.CONFIG.get('proxy', 'host')
  1855. self.PROXY_PORT = self.CONFIG.getint('proxy', 'port')
  1856. self.PROXY_USERNAME = self.CONFIG.get('proxy', 'username')
  1857. self.PROXY_PASSWROD = self.CONFIG.get('proxy', 'password')
  1858. if not self.PROXY_ENABLE and self.PROXY_AUTODETECT:
  1859. system_proxy = ProxyUtil.get_system_proxy()
  1860. if system_proxy and self.LISTEN_IP not in system_proxy:
  1861. _, username, password, address = ProxyUtil.parse_proxy(system_proxy)
  1862. proxyhost, _, proxyport = address.rpartition(':')
  1863. self.PROXY_ENABLE = 1
  1864. self.PROXY_USERNAME = username
  1865. self.PROXY_PASSWROD = password
  1866. self.PROXY_HOST = proxyhost
  1867. self.PROXY_PORT = int(proxyport)
  1868. if self.PROXY_ENABLE:
  1869. self.GAE_MODE = 'https'
  1870. self.AUTORANGE_HOSTS = self.CONFIG.get('autorange', 'hosts').split('|')
  1871. self.AUTORANGE_HOSTS_MATCH = [re.compile(fnmatch.translate(h)).match for h in self.AUTORANGE_HOSTS]
  1872. self.AUTORANGE_ENDSWITH = tuple(self.CONFIG.get('autorange', 'endswith').split('|'))
  1873. self.AUTORANGE_NOENDSWITH = tuple(self.CONFIG.get('autorange', 'noendswith').split('|'))
  1874. self.AUTORANGE_MAXSIZE = self.CONFIG.getint('autorange', 'maxsize')
  1875. self.AUTORANGE_WAITSIZE = self.CONFIG.getint('autorange', 'waitsize')
  1876. self.AUTORANGE_BUFSIZE = self.CONFIG.getint('autorange', 'bufsize')
  1877. self.AUTORANGE_THREADS = self.CONFIG.getint('autorange', 'threads')
  1878. self.FETCHMAX_LOCAL = self.CONFIG.getint('fetchmax', 'local') if self.CONFIG.get('fetchmax', 'local') else 3
  1879. self.FETCHMAX_SERVER = self.CONFIG.get('fetchmax', 'server')
  1880. self.DNS_ENABLE = self.CONFIG.getint('dns', 'enable')
  1881. self.DNS_LISTEN = self.CONFIG.get('dns', 'listen')
  1882. self.DNS_SERVERS = self.HTTP_DNS or self.CONFIG.get('dns', 'servers').split('|')
  1883. self.DNS_BLACKLIST = set(self.CONFIG.get('dns', 'blacklist').split('|'))
  1884. self.DNS_TCPOVER = tuple(self.CONFIG.get('dns', 'tcpover').split('|')) if self.CONFIG.get('dns', 'tcpover').strip() else tuple()
  1885. self.USERAGENT_ENABLE = self.CONFIG.getint('useragent', 'enable')
  1886. self.USERAGENT_STRING = self.CONFIG.get('useragent', 'string')
  1887. self.LOVE_ENABLE = self.CONFIG.getint('love', 'enable')
  1888. self.LOVE_TIP = self.CONFIG.get('love', 'tip').encode('utf8').decode('unicode-escape').split('|')
  1889. def extend_iplist(self, iplist_name, hosts):
  1890. logging.info('extend_iplist start for hosts=%s', hosts)
  1891. new_iplist = []
  1892. def do_remote_resolve(host, dnsserver, queue):
  1893. assert isinstance(dnsserver, basestring)
  1894. for dnslib_resolve in (dnslib_resolve_over_udp, dnslib_resolve_over_tcp):
  1895. try:
  1896. iplist = dnslib_record2iplist(dnslib_resolve(host, [dnsserver], timeout=4, blacklist=self.DNS_BLACKLIST))
  1897. queue.put((host, dnsserver, iplist))
  1898. except (socket.error, OSError) as e:
  1899. logging.warning('%r remote host=%r failed: %s', dnslib_resolve.func_name, host, e)
  1900. result_queue = Queue.Queue()
  1901. for host in hosts:
  1902. for dnsserver in self.DNS_SERVERS:
  1903. logging.debug('remote resolve host=%r from dnsserver=%r', host, dnsserver)
  1904. thread.start_new_thread(do_remote_resolve, (host, dnsserver, result_queue))
  1905. for _ in xrange(len(self.DNS_SERVERS) * len(hosts) * 2):
  1906. try:
  1907. host, dnsserver, iplist = result_queue.get(timeout=8)
  1908. logging.debug('%r remote host=%r return %s', dnsserver, host, iplist)
  1909. new_iplist += iplist
  1910. except Queue.Empty:
  1911. break
  1912. self.IPLIST_MAP[iplist_name] = list(set(self.IPLIST_MAP[iplist_name] + new_iplist))
  1913. logging.info('extend_iplist finished, added %s', len(set(new_iplist)))
  1914. def resolve_iplist(self):
  1915. # https://support.google.com/websearch/answer/186669?hl=zh-Hans
  1916. def do_local_resolve(host, queue):
  1917. assert isinstance(host, basestring)
  1918. for _ in xrange(3):
  1919. try:
  1920. queue.put((host, socket.gethostbyname_ex(host)[-1]))
  1921. except (socket.error, OSError) as e:
  1922. logging.warning('socket.gethostbyname_ex host=%r failed: %s', host, e)
  1923. time.sleep(0.1)
  1924. google_blacklist = ['216.239.32.20'] + list(self.DNS_BLACKLIST)
  1925. for name, need_resolve_hosts in list(self.IPLIST_MAP.items()):
  1926. if all(re.match(r'\d+\.\d+\.\d+\.\d+', x) or ':' in x for x in need_resolve_hosts):
  1927. continue
  1928. need_resolve_remote = [x for x in need_resolve_hosts if ':' not in x and not re.match(r'\d+\.\d+\.\d+\.\d+', x)]
  1929. resolved_iplist = [x for x in need_resolve_hosts if x not in need_resolve_remote]
  1930. result_queue = Queue.Queue()
  1931. for host in need_resolve_remote:
  1932. logging.debug('local resolve host=%r', host)
  1933. thread.start_new_thread(do_local_resolve, (host, result_queue))
  1934. for _ in xrange(len(need_resolve_remote)):
  1935. try:
  1936. host, iplist = result_queue.get(timeout=8)
  1937. resolved_iplist += iplist
  1938. except Queue.Empty:
  1939. break
  1940. if name == 'google_hk':
  1941. spawn_later(1, self.extend_iplist, name, need_resolve_remote)
  1942. if name.startswith('google_') and name not in ('google_cn', 'google_hk') and resolved_iplist:
  1943. iplist_prefix = re.split(r'[\.:]', resolved_iplist[0])[0]
  1944. resolved_iplist = list(set(x for x in resolved_iplist if x.startswith(iplist_prefix)))
  1945. else:
  1946. resolved_iplist = list(set(resolved_iplist))
  1947. if name.startswith('google_'):
  1948. resolved_iplist = list(set(resolved_iplist) - set(google_blacklist))
  1949. if len(resolved_iplist) == 0:
  1950. logging.error('resolve %s host return empty! please retry!', name)
  1951. sys.exit(-1)
  1952. logging.info('resolve name=%s host to iplist=%r', name, resolved_iplist)
  1953. common.IPLIST_MAP[name] = resolved_iplist
  1954. def info(self):
  1955. info = ''
  1956. info += '------------------------------------------------------\n'
  1957. info += 'GoAgent Version : %s (python/%s %spyopenssl/%s)\n' % (__version__, sys.version[:5], gevent and 'gevent/%s ' % gevent.__version__ or '', getattr(OpenSSL, '__version__', 'Disabled'))
  1958. 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 ''
  1959. info += 'Listen Address : %s:%d\n' % (self.LISTEN_IP, self.LISTEN_PORT)
  1960. info += 'Local Proxy : %s:%s\n' % (self.PROXY_HOST, self.PROXY_PORT) if self.PROXY_ENABLE else ''
  1961. info += 'Debug INFO : %s\n' % self.LISTEN_DEBUGINFO if self.LISTEN_DEBUGINFO else ''
  1962. info += 'GAE Mode : %s\n' % self.GAE_MODE
  1963. info += 'GAE Profile : %s\n' % self.GAE_PROFILE if self.GAE_PROFILE else ''
  1964. info += 'GAE APPID : %s\n' % '|'.join(self.GAE_APPIDS)
  1965. info += 'GAE Validate : %s\n' % self.GAE_VALIDATE if self.GAE_VALIDATE else ''
  1966. info += 'GAE Obfuscate : %s\n' % self.GAE_OBFUSCATE if self.GAE_OBFUSCATE else ''
  1967. if common.PAC_ENABLE:
  1968. 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)
  1969. info += 'Pac File : file://%s\n' % os.path.abspath(self.PAC_FILE)
  1970. if common.PHP_ENABLE:
  1971. info += 'PHP Listen : %s\n' % common.PHP_LISTEN
  1972. info += 'PHP FetchServer : %s\n' % common.PHP_FETCHSERVER
  1973. if common.DNS_ENABLE:
  1974. info += 'DNS Listen : %s\n' % common.DNS_LISTEN
  1975. info += 'DNS Servers : %s\n' % '|'.join(common.DNS_SERVERS)
  1976. info += '------------------------------------------------------\n'
  1977. return info
  1978. common = Common()
  1979. def message_html(title, banner, detail=''):
  1980. MESSAGE_TEMPLATE = '''
  1981. <html><head>
  1982. <meta http-equiv="content-type" content="text/html;charset=utf-8">
  1983. <title>$title</title>
  1984. <style><!--
  1985. body {font-family: arial,sans-serif}
  1986. div.nav {margin-top: 1ex}
  1987. div.nav A {font-size: 10pt; font-family: arial,sans-serif}
  1988. span.nav {font-size: 10pt; font-family: arial,sans-serif; font-weight: bold}
  1989. div.nav A,span.big {font-size: 12pt; color: #0000cc}
  1990. div.nav A {font-size: 10pt; color: black}
  1991. A.l:link {color: #6f6f6f}
  1992. A.u:link {color: green}
  1993. //--></style>
  1994. </head>
  1995. <body text=#000000 bgcolor=#ffffff>
  1996. <table border=0 cellpadding=2 cellspacing=0 width=100%>
  1997. <tr><td bgcolor=#3366cc><font face=arial,sans-serif color=#ffffff><b>Message From LocalProxy</b></td></tr>
  1998. <tr><td> </td></tr></table>
  1999. <blockquote>
  2000. <H1>$banner</H1>
  2001. $detail
  2002. <p>
  2003. </blockquote>
  2004. <table width=100% cellpadding=0 cellspacing=0><tr><td bgcolor=#3366cc><img alt="" width=1 height=4></td></tr></table>
  2005. </body></html>
  2006. '''
  2007. return string.Template(MESSAGE_TEMPLATE).substitute(title=title, banner=banner, detail=detail)
  2008. try:
  2009. from Crypto.Cipher.ARC4 import new as RC4Cipher
  2010. except ImportError:
  2011. logging.warn('Load Crypto.Cipher.ARC4 Failed, Use Pure Python Instead.')
  2012. class RC4Cipher(object):
  2013. def __init__(self, key):
  2014. x = 0
  2015. box = range(256)
  2016. for i, y in enumerate(box):
  2017. x = (x + y + ord(key[i % len(key)])) & 0xff
  2018. box[i], box[x] = box[x], y
  2019. self.__box = box
  2020. self.__x = 0
  2021. self.__y = 0
  2022. def encrypt(self, data):
  2023. out = []
  2024. out_append = out.append
  2025. x = self.__x
  2026. y = self.__y
  2027. box = self.__box
  2028. for char in data:
  2029. x = (x + 1) & 0xff
  2030. y = (y + box[x]) & 0xff
  2031. box[x], box[y] = box[y], box[x]
  2032. out_append(chr(ord(char) ^ box[(box[x] + box[y]) & 0xff]))
  2033. self.__x = x
  2034. self.__y = y
  2035. return ''.join(out)
  2036. class XORCipher(object):
  2037. """XOR Cipher Class"""
  2038. def __init__(self, key):
  2039. self.__key_gen = itertools.cycle([ord(x) for x in key]).next
  2040. self.__key_xor = lambda s: ''.join(chr(ord(x) ^ self.__key_gen()) for x in s)
  2041. if len(key) == 1:
  2042. try:
  2043. from Crypto.Util.strxor import strxor_c
  2044. c = ord(key)
  2045. self.__key_xor = lambda s: strxor_c(s, c)
  2046. except ImportError:
  2047. sys.stderr.write('Load Crypto.Util.strxor Failed, Use Pure Python Instead.\n')
  2048. def encrypt(self, data):
  2049. return self.__key_xor(data)
  2050. class CipherFileObject(object):
  2051. """fileobj wrapper for cipher"""
  2052. def __init__(self, fileobj, cipher):
  2053. self.__fileobj = fileobj
  2054. self.__cipher = cipher
  2055. def __getattr__(self, attr):
  2056. if attr not in ('__fileobj', '__cipher'):
  2057. return getattr(self.__fileobj, attr)
  2058. def read(self, size=-1):
  2059. return self.__cipher.encrypt(self.__fileobj.read(size))
  2060. class LocalProxyServer(SocketServer.ThreadingTCPServer):
  2061. """Local Proxy Server"""
  2062. allow_reuse_address = True
  2063. daemon_threads = True
  2064. def close_request(self, request):
  2065. try:
  2066. request.close()
  2067. except StandardError:
  2068. pass
  2069. def finish_request(self, request, client_address):
  2070. try:
  2071. self.RequestHandlerClass(request, client_address, self)
  2072. except NetWorkIOError as e:
  2073. if e[0] not in (errno.ECONNABORTED, errno.ECONNRESET, errno.EPIPE):
  2074. raise
  2075. def handle_error(self, *args):
  2076. """make ThreadingTCPServer happy"""
  2077. exc_info = sys.exc_info()
  2078. error = exc_info and len(exc_info) and exc_info[1]
  2079. if isinstance(error, NetWorkIOError) and len(error.args) > 1 and 'bad write retry' in error.args[1]:
  2080. exc_info = error = None
  2081. else:
  2082. del exc_info, error
  2083. SocketServer.ThreadingTCPServer.handle_error(self, *args)
  2084. class UserAgentFilter(BaseProxyHandlerFilter):
  2085. """user agent filter"""
  2086. def filter(self, handler):
  2087. if common.USERAGENT_ENABLE:
  2088. handler.headers['User-Agent'] = common.USERAGENT_STRING
  2089. class WithGAEFilter(BaseProxyHandlerFilter):
  2090. """with gae filter"""
  2091. def filter(self, handler):
  2092. if handler.host in common.HTTP_WITHGAE:
  2093. logging.debug('WithGAEFilter metched %r %r', handler.path, handler.headers)
  2094. # assume the last one handler is GAEFetchFilter
  2095. return handler.handler_filters[-1].filter(handler)
  2096. class ForceHttpsFilter(BaseProxyHandlerFilter):
  2097. """force https filter"""
  2098. def filter(self, handler):
  2099. if handler.command != 'CONNECT' and handler.host.endswith(common.HTTP_FORCEHTTPS) and handler.host not in common.HTTP_NOFORCEHTTPS:
  2100. if not handler.headers.get('Referer', '').startswith('https://') and not handler.path.startswith('https://'):
  2101. logging.debug('ForceHttpsFilter metched %r %r', handler.path, handler.headers)
  2102. headers = {'Location': handler.path.replace('http://', 'https://', 1), 'Connection': 'close'}
  2103. return [handler.MOCK, 301, headers, '']
  2104. class FakeHttpsFilter(BaseProxyHandlerFilter):
  2105. """fake https filter"""
  2106. def filter(self, handler):
  2107. if handler.command == 'CONNECT' and handler.host.endswith(common.HTTP_FAKEHTTPS) and handler.host not in common.HTTP_NOFAKEHTTPS:
  2108. logging.debug('FakeHttpsFilter metched %r %r', handler.path, handler.headers)
  2109. return [handler.STRIP, True, None]
  2110. class HostsFilter(BaseProxyHandlerFilter):
  2111. """force https filter"""
  2112. def filter_localfile(self, handler, filename):
  2113. content_type = None
  2114. try:
  2115. import mimetypes
  2116. content_type = mimetypes.types_map.get(os.path.splitext(filename)[1])
  2117. except StandardError as e:
  2118. logging.error('import mimetypes failed: %r', e)
  2119. try:
  2120. with open(filename, 'rb') as fp:
  2121. data = fp.read()
  2122. headers = {'Connection': 'close', 'Content-Length': str(len(data))}
  2123. if content_type:
  2124. headers['Content-Type'] = content_type
  2125. return [handler.MOCK, 200, headers, data]
  2126. except StandardError as e:
  2127. return [handler.MOCK, 403, {'Connection': 'close'}, 'read %r %r' % (filename, e)]
  2128. def filter(self, handler):
  2129. host, port = handler.host, handler.port
  2130. hostport = handler.path if handler.command == 'CONNECT' else '%s:%d' % (host, port)
  2131. hostname = ''
  2132. if host in common.HOST_MAP:
  2133. hostname = common.HOST_MAP[host] or host
  2134. elif host.endswith(common.HOST_POSTFIX_ENDSWITH):
  2135. hostname = next(common.HOST_POSTFIX_MAP[x] for x in common.HOST_POSTFIX_MAP if host.endswith(x)) or host
  2136. common.HOST_MAP[host] = hostname
  2137. if hostport in common.HOSTPORT_MAP:
  2138. hostname = common.HOSTPORT_MAP[hostport] or host
  2139. elif hostport.endswith(common.HOSTPORT_POSTFIX_ENDSWITH):
  2140. hostname = next(common.HOSTPORT_POSTFIX_MAP[x] for x in common.HOSTPORT_POSTFIX_MAP if hostport.endswith(x)) or host
  2141. common.HOSTPORT_MAP[hostport] = hostname
  2142. if handler.command != 'CONNECT' and common.URLRE_MAP:
  2143. try:
  2144. hostname = next(common.URLRE_MAP[x] for x in common.URLRE_MAP if x(handler.path)) or host
  2145. except StopIteration:
  2146. pass
  2147. if not hostname:
  2148. return None
  2149. elif hostname in common.IPLIST_MAP:
  2150. handler.dns_cache[host] = common.IPLIST_MAP[hostname]
  2151. elif hostname == host and host.endswith(common.DNS_TCPOVER) and host not in handler.dns_cache:
  2152. try:
  2153. iplist = dnslib_record2iplist(dnslib_resolve_over_tcp(host, handler.dns_servers, timeout=4, blacklist=handler.dns_blacklist))
  2154. logging.info('HostsFilter dnslib_resolve_over_tcp %r with %r return %s', host, handler.dns_servers, iplist)
  2155. handler.dns_cache[host] = iplist
  2156. except socket.error as e:
  2157. logging.warning('HostsFilter dnslib_resolve_over_tcp %r with %r failed: %r', host, handler.dns_servers, e)
  2158. elif re.match(r'^\d+\.\d+\.\d+\.\d+$', hostname) or ':' in hostname:
  2159. handler.dns_cache[host] = [hostname]
  2160. elif hostname.startswith('file://'):
  2161. filename = hostname.lstrip('file://')
  2162. if os.name == 'nt':
  2163. filename = filename.lstrip('/')
  2164. return self.filter_localfile(handler, filename)
  2165. cache_key = '%s:%s' % (hostname, port)
  2166. if handler.command == 'CONNECT':
  2167. return [handler.FORWARD, host, port, handler.connect_timeout, {'cache_key': cache_key}]
  2168. else:
  2169. if host.endswith(common.HTTP_CRLFSITES):
  2170. handler.close_connection = True
  2171. return [handler.DIRECT, {'crlf': True}]
  2172. else:
  2173. return [handler.DIRECT, {'cache_key': cache_key}]
  2174. class DirectRegionFilter(BaseProxyHandlerFilter):
  2175. """direct region filter"""
  2176. geoip = pygeoip.GeoIP(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'GeoIP.dat')) if pygeoip and common.GAE_REGIONS else None
  2177. region_cache = LRUCache(16*1024)
  2178. def get_country_code(self, hostname, dnsservers):
  2179. """http://dev.maxmind.com/geoip/legacy/codes/iso3166/"""
  2180. try:
  2181. return self.region_cache[hostname]
  2182. except KeyError:
  2183. pass
  2184. try:
  2185. if re.match(r'^\d+\.\d+\.\d+\.\d+$', hostname) or ':' in hostname:
  2186. iplist = [hostname]
  2187. elif dnsservers:
  2188. iplist = dnslib_record2iplist(dnslib_resolve_over_udp(hostname, dnsservers, timeout=2))
  2189. else:
  2190. iplist = socket.gethostbyname_ex(hostname)[-1]
  2191. country_code = self.geoip.country_code_by_addr(iplist[0])
  2192. except StandardError as e:
  2193. logging.warning('DirectRegionFilter cannot determine region for hostname=%r %r', hostname, e)
  2194. country_code = ''
  2195. self.region_cache[hostname] = country_code
  2196. return country_code
  2197. def filter(self, handler):
  2198. if self.geoip:
  2199. country_code = self.get_country_code(handler.host, handler.dns_servers)
  2200. if country_code in common.GAE_REGIONS:
  2201. if handler.command == 'CONNECT':
  2202. return [handler.FORWARD, handler.host, handler.port, handler.connect_timeout]
  2203. else:
  2204. return [handler.DIRECT, {}]
  2205. class AutoRangeFilter(BaseProxyHandlerFilter):
  2206. """force https filter"""
  2207. def filter(self, handler):
  2208. path = urlparse.urlsplit(handler.path).path
  2209. need_autorange = any(x(handler.host) for x in common.AUTORANGE_HOSTS_MATCH) or path.endswith(common.AUTORANGE_ENDSWITH)
  2210. if path.endswith(common.AUTORANGE_NOENDSWITH) or 'range=' in urlparse.urlsplit(path).query or handler.command == 'HEAD':
  2211. need_autorange = False
  2212. if handler.command != 'HEAD' and handler.headers.get('Range'):
  2213. m = re.search(r'bytes=(\d+)-', handler.headers['Range'])
  2214. start = int(m.group(1) if m else 0)
  2215. handler.headers['Range'] = 'bytes=%d-%d' % (start, start+common.AUTORANGE_MAXSIZE-1)
  2216. logging.info('autorange range=%r match url=%r', handler.headers['Range'], handler.path)
  2217. elif need_autorange:
  2218. logging.info('Found [autorange]endswith match url=%r', handler.path)
  2219. m = re.search(r'bytes=(\d+)-', handler.headers.get('Range', ''))
  2220. start = int(m.group(1) if m else 0)
  2221. handler.headers['Range'] = 'bytes=%d-%d' % (start, start+common.AUTORANGE_MAXSIZE-1)
  2222. class GAEFetchFilter(BaseProxyHandlerFilter):
  2223. """force https filter"""
  2224. def filter(self, handler):
  2225. """https://developers.google.com/appengine/docs/python/urlfetch/"""
  2226. if handler.command == 'CONNECT':
  2227. do_ssl_handshake = 440 <= handler.port <= 450 or 1024 <= handler.port <= 65535
  2228. return [handler.STRIP, do_ssl_handshake, self if not common.URLRE_MAP else None]
  2229. elif handler.command in ('GET', 'POST', 'HEAD', 'PUT', 'DELETE', 'PATCH'):
  2230. kwargs = {}
  2231. if common.GAE_PASSWORD:
  2232. kwargs['password'] = common.GAE_PASSWORD
  2233. if common.GAE_VALIDATE:
  2234. kwargs['validate'] = 1
  2235. fetchservers = ['%s://%s.appspot.com%s' % (common.GAE_MODE, x, common.GAE_PATH) for x in common.GAE_APPIDS]
  2236. return [handler.URLFETCH, fetchservers, common.FETCHMAX_LOCAL, kwargs]
  2237. else:
  2238. if common.PHP_ENABLE:
  2239. return PHPProxyHandler.handler_filters[-1].filter(handler)
  2240. else:
  2241. logging.warning('"%s %s" not supported by GAE, please enable PHP mode!', handler.command, handler.host)
  2242. return [handler.DIRECT, {}]
  2243. class GAEProxyHandler(AdvancedProxyHandler):
  2244. """GAE Proxy Handler"""
  2245. handler_filters = [UserAgentFilter(), WithGAEFilter(), FakeHttpsFilter(), ForceHttpsFilter(), HostsFilter(), DirectRegionFilter(), AutoRangeFilter(), GAEFetchFilter()]
  2246. def first_run(self):
  2247. """GAEProxyHandler setup, init domain/iplist map"""
  2248. if not common.PROXY_ENABLE:
  2249. logging.info('resolve common.IPLIST_MAP names=%s to iplist', list(common.IPLIST_MAP))
  2250. common.resolve_iplist()
  2251. random.shuffle(common.GAE_APPIDS)
  2252. def gethostbyname2(self, hostname):
  2253. for postfix in ('.appspot.com', '.googleusercontent.com'):
  2254. if hostname.endswith(postfix):
  2255. host = common.HOST_MAP.get(hostname) or common.HOST_POSTFIX_MAP[postfix]
  2256. return common.IPLIST_MAP.get(host) or host.split('|')
  2257. return AdvancedProxyHandler.gethostbyname2(self, hostname)
  2258. def handle_urlfetch_error(self, fetchserver, response):
  2259. gae_appid = urlparse.urlsplit(fetchserver).hostname.split('.')[-3]
  2260. if response.app_status == 503:
  2261. # appid over qouta, switch to next appid
  2262. if gae_appid == common.GAE_APPIDS[0] and len(common.GAE_APPIDS) > 1:
  2263. common.GAE_APPIDS.append(common.GAE_APPIDS.pop(0))
  2264. logging.info('gae_appid=%r over qouta, switch next appid=%r', gae_appid, common.GAE_APPIDS[0])
  2265. class PHPFetchFilter(BaseProxyHandlerFilter):
  2266. """force https filter"""
  2267. def filter(self, handler):
  2268. if handler.command == 'CONNECT':
  2269. return [handler.STRIP, True, self]
  2270. else:
  2271. kwargs = {}
  2272. if common.PHP_PASSWORD:
  2273. kwargs['password'] = common.PHP_PASSWORD
  2274. if common.PHP_VALIDATE:
  2275. kwargs['validate'] = 1
  2276. return [handler.URLFETCH, [common.PHP_FETCHSERVER], 1, kwargs]
  2277. class PHPProxyHandler(AdvancedProxyHandler):
  2278. """PHP Proxy Handler"""
  2279. first_run_lock = threading.Lock()
  2280. handler_filters = [UserAgentFilter(), FakeHttpsFilter(), ForceHttpsFilter(), PHPFetchFilter()]
  2281. def first_run(self):
  2282. if common.PHP_USEHOSTS:
  2283. self.handler_filters.insert(-1, HostsFilter())
  2284. if not common.PROXY_ENABLE:
  2285. common.resolve_iplist()
  2286. fetchhost = urlparse.urlsplit(common.PHP_FETCHSERVER).hostname
  2287. logging.info('resolve common.PHP_FETCHSERVER domain=%r to iplist', fetchhost)
  2288. if common.PHP_USEHOSTS and fetchhost in common.HOST_MAP:
  2289. hostname = common.HOST_MAP[fetchhost]
  2290. fetchhost_iplist = sum([socket.gethostbyname_ex(x)[-1] for x in common.IPLIST_MAP.get(hostname) or hostname.split('|')], [])
  2291. else:
  2292. fetchhost_iplist = self.gethostbyname2(fetchhost)
  2293. if len(fetchhost_iplist) == 0:
  2294. logging.error('resolve %r domain return empty! please use ip list to replace domain list!', fetchhost)
  2295. sys.exit(-1)
  2296. self.dns_cache[fetchhost] = list(set(fetchhost_iplist))
  2297. logging.info('resolve common.PHP_FETCHSERVER domain to iplist=%r', fetchhost_iplist)
  2298. return True
  2299. class ProxyChainMixin:
  2300. """proxy chain mixin"""
  2301. def gethostbyname2(self, hostname):
  2302. try:
  2303. return socket.gethostbyname_ex(hostname)[-1]
  2304. except socket.error:
  2305. return [hostname]
  2306. def create_tcp_connection(self, hostname, port, timeout, **kwargs):
  2307. sock = socket.create_connection((common.PROXY_HOST, int(common.PROXY_PORT)))
  2308. if hostname.endswith('.appspot.com'):
  2309. hostname = 'www.google.com'
  2310. request_data = 'CONNECT %s:%s HTTP/1.1\r\n' % (hostname, port)
  2311. if common.PROXY_USERNAME and common.PROXY_PASSWROD:
  2312. request_data += 'Proxy-Authorization: Basic %s\r\n' % base64.b64encode(('%s:%s' % (common.PROXY_USERNAME, common.PROXY_PASSWROD)).encode()).decode().strip()
  2313. request_data += '\r\n'
  2314. sock.sendall(request_data)
  2315. response = httplib.HTTPResponse(sock)
  2316. response.fp.close()
  2317. response.fp = sock.makefile('rb', 0)
  2318. response.begin()
  2319. if response.status >= 400:
  2320. raise httplib.BadStatusLine('%s %s %s' % (response.version, response.status, response.reason))
  2321. return sock
  2322. def create_ssl_connection(self, hostname, port, timeout, **kwargs):
  2323. sock = self.create_tcp_connection(hostname, port, timeout, **kwargs)
  2324. ssl_sock = ssl.wrap_socket(sock)
  2325. return ssl_sock
  2326. class GreenForwardMixin:
  2327. """green forward mixin"""
  2328. @staticmethod
  2329. def io_copy(dest, source, timeout, bufsize):
  2330. try:
  2331. dest.settimeout(timeout)
  2332. source.settimeout(timeout)
  2333. while 1:
  2334. data = source.recv(bufsize)
  2335. if not data:
  2336. break
  2337. dest.sendall(data)
  2338. except socket.timeout:
  2339. pass
  2340. except NetWorkIOError as e:
  2341. if e.args[0] not in (errno.ECONNABORTED, errno.ECONNRESET, errno.ENOTCONN, errno.EPIPE):
  2342. raise
  2343. if e.args[0] in (errno.EBADF,):
  2344. return
  2345. finally:
  2346. for sock in (dest, source):
  2347. try:
  2348. sock.close()
  2349. except StandardError:
  2350. pass
  2351. def forward_socket(self, local, remote, timeout):
  2352. """forward socket"""
  2353. bufsize = self.bufsize
  2354. thread.start_new_thread(GreenForwardMixin.io_copy, (remote.dup(), local.dup(), timeout, bufsize))
  2355. GreenForwardMixin.io_copy(local, remote, timeout, bufsize)
  2356. class ProxyChainGAEProxyHandler(ProxyChainMixin, GAEProxyHandler):
  2357. pass
  2358. class ProxyChainPHPProxyHandler(ProxyChainMixin, PHPProxyHandler):
  2359. pass
  2360. class GreenForwardGAEProxyHandler(GreenForwardMixin, GAEProxyHandler):
  2361. pass
  2362. class GreenForwardPHPProxyHandler(GreenForwardMixin, PHPProxyHandler):
  2363. pass
  2364. class ProxyChainGreenForwardGAEProxyHandler(ProxyChainMixin, GreenForwardGAEProxyHandler):
  2365. pass
  2366. class ProxyChainGreenForwardPHPProxyHandler(ProxyChainMixin, GreenForwardPHPProxyHandler):
  2367. pass
  2368. def get_uptime():
  2369. if os.name == 'nt':
  2370. import ctypes
  2371. try:
  2372. tick = ctypes.windll.kernel32.GetTickCount64()
  2373. except AttributeError:
  2374. tick = ctypes.windll.kernel32.GetTickCount()
  2375. return tick / 1000.0
  2376. elif os.path.isfile('/proc/uptime'):
  2377. with open('/proc/uptime', 'rb') as fp:
  2378. uptime = fp.readline().strip().split()[0].strip()
  2379. return float(uptime)
  2380. elif any(os.path.isfile(os.path.join(x, 'uptime')) for x in os.environ['PATH'].split(os.pathsep)):
  2381. # http://www.opensource.apple.com/source/lldb/lldb-69/test/pexpect-2.4/examples/uptime.py
  2382. 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])'
  2383. output = os.popen('uptime').read()
  2384. duration, _, _, _, _ = re.search(pattern, output).groups()
  2385. days, hours, mins = 0, 0, 0
  2386. if 'day' in duration:
  2387. m = re.search(r'([0-9]+)\s+day', duration)
  2388. days = int(m.group(1))
  2389. if ':' in duration:
  2390. m = re.search(r'([0-9]+):([0-9]+)', duration)
  2391. hours = int(m.group(1))
  2392. mins = int(m.group(2))
  2393. if 'min' in duration:
  2394. m = re.search(r'([0-9]+)\s+min', duration)
  2395. mins = int(m.group(1))
  2396. return days * 86400 + hours * 3600 + mins * 60
  2397. else:
  2398. #TODO: support other platforms
  2399. return None
  2400. class PacUtil(object):
  2401. """GoAgent Pac Util"""
  2402. @staticmethod
  2403. def update_pacfile(filename):
  2404. listen_ip = '127.0.0.1'
  2405. autoproxy = '%s:%s' % (listen_ip, common.LISTEN_PORT)
  2406. blackhole = '%s:%s' % (listen_ip, common.PAC_PORT)
  2407. default = 'PROXY %s:%s' % (common.PROXY_HOST, common.PROXY_PORT) if common.PROXY_ENABLE else 'DIRECT'
  2408. opener = urllib2.build_opener(urllib2.ProxyHandler({'http': autoproxy, 'https': autoproxy}))
  2409. content = ''
  2410. need_update = True
  2411. with open(filename, 'rb') as fp:
  2412. content = fp.read()
  2413. try:
  2414. placeholder = '// AUTO-GENERATED RULES, DO NOT MODIFY!'
  2415. content = content[:content.index(placeholder)+len(placeholder)]
  2416. content = re.sub(r'''blackhole\s*=\s*['"]PROXY [\.\w:]+['"]''', 'blackhole = \'PROXY %s\'' % blackhole, content)
  2417. content = re.sub(r'''autoproxy\s*=\s*['"]PROXY [\.\w:]+['"]''', 'autoproxy = \'PROXY %s\'' % autoproxy, content)
  2418. content = re.sub(r'''defaultproxy\s*=\s*['"](DIRECT|PROXY [\.\w:]+)['"]''', 'defaultproxy = \'%s\'' % default, content)
  2419. content = re.sub(r'''host\s*==\s*['"][\.\w:]+['"]\s*\|\|\s*isPlainHostName''', 'host == \'%s\' || isPlainHostName' % listen_ip, content)
  2420. if content.startswith('//'):
  2421. line = '// Proxy Auto-Config file generated by autoproxy2pac, %s\r\n' % time.strftime('%Y-%m-%d %H:%M:%S')
  2422. content = line + '\r\n'.join(content.splitlines()[1:])
  2423. except ValueError:
  2424. need_update = False
  2425. try:
  2426. if common.PAC_ADBLOCK:
  2427. admode = common.PAC_ADMODE
  2428. logging.info('try download %r to update_pacfile(%r)', common.PAC_ADBLOCK, filename)
  2429. adblock_content = opener.open(common.PAC_ADBLOCK).read()
  2430. logging.info('%r downloaded, try convert it with adblock2pac', common.PAC_ADBLOCK)
  2431. if 'gevent' in sys.modules and time.sleep is getattr(sys.modules['gevent'], 'sleep', None) and hasattr(gevent.get_hub(), 'threadpool'):
  2432. jsrule = gevent.get_hub().threadpool.apply_e(Exception, PacUtil.adblock2pac, (adblock_content, 'FindProxyForURLByAdblock', blackhole, default, admode))
  2433. else:
  2434. jsrule = PacUtil.adblock2pac(adblock_content, 'FindProxyForURLByAdblock', blackhole, default, admode)
  2435. content += '\r\n' + jsrule + '\r\n'
  2436. logging.info('%r downloaded and parsed', common.PAC_ADBLOCK)
  2437. else:
  2438. content += '\r\nfunction FindProxyForURLByAdblock(url, host) {return "DIRECT";}\r\n'
  2439. except StandardError as e:
  2440. need_update = False
  2441. logging.exception('update_pacfile failed: %r', e)
  2442. try:
  2443. logging.info('try download %r to update_pacfile(%r)', common.PAC_GFWLIST, filename)
  2444. autoproxy_content = base64.b64decode(opener.open(common.PAC_GFWLIST).read())
  2445. logging.info('%r downloaded, try convert it with autoproxy2pac_lite', common.PAC_GFWLIST)
  2446. if 'gevent' in sys.modules and time.sleep is getattr(sys.modules['gevent'], 'sleep', None) and hasattr(gevent.get_hub(), 'threadpool'):
  2447. jsrule = gevent.get_hub().threadpool.apply_e(Exception, PacUtil.autoproxy2pac_lite, (autoproxy_content, 'FindProxyForURLByAutoProxy', autoproxy, default))
  2448. else:
  2449. jsrule = PacUtil.autoproxy2pac_lite(autoproxy_content, 'FindProxyForURLByAutoProxy', autoproxy, default)
  2450. content += '\r\n' + jsrule + '\r\n'
  2451. logging.info('%r downloaded and parsed', common.PAC_GFWLIST)
  2452. except StandardError as e:
  2453. need_update = False
  2454. logging.exception('update_pacfile failed: %r', e)
  2455. if need_update:
  2456. with open(filename, 'wb') as fp:
  2457. fp.write(content)
  2458. logging.info('%r successfully updated', filename)
  2459. @staticmethod
  2460. def autoproxy2pac(content, func_name='FindProxyForURLByAutoProxy', proxy='127.0.0.1:8087', default='DIRECT', indent=4):
  2461. """Autoproxy to Pac, based on https://github.com/iamamac/autoproxy2pac"""
  2462. jsLines = []
  2463. for line in content.splitlines()[1:]:
  2464. if line and not line.startswith("!"):
  2465. use_proxy = True
  2466. if line.startswith("@@"):
  2467. line = line[2:]
  2468. use_proxy = False
  2469. return_proxy = 'PROXY %s' % proxy if use_proxy else default
  2470. if line.startswith('/') and line.endswith('/'):
  2471. jsLine = 'if (/%s/i.test(url)) return "%s";' % (line[1:-1], return_proxy)
  2472. elif line.startswith('||'):
  2473. domain = line[2:].lstrip('.')
  2474. if len(jsLines) > 0 and ('host.indexOf(".%s") >= 0' % domain in jsLines[-1] or 'host.indexOf("%s") >= 0' % domain in jsLines[-1]):
  2475. jsLines.pop()
  2476. jsLine = 'if (dnsDomainIs(host, ".%s") || host == "%s") return "%s";' % (domain, domain, return_proxy)
  2477. elif line.startswith('|'):
  2478. jsLine = 'if (url.indexOf("%s") == 0) return "%s";' % (line[1:], return_proxy)
  2479. elif '*' in line:
  2480. jsLine = 'if (shExpMatch(url, "*%s*")) return "%s";' % (line.strip('*'), return_proxy)
  2481. elif '/' not in line:
  2482. jsLine = 'if (host.indexOf("%s") >= 0) return "%s";' % (line, return_proxy)
  2483. else:
  2484. jsLine = 'if (url.indexOf("%s") >= 0) return "%s";' % (line, return_proxy)
  2485. jsLine = ' ' * indent + jsLine
  2486. if use_proxy:
  2487. jsLines.append(jsLine)
  2488. else:
  2489. jsLines.insert(0, jsLine)
  2490. function = 'function %s(url, host) {\r\n%s\r\n%sreturn "%s";\r\n}' % (func_name, '\n'.join(jsLines), ' '*indent, default)
  2491. return function
  2492. @staticmethod
  2493. def autoproxy2pac_lite(content, func_name='FindProxyForURLByAutoProxy', proxy='127.0.0.1:8087', default='DIRECT', indent=4):
  2494. """Autoproxy to Pac, based on https://github.com/iamamac/autoproxy2pac"""
  2495. direct_domain_set = set([])
  2496. proxy_domain_set = set([])
  2497. for line in content.splitlines()[1:]:
  2498. if line and not line.startswith(('!', '|!', '||!')):
  2499. use_proxy = True
  2500. if line.startswith("@@"):
  2501. line = line[2:]
  2502. use_proxy = False
  2503. domain = ''
  2504. if line.startswith('/') and line.endswith('/'):
  2505. line = line[1:-1]
  2506. if line.startswith('^https?:\\/\\/[^\\/]+') and re.match(r'^(\w|\\\-|\\\.)+$', line[18:]):
  2507. domain = line[18:].replace(r'\.', '.')
  2508. else:
  2509. logging.warning('unsupport gfwlist regex: %r', line)
  2510. elif line.startswith('||'):
  2511. domain = line[2:].lstrip('*').rstrip('/')
  2512. elif line.startswith('|'):
  2513. domain = urlparse.urlsplit(line[1:]).hostname.lstrip('*')
  2514. elif line.startswith(('http://', 'https://')):
  2515. domain = urlparse.urlsplit(line).hostname.lstrip('*')
  2516. elif re.search(r'^([\w\-\_\.]+)([\*\/]|$)', line):
  2517. domain = re.split(r'[\*\/]', line)[0]
  2518. else:
  2519. pass
  2520. if '*' in domain:
  2521. domain = domain.split('*')[-1]
  2522. if not domain or re.match(r'^\w+$', domain):
  2523. logging.debug('unsupport gfwlist rule: %r', line)
  2524. continue
  2525. if use_proxy:
  2526. proxy_domain_set.add(domain)
  2527. else:
  2528. direct_domain_set.add(domain)
  2529. proxy_domain_list = sorted(set(x.lstrip('.') for x in proxy_domain_set))
  2530. autoproxy_host = ',\r\n'.join('%s"%s": 1' % (' '*indent, x) for x in proxy_domain_list)
  2531. template = '''\
  2532. var autoproxy_host = {
  2533. %(autoproxy_host)s
  2534. };
  2535. function %(func_name)s(url, host) {
  2536. var lastPos;
  2537. do {
  2538. if (autoproxy_host.hasOwnProperty(host)) {
  2539. return 'PROXY %(proxy)s';
  2540. }
  2541. lastPos = host.indexOf('.') + 1;
  2542. host = host.slice(lastPos);
  2543. } while (lastPos >= 1);
  2544. return '%(default)s';
  2545. }'''
  2546. template = re.sub(r'(?m)^\s{%d}' % min(len(re.search(r' +', x).group()) for x in template.splitlines()), '', template)
  2547. template_args = {'autoproxy_host': autoproxy_host,
  2548. 'func_name': func_name,
  2549. 'proxy': proxy,
  2550. 'default': default}
  2551. return template % template_args
  2552. @staticmethod
  2553. def urlfilter2pac(content, func_name='FindProxyForURLByUrlfilter', proxy='127.0.0.1:8086', default='DIRECT', indent=4):
  2554. """urlfilter.ini to Pac, based on https://github.com/iamamac/autoproxy2pac"""
  2555. jsLines = []
  2556. for line in content[content.index('[exclude]'):].splitlines()[1:]:
  2557. if line and not line.startswith(';'):
  2558. use_proxy = True
  2559. if line.startswith("@@"):
  2560. line = line[2:]
  2561. use_proxy = False
  2562. return_proxy = 'PROXY %s' % proxy if use_proxy else default
  2563. if '*' in line:
  2564. jsLine = 'if (shExpMatch(url, "%s")) return "%s";' % (line, return_proxy)
  2565. else:
  2566. jsLine = 'if (url == "%s") return "%s";' % (line, return_proxy)
  2567. jsLine = ' ' * indent + jsLine
  2568. if use_proxy:
  2569. jsLines.append(jsLine)
  2570. else:
  2571. jsLines.insert(0, jsLine)
  2572. function = 'function %s(url, host) {\r\n%s\r\n%sreturn "%s";\r\n}' % (func_name, '\n'.join(jsLines), ' '*indent, default)
  2573. return function
  2574. @staticmethod
  2575. def adblock2pac(content, func_name='FindProxyForURLByAdblock', proxy='127.0.0.1:8086', default='DIRECT', admode=1, indent=4):
  2576. """adblock list to Pac, based on https://github.com/iamamac/autoproxy2pac"""
  2577. white_conditions = {'host': [], 'url.indexOf': [], 'shExpMatch': []}
  2578. black_conditions = {'host': [], 'url.indexOf': [], 'shExpMatch': []}
  2579. for line in content.splitlines()[1:]:
  2580. if not line or line.startswith('!') or '##' in line or '#@#' in line:
  2581. continue
  2582. use_proxy = True
  2583. use_start = False
  2584. use_end = False
  2585. use_domain = False
  2586. use_postfix = []
  2587. if '$' in line:
  2588. posfixs = line.split('$')[-1].split(',')
  2589. if any('domain' in x for x in posfixs):
  2590. continue
  2591. if 'image' in posfixs:
  2592. use_postfix += ['.jpg', '.gif']
  2593. elif 'script' in posfixs:
  2594. use_postfix += ['.js']
  2595. else:
  2596. continue
  2597. line = line.split('$')[0]
  2598. if line.startswith("@@"):
  2599. line = line[2:]
  2600. use_proxy = False
  2601. if '||' == line[:2]:
  2602. line = line[2:]
  2603. if '/' not in line:
  2604. use_domain = True
  2605. else:
  2606. use_start = True
  2607. elif '|' == line[0]:
  2608. line = line[1:]
  2609. use_start = True
  2610. if line[-1] in ('^', '|'):
  2611. line = line[:-1]
  2612. if not use_postfix:
  2613. use_end = True
  2614. line = line.replace('^', '*').strip('*')
  2615. conditions = black_conditions if use_proxy else white_conditions
  2616. if use_start and use_end:
  2617. conditions['shExpMatch'] += ['*%s*' % line]
  2618. elif use_start:
  2619. if '*' in line:
  2620. if use_postfix:
  2621. conditions['shExpMatch'] += ['*%s*%s' % (line, x) for x in use_postfix]
  2622. else:
  2623. conditions['shExpMatch'] += ['*%s*' % line]
  2624. else:
  2625. conditions['url.indexOf'] += [line]
  2626. elif use_domain and use_end:
  2627. if '*' in line:
  2628. conditions['shExpMatch'] += ['%s*' % line]
  2629. else:
  2630. conditions['host'] += [line]
  2631. elif use_domain:
  2632. if line.split('/')[0].count('.') <= 1:
  2633. if use_postfix:
  2634. conditions['shExpMatch'] += ['*.%s*%s' % (line, x) for x in use_postfix]
  2635. else:
  2636. conditions['shExpMatch'] += ['*.%s*' % line]
  2637. else:
  2638. if '*' in line:
  2639. if use_postfix:
  2640. conditions['shExpMatch'] += ['*%s*%s' % (line, x) for x in use_postfix]
  2641. else:
  2642. conditions['shExpMatch'] += ['*%s*' % line]
  2643. else:
  2644. if use_postfix:
  2645. conditions['shExpMatch'] += ['*%s*%s' % (line, x) for x in use_postfix]
  2646. else:
  2647. conditions['url.indexOf'] += ['http://%s' % line]
  2648. else:
  2649. if use_postfix:
  2650. conditions['shExpMatch'] += ['*%s*%s' % (line, x) for x in use_postfix]
  2651. else:
  2652. conditions['shExpMatch'] += ['*%s*' % line]
  2653. templates = ['''\
  2654. function %(func_name)s(url, host) {
  2655. return '%(default)s';
  2656. }''',
  2657. '''\
  2658. var blackhole_host = {
  2659. %(blackhole_host)s
  2660. };
  2661. function %(func_name)s(url, host) {
  2662. // untrusted ablock plus list, disable whitelist until chinalist come back.
  2663. if (blackhole_host.hasOwnProperty(host)) {
  2664. return 'PROXY %(proxy)s';
  2665. }
  2666. return '%(default)s';
  2667. }''',
  2668. '''\
  2669. var blackhole_host = {
  2670. %(blackhole_host)s
  2671. };
  2672. var blackhole_url_indexOf = [
  2673. %(blackhole_url_indexOf)s
  2674. ];
  2675. function %s(url, host) {
  2676. // untrusted ablock plus list, disable whitelist until chinalist come back.
  2677. if (blackhole_host.hasOwnProperty(host)) {
  2678. return 'PROXY %(proxy)s';
  2679. }
  2680. for (i = 0; i < blackhole_url_indexOf.length; i++) {
  2681. if (url.indexOf(blackhole_url_indexOf[i]) >= 0) {
  2682. return 'PROXY %(proxy)s';
  2683. }
  2684. }
  2685. return '%(default)s';
  2686. }''',
  2687. '''\
  2688. var blackhole_host = {
  2689. %(blackhole_host)s
  2690. };
  2691. var blackhole_url_indexOf = [
  2692. %(blackhole_url_indexOf)s
  2693. ];
  2694. var blackhole_shExpMatch = [
  2695. %(blackhole_shExpMatch)s
  2696. ];
  2697. function %(func_name)s(url, host) {
  2698. // untrusted ablock plus list, disable whitelist until chinalist come back.
  2699. if (blackhole_host.hasOwnProperty(host)) {
  2700. return 'PROXY %(proxy)s';
  2701. }
  2702. for (i = 0; i < blackhole_url_indexOf.length; i++) {
  2703. if (url.indexOf(blackhole_url_indexOf[i]) >= 0) {
  2704. return 'PROXY %(proxy)s';
  2705. }
  2706. }
  2707. for (i = 0; i < blackhole_shExpMatch.length; i++) {
  2708. if (shExpMatch(url, blackhole_shExpMatch[i])) {
  2709. return 'PROXY %(proxy)s';
  2710. }
  2711. }
  2712. return '%(default)s';
  2713. }''']
  2714. template = re.sub(r'(?m)^\s{%d}' % min(len(re.search(r' +', x).group()) for x in templates[admode].splitlines()), '', templates[admode])
  2715. template_kwargs = {'blackhole_host': ',\r\n'.join("%s'%s': 1" % (' '*indent, x) for x in sorted(black_conditions['host'])),
  2716. 'blackhole_url_indexOf': ',\r\n'.join("%s'%s'" % (' '*indent, x) for x in sorted(black_conditions['url.indexOf'])),
  2717. 'blackhole_shExpMatch': ',\r\n'.join("%s'%s'" % (' '*indent, x) for x in sorted(black_conditions['shExpMatch'])),
  2718. 'func_name': func_name,
  2719. 'proxy': proxy,
  2720. 'default': default}
  2721. return template % template_kwargs
  2722. class PacFileFilter(BaseProxyHandlerFilter):
  2723. """pac file filter"""
  2724. def filter(self, handler):
  2725. is_local_client = handler.client_address[0] in ('127.0.0.1', '::1')
  2726. pacfile = os.path.join(os.path.dirname(os.path.abspath(__file__)), common.PAC_FILE)
  2727. urlparts = urlparse.urlsplit(handler.path)
  2728. if handler.command == 'GET' and urlparts.path.lstrip('/') == common.PAC_FILE:
  2729. if urlparts.query == 'flush':
  2730. if is_local_client:
  2731. thread.start_new_thread(PacUtil.update_pacfile, (pacfile,))
  2732. else:
  2733. return [handler.MOCK, 403, {'Content-Type': 'text/plain'}, 'client address %r not allowed' % handler.client_address[0]]
  2734. if time.time() - os.path.getmtime(pacfile) > common.PAC_EXPIRED:
  2735. # check system uptime > 30 minutes
  2736. uptime = get_uptime()
  2737. if uptime and uptime > 1800:
  2738. thread.start_new_thread(lambda: os.utime(pacfile, (time.time(), time.time())) or PacUtil.update_pacfile(pacfile), tuple())
  2739. with open(pacfile, 'rb') as fp:
  2740. content = fp.read()
  2741. if not is_local_client:
  2742. serving_addr = urlparts.hostname or ProxyUtil.get_listen_ip()
  2743. content = content.replace('127.0.0.1', serving_addr)
  2744. headers = {'Content-Type': 'text/plain'}
  2745. if 'gzip' in handler.headers.get('Accept-Encoding', ''):
  2746. headers['Content-Encoding'] = 'gzip'
  2747. compressobj = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -zlib.MAX_WBITS, zlib.DEF_MEM_LEVEL, 0)
  2748. dataio = io.BytesIO()
  2749. dataio.write('\x1f\x8b\x08\x00\x00\x00\x00\x00\x02\xff')
  2750. dataio.write(compressobj.compress(content))
  2751. dataio.write(compressobj.flush())
  2752. dataio.write(struct.pack('<LL', zlib.crc32(content) & 0xFFFFFFFFL, len(content) & 0xFFFFFFFFL))
  2753. content = dataio.getvalue()
  2754. return [handler.MOCK, 200, headers, content]
  2755. class StaticFileFilter(BaseProxyHandlerFilter):
  2756. """static file filter"""
  2757. index_file = 'index.html'
  2758. def format_index_html(self, dirname):
  2759. INDEX_TEMPLATE = u'''
  2760. <html>
  2761. <title>Directory listing for $dirname</title>
  2762. <body>
  2763. <h2>Directory listing for $dirname</h2>
  2764. <hr>
  2765. <ul>
  2766. $html
  2767. </ul>
  2768. <hr>
  2769. </body></html>
  2770. '''
  2771. html = ''
  2772. if not isinstance(dirname, unicode):
  2773. dirname = dirname.decode(sys.getfilesystemencoding())
  2774. for name in os.listdir(dirname):
  2775. fullname = os.path.join(dirname, name)
  2776. suffix = u'/' if os.path.isdir(fullname) else u''
  2777. html += u'<li><a href="%s%s">%s%s</a>\r\n' % (name, suffix, name, suffix)
  2778. return string.Template(INDEX_TEMPLATE).substitute(dirname=dirname, html=html)
  2779. def filter(self, handler):
  2780. path = urlparse.urlsplit(handler.path).path
  2781. if path.startswith('/'):
  2782. path = urllib.unquote_plus(path.lstrip('/') or '.').decode('utf8')
  2783. if os.path.isdir(path):
  2784. index_file = os.path.join(path, self.index_file)
  2785. if not os.path.isfile(index_file):
  2786. content = self.format_index_html(path).encode('UTF-8')
  2787. headers = {'Content-Type': 'text/html; charset=utf-8', 'Connection': 'close'}
  2788. return [handler.MOCK, 200, headers, content]
  2789. else:
  2790. path = index_file
  2791. if os.path.isfile(path):
  2792. content_type = 'application/octet-stream'
  2793. try:
  2794. import mimetypes
  2795. content_type = mimetypes.types_map.get(os.path.splitext(path)[1])
  2796. except StandardError as e:
  2797. logging.error('import mimetypes failed: %r', e)
  2798. with open(path, 'rb') as fp:
  2799. content = fp.read()
  2800. headers = {'Connection': 'close', 'Content-Type': content_type}
  2801. return [handler.MOCK, 200, headers, content]
  2802. class BlackholeFilter(BaseProxyHandlerFilter):
  2803. """blackhole filter"""
  2804. 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;'
  2805. def filter(self, handler):
  2806. if handler.command == 'CONNECT':
  2807. return [handler.STRIP, True, self]
  2808. elif handler.path.startswith(('http://', 'https://')):
  2809. headers = {'Cache-Control': 'max-age=86400',
  2810. 'Expires': 'Oct, 01 Aug 2100 00:00:00 GMT',
  2811. 'Connection': 'close'}
  2812. content = ''
  2813. if urlparse.urlsplit(handler.path).path.lower().endswith(('.jpg', '.gif', '.png','.jpeg', '.bmp')):
  2814. headers['Content-Type'] = 'image/gif'
  2815. content = self.one_pixel_gif
  2816. return [handler.MOCK, 200, headers, content]
  2817. else:
  2818. return [handler.MOCK, 404, {'Connection': 'close'}, '']
  2819. class PACProxyHandler(SimpleProxyHandler):
  2820. """pac proxy handler"""
  2821. handler_filters = [PacFileFilter(), StaticFileFilter(), BlackholeFilter()]
  2822. def get_process_list():
  2823. import os
  2824. import glob
  2825. import ctypes
  2826. import collections
  2827. Process = collections.namedtuple('Process', 'pid name exe')
  2828. process_list = []
  2829. if os.name == 'nt':
  2830. PROCESS_QUERY_INFORMATION = 0x0400
  2831. PROCESS_VM_READ = 0x0010
  2832. lpidProcess = (ctypes.c_ulong * 1024)()
  2833. cb = ctypes.sizeof(lpidProcess)
  2834. cbNeeded = ctypes.c_ulong()
  2835. ctypes.windll.psapi.EnumProcesses(ctypes.byref(lpidProcess), cb, ctypes.byref(cbNeeded))
  2836. nReturned = cbNeeded.value/ctypes.sizeof(ctypes.c_ulong())
  2837. pidProcess = [i for i in lpidProcess][:nReturned]
  2838. has_queryimage = hasattr(ctypes.windll.kernel32, 'QueryFullProcessImageNameA')
  2839. for pid in pidProcess:
  2840. hProcess = ctypes.windll.kernel32.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, 0, pid)
  2841. if hProcess:
  2842. modname = ctypes.create_string_buffer(2048)
  2843. count = ctypes.c_ulong(ctypes.sizeof(modname))
  2844. if has_queryimage:
  2845. ctypes.windll.kernel32.QueryFullProcessImageNameA(hProcess, 0, ctypes.byref(modname), ctypes.byref(count))
  2846. else:
  2847. ctypes.windll.psapi.GetModuleFileNameExA(hProcess, 0, ctypes.byref(modname), ctypes.byref(count))
  2848. exe = modname.value
  2849. name = os.path.basename(exe)
  2850. process_list.append(Process(pid=pid, name=name, exe=exe))
  2851. ctypes.windll.kernel32.CloseHandle(hProcess)
  2852. elif sys.platform.startswith('linux'):
  2853. for filename in glob.glob('/proc/[0-9]*/cmdline'):
  2854. pid = int(filename.split('/')[2])
  2855. exe_link = '/proc/%d/exe' % pid
  2856. if os.path.exists(exe_link):
  2857. exe = os.readlink(exe_link)
  2858. name = os.path.basename(exe)
  2859. process_list.append(Process(pid=pid, name=name, exe=exe))
  2860. else:
  2861. try:
  2862. import psutil
  2863. process_list = psutil.get_process_list()
  2864. except StandardError as e:
  2865. logging.exception('psutil.get_process_list() failed: %r', e)
  2866. return process_list
  2867. def pre_start():
  2868. if not OpenSSL:
  2869. logging.warning('python-openssl not found, please install it!')
  2870. if sys.platform == 'cygwin':
  2871. logging.info('cygwin is not officially supported, please continue at your own risk :)')
  2872. #sys.exit(-1)
  2873. elif os.name == 'posix':
  2874. try:
  2875. import resource
  2876. resource.setrlimit(resource.RLIMIT_NOFILE, (8192, -1))
  2877. except ValueError:
  2878. pass
  2879. elif os.name == 'nt':
  2880. import ctypes
  2881. ctypes.windll.kernel32.SetConsoleTitleW(u'GoAgent v%s' % __version__)
  2882. if not common.LISTEN_VISIBLE:
  2883. ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 0)
  2884. else:
  2885. ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 1)
  2886. if common.LOVE_ENABLE and random.randint(1, 100) <= 5:
  2887. title = ctypes.create_unicode_buffer(1024)
  2888. ctypes.windll.kernel32.GetConsoleTitleW(ctypes.byref(title), len(title)-1)
  2889. ctypes.windll.kernel32.SetConsoleTitleW('%s %s' % (title.value, random.choice(common.LOVE_TIP)))
  2890. blacklist = {'360safe': False,
  2891. 'QQProtect': False, }
  2892. softwares = [k for k, v in blacklist.items() if v]
  2893. if softwares:
  2894. tasklist = '\n'.join(x.name for x in get_process_list()).lower()
  2895. softwares = [x for x in softwares if x.lower() in tasklist]
  2896. if softwares:
  2897. title = u'GoAgent 建议'
  2898. error = u'某些安全软件(如 %s)可能和本软件存在冲突,造成 CPU 占用过高。\n如有此现象建议暂时退出此安全软件来继续运行GoAgent' % ','.join(softwares)
  2899. ctypes.windll.user32.MessageBoxW(None, error, title, 0)
  2900. #sys.exit(0)
  2901. if os.path.isfile('/proc/cpuinfo'):
  2902. with open('/proc/cpuinfo', 'rb') as fp:
  2903. m = re.search(r'(?im)(BogoMIPS|cpu MHz)\s+:\s+([\d\.]+)', fp.read())
  2904. if m and float(m.group(2)) < 1000:
  2905. logging.warning("*NOTE*, Please set [gae]window=2 [gae]keepalive=1")
  2906. if GAEProxyHandler.max_window != common.GAE_WINDOW:
  2907. GAEProxyHandler.max_window = common.GAE_WINDOW
  2908. if common.GAE_KEEPALIVE and common.GAE_MODE == 'https':
  2909. GAEProxyHandler.ssl_connection_keepalive = True
  2910. if common.GAE_PAGESPEED and not common.GAE_OBFUSCATE:
  2911. logging.critical("*NOTE*, [gae]pagespeed=1 requires [gae]obfuscate=1")
  2912. sys.exit(-1)
  2913. if common.GAE_SSLVERSION:
  2914. GAEProxyHandler.ssl_version = getattr(ssl, 'PROTOCOL_%s' % common.GAE_SSLVERSION)
  2915. GAEProxyHandler.openssl_context = SSLConnection.context_builder(common.GAE_SSLVERSION)
  2916. if common.GAE_APPIDS[0] == 'goagent':
  2917. logging.critical('please edit %s to add your appid to [gae] !', common.CONFIG_FILENAME)
  2918. sys.exit(-1)
  2919. if common.GAE_MODE == 'http' and common.GAE_PASSWORD == '':
  2920. logging.critical('to enable http mode, you should set %r [gae]password = <your_pass> and [gae]options = rc4', common.CONFIG_FILENAME)
  2921. sys.exit(-1)
  2922. if common.GAE_TRANSPORT:
  2923. GAEProxyHandler.disable_transport_ssl = False
  2924. if common.GAE_REGIONS and not pygeoip:
  2925. logging.critical('to enable [gae]regions mode, you should install pygeoip')
  2926. sys.exit(-1)
  2927. if common.PAC_ENABLE:
  2928. pac_ip = ProxyUtil.get_listen_ip() if common.PAC_IP in ('', '::', '0.0.0.0') else common.PAC_IP
  2929. url = 'http://%s:%d/%s' % (pac_ip, common.PAC_PORT, common.PAC_FILE)
  2930. spawn_later(600, urllib2.build_opener(urllib2.ProxyHandler({})).open, url)
  2931. if not dnslib:
  2932. logging.error('dnslib not found, please put dnslib-0.8.3.egg to %r!', os.path.dirname(os.path.abspath(__file__)))
  2933. sys.exit(-1)
  2934. if not common.DNS_ENABLE:
  2935. if not common.HTTP_DNS:
  2936. common.HTTP_DNS = common.DNS_SERVERS[:]
  2937. for dnsservers_ref in (common.HTTP_DNS, common.DNS_SERVERS):
  2938. any(dnsservers_ref.insert(0, x) for x in [y for y in get_dnsserver_list() if y not in dnsservers_ref])
  2939. AdvancedProxyHandler.dns_servers = common.HTTP_DNS
  2940. AdvancedProxyHandler.dns_blacklist = common.DNS_BLACKLIST
  2941. else:
  2942. AdvancedProxyHandler.dns_servers = common.HTTP_DNS or common.DNS_SERVERS
  2943. AdvancedProxyHandler.dns_blacklist = common.DNS_BLACKLIST
  2944. RangeFetch.threads = common.AUTORANGE_THREADS
  2945. RangeFetch.maxsize = common.AUTORANGE_MAXSIZE
  2946. RangeFetch.bufsize = common.AUTORANGE_BUFSIZE
  2947. RangeFetch.waitsize = common.AUTORANGE_WAITSIZE
  2948. if common.LISTEN_USERNAME and common.LISTEN_PASSWORD:
  2949. GAEProxyHandler.handler_filters.insert(0, AuthFilter(common.LISTEN_USERNAME, common.LISTEN_PASSWORD))
  2950. def main():
  2951. global __file__
  2952. __file__ = os.path.abspath(__file__)
  2953. if os.path.islink(__file__):
  2954. __file__ = getattr(os, 'readlink', lambda x: x)(__file__)
  2955. os.chdir(os.path.dirname(os.path.abspath(__file__)))
  2956. 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]')
  2957. pre_start()
  2958. CertUtil.check_ca()
  2959. sys.stderr.write(common.info())
  2960. uvent_enabled = 'uvent.loop' in sys.modules and isinstance(gevent.get_hub().loop, __import__('uvent').loop.UVLoop)
  2961. if common.PHP_ENABLE:
  2962. host, port = common.PHP_LISTEN.split(':')
  2963. HandlerClass = ((PHPProxyHandler, GreenForwardPHPProxyHandler) if not common.PROXY_ENABLE else (ProxyChainPHPProxyHandler, ProxyChainGreenForwardPHPProxyHandler))[uvent_enabled]
  2964. server = LocalProxyServer((host, int(port)), HandlerClass)
  2965. thread.start_new_thread(server.serve_forever, tuple())
  2966. if common.PAC_ENABLE:
  2967. server = LocalProxyServer((common.PAC_IP, common.PAC_PORT), PACProxyHandler)
  2968. thread.start_new_thread(server.serve_forever, tuple())
  2969. if common.DNS_ENABLE:
  2970. try:
  2971. sys.path += ['.']
  2972. from dnsproxy import DNSServer
  2973. host, port = common.DNS_LISTEN.split(':')
  2974. server = DNSServer((host, int(port)), dns_servers=common.DNS_SERVERS, dns_blacklist=common.DNS_BLACKLIST, dns_tcpover=common.DNS_TCPOVER)
  2975. thread.start_new_thread(server.serve_forever, tuple())
  2976. except ImportError:
  2977. logging.exception('GoAgent DNSServer requires dnslib and gevent 1.0')
  2978. sys.exit(-1)
  2979. HandlerClass = ((GAEProxyHandler, GreenForwardGAEProxyHandler) if not common.PROXY_ENABLE else (ProxyChainGAEProxyHandler, ProxyChainGreenForwardGAEProxyHandler))[uvent_enabled]
  2980. server = LocalProxyServer((common.LISTEN_IP, common.LISTEN_PORT), HandlerClass)
  2981. try:
  2982. server.serve_forever()
  2983. except SystemError as e:
  2984. if '(libev) select: ' in repr(e):
  2985. logging.error('PLEASE START GOAGENT BY uvent.bat')
  2986. sys.exit(-1)
  2987. if __name__ == '__main__':
  2988. main()