waybackproxy.py 22 KB

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