httputil.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2009 Facebook
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  6. # not use this file except in compliance with the License. You may obtain
  7. # a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14. # License for the specific language governing permissions and limitations
  15. # under the License.
  16. """HTTP utility code shared by clients and servers.
  17. This module also defines the `HTTPServerRequest` class which is exposed
  18. via `tornado.web.RequestHandler.request`.
  19. """
  20. from __future__ import absolute_import, division, print_function, with_statement
  21. import calendar
  22. import collections
  23. import copy
  24. import datetime
  25. import email.utils
  26. import numbers
  27. import re
  28. import time
  29. from tornado.escape import native_str, parse_qs_bytes, utf8
  30. from tornado.log import gen_log
  31. from tornado.util import ObjectDict
  32. try:
  33. import Cookie # py2
  34. except ImportError:
  35. import http.cookies as Cookie # py3
  36. try:
  37. from httplib import responses # py2
  38. except ImportError:
  39. from http.client import responses # py3
  40. # responses is unused in this file, but we re-export it to other files.
  41. # Reference it so pyflakes doesn't complain.
  42. responses
  43. try:
  44. from urllib import urlencode # py2
  45. except ImportError:
  46. from urllib.parse import urlencode # py3
  47. try:
  48. from ssl import SSLError
  49. except ImportError:
  50. # ssl is unavailable on app engine.
  51. class SSLError(Exception):
  52. pass
  53. # RFC 7230 section 3.5: a recipient MAY recognize a single LF as a line
  54. # terminator and ignore any preceding CR.
  55. _CRLF_RE = re.compile(r'\r?\n')
  56. class _NormalizedHeaderCache(dict):
  57. """Dynamic cached mapping of header names to Http-Header-Case.
  58. Implemented as a dict subclass so that cache hits are as fast as a
  59. normal dict lookup, without the overhead of a python function
  60. call.
  61. >>> normalized_headers = _NormalizedHeaderCache(10)
  62. >>> normalized_headers["coNtent-TYPE"]
  63. 'Content-Type'
  64. """
  65. def __init__(self, size):
  66. super(_NormalizedHeaderCache, self).__init__()
  67. self.size = size
  68. self.queue = collections.deque()
  69. def __missing__(self, key):
  70. normalized = "-".join([w.capitalize() for w in key.split("-")])
  71. self[key] = normalized
  72. self.queue.append(key)
  73. if len(self.queue) > self.size:
  74. # Limit the size of the cache. LRU would be better, but this
  75. # simpler approach should be fine. In Python 2.7+ we could
  76. # use OrderedDict (or in 3.2+, @functools.lru_cache).
  77. old_key = self.queue.popleft()
  78. del self[old_key]
  79. return normalized
  80. _normalized_headers = _NormalizedHeaderCache(1000)
  81. class HTTPHeaders(collections.abc.MutableMapping):
  82. """A dictionary that maintains ``Http-Header-Case`` for all keys.
  83. Supports multiple values per key via a pair of new methods,
  84. `add()` and `get_list()`. The regular dictionary interface
  85. returns a single value per key, with multiple values joined by a
  86. comma.
  87. >>> h = HTTPHeaders({"content-type": "text/html"})
  88. >>> list(h.keys())
  89. ['Content-Type']
  90. >>> h["Content-Type"]
  91. 'text/html'
  92. >>> h.add("Set-Cookie", "A=B")
  93. >>> h.add("Set-Cookie", "C=D")
  94. >>> h["set-cookie"]
  95. 'A=B,C=D'
  96. >>> h.get_list("set-cookie")
  97. ['A=B', 'C=D']
  98. >>> for (k,v) in sorted(h.get_all()):
  99. ... print('%s: %s' % (k,v))
  100. ...
  101. Content-Type: text/html
  102. Set-Cookie: A=B
  103. Set-Cookie: C=D
  104. """
  105. def __init__(self, *args, **kwargs):
  106. self._dict = {}
  107. self._as_list = {}
  108. self._last_key = None
  109. if (len(args) == 1 and len(kwargs) == 0 and
  110. isinstance(args[0], HTTPHeaders)):
  111. # Copy constructor
  112. for k, v in args[0].get_all():
  113. self.add(k, v)
  114. else:
  115. # Dict-style initialization
  116. self.update(*args, **kwargs)
  117. # new public methods
  118. def add(self, name, value):
  119. """Adds a new value for the given key."""
  120. norm_name = _normalized_headers[name]
  121. self._last_key = norm_name
  122. if norm_name in self:
  123. self._dict[norm_name] = (native_str(self[norm_name]) + ',' +
  124. native_str(value))
  125. self._as_list[norm_name].append(value)
  126. else:
  127. self[norm_name] = value
  128. def get_list(self, name):
  129. """Returns all values for the given header as a list."""
  130. norm_name = _normalized_headers[name]
  131. return self._as_list.get(norm_name, [])
  132. def get_all(self):
  133. """Returns an iterable of all (name, value) pairs.
  134. If a header has multiple values, multiple pairs will be
  135. returned with the same name.
  136. """
  137. for name, values in self._as_list.items():
  138. for value in values:
  139. yield (name, value)
  140. def parse_line(self, line):
  141. """Updates the dictionary with a single header line.
  142. >>> h = HTTPHeaders()
  143. >>> h.parse_line("Content-Type: text/html")
  144. >>> h.get('content-type')
  145. 'text/html'
  146. """
  147. if line[0].isspace():
  148. # continuation of a multi-line header
  149. new_part = ' ' + line.lstrip()
  150. self._as_list[self._last_key][-1] += new_part
  151. self._dict[self._last_key] += new_part
  152. else:
  153. name, value = line.split(":", 1)
  154. self.add(name, value.strip())
  155. @classmethod
  156. def parse(cls, headers):
  157. """Returns a dictionary from HTTP header text.
  158. >>> h = HTTPHeaders.parse("Content-Type: text/html\\r\\nContent-Length: 42\\r\\n")
  159. >>> sorted(h.items())
  160. [('Content-Length', '42'), ('Content-Type', 'text/html')]
  161. """
  162. h = cls()
  163. for line in _CRLF_RE.split(headers):
  164. if line:
  165. h.parse_line(line)
  166. return h
  167. # MutableMapping abstract method implementations.
  168. def __setitem__(self, name, value):
  169. norm_name = _normalized_headers[name]
  170. self._dict[norm_name] = value
  171. self._as_list[norm_name] = [value]
  172. def __getitem__(self, name):
  173. return self._dict[_normalized_headers[name]]
  174. def __delitem__(self, name):
  175. norm_name = _normalized_headers[name]
  176. del self._dict[norm_name]
  177. del self._as_list[norm_name]
  178. def __len__(self):
  179. return len(self._dict)
  180. def __iter__(self):
  181. return iter(self._dict)
  182. def copy(self):
  183. # defined in dict but not in MutableMapping.
  184. return HTTPHeaders(self)
  185. # Use our overridden copy method for the copy.copy module.
  186. # This makes shallow copies one level deeper, but preserves
  187. # the appearance that HTTPHeaders is a single container.
  188. __copy__ = copy
  189. class HTTPServerRequest(object):
  190. """A single HTTP request.
  191. All attributes are type `str` unless otherwise noted.
  192. .. attribute:: method
  193. HTTP request method, e.g. "GET" or "POST"
  194. .. attribute:: uri
  195. The requested uri.
  196. .. attribute:: path
  197. The path portion of `uri`
  198. .. attribute:: query
  199. The query portion of `uri`
  200. .. attribute:: version
  201. HTTP version specified in request, e.g. "HTTP/1.1"
  202. .. attribute:: headers
  203. `.HTTPHeaders` dictionary-like object for request headers. Acts like
  204. a case-insensitive dictionary with additional methods for repeated
  205. headers.
  206. .. attribute:: body
  207. Request body, if present, as a byte string.
  208. .. attribute:: remote_ip
  209. Client's IP address as a string. If ``HTTPServer.xheaders`` is set,
  210. will pass along the real IP address provided by a load balancer
  211. in the ``X-Real-Ip`` or ``X-Forwarded-For`` header.
  212. .. versionchanged:: 3.1
  213. The list format of ``X-Forwarded-For`` is now supported.
  214. .. attribute:: protocol
  215. The protocol used, either "http" or "https". If ``HTTPServer.xheaders``
  216. is set, will pass along the protocol used by a load balancer if
  217. reported via an ``X-Scheme`` header.
  218. .. attribute:: host
  219. The requested hostname, usually taken from the ``Host`` header.
  220. .. attribute:: arguments
  221. GET/POST arguments are available in the arguments property, which
  222. maps arguments names to lists of values (to support multiple values
  223. for individual names). Names are of type `str`, while arguments
  224. are byte strings. Note that this is different from
  225. `.RequestHandler.get_argument`, which returns argument values as
  226. unicode strings.
  227. .. attribute:: query_arguments
  228. Same format as ``arguments``, but contains only arguments extracted
  229. from the query string.
  230. .. versionadded:: 3.2
  231. .. attribute:: body_arguments
  232. Same format as ``arguments``, but contains only arguments extracted
  233. from the request body.
  234. .. versionadded:: 3.2
  235. .. attribute:: files
  236. File uploads are available in the files property, which maps file
  237. names to lists of `.HTTPFile`.
  238. .. attribute:: connection
  239. An HTTP request is attached to a single HTTP connection, which can
  240. be accessed through the "connection" attribute. Since connections
  241. are typically kept open in HTTP/1.1, multiple requests can be handled
  242. sequentially on a single connection.
  243. .. versionchanged:: 4.0
  244. Moved from ``tornado.httpserver.HTTPRequest``.
  245. """
  246. def __init__(self, method=None, uri=None, version="HTTP/1.0", headers=None,
  247. body=None, host=None, files=None, connection=None,
  248. start_line=None):
  249. if start_line is not None:
  250. method, uri, version = start_line
  251. self.method = method
  252. self.uri = uri
  253. self.version = version
  254. self.headers = headers or HTTPHeaders()
  255. self.body = body or b""
  256. # set remote IP and protocol
  257. context = getattr(connection, 'context', None)
  258. self.remote_ip = getattr(context, 'remote_ip', None)
  259. self.protocol = getattr(context, 'protocol', "http")
  260. self.host = host or self.headers.get("Host") or "127.0.0.1"
  261. self.files = files or {}
  262. self.connection = connection
  263. self._start_time = time.time()
  264. self._finish_time = None
  265. self.path, sep, self.query = uri.partition('?')
  266. self.arguments = parse_qs_bytes(self.query, keep_blank_values=True)
  267. self.query_arguments = copy.deepcopy(self.arguments)
  268. self.body_arguments = {}
  269. def supports_http_1_1(self):
  270. """Returns True if this request supports HTTP/1.1 semantics.
  271. .. deprecated:: 4.0
  272. Applications are less likely to need this information with the
  273. introduction of `.HTTPConnection`. If you still need it, access
  274. the ``version`` attribute directly.
  275. """
  276. return self.version == "HTTP/1.1"
  277. @property
  278. def cookies(self):
  279. """A dictionary of Cookie.Morsel objects."""
  280. if not hasattr(self, "_cookies"):
  281. self._cookies = Cookie.SimpleCookie()
  282. if "Cookie" in self.headers:
  283. try:
  284. self._cookies.load(
  285. native_str(self.headers["Cookie"]))
  286. except Exception:
  287. self._cookies = {}
  288. return self._cookies
  289. def write(self, chunk, callback=None):
  290. """Writes the given chunk to the response stream.
  291. .. deprecated:: 4.0
  292. Use ``request.connection`` and the `.HTTPConnection` methods
  293. to write the response.
  294. """
  295. assert isinstance(chunk, bytes)
  296. assert self.version.startswith("HTTP/1."), \
  297. "deprecated interface only supported in HTTP/1.x"
  298. self.connection.write(chunk, callback=callback)
  299. def finish(self):
  300. """Finishes this HTTP request on the open connection.
  301. .. deprecated:: 4.0
  302. Use ``request.connection`` and the `.HTTPConnection` methods
  303. to write the response.
  304. """
  305. self.connection.finish()
  306. self._finish_time = time.time()
  307. def full_url(self):
  308. """Reconstructs the full URL for this request."""
  309. return self.protocol + "://" + self.host + self.uri
  310. def request_time(self):
  311. """Returns the amount of time it took for this request to execute."""
  312. if self._finish_time is None:
  313. return time.time() - self._start_time
  314. else:
  315. return self._finish_time - self._start_time
  316. def get_ssl_certificate(self, binary_form=False):
  317. """Returns the client's SSL certificate, if any.
  318. To use client certificates, the HTTPServer's
  319. `ssl.SSLContext.verify_mode` field must be set, e.g.::
  320. ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
  321. ssl_ctx.load_cert_chain("foo.crt", "foo.key")
  322. ssl_ctx.load_verify_locations("cacerts.pem")
  323. ssl_ctx.verify_mode = ssl.CERT_REQUIRED
  324. server = HTTPServer(app, ssl_options=ssl_ctx)
  325. By default, the return value is a dictionary (or None, if no
  326. client certificate is present). If ``binary_form`` is true, a
  327. DER-encoded form of the certificate is returned instead. See
  328. SSLSocket.getpeercert() in the standard library for more
  329. details.
  330. http://docs.python.org/library/ssl.html#sslsocket-objects
  331. """
  332. try:
  333. return self.connection.stream.socket.getpeercert(
  334. binary_form=binary_form)
  335. except SSLError:
  336. return None
  337. def _parse_body(self):
  338. parse_body_arguments(
  339. self.headers.get("Content-Type", ""), self.body,
  340. self.body_arguments, self.files,
  341. self.headers)
  342. for k, v in self.body_arguments.items():
  343. self.arguments.setdefault(k, []).extend(v)
  344. def __repr__(self):
  345. attrs = ("protocol", "host", "method", "uri", "version", "remote_ip")
  346. args = ", ".join(["%s=%r" % (n, getattr(self, n)) for n in attrs])
  347. return "%s(%s, headers=%s)" % (
  348. self.__class__.__name__, args, dict(self.headers))
  349. class HTTPInputError(Exception):
  350. """Exception class for malformed HTTP requests or responses
  351. from remote sources.
  352. .. versionadded:: 4.0
  353. """
  354. pass
  355. class HTTPOutputError(Exception):
  356. """Exception class for errors in HTTP output.
  357. .. versionadded:: 4.0
  358. """
  359. pass
  360. class HTTPServerConnectionDelegate(object):
  361. """Implement this interface to handle requests from `.HTTPServer`.
  362. .. versionadded:: 4.0
  363. """
  364. def start_request(self, server_conn, request_conn):
  365. """This method is called by the server when a new request has started.
  366. :arg server_conn: is an opaque object representing the long-lived
  367. (e.g. tcp-level) connection.
  368. :arg request_conn: is a `.HTTPConnection` object for a single
  369. request/response exchange.
  370. This method should return a `.HTTPMessageDelegate`.
  371. """
  372. raise NotImplementedError()
  373. def on_close(self, server_conn):
  374. """This method is called when a connection has been closed.
  375. :arg server_conn: is a server connection that has previously been
  376. passed to ``start_request``.
  377. """
  378. pass
  379. class HTTPMessageDelegate(object):
  380. """Implement this interface to handle an HTTP request or response.
  381. .. versionadded:: 4.0
  382. """
  383. def headers_received(self, start_line, headers):
  384. """Called when the HTTP headers have been received and parsed.
  385. :arg start_line: a `.RequestStartLine` or `.ResponseStartLine`
  386. depending on whether this is a client or server message.
  387. :arg headers: a `.HTTPHeaders` instance.
  388. Some `.HTTPConnection` methods can only be called during
  389. ``headers_received``.
  390. May return a `.Future`; if it does the body will not be read
  391. until it is done.
  392. """
  393. pass
  394. def data_received(self, chunk):
  395. """Called when a chunk of data has been received.
  396. May return a `.Future` for flow control.
  397. """
  398. pass
  399. def finish(self):
  400. """Called after the last chunk of data has been received."""
  401. pass
  402. def on_connection_close(self):
  403. """Called if the connection is closed without finishing the request.
  404. If ``headers_received`` is called, either ``finish`` or
  405. ``on_connection_close`` will be called, but not both.
  406. """
  407. pass
  408. class HTTPConnection(object):
  409. """Applications use this interface to write their responses.
  410. .. versionadded:: 4.0
  411. """
  412. def write_headers(self, start_line, headers, chunk=None, callback=None):
  413. """Write an HTTP header block.
  414. :arg start_line: a `.RequestStartLine` or `.ResponseStartLine`.
  415. :arg headers: a `.HTTPHeaders` instance.
  416. :arg chunk: the first (optional) chunk of data. This is an optimization
  417. so that small responses can be written in the same call as their
  418. headers.
  419. :arg callback: a callback to be run when the write is complete.
  420. The ``version`` field of ``start_line`` is ignored.
  421. Returns a `.Future` if no callback is given.
  422. """
  423. raise NotImplementedError()
  424. def write(self, chunk, callback=None):
  425. """Writes a chunk of body data.
  426. The callback will be run when the write is complete. If no callback
  427. is given, returns a Future.
  428. """
  429. raise NotImplementedError()
  430. def finish(self):
  431. """Indicates that the last body data has been written.
  432. """
  433. raise NotImplementedError()
  434. def url_concat(url, args):
  435. """Concatenate url and arguments regardless of whether
  436. url has existing query parameters.
  437. ``args`` may be either a dictionary or a list of key-value pairs
  438. (the latter allows for multiple values with the same key.
  439. >>> url_concat("http://example.com/foo", dict(c="d"))
  440. 'http://example.com/foo?c=d'
  441. >>> url_concat("http://example.com/foo?a=b", dict(c="d"))
  442. 'http://example.com/foo?a=b&c=d'
  443. >>> url_concat("http://example.com/foo?a=b", [("c", "d"), ("c", "d2")])
  444. 'http://example.com/foo?a=b&c=d&c=d2'
  445. """
  446. if not args:
  447. return url
  448. if url[-1] not in ('?', '&'):
  449. url += '&' if ('?' in url) else '?'
  450. return url + urlencode(args)
  451. class HTTPFile(ObjectDict):
  452. """Represents a file uploaded via a form.
  453. For backwards compatibility, its instance attributes are also
  454. accessible as dictionary keys.
  455. * ``filename``
  456. * ``body``
  457. * ``content_type``
  458. """
  459. pass
  460. def _parse_request_range(range_header):
  461. """Parses a Range header.
  462. Returns either ``None`` or tuple ``(start, end)``.
  463. Note that while the HTTP headers use inclusive byte positions,
  464. this method returns indexes suitable for use in slices.
  465. >>> start, end = _parse_request_range("bytes=1-2")
  466. >>> start, end
  467. (1, 3)
  468. >>> [0, 1, 2, 3, 4][start:end]
  469. [1, 2]
  470. >>> _parse_request_range("bytes=6-")
  471. (6, None)
  472. >>> _parse_request_range("bytes=-6")
  473. (-6, None)
  474. >>> _parse_request_range("bytes=-0")
  475. (None, 0)
  476. >>> _parse_request_range("bytes=")
  477. (None, None)
  478. >>> _parse_request_range("foo=42")
  479. >>> _parse_request_range("bytes=1-2,6-10")
  480. Note: only supports one range (ex, ``bytes=1-2,6-10`` is not allowed).
  481. See [0] for the details of the range header.
  482. [0]: http://greenbytes.de/tech/webdav/draft-ietf-httpbis-p5-range-latest.html#byte.ranges
  483. """
  484. unit, _, value = range_header.partition("=")
  485. unit, value = unit.strip(), value.strip()
  486. if unit != "bytes":
  487. return None
  488. start_b, _, end_b = value.partition("-")
  489. try:
  490. start = _int_or_none(start_b)
  491. end = _int_or_none(end_b)
  492. except ValueError:
  493. return None
  494. if end is not None:
  495. if start is None:
  496. if end != 0:
  497. start = -end
  498. end = None
  499. else:
  500. end += 1
  501. return (start, end)
  502. def _get_content_range(start, end, total):
  503. """Returns a suitable Content-Range header:
  504. >>> print(_get_content_range(None, 1, 4))
  505. bytes 0-0/4
  506. >>> print(_get_content_range(1, 3, 4))
  507. bytes 1-2/4
  508. >>> print(_get_content_range(None, None, 4))
  509. bytes 0-3/4
  510. """
  511. start = start or 0
  512. end = (end or total) - 1
  513. return "bytes %s-%s/%s" % (start, end, total)
  514. def _int_or_none(val):
  515. val = val.strip()
  516. if val == "":
  517. return None
  518. return int(val)
  519. def parse_body_arguments(content_type, body, arguments, files, headers=None):
  520. """Parses a form request body.
  521. Supports ``application/x-www-form-urlencoded`` and
  522. ``multipart/form-data``. The ``content_type`` parameter should be
  523. a string and ``body`` should be a byte string. The ``arguments``
  524. and ``files`` parameters are dictionaries that will be updated
  525. with the parsed contents.
  526. """
  527. if headers and 'Content-Encoding' in headers:
  528. gen_log.warning("Unsupported Content-Encoding: %s",
  529. headers['Content-Encoding'])
  530. return
  531. if content_type.startswith("application/x-www-form-urlencoded"):
  532. try:
  533. uri_arguments = parse_qs_bytes(native_str(body), keep_blank_values=True)
  534. except Exception as e:
  535. gen_log.warning('Invalid x-www-form-urlencoded body: %s', e)
  536. uri_arguments = {}
  537. for name, values in uri_arguments.items():
  538. if values:
  539. arguments.setdefault(name, []).extend(values)
  540. elif content_type.startswith("multipart/form-data"):
  541. try:
  542. fields = content_type.split(";")
  543. for field in fields:
  544. k, sep, v = field.strip().partition("=")
  545. if k == "boundary" and v:
  546. parse_multipart_form_data(utf8(v), body, arguments, files)
  547. break
  548. else:
  549. raise ValueError("multipart boundary not found")
  550. except Exception as e:
  551. gen_log.warning("Invalid multipart/form-data: %s", e)
  552. def parse_multipart_form_data(boundary, data, arguments, files):
  553. """Parses a ``multipart/form-data`` body.
  554. The ``boundary`` and ``data`` parameters are both byte strings.
  555. The dictionaries given in the arguments and files parameters
  556. will be updated with the contents of the body.
  557. """
  558. # The standard allows for the boundary to be quoted in the header,
  559. # although it's rare (it happens at least for google app engine
  560. # xmpp). I think we're also supposed to handle backslash-escapes
  561. # here but I'll save that until we see a client that uses them
  562. # in the wild.
  563. if boundary.startswith(b'"') and boundary.endswith(b'"'):
  564. boundary = boundary[1:-1]
  565. final_boundary_index = data.rfind(b"--" + boundary + b"--")
  566. if final_boundary_index == -1:
  567. gen_log.warning("Invalid multipart/form-data: no final boundary")
  568. return
  569. parts = data[:final_boundary_index].split(b"--" + boundary + b"\r\n")
  570. for part in parts:
  571. if not part:
  572. continue
  573. eoh = part.find(b"\r\n\r\n")
  574. if eoh == -1:
  575. gen_log.warning("multipart/form-data missing headers")
  576. continue
  577. headers = HTTPHeaders.parse(part[:eoh].decode("utf-8"))
  578. disp_header = headers.get("Content-Disposition", "")
  579. disposition, disp_params = _parse_header(disp_header)
  580. if disposition != "form-data" or not part.endswith(b"\r\n"):
  581. gen_log.warning("Invalid multipart/form-data")
  582. continue
  583. value = part[eoh + 4:-2]
  584. if not disp_params.get("name"):
  585. gen_log.warning("multipart/form-data value missing name")
  586. continue
  587. name = disp_params["name"]
  588. if disp_params.get("filename"):
  589. ctype = headers.get("Content-Type", "application/unknown")
  590. files.setdefault(name, []).append(HTTPFile(
  591. filename=disp_params["filename"], body=value,
  592. content_type=ctype))
  593. else:
  594. arguments.setdefault(name, []).append(value)
  595. def format_timestamp(ts):
  596. """Formats a timestamp in the format used by HTTP.
  597. The argument may be a numeric timestamp as returned by `time.time`,
  598. a time tuple as returned by `time.gmtime`, or a `datetime.datetime`
  599. object.
  600. >>> format_timestamp(1359312200)
  601. 'Sun, 27 Jan 2013 18:43:20 GMT'
  602. """
  603. if isinstance(ts, numbers.Real):
  604. pass
  605. elif isinstance(ts, (tuple, time.struct_time)):
  606. ts = calendar.timegm(ts)
  607. elif isinstance(ts, datetime.datetime):
  608. ts = calendar.timegm(ts.utctimetuple())
  609. else:
  610. raise TypeError("unknown timestamp type: %r" % ts)
  611. return email.utils.formatdate(ts, usegmt=True)
  612. RequestStartLine = collections.namedtuple(
  613. 'RequestStartLine', ['method', 'path', 'version'])
  614. def parse_request_start_line(line):
  615. """Returns a (method, path, version) tuple for an HTTP 1.x request line.
  616. The response is a `collections.namedtuple`.
  617. >>> parse_request_start_line("GET /foo HTTP/1.1")
  618. RequestStartLine(method='GET', path='/foo', version='HTTP/1.1')
  619. """
  620. try:
  621. method, path, version = line.split(" ")
  622. except ValueError:
  623. raise HTTPInputError("Malformed HTTP request line")
  624. if not re.match(r"^HTTP/1\.[0-9]$", version):
  625. raise HTTPInputError(
  626. "Malformed HTTP version in HTTP Request-Line: %r" % version)
  627. return RequestStartLine(method, path, version)
  628. ResponseStartLine = collections.namedtuple(
  629. 'ResponseStartLine', ['version', 'code', 'reason'])
  630. def parse_response_start_line(line):
  631. """Returns a (version, code, reason) tuple for an HTTP 1.x response line.
  632. The response is a `collections.namedtuple`.
  633. >>> parse_response_start_line("HTTP/1.1 200 OK")
  634. ResponseStartLine(version='HTTP/1.1', code=200, reason='OK')
  635. """
  636. line = native_str(line)
  637. match = re.match("(HTTP/1.[0-9]) ([0-9]+) ([^\r]*)", line)
  638. if not match:
  639. raise HTTPInputError("Error parsing response start line")
  640. return ResponseStartLine(match.group(1), int(match.group(2)),
  641. match.group(3))
  642. # _parseparam and _parse_header are copied and modified from python2.7's cgi.py
  643. # The original 2.7 version of this code did not correctly support some
  644. # combinations of semicolons and double quotes.
  645. # It has also been modified to support valueless parameters as seen in
  646. # websocket extension negotiations.
  647. def _parseparam(s):
  648. while s[:1] == ';':
  649. s = s[1:]
  650. end = s.find(';')
  651. while end > 0 and (s.count('"', 0, end) - s.count('\\"', 0, end)) % 2:
  652. end = s.find(';', end + 1)
  653. if end < 0:
  654. end = len(s)
  655. f = s[:end]
  656. yield f.strip()
  657. s = s[end:]
  658. def _parse_header(line):
  659. """Parse a Content-type like header.
  660. Return the main content-type and a dictionary of options.
  661. """
  662. parts = _parseparam(';' + line)
  663. key = next(parts)
  664. pdict = {}
  665. for p in parts:
  666. i = p.find('=')
  667. if i >= 0:
  668. name = p[:i].strip().lower()
  669. value = p[i + 1:].strip()
  670. if len(value) >= 2 and value[0] == value[-1] == '"':
  671. value = value[1:-1]
  672. value = value.replace('\\\\', '\\').replace('\\"', '"')
  673. pdict[name] = value
  674. else:
  675. pdict[p] = None
  676. return key, pdict
  677. def _encode_header(key, pdict):
  678. """Inverse of _parse_header.
  679. >>> _encode_header('permessage-deflate',
  680. ... {'client_max_window_bits': 15, 'client_no_context_takeover': None})
  681. 'permessage-deflate; client_max_window_bits=15; client_no_context_takeover'
  682. """
  683. if not pdict:
  684. return key
  685. out = [key]
  686. # Sort the parameters just to make it easy to test.
  687. for k, v in sorted(pdict.items()):
  688. if v is None:
  689. out.append(k)
  690. else:
  691. # TODO: quote if necessary.
  692. out.append('%s=%s' % (k, v))
  693. return '; '.join(out)
  694. def doctests():
  695. import doctest
  696. return doctest.DocTestSuite()
  697. def split_host_and_port(netloc):
  698. """Returns ``(host, port)`` tuple from ``netloc``.
  699. Returned ``port`` will be ``None`` if not present.
  700. .. versionadded:: 4.1
  701. """
  702. match = re.match(r'^(.+):(\d+)$', netloc)
  703. if match:
  704. host = match.group(1)
  705. port = int(match.group(2))
  706. else:
  707. host = netloc
  708. port = None
  709. return (host, port)