waybackproxy.py 17 KB

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