waybackproxy.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. #!/usr/bin/env python3
  2. import base64, datetime, lrudict, re, socket, socketserver, sys, threading, urllib.request, urllib.error, urllib.parse
  3. from config import *
  4. # internal LRU dictionary for preserving URLs on redirect
  5. date_cache = lrudict.LRUDict(maxduration=86400, maxsize=1024)
  6. class ThreadingTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
  7. """TCPServer with ThreadingMixIn added."""
  8. pass
  9. class Handler(socketserver.BaseRequestHandler):
  10. """Main request handler."""
  11. def handle(self):
  12. """Handle a request."""
  13. global DATE
  14. # readline is pretty convenient
  15. f = self.request.makefile()
  16. # read request line
  17. reqline = line = f.readline()
  18. split = line.rstrip('\r\n').split(' ')
  19. http_version = len(split) > 2 and split[2] or 'HTTP/0.9'
  20. if split[0] != 'GET':
  21. # only GET is implemented
  22. return self.error_page(http_version, 501, 'Not Implemented')
  23. # read out the headers
  24. request_host = None
  25. pac_host = '" + location.host + ":' + str(LISTEN_PORT) # may not actually work
  26. effective_date = DATE
  27. auth = None
  28. while line.rstrip('\r\n') != '':
  29. line = f.readline()
  30. ll = line.lower()
  31. if ll[:6] == 'host: ':
  32. pac_host = request_host = line[6:].rstrip('\r\n')
  33. if ':' not in pac_host: # who would run this on port 80 anyway?
  34. pac_host += ':80'
  35. elif ll[:21] == 'x-waybackproxy-date: ':
  36. # API for a personal project of mine
  37. effective_date = line[21:].rstrip('\r\n')
  38. elif ll[:21] == 'authorization: basic ':
  39. # asset date code passed as username:password
  40. auth = base64.b64decode(ll[21:])
  41. # parse the URL
  42. pac_file_paths = ('/proxy.pac', '/wpad.dat', '/wpad.da')
  43. if split[1][0] == '/' and split[1] not in pac_file_paths:
  44. # just a path (not corresponding to a PAC file) => transparent proxy
  45. # Host header and therefore HTTP/1.1 are required
  46. if not request_host:
  47. return self.error_page(http_version, 400, 'Host header missing')
  48. archived_url = 'http://' + request_host + split[1]
  49. else:
  50. # full URL => explicit proxy
  51. archived_url = split[1]
  52. request_url = archived_url
  53. parsed = urllib.parse.urlparse(request_url)
  54. # make a path
  55. path = parsed.path
  56. if parsed.query != '': path += '?' + parsed.query
  57. if path == '': path == '/'
  58. # get the hostname for later
  59. host = parsed.netloc.split(':')
  60. hostname = host[0]
  61. # get cached date for redirects, if available
  62. original_date = effective_date
  63. effective_date = date_cache.get(effective_date + '\x00' + archived_url, effective_date)
  64. # get date from username:password, if available
  65. if auth:
  66. effective_date = auth.replace(':', '')
  67. try:
  68. if path in pac_file_paths:
  69. # PAC file to bypass QUICK_IMAGES requests
  70. pac = http_version.encode('ascii', 'ignore') + b''' 200 OK\r\n'''
  71. pac += b'''Content-Type: application/x-ns-proxy-autoconfig\r\n'''
  72. pac += b'''\r\n'''
  73. pac += b'''function FindProxyForURL(url, host)\r\n'''
  74. pac += b'''{\r\n'''
  75. pac += b''' if (shExpMatch(url, "http://web.archive.org/web/*") && !shExpMatch(url, "http://web.archive.org/web/??????????????if_/*"))\r\n'''
  76. pac += b''' {\r\n'''
  77. pac += b''' return "DIRECT";\r\n'''
  78. pac += b''' }\r\n'''
  79. pac += b''' return "PROXY ''' + pac_host.encode('ascii', 'ignore') + b'''";\r\n'''
  80. pac += b'''}\r\n'''
  81. self.request.sendall(pac)
  82. return
  83. elif hostname == 'web.archive.org':
  84. if path[:5] != '/web/':
  85. # launch settings if enabled
  86. if SETTINGS_PAGE:
  87. return self.handle_settings(parsed.query)
  88. else:
  89. return self.error_page(http_version, 404, 'Not Found')
  90. else:
  91. # pass-through requests to web.archive.org
  92. # required for QUICK_IMAGES
  93. archived_url = '/'.join(request_url.split('/')[5:])
  94. _print('[>] [QI] {0}'.format(archived_url))
  95. try:
  96. conn = urllib.request.urlopen(request_url)
  97. except urllib.error.HTTPError as e:
  98. if e.code == 404:
  99. # Try this file on another date, might be redundant
  100. return self.redirect_page(http_version, archived_url)
  101. else:
  102. raise e
  103. elif GEOCITIES_FIX and hostname == 'www.geocities.com':
  104. # apply GEOCITIES_FIX and pass it through
  105. _print('[>] {0}'.format(archived_url))
  106. split = archived_url.split('/')
  107. hostname = split[2] = 'www.oocities.org'
  108. request_url = '/'.join(split)
  109. conn = urllib.request.urlopen(request_url)
  110. else:
  111. # get from Wayback
  112. _print('[>] {0}'.format(archived_url))
  113. request_url = 'http://web.archive.org/web/{0}/{1}'.format(effective_date, archived_url)
  114. conn = urllib.request.urlopen(request_url)
  115. except urllib.error.HTTPError as e:
  116. # an error has been found
  117. if e.code in (403, 404, 412):
  118. # 403, 404 or tolerance exceeded => heuristically determine the static URL for some redirect scripts
  119. match = re.search('''[^/]/((?:http(?:%3A|:)(?:%2F|/)|www(?:[0-9]+)?\.(?:[^/%]+))(?:%2F|/).+)''', archived_url, re.I)
  120. if not match:
  121. match = re.search('''(?:\?|&)(?:[^=]+)=((?:http(?:%3A|:)(?:%2F|/)|www(?:[0-9]+)?\.(?:[^/%]+))?(?:%2F|/)[^&]+)''', archived_url, re.I)
  122. if match:
  123. print(match.groups())
  124. # we found it
  125. new_url = urllib.parse.unquote_plus(match.group(1))
  126. # add protocol if the URL is absolute but missing a protocol
  127. if new_url[0] != '/' and '://' not in new_url:
  128. new_url = 'http://' + new_url
  129. _print('[r]', new_url)
  130. return self.redirect_page(http_version, new_url)
  131. elif e.code in (301, 302):
  132. # 301 or 302 => urllib-generated error about an infinite redirect loop
  133. _print('[!] Infinite redirect loop')
  134. return self.error_page(http_version, 508, 'Infinite Redirect Loop')
  135. if e.code != 412: # tolerance exceeded has its own error message above
  136. _print('[!] {0} {1}'.format(e.code, e.reason))
  137. # If the memento Link header is present, this is a website error
  138. # instead of a Wayback error. Pass it along if that's the case.
  139. if 'Link' in e.headers:
  140. conn = e
  141. else:
  142. return self.error_page(http_version, e.code, e.reason)
  143. # get content type
  144. content_type = conn.info().get('Content-Type')
  145. if content_type == None: content_type = 'text/html'
  146. if not CONTENT_TYPE_ENCODING and content_type.find(';') > -1: content_type = content_type[:content_type.find(';')]
  147. # set the mode: [0]wayback [1]oocities
  148. mode = 0
  149. if GEOCITIES_FIX and hostname in ['www.oocities.org', 'www.oocities.com']: mode = 1
  150. # Wayback will add its HTML to anything it thinks is HTML
  151. guessed_content_type = conn.info().get('X-Archive-Guessed-Content-Type')
  152. if not guessed_content_type:
  153. guessed_content_type = content_type
  154. if 'text/html' in guessed_content_type:
  155. # Some dynamically generated links may end up pointing to
  156. # web.archive.org. Correct that by redirecting the Wayback
  157. # portion of the URL away if it ends up being HTML consumed
  158. # through the QUICK_IMAGES interface.
  159. if hostname == 'web.archive.org':
  160. conn.close()
  161. archived_url = '/'.join(request_url.split('/')[5:])
  162. _print('[r] [QI]', archived_url)
  163. return self.redirect_page(http_version, archived_url, 301)
  164. # check if the date is within tolerance
  165. if DATE_TOLERANCE is not None:
  166. match = re.search('''//web\.archive\.org/web/([0-9]+)''', conn.geturl())
  167. if match:
  168. requested_date = match.group(1)
  169. if self.wayback_to_datetime(requested_date) > self.wayback_to_datetime(original_date) + datetime.timedelta(DATE_TOLERANCE):
  170. _print('[!]', requested_date, 'is outside the configured tolerance of', DATE_TOLERANCE, 'days')
  171. conn.close()
  172. return self.error_page(http_version, 412, 'Snapshot ' + requested_date + ' not available')
  173. # consume all data
  174. data = conn.read()
  175. # patch the page
  176. if mode == 0: # wayback
  177. if b'<title>Wayback Machine</title>' in data:
  178. match = re.search(b'<iframe id="playback" src="((?:(?:http(?:s)?:)?//web.archive.org)?/web/[^"]+)"', data)
  179. if match:
  180. # media playback iframe
  181. # Some websites (especially ones that use frames)
  182. # inexplicably render inside a media playback iframe.
  183. # In that case, a simple redirect would result in a
  184. # redirect loop. Download the URL and render it instead.
  185. request_url = match.group(1).decode('ascii', 'ignore')
  186. archived_url = '/'.join(request_url.split('/')[5:])
  187. print('[f]', archived_url)
  188. try:
  189. conn = urllib.request.urlopen(request_url)
  190. except urllib.error.HTTPError as e:
  191. _print('[!]', e.code, e.reason)
  192. # If the memento Link header is present, this is a website error
  193. # instead of a Wayback error. Pass it along if that's the case.
  194. if 'Link' in e.headers:
  195. conn = e
  196. else:
  197. return self.error_page(http_version, e.code, e.reason)
  198. content_type = conn.info().get('Content-Type')
  199. if not CONTENT_TYPE_ENCODING and content_type.find(';') > -1: content_type = content_type[:content_type.find(';')]
  200. data = conn.read()
  201. if b'<title></title>' in data and b'<h1><span>Internet Archive\'s Wayback Machine</span></h1>' in data:
  202. match = re.search(b'<p class="impatient"><a href="(?:(?:http(?:s)?:)?//web\.archive\.org)?/web/([^/]+)/([^"]+)">Impatient\?</a></p>', data)
  203. if match:
  204. # wayback redirect page, follow it
  205. match2 = re.search(b'<p class="code shift red">Got an HTTP ([0-9]+)', data)
  206. try:
  207. redirect_code = int(match2.group(1))
  208. except:
  209. redirect_code = 302
  210. archived_url = match.group(2).decode('ascii', 'ignore')
  211. date_cache[effective_date + '\x00' + archived_url] = match.group(1).decode('ascii', 'ignore')
  212. print('[r]', archived_url)
  213. return self.redirect_page(http_version, archived_url, redirect_code)
  214. # pre-toolbar scripts and CSS
  215. data = re.sub(b'<script src="//archive\.org/(?:.*)<!-- End Wayback Rewrite JS Include -->(?:\r)?\n', b'', data, flags=re.S)
  216. # toolbar
  217. data = re.sub(b'<!-- BEGIN WAYBACK TOOLBAR INSERT -->(?:.*)<!-- END WAYBACK TOOLBAR INSERT -->', b'', data, flags=re.S)
  218. # comments on footer
  219. data = re.sub(b'<!--(?:\r)?\n FILE ARCHIVED (?:.*)$', b'', data, flags=re.S)
  220. # fix base tag
  221. data = re.sub(b'(<base (?:[^>]*)href=(?:["\'])?)(?:(?:http(?:s)?:)?//web.archive.org)?/web/(?:[^/]+)/', b'\\1', data, flags=re.I + re.S)
  222. # remove extraneous :80 from links
  223. data = re.sub(b'((?:(?:http(?:s)?:)?//web.archive.org)?/web/)([^/]+)/([^:]+)://([^:]+):80/', b'\\1\\2/\\3://\\4/', data)
  224. # fix links
  225. if QUICK_IMAGES:
  226. # QUICK_IMAGES works by intercepting asset URLs (those
  227. # with a date code ending in im_, js_...) and letting the
  228. # proxy pass them through. This may reduce load time
  229. # because Wayback doesn't have to hunt down the closest
  230. # copy of that asset to DATE, as those URLs have specific
  231. # date codes. This taints the HTML with web.archive.org
  232. # URLs. QUICK_IMAGES=2 uses the original URLs with an added
  233. # username:password, which taints less but is not supported
  234. # by all browsers - IE notably kills the whole page if it
  235. # sees an iframe pointing to an invalid URL.
  236. data = re.sub(b'(?:(?:http(?:s)?:)?//web.archive.org)?/web/([0-9]+)([a-z]+_)/([^:]+)://',
  237. QUICK_IMAGES == 2 and b'\\3://\\1:\\2@' or b'http://web.archive.org/web/\\1\\2/\\3://', data)
  238. data = re.sub(b'(?:(?:http(?:s)?:)?//web.archive.org)?/web/([0-9]+)/', b'', data)
  239. else:
  240. #data = re.sub(b'(?:(?:http(?:s)?:)?//web.archive.org)?/web/([^/]+)/', b'', data)
  241. def add_to_date_cache(match):
  242. orig_url = match.group(2)
  243. date_cache[effective_date + '\x00' + orig_url.decode('ascii', 'ignore')] = match.group(1).decode('ascii', 'ignore')
  244. return orig_url
  245. data = re.sub(b'(?:(?:http(?:s)?:)?//web.archive.org)?/web/([^/]+)/([^"\'#<>]+)', add_to_date_cache, data)
  246. elif mode == 1: # oocities
  247. # viewport/cache-control/max-width code (header)
  248. data = re.sub(b'^(?:.*?)\n\n', b'', data, flags=re.S)
  249. # archive notice and tracking code (footer)
  250. data = re.sub(b'<style> \n.zoomout { -webkit-transition: (?:.*)$', b'', data, flags=re.S)
  251. # clearly labeled snippets from Geocities
  252. data = re.sub(b'^(?:.*)<\!-- text above generated by server\. PLEASE REMOVE -->', b'', data, flags=re.S)
  253. data = re.sub(b'<\!-- following code added by server\. PLEASE REMOVE -->(?:.*)<\!-- preceding code added by server\. PLEASE REMOVE -->', b'', data, flags=re.S)
  254. data = re.sub(b'<\!-- text below generated by server\. PLEASE REMOVE -->(?:.*)$', b'', data, flags=re.S)
  255. # fix links
  256. data = re.sub(b'//([^.]*)\.oocities\.com/', b'//\\1.geocities.com/', data, flags=re.S)
  257. self.send_response_headers(conn, http_version, content_type, request_url)
  258. self.request.sendall(data)
  259. else: # other data
  260. self.send_response_headers(conn, http_version, content_type, request_url)
  261. while True:
  262. data = conn.read(1024)
  263. if not data: break
  264. self.request.sendall(data)
  265. self.request.close()
  266. def send_response_headers(self, conn, http_version, content_type, request_url):
  267. """Generate and send the response headers."""
  268. response = http_version
  269. # pass the error code if there is one
  270. if isinstance(conn, urllib.error.HTTPError):
  271. response += '{0} {1}'.format(conn.code, conn.reason.replace('\n', ' '))
  272. else:
  273. response += '200 OK'
  274. # add content type, and the ETag for caching
  275. response += '\r\nContent-Type: ' + content_type + '\r\nETag: "' + request_url.replace('"', '') + '"\r\n'
  276. # add X-Archive-Orig-* headers
  277. headers = conn.info()
  278. for header in headers:
  279. if header.find('X-Archive-Orig-') == 0:
  280. orig_header = header[15:]
  281. # blacklist certain headers which may alter the client
  282. if orig_header.lower() not in ('connection', 'location', 'content-type', 'content-length', 'etag', 'authorization', 'set-cookie'):
  283. response += orig_header + ': ' + headers[header] + '\r\n'
  284. # finish and send the request
  285. response += '\r\n'
  286. self.request.sendall(response.encode('ascii', 'ignore'))
  287. def error_page(self, http_version, code, reason):
  288. """Generate an error page."""
  289. # make error page
  290. errorpage = '<html><head><title>{0} {1}</title>'.format(code, reason)
  291. # IE's same-origin policy throws "Access is denied." inside frames
  292. # loaded from a different origin. Use that to our advantage, even
  293. # though regular frames are also affected. IE also doesn't recognize
  294. # language="javascript1.4", so use 1.3 while blocking IE4 by detecting
  295. # the lack of screenLeft as IE4 is quite noisy with script errors.
  296. errorpage += '<script language="javascript1.3">if (window.screenLeft != null) { eval(\'try { var frameElement = window.frameElement; } catch (e) { document.location.href = "about:blank"; }\'); }</script>'
  297. errorpage += '<script language="javascript">if (window.self != window.top && !(window.frameElement && window.frameElement.tagName == "FRAME")) { document.location.href = "about:blank"; }</script>'
  298. errorpage += '</head><body><h1>{0}</h1><p>'.format(reason)
  299. # add code information
  300. if code in (404, 508): # page not archived or redirect loop
  301. errorpage += 'This page may not be archived by the Wayback Machine.'
  302. elif code == 403: # not crawled due to robots.txt
  303. errorpage += 'This page was not archived due to a robots.txt block.'
  304. elif code == 501: # method not implemented
  305. errorpage += 'WaybackProxy only implements the GET method.'
  306. elif code == 412: # outside of tolerance
  307. errorpage += 'The earliest snapshot for this page is outside of the configured tolerance interval.'
  308. elif code == 400 and reason == 'Host header missing': # no host header in transparent mode
  309. errorpage += 'WaybackProxy\'s transparent mode requires an HTTP/1.1 compliant client.'
  310. else: # another error
  311. errorpage += 'Unknown error. The Wayback Machine may be experiencing technical difficulties.'
  312. errorpage += '</p><hr><i>'
  313. errorpage += self.signature()
  314. errorpage += '</i></body></html>'
  315. # add padding for IE
  316. if len(errorpage) <= 512:
  317. padding = '\n<!-- This comment pads the HTML so Internet Explorer displays this error page instead of its own. '
  318. remainder = 510 - len(errorpage) - len(padding)
  319. if remainder > 0:
  320. padding += ' ' * remainder
  321. padding += '-->'
  322. errorpage += padding
  323. # send error page and stop
  324. self.request.sendall('{0} {1} {2}\r\nContent-Type: text/html\r\nContent-Length: {3}\r\n\r\n{4}'.format(http_version, code, reason, len(errorpage), errorpage).encode('utf8', 'ignore'))
  325. self.request.close()
  326. def redirect_page(self, http_version, target, code=302):
  327. """Generate a redirect page."""
  328. # make redirect page
  329. redirectpage = '<html><head><title>Redirect</title><meta http-equiv="refresh" content="0;url='
  330. redirectpage += target
  331. redirectpage += '"></head><body><p>If you are not redirected, <a href="'
  332. redirectpage += target
  333. redirectpage += '">click here</a>.</p></body></html>'
  334. # send redirect page and stop
  335. self.request.sendall('{0} {1} Found\r\nLocation: {2}\r\nContent-Type: text/html\r\nContent-Length: {3}\r\n\r\n{4}'.format(http_version, code, target, len(redirectpage), redirectpage).encode('utf8', 'ignore'))
  336. self.request.close()
  337. def handle_settings(self, query):
  338. """Generate the settings page."""
  339. global DATE, GEOCITIES_FIX, QUICK_IMAGES, CONTENT_TYPE_ENCODING
  340. if query != '': # handle any parameters that may have been sent
  341. parsed = urllib.parse.parse_qs(query)
  342. if 'date' in parsed and DATE != parsed['date'][0]:
  343. DATE = parsed['date'][0]
  344. date_cache.clear()
  345. if 'dateTolerance' in parsed and DATE_TOLERANCE != parsed['dateTolerance'][0]:
  346. DATE_TOLERANCE = parsed['dateTolerance'][0]
  347. GEOCITIES_FIX = 'gcFix' in parsed
  348. QUICK_IMAGES = 'quickImages' in parsed
  349. CONTENT_TYPE_ENCODING = 'ctEncoding' in parsed
  350. # send the page and stop
  351. settingspage = 'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n'
  352. settingspage += '<html><head><title>WaybackProxy Settings</title></head><body><p><b>'
  353. settingspage += self.signature()
  354. settingspage += '</b></p><form method="get" action="/">'
  355. settingspage += '<p>Date to get pages from: <input type="text" name="date" size="8" value="'
  356. settingspage += DATE
  357. settingspage += '"><p>Date tolerance: <input type="text" name="dateTolerance" size="8" value="'
  358. settingspage += DATE_TOLERANCE
  359. settingspage += '"> days<br><input type="checkbox" name="gcFix"'
  360. if GEOCITIES_FIX: settingspage += ' checked'
  361. settingspage += '> Geocities Fix<br><input type="checkbox" name="quickImages"'
  362. if QUICK_IMAGES: settingspage += ' checked'
  363. settingspage += '> Quick images<br><input type="checkbox" name="ctEncoding"'
  364. if CONTENT_TYPE_ENCODING: settingspage += ' checked'
  365. settingspage += '> Encoding in Content-Type</p><p><input type="submit" value="Save"></p></form></body></html>'
  366. self.request.send(settingspage.encode('utf8', 'ignore'))
  367. self.request.close()
  368. def signature(self):
  369. """Return the server signature."""
  370. return 'WaybackProxy on {0}'.format(socket.gethostname())
  371. def wayback_to_datetime(self, date):
  372. """Convert a Wayback format date string to a datetime.datetime object."""
  373. # parse the string
  374. year = 1995
  375. month = 12
  376. day = 31
  377. hour = 0
  378. minute = 0
  379. second = 0
  380. if len(date) > 0:
  381. year = int(date[:4])
  382. if len(date) > 4:
  383. month = int(date[4:6])
  384. if len(date) > 6:
  385. day = int(date[6:8])
  386. if len(date) > 8:
  387. hour = int(date[8:10])
  388. if len(date) > 10:
  389. minute = int(date[10:12])
  390. if len(date) > 12:
  391. second = int(date[12:14])
  392. # sanitize the numbers
  393. if month < 1:
  394. month = 1
  395. elif month > 12:
  396. month = 12
  397. if day < 1:
  398. day = 1
  399. elif day > 31:
  400. day = 31
  401. if hour > 23:
  402. hour = 23
  403. elif hour < 0:
  404. hour = 0
  405. if minute > 59:
  406. minute = 59
  407. elif minute < 0:
  408. minute = 0
  409. if second > 59:
  410. second = 59
  411. elif second < 0:
  412. second = 0
  413. # if the day is invalid for that month, work its way down
  414. try:
  415. dt = datetime.datetime(year, month, day, hour, minute, second) # max 31
  416. except:
  417. try:
  418. dt = datetime.datetime(year, month, day - 1, hour, minute, second) # max 30
  419. except:
  420. try:
  421. dt = datetime.datetime(year, month, day - 2, hour, minute, second) # max 29
  422. except:
  423. dt = datetime.datetime(year, month, day - 3, hour, minute, second) # max 28
  424. return dt
  425. print_lock = threading.Lock()
  426. def _print(*args, linebreak=True):
  427. """Logging function."""
  428. if SILENT: return
  429. s = ' '.join([str(x) for x in args])
  430. print_lock.acquire()
  431. sys.stdout.write(linebreak and (s + '\n') or s)
  432. sys.stdout.flush()
  433. print_lock.release()
  434. def main():
  435. """Starts the server."""
  436. server = ThreadingTCPServer(('', LISTEN_PORT), Handler)
  437. _print('[-] Now listening on port {0}'.format(LISTEN_PORT))
  438. try:
  439. server.serve_forever()
  440. except KeyboardInterrupt: # Ctrl+C to stop
  441. pass
  442. if __name__ == '__main__':
  443. main()