tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

record-headers.py (2168B)


      1 import os
      2 import uuid
      3 import hashlib
      4 import time
      5 import json
      6 
      7 
      8 def bytes_to_strings(d):
      9  # Recursively convert bytes to strings in `d`.
     10  if not isinstance(d, dict):
     11    if isinstance(d, (tuple,list,set)):
     12      v = [bytes_to_strings(x) for x in d]
     13      return v
     14    else:
     15      if isinstance(d, bytes):
     16        d = d.decode()
     17      return d
     18 
     19  result = {}
     20  for k,v in d.items():
     21    if isinstance(k, bytes):
     22      k = k.decode()
     23    if isinstance(v, dict):
     24      v = bytes_to_strings(v)
     25    elif isinstance(v, (tuple,list,set)):
     26      v = [bytes_to_strings(x) for x in v]
     27    elif isinstance(v, bytes):
     28      v = v.decode()
     29    result[k] = v
     30  return result
     31 
     32 
     33 def main(request, response):
     34  # This condition avoids false positives from CORS preflight checks, where the
     35  # request under test may be followed immediately by a request to the same URL
     36  # using a different HTTP method.
     37  if b'requireOPTIONS' in request.GET and request.method != b'OPTIONS':
     38      return
     39 
     40  if b'key' in request.GET:
     41    key = request.GET[b'key']
     42  elif b'key' in request.POST:
     43    key = request.POST[b'key']
     44 
     45  ## Convert the key from String to UUID valid String ##
     46  testId = hashlib.md5(key).hexdigest()
     47 
     48  ## Handle the header retrieval request ##
     49  if b'retrieve' in request.GET:
     50    recorded_headers = request.server.stash.take(testId)
     51 
     52    if recorded_headers is None:
     53      return (204, [], b'')
     54 
     55    return (200, [], recorded_headers)
     56 
     57  ## Record incoming fetch metadata header value
     58  else:
     59    try:
     60      request.server.stash.put(testId, json.dumps(bytes_to_strings(request.headers)))
     61    except KeyError:
     62      ## The header is already recorded or it doesn't exist
     63      pass
     64 
     65    ## Prevent the browser from caching returned responses and allow CORS ##
     66    response.headers.set(b"Access-Control-Allow-Origin", b"*")
     67    response.headers.set(b"Cache-Control", b"no-cache, no-store, must-revalidate")
     68    response.headers.set(b"Pragma", b"no-cache")
     69    response.headers.set(b"Expires", b"0")
     70    if b"mime" in request.GET:
     71        response.headers.set(b"Content-Type", request.GET.first(b"mime"))
     72 
     73    return request.GET.first(b"body", request.POST.first(b"body", b""))