waybackproxy.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. #!/usr/bin/env python3
  2. import base64, datetime, json, lrudict, re, socket, socketserver, string, sys, threading, time, traceback, urllib.parse
  3. try:
  4. import urllib3
  5. except ImportError:
  6. print('WaybackProxy now requires urllib3 to be installed. Follow setup step 3 on the readme to fix this.')
  7. sys.exit(1)
  8. from config_handler import *
  9. class ThreadingTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
  10. """TCPServer with ThreadingMixIn added."""
  11. pass
  12. class SharedState:
  13. """Class for storing shared state across instances of Handler."""
  14. def __init__(self):
  15. # Create urllib3 connection pool.
  16. self.http = urllib3.PoolManager(maxsize=4, block=True)
  17. urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
  18. # Create internal LRU dictionary for preserving URLs on redirect.
  19. self.date_cache = lrudict.LRUDict(maxduration=86400, maxsize=1024)
  20. # Create internal LRU dictionary for date availability.
  21. self.availability_cache = lrudict.LRUDict(maxduration=86400, maxsize=1024) if WAYBACK_API else None
  22. # Read domain whitelist file.
  23. try:
  24. with open('whitelist.txt', 'r') as f:
  25. self.whitelist = f.read().splitlines()
  26. except:
  27. self.whitelist = []
  28. shared_state = SharedState()
  29. class Handler(socketserver.BaseRequestHandler):
  30. """Main request handler."""
  31. def setup(self, *args, **kwargs):
  32. """Set up this instance of Handler."""
  33. super().setup(*args, **kwargs)
  34. # Store a local pointer to SharedState.
  35. self.shared_state = shared_state
  36. def handle(self):
  37. """Handle a request."""
  38. # readline is pretty convenient
  39. f = self.request.makefile()
  40. # read request line
  41. reqline = line = f.readline()
  42. split = line.rstrip().split(' ')
  43. http_version = len(split) > 2 and split[2] or 'HTTP/0.9'
  44. if len(split) < 2 or split[0] != 'GET':
  45. # only GET is implemented
  46. return self.send_error_page(http_version, 501, 'Not Implemented')
  47. # read out the headers
  48. request_host = None
  49. pac_host = '" + location.host + ":' + str(LISTEN_PORT) # may not actually work
  50. effective_date = DATE
  51. auth = None
  52. while line.strip() != '':
  53. line = f.readline()
  54. ll = line.lower()
  55. if ll[:6] == 'host: ':
  56. pac_host = request_host = line[6:].rstrip()
  57. if ':' not in pac_host: # explicitly specify port if running on port 80
  58. pac_host += ':80'
  59. elif ll[:21] == 'x-waybackproxy-date: ':
  60. # API for a personal project of mine
  61. effective_date = line[21:].rstrip()
  62. elif ll[:21] == 'authorization: basic ':
  63. # asset date code passed as username:password
  64. auth = base64.b64decode(ll[21:])
  65. # parse the URL
  66. pac_file_paths = ('/proxy.pac', '/wpad.dat', '/wpad.da')
  67. if split[1][0] == '/' and split[1] not in pac_file_paths:
  68. # just a path (not corresponding to a PAC file) => transparent proxy
  69. # Host header and therefore HTTP/1.1 are required
  70. if not request_host:
  71. return self.send_error_page(http_version, 400, 'Host header missing')
  72. archived_url = 'http://' + request_host + split[1]
  73. else:
  74. # full URL => explicit proxy
  75. archived_url = split[1]
  76. request_url = archived_url
  77. parsed = urllib.parse.urlparse(request_url)
  78. # make a path
  79. path = parsed.path
  80. if parsed.query:
  81. path += '?' + parsed.query
  82. elif path == '':
  83. path == '/'
  84. # get the hostname for later
  85. host = parsed.netloc.split(':')
  86. hostname = host[0]
  87. # get cached date for redirects, if available
  88. original_date = effective_date
  89. effective_date = self.shared_state.date_cache.get(str(effective_date) + '\x00' + str(archived_url), effective_date)
  90. # get date from username:password, if available
  91. if auth:
  92. effective_date = auth.replace(':', '')
  93. # Effectively handle the request.
  94. try:
  95. if path in pac_file_paths:
  96. # PAC file to bypass QUICK_IMAGES requests if WAYBACK_API is not enabled.
  97. pac = http_version + ''' 200 OK\r\n'''
  98. pac += '''Content-Type: application/x-ns-proxy-autoconfig\r\n'''
  99. pac += '''\r\n'''
  100. pac += '''function FindProxyForURL(url, host)\r\n'''
  101. pac += '''{\r\n'''
  102. if self.shared_state.availability_cache == None:
  103. pac += ''' if (shExpMatch(url, "http://web.archive.org/web/*") && !shExpMatch(url, "http://web.archive.org/web/??????????????if_/*"))\r\n'''
  104. pac += ''' {\r\n'''
  105. pac += ''' return "DIRECT";\r\n'''
  106. pac += ''' }\r\n'''
  107. pac += ''' return "PROXY ''' + pac_host + '''";\r\n'''
  108. pac += '''}\r\n'''
  109. self.request.sendall(pac.encode('ascii', 'ignore'))
  110. return
  111. elif hostname in self.shared_state.whitelist:
  112. _print('[>] [byp]', archived_url)
  113. elif hostname == 'web.archive.org':
  114. if path[:5] != '/web/':
  115. # Launch settings if enabled.
  116. if SETTINGS_PAGE:
  117. return self.handle_settings(parsed.query)
  118. else:
  119. return self.send_error_page(http_version, 404, 'Not Found')
  120. else:
  121. # Pass requests through to web.archive.org. Required for QUICK_IMAGES.
  122. split = request_url.split('/')
  123. effective_date = split[4]
  124. archived_url = '/'.join(split[5:])
  125. _print('[>] [QI]', archived_url)
  126. elif GEOCITIES_FIX and hostname == 'www.geocities.com':
  127. # Apply GEOCITIES_FIX and pass it through.
  128. _print('[>]', archived_url)
  129. split = archived_url.split('/')
  130. hostname = split[2] = 'www.oocities.org'
  131. request_url = '/'.join(split)
  132. else:
  133. # Get from the Wayback Machine.
  134. _print('[>]', archived_url)
  135. request_url = 'https://web.archive.org/web/{0}if_/{1}'.format(effective_date, archived_url)
  136. # Check Wayback Machine Availability API where applicable, to avoid archived 404 pages and other site errors.
  137. if self.shared_state.availability_cache != None:
  138. # Are we requesting from the Wayback Machine?
  139. split = request_url.split('/')
  140. # If so, get the closest available date from the API.
  141. if split[2] == 'web.archive.org':
  142. # Remove extraneous :80 from URL.
  143. if ':' in split[5]:
  144. if split[7][-3:] == ':80':
  145. split[7] = split[7][:-3]
  146. elif split[5][-3:] == ':80':
  147. split[5] = split[5][:-3]
  148. # Check availability LRU cache.
  149. availability_url = '/'.join(split[5:])
  150. new_url = self.shared_state.availability_cache.get(availability_url, None)
  151. if new_url:
  152. # In cache => replace URL immediately.
  153. request_url = new_url
  154. else:
  155. # Not in cache => contact API.
  156. try:
  157. availability_endpoint = 'https://archive.org/wayback/available?url=' + urllib.parse.quote_plus(availability_url) + '&timestamp=' + effective_date[:14]
  158. availability = json.loads(self.shared_state.http.request('GET', availability_endpoint, timeout=10, retries=1).data)
  159. closest = availability.get('archived_snapshots', {}).get('closest', {})
  160. new_date = closest.get('timestamp', None)
  161. except:
  162. _print('[!] Failed to fetch Wayback availability data')
  163. new_date = None
  164. if new_date and new_date != effective_date[:14]:
  165. # Returned date is different.
  166. new_url = closest['url']
  167. # Add asset tag to the date.
  168. split = new_url.split('/')
  169. if len(effective_date) > 14:
  170. split[4] += effective_date[14:]
  171. else:
  172. split[4] += 'if_'
  173. new_url = '/'.join(split)
  174. # Replace URL and add it to the availability cache.
  175. request_url = self.shared_state.availability_cache[availability_url] = new_url
  176. # Start fetching the URL.
  177. retry = urllib3.util.retry.Retry(total=10, connect=10, read=5, redirect=5, backoff_factor=1, raise_on_redirect=True)
  178. conn = self.shared_state.http.urlopen('GET', request_url, retries=retry, preload_content=False)
  179. except urllib3.exceptions.MaxRetryError as e:
  180. _print('[!] Fetch retries exceeded:', e.reason)
  181. return self.send_error_page(http_version, 504, 'Gateway Timeout')
  182. except:
  183. # Some other fetch exception has occurred.
  184. _print('[!] Fetch exception:')
  185. traceback.print_exc()
  186. return self.send_error_page(http_version, 502, 'Bad Gateway')
  187. # Check for HTTP errors.
  188. if conn.status != 200:
  189. if conn.status in (403, 404): # not found
  190. if self.guess_and_send_redirect(http_version, archived_url):
  191. conn.release_conn()
  192. return
  193. elif conn.status in (301, 302): # urllib3-generated error about an infinite redirect loop
  194. conn.release_conn()
  195. _print('[!] Infinite redirect loop')
  196. return self.send_error_page(http_version, 508, 'Infinite Redirect Loop')
  197. if conn.status != 412: # tolerance exceeded has its own error message above
  198. _print('[!]', conn.status, conn.reason)
  199. # If the memento Link header is present, this is a website error
  200. # instead of a Wayback error. Pass it along if that's the case.
  201. if 'Link' not in conn.headers:
  202. conn.release_conn()
  203. return self.send_error_page(http_version, conn.status, conn.reason)
  204. # Get content type.
  205. content_type = conn.headers.get('Content-Type')
  206. if content_type == None:
  207. content_type = 'text/html'
  208. elif not CONTENT_TYPE_ENCODING:
  209. idx = content_type.find(';')
  210. if idx > -1:
  211. content_type = content_type[:idx]
  212. # Set the archive mode.
  213. if GEOCITIES_FIX and hostname in ('www.oocities.org', 'www.oocities.com'):
  214. mode = 1 # oocities
  215. else:
  216. mode = 0 # Wayback Machine
  217. # Check content type to determine if this is HTML we need to patch.
  218. # Wayback will add its HTML to anything it thinks is HTML.
  219. guessed_content_type = conn.headers.get('X-Archive-Guessed-Content-Type')
  220. if not guessed_content_type:
  221. guessed_content_type = content_type
  222. if 'text/html' in guessed_content_type:
  223. # Some dynamically-generated links may end up pointing to
  224. # web.archive.org. Correct that by redirecting the Wayback
  225. # portion of the URL away if it ends up being HTML consumed
  226. # through the QUICK_IMAGES interface.
  227. if hostname == 'web.archive.org':
  228. conn.release_conn()
  229. archived_url = '/'.join(request_url.split('/')[5:])
  230. _print('[r] [QI]', archived_url)
  231. return self.send_redirect_page(http_version, archived_url, 301)
  232. # Check if the date is within tolerance.
  233. if DATE_TOLERANCE != None:
  234. match = re.search('''//web\\.archive\\.org/web/([0-9]+)''', conn.geturl() or '')
  235. if match:
  236. requested_date = match.group(1)
  237. if self.wayback_to_datetime(requested_date) > self.wayback_to_datetime(original_date) + datetime.timedelta(int(DATE_TOLERANCE)):
  238. conn.release_conn()
  239. _print('[!]', requested_date, 'is outside the configured tolerance of', DATE_TOLERANCE, 'days')
  240. if not self.guess_and_send_redirect(http_version, archived_url):
  241. self.send_error_page(http_version, 412, 'Snapshot ' + requested_date + ' not available')
  242. return
  243. # Consume all data.
  244. data = conn.read()
  245. conn.release_conn()
  246. # Patch the page.
  247. if mode == 0: # Wayback Machine
  248. # Check if this is a Wayback Machine page.
  249. if b'<title>Wayback Machine</title>' in data:
  250. # Check if this is an exclusion (robots.txt?) error page.
  251. if b'<p>This URL has been excluded from the Wayback Machine.</p>' in data:
  252. return self.send_error_page(http_version, 403, 'URL excluded')
  253. # Check if this is a media playback iframe page.
  254. # Some websites (especially ones that use frames)
  255. # inexplicably render inside a media playback iframe.
  256. # In that case, a simple redirect would result in a
  257. # redirect loop, so fetch and render the URL instead.
  258. match = re.search(b'''<iframe id="playback" src="((?:(?:https?:)?//web.archive.org)?/web/[^"]+)"''', data)
  259. if match:
  260. # Extract the content URL.
  261. request_url = match.group(1).decode('ascii', 'ignore')
  262. archived_url = '/'.join(request_url.split('/')[5:])
  263. # Start fetching the URL.
  264. _print('[f]', archived_url)
  265. conn = self.shared_state.http.urlopen('GET', request_url, retries=retry, preload_content=False)
  266. if conn.status != 200:
  267. _print('[!]', conn.status, conn.reason)
  268. # If the memento Link header is present, this is a website error
  269. # instead of a Wayback error. Pass it along if that's the case.
  270. if 'Link' not in conn.headers:
  271. conn.release_conn()
  272. return self.send_error_page(http_version, conn.status, conn.reason)
  273. # Identify content type so we don't modify non-HTML content.
  274. content_type = conn.headers.get('Content-Type')
  275. if not CONTENT_TYPE_ENCODING:
  276. idx = content_type.find(';')
  277. if idx > -1:
  278. content_type = content_type[:idx]
  279. if 'text/html' in content_type:
  280. # Consume all data and proceed with patching the page.
  281. data = conn.read()
  282. conn.release_conn()
  283. else:
  284. # Pass non-HTML data through.
  285. return self.send_passthrough(conn, http_version, content_type, request_url)
  286. # Check if this is a Wayback Machine redirect page.
  287. if b'<title></title>' in data and b'<span class="label style-scope media-button"><!---->Wayback Machine<!----></span>' in data:
  288. match = re.search(b'''<p class="impatient"><a href="(?:(?:https?:)?//web\\.archive\\.org)?/web/([^/]+)/([^"]+)">Impatient\\?</a></p>''', data)
  289. if match:
  290. # Sanitize the URL.
  291. archived_url = self.sanitize_redirect(match.group(2).decode('ascii', 'ignore'))
  292. # Add URL to the date LRU cache.
  293. self.shared_state.date_cache[str(effective_date) + '\x00' + archived_url] = match.group(1).decode('ascii', 'ignore')
  294. # Get the original HTTP redirect code.
  295. match = re.search(b'''<p class="code shift red">Got an HTTP ([0-9]+)''', data)
  296. try:
  297. redirect_code = int(match.group(1))
  298. except:
  299. redirect_code = 302
  300. # Redirect client to the URL.
  301. _print('[r]', archived_url)
  302. return self.send_redirect_page(http_version, archived_url, redirect_code)
  303. # Remove pre-toolbar scripts and CSS.
  304. data = re.sub(b'''<script (?:type="text/javascript" )?src="(?:https?:)?//(?:web-static\\.)?archive\\.org/_static/js/.*<!-- End Wayback Rewrite JS Include -->\\r?\\n''', b'', data, count=1, flags=re.S)
  305. # Remove toolbar. The if_ asset tag serves no toolbar, but we remove it just in case.
  306. data = re.sub(b'''<!-- BEGIN WAYBACK TOOLBAR INSERT -->.*<!-- END WAYBACK TOOLBAR INSERT -->''', b'', data, count=1, flags=re.S)
  307. # Remove comments on footer.
  308. data = re.sub(b'''<!--\\r?\\n FILE ARCHIVED .*$''', b'', data, flags=re.S)
  309. # Fix base tag.
  310. data = re.sub(b'''(<base\\s+[^>]*href=["']?)(?:(?:https?:)?//web.archive.org)?/web/[^/]+/(?:[^:/]+://)?''', b'\\1http://', data, flags=re.I + re.S)
  311. # Remove extraneous :80 from links.
  312. data = re.sub(b'((?:(?:https?:)?//web.archive.org)?/web/)([^/]+)/([^/:]+)://([^/:]+):80/', b'\\1\\2/\\3://\\4/', data)
  313. # Fix links.
  314. if QUICK_IMAGES:
  315. # QUICK_IMAGES works by intercepting asset URLs (those
  316. # with a date code ending in im_, js_...) and letting the
  317. # proxy pass them through. This may reduce load time
  318. # because Wayback doesn't have to hunt down the closest
  319. # copy of that asset to DATE, as those URLs have specific
  320. # date codes. This taints the HTML with web.archive.org
  321. # URLs. QUICK_IMAGES=2 uses the original URLs with an added
  322. # username:password, which taints less but is not supported
  323. # by all browsers - IE notably kills the whole page if it
  324. # sees an iframe pointing to an invalid URL.
  325. def filter_asset(match):
  326. if match.group(2) in (None, b'if_', b'fw_'): # non-asset URL
  327. return match.group(3) == b'https://' and b'http://' or match.group(3) # convert secure non-asset URLs to regular HTTP
  328. elif QUICK_IMAGES == 2:
  329. return b'http://' + match.group(1) + b':' + match.group(2) + b'@'
  330. else:
  331. return b'http://web.archive.org/web/' + match.group(1) + match.group(2) + b'/' + match.group(3)
  332. data = re.sub(b'(?:(?:https?:)?//web.archive.org)?/web/([0-9]+)([a-z]+_)?/([^:/]+://)', filter_asset, data)
  333. else:
  334. # Remove asset URLs while simultaneously adding them to the date LRU cache
  335. # with their respective date and converting secure URLs to regular HTTP.
  336. def add_to_date_cache(match):
  337. orig_url = match.group(2)
  338. if orig_url[:8] == b'https://':
  339. orig_url = b'http://' + orig_url[8:]
  340. self.shared_state.date_cache[str(effective_date) + '\x00' + orig_url.decode('ascii', 'ignore')] = match.group(1).decode('ascii', 'ignore')
  341. return orig_url
  342. data = re.sub(b'''(?:(?:https?:)?//web.archive.org)?/web/([^/]+)/([^"\\'#<>]+)''', add_to_date_cache, data)
  343. elif mode == 1: # oocities
  344. # Remove viewport/cache-control/max-width code from the header.
  345. data = re.sub(b'''^.*?\n\n''', b'', data, flags=re.S)
  346. # Remove archive notice and tracking code from the footer.
  347. data = re.sub(b'''<style> \n.zoomout { -webkit-transition: .*$''', b'', data, flags=re.S)
  348. # Remove clearly labeled snippets from Geocities.
  349. data = re.sub(b'''^.*<\\!-- text above generated by server\\. PLEASE REMOVE -->''', b'', data, flags=re.S)
  350. data = re.sub(b'''<\\!-- following code added by server\\. PLEASE REMOVE -->.*<\!-- preceding code added by server\. PLEASE REMOVE -->''', b'', data, flags=re.S)
  351. data = re.sub(b'''<\\!-- text below generated by server\\. PLEASE REMOVE -->.*$''', b'', data, flags=re.S)
  352. # Fix links.
  353. data = re.sub(b'''//([^\\.]*\\.)?oocities\\.com/''', b'//\\1geocities.com/', data, flags=re.S)
  354. # Send patched page.
  355. self.send_response_headers(conn, http_version, content_type, request_url, content_length=len(data))
  356. self.request.sendall(data)
  357. self.request.close()
  358. else:
  359. # Pass non-HTML data through.
  360. self.send_passthrough(conn, http_version, content_type, request_url)
  361. def send_passthrough(self, conn, http_version, content_type, request_url):
  362. """Pass data through to the client unmodified (save for our headers)."""
  363. self.send_response_headers(conn, http_version, content_type, request_url, content_length=True)
  364. for data in conn.stream(1024):
  365. self.request.sendall(data)
  366. conn.release_conn()
  367. self.request.close()
  368. def send_response_headers(self, conn, http_version, content_type, request_url, content_length=False):
  369. """Generate and send the response headers."""
  370. # Pass the HTTP version, and error code if there is one.
  371. response = '{0} {1} {2}'.format(http_version, conn.status, conn.reason.replace('\n', ' '))
  372. # Add Content-Type, Content-Length and the caching ETag.
  373. response += '\r\nContent-Type: ' + content_type
  374. if type(content_length) == int:
  375. response += '\r\nContent-Length: ' + str(content_length)
  376. content_length = False # don't pass the original length through
  377. response += '\r\nETag: "' + request_url.replace('"', '') + '"'
  378. response += '\r\nConnection: close' # helps with IE6 trying to use proxy keep alive and holding half-open connections
  379. # Pass X-Archive-Orig-* (and Content-Length if requested) headers through.
  380. for header in conn.headers:
  381. if header.find('X-Archive-Orig-') == 0:
  382. orig_header = header[15:]
  383. # Skip headers which may affect client behavior.
  384. if orig_header.lower() not in ('connection', 'location', 'content-type', 'content-length', 'etag', 'authorization', 'set-cookie'):
  385. response += '\r\n' + orig_header + ': ' + conn.headers[header]
  386. elif content_length and header.lower() == 'content-length':
  387. response += '\r\n' + header + ': ' + conn.headers[header]
  388. # Finish and send the request.
  389. response += '\r\n\r\n'
  390. self.request.sendall(response.encode('utf8', 'ignore'))
  391. def send_error_page(self, http_version, code, reason):
  392. """Generate an error page."""
  393. # Get a description for this error code.
  394. if code in (404, 508): # page not archived or redirect loop
  395. description = 'This page may not be archived by the Wayback Machine.'
  396. elif code == 403: # not crawled due to exclusion
  397. description = 'This page was not archived due to a Wayback Machine exclusion.'
  398. elif code == 501: # method not implemented
  399. description = 'WaybackProxy only implements the GET method.'
  400. elif code == 502: # exception
  401. description = 'This page could not be fetched due to an unknown error.'
  402. elif code == 504: # timeout
  403. description = 'This page could not be fetched due to a Wayback Machine server timeout.'
  404. elif code == 412: # outside of tolerance
  405. description = 'The earliest snapshot for this page is outside of the configured tolerance interval.'
  406. elif code == 400 and reason == 'Host header missing': # no host header in transparent mode
  407. description = 'WaybackProxy\'s transparent mode requires an HTTP/1.1 compliant client.'
  408. else: # another error
  409. description = 'Unknown error. The Wayback Machine may be experiencing technical difficulties.'
  410. # Read error page file.
  411. try:
  412. with open('error.html', 'r', encoding='utf8', errors='ignore') as f:
  413. error_page = f.read()
  414. except:
  415. # Just send the code and reason as a backup.
  416. error_page = '${code} ${reason}'
  417. # Format error page template.
  418. signature = self.signature()
  419. error_page = string.Template(error_page).substitute(**locals())
  420. error_page_len = len(error_page)
  421. # Send formatted error page and stop.
  422. self.request.sendall(
  423. '{http_version} {code} {reason}\r\n'
  424. 'Content-Type: text/html\r\n'
  425. 'Content-Length: {error_page_len}\r\n'
  426. '\r\n'
  427. '{error_page}'
  428. .format(**locals()).encode('utf8', 'ignore')
  429. )
  430. self.request.close()
  431. def send_redirect_page(self, http_version, target, code=302):
  432. """Generate a redirect page."""
  433. # make redirect page
  434. redirectpage = '<html><head><title>Redirect</title><meta http-equiv="refresh" content="0;url='
  435. redirectpage += target
  436. redirectpage += '"></head><body><p>If you are not redirected, <a href="'
  437. redirectpage += target
  438. redirectpage += '">click here</a>.</p></body></html>'
  439. # send redirect page and stop
  440. 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'))
  441. self.request.close()
  442. def guess_and_send_redirect(self, http_version, guess_url):
  443. # Heuristically determine the static URL for some redirect scripts.
  444. parsed = urllib.parse.urlparse(guess_url)
  445. match = re.search('''(?:^|&)[^=]+=((?:https?(?:%3A|:)(?:%2F|/)|www[0-9]*\\.[^/%]+)?(?:%2F|/)[^&]+)''', parsed.query, re.I) # URL in query parameters
  446. if not match:
  447. full_path = parsed.path
  448. if parsed.query:
  449. full_path += '?' + parsed.query
  450. match = re.search('''((?:https?(?:%3A|:)(?:%2F|/)|www[0-9]*\\.[^/%]+)(?:(?:%2F|/).+|$))''', full_path, re.I) # URL in path or full query
  451. if match: # found URL
  452. # Decode and sanitize the URL.
  453. new_url = self.sanitize_redirect(urllib.parse.unquote_plus(match.group(1)))
  454. # Redirect client to the URL.
  455. _print('[r] [g]', new_url)
  456. self.send_redirect_page(http_version, new_url)
  457. return True
  458. return False
  459. def handle_settings(self, query):
  460. """Generate the settings page."""
  461. global DATE, DATE_TOLERANCE, GEOCITIES_FIX, QUICK_IMAGES, WAYBACK_API, CONTENT_TYPE_ENCODING, SILENT, SETTINGS_PAGE
  462. if query != '': # handle any parameters that may have been sent
  463. parsed = urllib.parse.parse_qs(query)
  464. if 'date' in parsed and 'dateTolerance' in parsed:
  465. if DATE != parsed['date'][0]:
  466. DATE = parsed['date'][0]
  467. self.shared_state.date_cache.clear()
  468. if self.shared_state.availability_cache:
  469. self.shared_state.availability_cache.clear()
  470. if DATE_TOLERANCE != parsed['dateTolerance'][0]:
  471. DATE_TOLERANCE = parsed['dateTolerance'][0]
  472. GEOCITIES_FIX = 'gcFix' in parsed
  473. QUICK_IMAGES = 'quickImages' in parsed
  474. CONTENT_TYPE_ENCODING = 'ctEncoding' in parsed
  475. # send the page and stop
  476. settingspage = 'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n'
  477. settingspage += '<html><head><title>WaybackProxy Settings</title></head><body><p><b>'
  478. settingspage += self.signature()
  479. settingspage += '</b></p><form method="get" action="/">'
  480. settingspage += '<p>Date to get pages from: <input type="text" name="date" size="8" value="'
  481. settingspage += str(DATE)
  482. settingspage += '"><p>Date tolerance: <input type="text" name="dateTolerance" size="8" value="'
  483. settingspage += str(DATE_TOLERANCE)
  484. settingspage += '"> days<br><input type="checkbox" name="gcFix"'
  485. if GEOCITIES_FIX:
  486. settingspage += ' checked'
  487. settingspage += '> Geocities Fix<br><input type="checkbox" name="quickImages"'
  488. if QUICK_IMAGES:
  489. settingspage += ' checked'
  490. settingspage += '> Quick images<br><input type="checkbox" name="ctEncoding"'
  491. if CONTENT_TYPE_ENCODING:
  492. settingspage += ' checked'
  493. settingspage += '> Encoding in Content-Type</p><p><input type="submit" value="Save"></p></form></body></html>'
  494. self.request.send(settingspage.encode('utf8', 'ignore'))
  495. self.request.close()
  496. def sanitize_redirect(self, url):
  497. """Sanitize an URL for client-side redirection."""
  498. if url[0] != '/' and '://' not in url:
  499. # Add protocol if the URL is absolute but missing a protocol.
  500. return 'http://' + url
  501. elif url[:8].lower() == 'https://':
  502. # Convert secure URLs to regular HTTP.
  503. return 'http://' + url[8:]
  504. else:
  505. # No changes required.
  506. return url
  507. def signature(self):
  508. """Return the server signature."""
  509. return 'WaybackProxy on {0}'.format(socket.gethostname())
  510. def wayback_to_datetime(self, date):
  511. """Convert a Wayback format date string to a datetime.datetime object."""
  512. date = str(date)
  513. fmt = '%Y%m%d%H%M%S'
  514. fmt_len = 14
  515. while fmt:
  516. try:
  517. return datetime.datetime.strptime(date[:fmt_len], fmt)
  518. except:
  519. fmt = fmt[:-2]
  520. fmt_len -= 2
  521. print_lock = threading.Lock()
  522. def _print(*args, **kwargs):
  523. """Logging function."""
  524. if SILENT:
  525. return
  526. with print_lock:
  527. print(*args, **kwargs, flush=True)
  528. def main():
  529. """Starts the server."""
  530. server = ThreadingTCPServer(('', LISTEN_PORT), Handler)
  531. _print('[-] Now listening on port', LISTEN_PORT)
  532. _print('[-] Date set to', DATE)
  533. try:
  534. server.serve_forever()
  535. except KeyboardInterrupt: # Ctrl+C to stop
  536. pass
  537. if __name__ == '__main__':
  538. main()