waybackproxy.py 24 KB

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