waybackproxy.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. #!/usr/bin/env python
  2. import re, socket, SocketServer, sys, threading, urllib2, urlparse
  3. from config import *
  4. class ThreadingTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
  5. """TCPServer with ThreadingMixIn added."""
  6. pass
  7. class Handler(SocketServer.BaseRequestHandler):
  8. """Main request handler."""
  9. def handle(self):
  10. """Handle a request."""
  11. # readline is pretty convenient
  12. f = self.request.makefile()
  13. # read request line
  14. reqline = line = f.readline()
  15. split = line.rstrip('\r\n').split(' ')
  16. http_version = len(split) > 2 and split[2] or 'HTTP/0.9'
  17. if split[0] != 'GET':
  18. # only GET is implemented
  19. return self.error_page(http_version, 501, 'Not Implemented')
  20. # parse the URL
  21. request_url = split[1]
  22. parsed = urlparse.urlparse(request_url)
  23. # make a path
  24. path = parsed.path
  25. if parsed.query != '': path += '?' + parsed.query
  26. if path == '': path == '/'
  27. # get the hostname for later
  28. host = parsed.netloc.split(':')
  29. hostname = host[0]
  30. # read out the headers, saving the PAC file host
  31. pac_host = '" + location.host + ":' + str(LISTEN_PORT) # may not actually work
  32. while line.rstrip('\r\n') != '':
  33. line = f.readline()
  34. if line[:6].lower() == 'host: ':
  35. pac_host = line[6:].rstrip('\r\n')
  36. if ':' not in pac_host: # who would run this on port 80 anyway?
  37. pac_host += ':80'
  38. try:
  39. if path == '/proxy.pac':
  40. # PAC file to bypass QUICK_IMAGES requests
  41. pac = http_version + ''' 200 OK\r\n'''
  42. pac += '''Content-Type: application/x-ns-proxy-autoconfig\r\n'''
  43. pac += '''\r\n'''
  44. pac += '''function FindProxyForURL(url, host)\r\n'''
  45. pac += '''{\r\n'''
  46. pac += ''' if (shExpMatch(url, "http://web.archive.org/web/*"))\r\n'''
  47. pac += ''' {\r\n'''
  48. pac += ''' return "DIRECT";\r\n'''
  49. pac += ''' }\r\n'''
  50. pac += ''' return "PROXY {0}";\r\n'''.format(pac_host)
  51. pac += '''}\r\n'''
  52. self.request.sendall(pac)
  53. return
  54. elif hostname == 'web.archive.org':
  55. if path[:5] != '/web/':
  56. # launch settings
  57. return self.handle_settings(parsed.query)
  58. else:
  59. # pass-through requests to web.archive.org
  60. # required for QUICK_IMAGES
  61. _print('[>] [QI] {0}'.format('/'.join(request_url.split('/')[5:])))
  62. conn = urllib2.urlopen(request_url)
  63. elif GEOCITIES_FIX and hostname == 'www.geocities.com':
  64. # apply GEOCITIES_FIX and pass it through
  65. split = request_url.split('/')
  66. hostname = split[2] = 'www.oocities.org'
  67. request_url = '/'.join(split)
  68. _print('[>] {0}'.format(request_url))
  69. conn = urllib2.urlopen(request_url)
  70. else:
  71. # get from Wayback
  72. _print('[>] {0}'.format(request_url))
  73. conn = urllib2.urlopen('http://web.archive.org/web/{0}/{1}'.format(DATE, request_url))
  74. except urllib2.HTTPError as e:
  75. # an error has been found
  76. _print('[!] {0} {1}'.format(e.code, e.reason))
  77. return self.error_page(http_version, e.code, e.reason)
  78. # get content type
  79. content_type = conn.info().getheader('Content-Type')
  80. if not CONTENT_TYPE_ENCODING and content_type.find(';') > -1: content_type = content_type[:content_type.find(';')]
  81. # send headers
  82. self.request.sendall('{0} 200 OK\r\nContent-Type: {1}\r\n\r\n'.format(http_version, content_type))
  83. # set the mode: [0]wayback [1]oocities
  84. mode = 0
  85. if GEOCITIES_FIX and hostname in ['www.oocities.org', 'www.oocities.com']: mode = 1
  86. if content_type[:9] == 'text/html' in content_type: # HTML
  87. toolbar = mode == 1 # oocities header starts without warning
  88. after_header = False
  89. redirect_page = False
  90. for line in conn:
  91. line = line.rstrip('\r\n')
  92. if mode == 0:
  93. if toolbar:
  94. if line == '<!-- END WAYBACK TOOLBAR INSERT -->':
  95. # toolbar is done - resume relaying on the next line
  96. toolbar = False
  97. after_header = True
  98. continue
  99. elif redirect_page:
  100. # this is a really bad way to deal with Wayback's 302
  101. # pages, but necessary with the way this proxy works
  102. match = re.search('<p class="impatient"><a href="/web/(?:[^/]+)/([^"]+)">Impatient\\?</a></p>', line)
  103. if match:
  104. line = '<title>WaybackProxy Redirect</title><meta http-equiv="refresh" content="0;url='
  105. line += match.group(1)
  106. line += '"></head><body>If you are not redirected, <a href="'
  107. line += match.group(1)
  108. line += '">click here</a>.</body></html>'
  109. self.request.sendall(line)
  110. break
  111. continue
  112. if not after_header:
  113. ll = line.lower()
  114. if line == '<script type="text/javascript" src="/static/js/analytics.js"></script>' or line == '<link type="text/css" rel="stylesheet" href="/static/css/banner-styles.css"/>' or line[:69] == '<script type="text/javascript">archive_analytics.values.server_name="':
  115. # remove the CSS and tracking scripts added to <head>
  116. continue
  117. elif ll[:6] == '<base ':
  118. # fix base
  119. line = re.sub('/web/([0-9]+)/', '', line)
  120. if line == '<!-- BEGIN WAYBACK TOOLBAR INSERT -->':
  121. # remove the toolbar - stop relaying from now on
  122. toolbar = True
  123. continue
  124. elif line == '\t\t<title>Internet Archive Wayback Machine</title>':
  125. # redirect 302s - see the redirect_page code above
  126. redirect_page = True
  127. continue
  128. if QUICK_IMAGES:
  129. # QUICK_IMAGES works by intercepting asset URLs (those
  130. # with a date code ending in im_, js_...) and letting the
  131. # proxy pass them through. This may reduce load time
  132. # because Wayback doesn't have to hunt down the closest
  133. # copy of that asset to DATE, as those URLs have specific
  134. # date codes. The only side effect is tainting the HTML
  135. # with web.archive.org URLs.
  136. line = re.sub('/web/([0-9]+)([a-z]+_)/',
  137. 'http://web.archive.org/web/\\1\\2/', line)
  138. line = re.sub('/web/([0-9]+)/', '', line)
  139. else:
  140. line = re.sub('/web/([^/]+)/', '', line)
  141. elif mode == 1:
  142. # remove the geocities/oocities-added code, which is
  143. # conveniently wrapped around comments
  144. if toolbar:
  145. if line in ['<!-- text above generated by server. PLEASE REMOVE -->', '<!-- preceding code added by server. PLEASE REMOVE -->']:
  146. toolbar = False
  147. continue
  148. elif line == '<!-- following code added by server. PLEASE REMOVE -->' or line[:54] == '<!-- text below generated by server. PLEASE REMOVE -->':
  149. toolbar = True
  150. continue
  151. # taint? what taint?
  152. line = line.replace('http://oocities.com', 'http://geocities.com')
  153. line = line.replace('http://www.oocities.com', 'http://www.geocities.com')
  154. self.request.sendall(line)
  155. self.request.sendall('\r\n')
  156. else: # other data
  157. while True:
  158. data = conn.read(1024)
  159. if data == '': break
  160. self.request.sendall(data)
  161. self.request.close()
  162. def error_page(self, http_version, code, reason):
  163. """Generate an error page."""
  164. # make error page
  165. errorpage = '<html><head><title>{0} {1}</title></head><body><h1>{1}</h1><p>'.format(code, reason)
  166. # add code information
  167. if code == 404: # page not archived
  168. errorpage += 'This page may not be archived by the Wayback Machine.'
  169. elif code == 403: # not crawled due to robots.txt
  170. errorpage += 'This page was not archived due to a robots.txt block.'
  171. elif code == 501: # method not implemented
  172. errorpage += 'WaybackProxy only implements the GET method.'
  173. else: # another error
  174. errorpage += 'Unknown error. The Wayback Machine may be experiencing technical difficulties.'
  175. errorpage += '</p><hr><i>{0}</i></body></html>'.format(self.signature())
  176. # send error page and stop
  177. self.request.sendall('{0} {1} {2}\r\nContent-Length: {3}\r\n\r\n'.format(http_version, code, reason, len(errorpage)))
  178. self.request.sendall(errorpage)
  179. self.request.close()
  180. def handle_settings(self, query):
  181. """Generate the settings page."""
  182. global DATE, GEOCITIES_FIX, QUICK_IMAGES, CONTENT_TYPE_ENCODING
  183. if query != '': # handle any parameters that may have been sent
  184. parsed = urlparse.parse_qs(query)
  185. if 'date' in parsed: DATE = parsed['date'][0]
  186. GEOCITIES_FIX = 'gcFix' in parsed
  187. QUICK_IMAGES = 'quickImages' in parsed
  188. CONTENT_TYPE_ENCODING = 'ctEncoding' in parsed
  189. # send the page and stop
  190. self.request.sendall('HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n')
  191. self.request.sendall('<html><head><title>WaybackProxy Settings</title></head><body><p><b>')
  192. self.request.sendall(self.signature())
  193. self.request.sendall('</b></p><form method="get" action="/"><p>Date to get pages from: <input type="text" name="date" size="8" value="')
  194. self.request.sendall(DATE)
  195. self.request.sendall('"><br><input type="checkbox" name="gcFix"')
  196. if GEOCITIES_FIX: self.request.sendall(' checked')
  197. self.request.sendall('> Geocities Fix<br><input type="checkbox" name="quickImages"')
  198. if QUICK_IMAGES: self.request.sendall(' checked')
  199. self.request.sendall('> Quick images<br><input type="checkbox" name="ctEncoding"')
  200. if CONTENT_TYPE_ENCODING: self.request.sendall(' checked')
  201. self.request.sendall('> Encoding in Content-Type</p><p><input type="submit" value="Save"></p></form></body></html>')
  202. self.request.close()
  203. def signature(self):
  204. """Return the server signature."""
  205. return 'WaybackProxy on {0}'.format(socket.gethostname())
  206. print_lock = threading.Lock()
  207. def _print(s, linebreak=True):
  208. print_lock.acquire()
  209. sys.stdout.write(linebreak and (s + '\n') or s)
  210. sys.stdout.flush()
  211. print_lock.release()
  212. def main():
  213. """Starts the server."""
  214. server = ThreadingTCPServer(('', LISTEN_PORT), Handler)
  215. _print('[-] Now listening on port {0}'.format(LISTEN_PORT))
  216. try:
  217. server.serve_forever()
  218. except KeyboardInterrupt: # Ctrl+C to stop
  219. pass
  220. if __name__ == '__main__':
  221. main()