tor-browser

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

header-helpers.py (2008B)


      1 import hashlib
      2 import json
      3 
      4 RETRIEVAL_PATH = '/storage-access-api/resources/retrieve-storage-access-headers.py'
      5 
      6 def get_stashable_headers(headers):
      7  def bytes_to_strings(d):
      8    # Recursively convert bytes to strings in `d`.
      9    if isinstance(d, (tuple,list,set)):
     10      return [bytes_to_strings(x) for x in d]
     11    elif isinstance(d, bytes):
     12      return d.decode()
     13    elif isinstance(d, dict):
     14      return {bytes_to_strings(k): bytes_to_strings(v) for (k, v) in d.items()}
     15    return d
     16  return json.dumps(bytes_to_strings(headers))
     17 
     18 # Makes a string representation of the hash generated for the given key.
     19 def make_stash_key(key, request_params):
     20  # Redirected requests stash their headers at a different key.
     21  key += b'redirected' if b'redirected' in request_params else b''
     22  return hashlib.md5(key).hexdigest()
     23 
     24 # Sets the response to redirect to the location passed by the request if its
     25 # parameters contain a `redirect-location` or a `once-active-redirect-location`
     26 # with an active `storage_access_status`.
     27 def maybe_set_redirect(request_params, response, storage_access_status):
     28  if storage_access_status == b'active':
     29    location = request_params.first(b'once-active-redirect-location', '')
     30  else:
     31    location = request_params.first(b'redirect-location', '')
     32 
     33  if location:
     34    response.status = 302
     35    response.headers.set(b'Location', location)
     36 
     37 # Returns an HTML body with an embedded responder if one is included in
     38 # `request_params`, otherwise returns an empty byte-string.
     39 def make_response_body(request_params):
     40  script = request_params.first(b'script', None)
     41  if script is None:
     42    return b''
     43  return b"""
     44    <!DOCTYPE html>
     45  <meta charset="utf-8">
     46  <title>Subframe with script</title>
     47  <script src="/resources/testharness.js"></script>
     48  <script src="/resources/testdriver.js"></script>
     49  <script src="/resources/testdriver-vendor.js"></script>
     50  <script>
     51    var should_ack_load = false;
     52  </script>
     53 
     54  <body>
     55  <script src="%s"></script>
     56  </body>
     57 
     58  """ % (script)