PageRenderTime 42ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/local/proxy.py

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