| 1 |
"""Utility functions for HTTP header value parsing and construction. |
| 2 |
|
| 3 |
Copyright 1997-1998, Gisle Aas |
| 4 |
Copyright 2002-2006, John J. Lee |
| 5 |
|
| 6 |
This code is free software; you can redistribute it and/or modify it |
| 7 |
under the terms of the BSD or ZPL 2.1 licenses (see the file |
| 8 |
LICENSE included with the distribution). |
| 9 |
|
| 10 |
""" |
| 11 |
|
| 12 |
from __future__ import absolute_import |
| 13 |
|
| 14 |
import os |
| 15 |
import re |
| 16 |
|
| 17 |
from . import _rfc3986 |
| 18 |
from ._util import http2time |
| 19 |
from .polyglot import is_string |
| 20 |
|
| 21 |
|
| 22 |
def is_html_file_extension(url, allow_xhtml): |
| 23 |
if url is None: |
| 24 |
return False |
| 25 |
ext = os.path.splitext(_rfc3986.urlsplit(url)[2])[1] |
| 26 |
html_exts = [".htm", ".html"] |
| 27 |
if allow_xhtml: |
| 28 |
html_exts += [".xhtml"] |
| 29 |
return ext in html_exts |
| 30 |
|
| 31 |
|
| 32 |
def is_html(ct_headers, url=None, allow_xhtml=False): |
| 33 |
""" |
| 34 |
ct_headers: Sequence of Content-Type headers |
| 35 |
url: Response URL |
| 36 |
|
| 37 |
""" |
| 38 |
if not ct_headers: |
| 39 |
return is_html_file_extension(url, allow_xhtml) |
| 40 |
headers = split_header_words(ct_headers) |
| 41 |
if len(headers) < 1: |
| 42 |
return is_html_file_extension(url, allow_xhtml) |
| 43 |
first_header = headers[0] |
| 44 |
first_parameter = first_header[0] |
| 45 |
ct = first_parameter[0] |
| 46 |
html_types = ["text/html"] |
| 47 |
if allow_xhtml: |
| 48 |
html_types += [ |
| 49 |
"text/xhtml", |
| 50 |
"text/xml", |
| 51 |
"application/xml", |
| 52 |
"application/xhtml+xml", |
| 53 |
] |
| 54 |
return ct in html_types |
| 55 |
|
| 56 |
|
| 57 |
def unmatched(match): |
| 58 |
"""Return unmatched part of re.Match object.""" |
| 59 |
start, end = match.span(0) |
| 60 |
return match.string[:start] + match.string[end:] |
| 61 |
|
| 62 |
|
| 63 |
token_re = re.compile(r"^\s*([^=\s;,]+)") |
| 64 |
quoted_value_re = re.compile(r"^\s*=\s*\"([^\"\\]*(?:\\.[^\"\\]*)*)\"") |
| 65 |
value_re = re.compile(r"^\s*=\s*([^\s;,]*)") |
| 66 |
escape_re = re.compile(r"\\(.)") |
| 67 |
|
| 68 |
|
| 69 |
def split_header_words(header_values): |
| 70 |
r"""Parse header values into a list of lists containing key,value pairs. |
| 71 |
|
| 72 |
The function knows how to deal with ",", ";" and "=" as well as quoted |
| 73 |
values after "=". A list of space separated tokens are parsed as if they |
| 74 |
were separated by ";". |
| 75 |
|
| 76 |
If the header_values passed as argument contains multiple values, then they |
| 77 |
are treated as if they were a single value separated by comma ",". |
| 78 |
|
| 79 |
This means that this function is useful for parsing header fields that |
| 80 |
follow this syntax (BNF as from the HTTP/1.1 specification, but we relax |
| 81 |
the requirement for tokens). |
| 82 |
|
| 83 |
headers = #header |
| 84 |
header = (token | parameter) *( [";"] (token | parameter)) |
| 85 |
|
| 86 |
token = 1*<any CHAR except CTLs or separators> |
| 87 |
separators = "(" | ")" | "<" | ">" | "@" |
| 88 |
| "," | ";" | ":" | "\" | <"> |
| 89 |
| "/" | "[" | "]" | "?" | "=" |
| 90 |
| "{" | "}" | SP | HT |
| 91 |
|
| 92 |
quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) |
| 93 |
qdtext = <any TEXT except <">> |
| 94 |
quoted-pair = "\" CHAR |
| 95 |
|
| 96 |
parameter = attribute "=" value |
| 97 |
attribute = token |
| 98 |
value = token | quoted-string |
| 99 |
|
| 100 |
Each header is represented by a list of key/value pairs. The value for a |
| 101 |
simple token (not part of a parameter) is None. Syntactically incorrect |
| 102 |
headers will not necessarily be parsed as you would want. |
| 103 |
|
| 104 |
This is easier to describe with some examples: |
| 105 |
|
| 106 |
>>> split_header_words(['foo="bar"; port="80,81"; discard, bar=baz']) |
| 107 |
[[('foo', 'bar'), ('port', '80,81'), ('discard', None)], [('bar', 'baz')]] |
| 108 |
>>> split_header_words(['text/html; charset="iso-8859-1"']) |
| 109 |
[[('text/html', None), ('charset', 'iso-8859-1')]] |
| 110 |
>>> split_header_words([r'Basic realm="\"foo\bar\""']) |
| 111 |
[[('Basic', None), ('realm', '"foobar"')]] |
| 112 |
|
| 113 |
""" |
| 114 |
assert not is_string(header_values) |
| 115 |
result = [] |
| 116 |
for text in header_values: |
| 117 |
orig_text = text |
| 118 |
pairs = [] |
| 119 |
while text: |
| 120 |
m = token_re.search(text) |
| 121 |
if m: |
| 122 |
text = unmatched(m) |
| 123 |
name = m.group(1) |
| 124 |
m = quoted_value_re.search(text) |
| 125 |
if m: |
| 126 |
text = unmatched(m) |
| 127 |
value = m.group(1) |
| 128 |
value = escape_re.sub(r"\1", value) |
| 129 |
else: |
| 130 |
m = value_re.search(text) |
| 131 |
if m: |
| 132 |
text = unmatched(m) |
| 133 |
value = m.group(1) |
| 134 |
value = value.rstrip() |
| 135 |
else: |
| 136 |
|
| 137 |
value = None |
| 138 |
pairs.append((name, value)) |
| 139 |
elif text.lstrip().startswith(","): |
| 140 |
|
| 141 |
text = text.lstrip()[1:] |
| 142 |
if pairs: |
| 143 |
result.append(pairs) |
| 144 |
pairs = [] |
| 145 |
else: |
| 146 |
|
| 147 |
non_junk, nr_junk_chars = re.subn(r"^[=\s;]*", "", text) |
| 148 |
assert nr_junk_chars > 0, ( |
| 149 |
"split_header_words bug: '%s', '%s', %s" % |
| 150 |
(orig_text, text, pairs)) |
| 151 |
text = non_junk |
| 152 |
if pairs: |
| 153 |
result.append(pairs) |
| 154 |
return result |
| 155 |
|
| 156 |
|
| 157 |
join_escape_re = re.compile(r"([\"\\])") |
| 158 |
|
| 159 |
|
| 160 |
def join_header_words(lists): |
| 161 |
"""Do the inverse of the conversion done by split_header_words. |
| 162 |
|
| 163 |
Takes a list of lists of (key, value) pairs and produces a single header |
| 164 |
value. Attribute values are quoted if needed. |
| 165 |
|
| 166 |
>>> join_header_words([[("text/plain", None), ("charset", "iso-8859/1")]]) |
| 167 |
'text/plain; charset="iso-8859/1"' |
| 168 |
>>> join_header_words([[(\ |
| 169 |
"text/plain", None)], [("charset", "iso-8859/1")]]) |
| 170 |
'text/plain, charset="iso-8859/1"' |
| 171 |
|
| 172 |
""" |
| 173 |
headers = [] |
| 174 |
for pairs in lists: |
| 175 |
attr = [] |
| 176 |
for k, v in pairs: |
| 177 |
if v is not None: |
| 178 |
if not re.search(r"^\w+$", v): |
| 179 |
v = join_escape_re.sub(r"\\\1", v) |
| 180 |
v = '"%s"' % v |
| 181 |
if k is None: |
| 182 |
k = v |
| 183 |
else: |
| 184 |
k = "%s=%s" % (k, v) |
| 185 |
attr.append(k) |
| 186 |
if attr: |
| 187 |
headers.append("; ".join(attr)) |
| 188 |
return ", ".join(headers) |
| 189 |
|
| 190 |
|
| 191 |
def strip_quotes(text): |
| 192 |
if text.startswith('"'): |
| 193 |
text = text[1:] |
| 194 |
if text.endswith('"'): |
| 195 |
text = text[:-1] |
| 196 |
return text |
| 197 |
|
| 198 |
|
| 199 |
def parse_ns_headers(ns_headers): |
| 200 |
"""Ad-hoc parser for Netscape protocol cookie-attributes. |
| 201 |
|
| 202 |
The old Netscape cookie format for Set-Cookie can for instance contain |
| 203 |
an unquoted "," in the expires field, so we have to use this ad-hoc |
| 204 |
parser instead of split_header_words. |
| 205 |
|
| 206 |
XXX This may not make the best possible effort to parse all the crap |
| 207 |
that Netscape Cookie headers contain. Ronald Tschalar's HTTPClient |
| 208 |
parser is probably better, so could do worse than following that if |
| 209 |
this ever gives any trouble. |
| 210 |
|
| 211 |
Currently, this is also used for parsing RFC 2109 cookies. |
| 212 |
|
| 213 |
""" |
| 214 |
known_attrs = ( |
| 215 |
"expires", |
| 216 |
"domain", |
| 217 |
"path", |
| 218 |
"secure", |
| 219 |
|
| 220 |
"version", |
| 221 |
"port", |
| 222 |
"max-age") |
| 223 |
|
| 224 |
result = [] |
| 225 |
for ns_header in ns_headers: |
| 226 |
pairs = [] |
| 227 |
version_set = False |
| 228 |
params = re.split(r";\s*", ns_header) |
| 229 |
for ii in range(len(params)): |
| 230 |
param = params[ii] |
| 231 |
param = param.rstrip() |
| 232 |
if param == "": |
| 233 |
continue |
| 234 |
if "=" not in param: |
| 235 |
k, v = param, None |
| 236 |
else: |
| 237 |
k, v = re.split(r"\s*=\s*", param, 1) |
| 238 |
k = k.lstrip() |
| 239 |
if ii != 0: |
| 240 |
lc = k.lower() |
| 241 |
if lc in known_attrs: |
| 242 |
k = lc |
| 243 |
if k == "version": |
| 244 |
|
| 245 |
v = strip_quotes(v) |
| 246 |
version_set = True |
| 247 |
if k == "expires": |
| 248 |
|
| 249 |
v = http2time(strip_quotes(v)) |
| 250 |
pairs.append((k, v)) |
| 251 |
|
| 252 |
if pairs: |
| 253 |
if not version_set: |
| 254 |
pairs.append(("version", "0")) |
| 255 |
result.append(pairs) |
| 256 |
|
| 257 |
return result |
| 258 |
|
| 259 |
|
| 260 |
uppercase_headers = {'WWW', 'TE'} |
| 261 |
|
| 262 |
|
| 263 |
def normalize_header_name(name): |
| 264 |
parts = [x.capitalize() for x in name.split('-')] |
| 265 |
q = parts[0].upper() |
| 266 |
if q in uppercase_headers: |
| 267 |
parts[0] = q |
| 268 |
if len(parts) == 3 and parts[1] == 'Websocket': |
| 269 |
parts[1] = 'WebSocket' |
| 270 |
return '-'.join(parts) |
| 271 |
|
| 272 |
|
| 273 |
def _test(): |
| 274 |
import doctest |
| 275 |
from . import _headersutil |
| 276 |
return doctest.testmod(_headersutil) |
| 277 |
|
| 278 |
|
| 279 |
if __name__ == "__main__": |
| 280 |
_test() |