PageRenderTime 68ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/local/proxy.py

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