PageRenderTime 80ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/local/proxy.py

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