waybackproxy.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. #!/usr/bin/env python
  2. import base64, 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=60, 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. # get cached date for redirects, if available
  51. effective_date = date_cache.get(effective_date + '\x00' + archived_url, effective_date)
  52. # get date from username:password, if available
  53. if auth:
  54. effective_date = auth.replace(':', '')
  55. try:
  56. if path in ('/proxy.pac', '/wpad.dat', '/wpad.da'):
  57. # PAC file to bypass QUICK_IMAGES requests
  58. pac = http_version.encode('ascii', 'ignore') + b''' 200 OK\r\n'''
  59. pac += b'''Content-Type: application/x-ns-proxy-autoconfig\r\n'''
  60. pac += b'''\r\n'''
  61. pac += b'''function FindProxyForURL(url, host)\r\n'''
  62. pac += b'''{\r\n'''
  63. pac += b''' if (shExpMatch(url, "http://web.archive.org/web/*") && !shExpMatch(url, "http://web.archive.org/web/??????????????if_/*"))\r\n'''
  64. pac += b''' {\r\n'''
  65. pac += b''' return "DIRECT";\r\n'''
  66. pac += b''' }\r\n'''
  67. pac += b''' return "PROXY ''' + pac_host.encode('ascii', 'ignore') + b'''";\r\n'''
  68. pac += b'''}\r\n'''
  69. self.request.sendall(pac)
  70. return
  71. elif hostname == 'web.archive.org':
  72. if path[:5] != '/web/':
  73. # launch settings
  74. return self.handle_settings(parsed.query)
  75. else:
  76. # pass-through requests to web.archive.org
  77. # required for QUICK_IMAGES
  78. archived_url = '/'.join(request_url.split('/')[5:])
  79. _print('[>] [QI] {0}'.format(archived_url))
  80. try:
  81. conn = urllib.request.urlopen(request_url)
  82. except urllib.error.HTTPError as e:
  83. if e.code == 404:
  84. # Try this file on another date, might be redundant
  85. return self.redirect_page(http_version, archived_url)
  86. else:
  87. raise e
  88. elif GEOCITIES_FIX and hostname == 'www.geocities.com':
  89. # apply GEOCITIES_FIX and pass it through
  90. _print('[>] {0}'.format(archived_url))
  91. split = archived_url.split('/')
  92. hostname = split[2] = 'www.oocities.org'
  93. request_url = '/'.join(split)
  94. conn = urllib.request.urlopen(request_url)
  95. else:
  96. # get from Wayback
  97. _print('[>] {0}'.format(archived_url))
  98. request_url = 'http://web.archive.org/web/{0}/{1}'.format(effective_date, archived_url)
  99. conn = urllib.request.urlopen(request_url)
  100. except urllib.error.HTTPError as e:
  101. # an error has been found
  102. if e.code in (403, 404):
  103. # 403 or 404 => heuristically determine the static URL for some redirect scripts
  104. match = re.search('''(?:\?|&)(?:target|trg|dest(?:ination)?|to|go)?(?:url)?=(http[^&]+)''', archived_url, re.IGNORECASE)
  105. if not match:
  106. match = re.search('''/(?:target|trg|dest(?:ination)?|to|go)?(?:url)?/(http.+)''', archived_url, re.IGNORECASE)
  107. if match:
  108. # we found it
  109. new_url = urllib.parse.unquote_plus(match.group(1))
  110. _print('[r]', new_url)
  111. return self.redirect_page(http_version, new_url)
  112. elif e.code in (301, 302):
  113. # 301 or 302 => urllib-generated error about an infinite redirect loop
  114. _print('[!] Infinite redirect loop')
  115. return self.error_page(http_version, 508, 'Infinite Redirect Loop')
  116. _print('[!] {0} {1}'.format(e.code, e.reason))
  117. return self.error_page(http_version, e.code, e.reason)
  118. # get content type
  119. content_type = conn.info().get('Content-Type')
  120. if content_type == None: content_type = 'text/html'
  121. if not CONTENT_TYPE_ENCODING and content_type.find(';') > -1: content_type = content_type[:content_type.find(';')]
  122. # set the mode: [0]wayback [1]oocities
  123. mode = 0
  124. if GEOCITIES_FIX and hostname in ['www.oocities.org', 'www.oocities.com']: mode = 1
  125. if 'text/html' in content_type: # HTML
  126. # Some dynamically generated links may end up pointing to
  127. # web.archive.org. Correct that by redirecting the Wayback
  128. # portion of the URL away if it ends up being HTML consumed
  129. # through the QUICK_IMAGES interface.
  130. if hostname == 'web.archive.org':
  131. conn.close()
  132. return self.redirect_page(http_version, '/'.join(request_url.split('/')[5:]), 301)
  133. # consume all data
  134. data = conn.read()
  135. # patch the page
  136. if mode == 0: # wayback
  137. if b'<title>Wayback Machine</title>' in data:
  138. match = re.search(b'<iframe id="playback" src="((?:(?:http(?:s)?:)?//web.archive.org)?/web/[^"]+)"', data)
  139. if match:
  140. # media playback iframe
  141. # Some websites (especially ones that use frames)
  142. # inexplicably render inside a media playback iframe.
  143. # In that case, a simple redirect would result in a
  144. # redirect loop. Download the URL and render it instead.
  145. request_url = match.group(1).decode('ascii', 'ignore')
  146. archived_url = '/'.join(request_url.split('/')[5:])
  147. print('[f]', archived_url)
  148. try:
  149. conn = urllib.request.urlopen(request_url)
  150. except urllib.error.HTTPError as e:
  151. _print('[!]', e.code, e.reason)
  152. return self.error_page(http_version, e.code, e.reason)
  153. content_type = conn.info().get('Content-Type')
  154. if not CONTENT_TYPE_ENCODING and content_type.find(';') > -1: content_type = content_type[:content_type.find(';')]
  155. data = conn.read()
  156. if b'<title></title>' in data and b'<h1><span>Internet Archive\'s Wayback Machine</span></h1>' in data:
  157. match = re.search(b'<p class="impatient"><a href="(?:(?:http(?:s)?:)?//web\.archive\.org)?/web/([^/]+)/([^"]+)">Impatient\?</a></p>', data)
  158. if match:
  159. # wayback redirect page, follow it
  160. match2 = re.search(b'<p class="code shift red">Got an HTTP ([0-9]+)', data)
  161. try:
  162. redirect_code = int(match2.group(1))
  163. except:
  164. redirect_code = 302
  165. archived_url = match.group(2).decode('ascii', 'ignore')
  166. date_cache[effective_date + '\x00' + archived_url] = match.group(1).decode('ascii', 'ignore')
  167. print('[r]', archived_url)
  168. return self.redirect_page(http_version, archived_url, redirect_code)
  169. # pre-toolbar scripts and CSS
  170. data = re.sub(b'<script src="//archive\.org/(?:.*)<!-- End Wayback Rewrite JS Include -->', b'', data, flags=re.S)
  171. # toolbar
  172. data = re.sub(b'<!-- BEGIN WAYBACK TOOLBAR INSERT -->(?:.*)<!-- END WAYBACK TOOLBAR INSERT -->', b'', data, flags=re.S)
  173. # comments on footer
  174. data = re.sub(b'\n<!--\n FILE ARCHIVED (?:.*)$', b'', data, flags=re.S)
  175. # fix base tag
  176. data = re.sub(b'(<base (?:[^>]*)href=(?:["\'])?)(?:(?:http(?:s)?:)?//web.archive.org)?/web/(?:[^/]+)/', b'\\1', data, flags=re.I + re.S)
  177. # remove extraneous :80 from links
  178. data = re.sub(b'((?:(?:http(?:s)?:)?//web.archive.org)?/web/)([^/]+)/([^:]+)://([^:]+):80/', b'\\1\\2/\\3://\\4/', data)
  179. # fix links
  180. if QUICK_IMAGES:
  181. # QUICK_IMAGES works by intercepting asset URLs (those
  182. # with a date code ending in im_, js_...) and letting the
  183. # proxy pass them through. This may reduce load time
  184. # because Wayback doesn't have to hunt down the closest
  185. # copy of that asset to DATE, as those URLs have specific
  186. # date codes. This taints the HTML with web.archive.org
  187. # URLs. QUICK_IMAGES=2 uses the original URLs with an added
  188. # username:password, which taints less but is not supported
  189. # by all browsers - IE6 notably kills the whole page if it
  190. # sees an iframe pointing to an invalid URL.
  191. data = re.sub(b'(?:(?:http(?:s)?:)?//web.archive.org)?/web/([0-9]+)([a-z]+_)/([^:]+)://',
  192. QUICK_IMAGES == 2 and b'\\3://\\1:\\2@' or b'http://web.archive.org/web/\\1\\2/\\3://', data)
  193. data = re.sub(b'(?:(?:http(?:s)?:)?//web.archive.org)?/web/([0-9]+)/', b'', data)
  194. else:
  195. #data = re.sub(b'(?:(?:http(?:s)?:)?//web.archive.org)?/web/([^/]+)/', b'', data)
  196. def add_to_date_cache(match):
  197. orig_url = match.group(2)
  198. date_cache[effective_date + '\x00' + orig_url.decode('ascii', 'ignore')] = match.group(1).decode('ascii', 'ignore')
  199. return orig_url
  200. data = re.sub(b'(?:(?:http(?:s)?:)?//web.archive.org)?/web/([^/]+)/([^"\'#<>]+)', add_to_date_cache, data)
  201. elif mode == 1: # oocities
  202. # viewport/cache-control/max-width code (header)
  203. data = re.sub(b'^(?:.*?)\n\n', b'', data, flags=re.S)
  204. # archive notice and tracking code (footer)
  205. data = re.sub(b'<style> \n.zoomout { -webkit-transition: (?:.*)$', b'', data, flags=re.S)
  206. # clearly labeled snippets from Geocities
  207. data = re.sub(b'^(?:.*)<\!-- text above generated by server\. PLEASE REMOVE -->', b'', data, flags=re.S)
  208. data = re.sub(b'<\!-- following code added by server\. PLEASE REMOVE -->(?:.*)<\!-- preceding code added by server\. PLEASE REMOVE -->', b'', data, flags=re.S)
  209. data = re.sub(b'<\!-- text below generated by server\. PLEASE REMOVE -->(?:.*)$', b'', data, flags=re.S)
  210. # fix links
  211. data = re.sub(b'//([^.]*)\.oocities\.com/', b'//\\1.geocities.com/', data, flags=re.S)
  212. 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'))
  213. self.request.sendall(data)
  214. else: # other data
  215. 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'))
  216. while True:
  217. data = conn.read(1024)
  218. if not data: break
  219. self.request.sendall(data)
  220. self.request.close()
  221. def error_page(self, http_version, code, reason):
  222. """Generate an error page."""
  223. # make error page
  224. errorpage = '<html><head><title>{0} {1}</title></head><body><h1>{1}</h1><p>'.format(code, reason)
  225. # add code information
  226. if code in (404, 508): # page not archived or redirect loop
  227. errorpage += 'This page may not be archived by the Wayback Machine.'
  228. elif code == 403: # not crawled due to robots.txt
  229. errorpage += 'This page was not archived due to a robots.txt block.'
  230. elif code == 501: # method not implemented
  231. errorpage += 'WaybackProxy only implements the GET method.'
  232. else: # another error
  233. errorpage += 'Unknown error. The Wayback Machine may be experiencing technical difficulties.'
  234. errorpage += '</p><hr><i>'
  235. errorpage += self.signature()
  236. errorpage += '</i></body></html>'
  237. # send error page and stop
  238. 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'))
  239. self.request.close()
  240. def redirect_page(self, http_version, target, code=302):
  241. """Generate a redirect page."""
  242. # make redirect page
  243. redirectpage = '<html><head><title>Redirect</title><meta http-equiv="refresh" content="0;url='
  244. redirectpage += target
  245. redirectpage += '"></head><body><p>If you are not redirected, <a href="'
  246. redirectpage += target
  247. redirectpage += '">click here</a>.</p></body></html>'
  248. # send redirect page and stop
  249. 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'))
  250. self.request.close()
  251. def handle_settings(self, query):
  252. """Generate the settings page."""
  253. global DATE, GEOCITIES_FIX, QUICK_IMAGES, CONTENT_TYPE_ENCODING
  254. if query != '': # handle any parameters that may have been sent
  255. parsed = urllib.parse.parse_qs(query)
  256. if 'date' in parsed: DATE = parsed['date'][0]
  257. GEOCITIES_FIX = 'gcFix' in parsed
  258. QUICK_IMAGES = 'quickImages' in parsed
  259. CONTENT_TYPE_ENCODING = 'ctEncoding' in parsed
  260. # send the page and stop
  261. settingspage = 'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n'
  262. settingspage += '<html><head><title>WaybackProxy Settings</title></head><body><p><b>'
  263. settingspage += self.signature()
  264. settingspage += '</b></p><form method="get" action="/"><p>Date to get pages from: <input type="text" name="date" size="8" value="'
  265. settingspage += DATE
  266. settingspage += '"><br><input type="checkbox" name="gcFix"'
  267. if GEOCITIES_FIX: settingspage += ' checked'
  268. settingspage += '> Geocities Fix<br><input type="checkbox" name="quickImages"'
  269. if QUICK_IMAGES: settingspage += ' checked'
  270. settingspage += '> Quick images<br><input type="checkbox" name="ctEncoding"'
  271. if CONTENT_TYPE_ENCODING: settingspage += ' checked'
  272. settingspage += '> Encoding in Content-Type</p><p><input type="submit" value="Save"></p></form></body></html>'
  273. self.request.send(settingspage.encode('utf8', 'ignore'))
  274. self.request.close()
  275. def signature(self):
  276. """Return the server signature."""
  277. return 'WaybackProxy on {0}'.format(socket.gethostname())
  278. print_lock = threading.Lock()
  279. def _print(*args, linebreak=True):
  280. """Logging function."""
  281. if SILENT: return
  282. s = ' '.join([str(x) for x in args])
  283. print_lock.acquire()
  284. sys.stdout.write(linebreak and (s + '\n') or s)
  285. sys.stdout.flush()
  286. print_lock.release()
  287. def main():
  288. """Starts the server."""
  289. server = ThreadingTCPServer(('', LISTEN_PORT), Handler)
  290. _print('[-] Now listening on port {0}'.format(LISTEN_PORT))
  291. try:
  292. server.serve_forever()
  293. except KeyboardInterrupt: # Ctrl+C to stop
  294. pass
  295. if __name__ == '__main__':
  296. main()