2015-09-15 17:12:15 +00:00
|
|
|
from __future__ import absolute_import, print_function, division
|
|
|
|
import time
|
|
|
|
import sys
|
|
|
|
import re
|
|
|
|
|
2016-05-31 23:12:10 +00:00
|
|
|
from netlib.http import request
|
|
|
|
from netlib.http import response
|
|
|
|
from netlib.http import headers
|
|
|
|
from netlib.http import url
|
|
|
|
from netlib import utils
|
|
|
|
from netlib import exceptions
|
2015-09-15 17:12:15 +00:00
|
|
|
|
|
|
|
|
2016-05-31 06:54:42 +00:00
|
|
|
def get_header_tokens(headers, key):
|
|
|
|
"""
|
|
|
|
Retrieve all tokens for a header key. A number of different headers
|
|
|
|
follow a pattern where each header line can containe comma-separated
|
|
|
|
tokens, and headers can be set multiple times.
|
|
|
|
"""
|
|
|
|
if key not in headers:
|
|
|
|
return []
|
|
|
|
tokens = headers[key].split(",")
|
|
|
|
return [token.strip() for token in tokens]
|
|
|
|
|
|
|
|
|
2015-09-15 17:12:15 +00:00
|
|
|
def read_request(rfile, body_size_limit=None):
|
|
|
|
request = read_request_head(rfile)
|
2015-09-15 22:04:23 +00:00
|
|
|
expected_body_size = expected_http_body_size(request)
|
2015-09-25 22:39:04 +00:00
|
|
|
request.data.content = b"".join(read_body(rfile, expected_body_size, limit=body_size_limit))
|
2015-09-15 17:12:15 +00:00
|
|
|
request.timestamp_end = time.time()
|
|
|
|
return request
|
|
|
|
|
|
|
|
|
|
|
|
def read_request_head(rfile):
|
|
|
|
"""
|
|
|
|
Parse an HTTP request head (request line + headers) from an input stream
|
|
|
|
|
|
|
|
Args:
|
|
|
|
rfile: The input stream
|
|
|
|
|
|
|
|
Returns:
|
2015-09-15 22:04:23 +00:00
|
|
|
The HTTP request object (without body)
|
2015-09-15 17:12:15 +00:00
|
|
|
|
|
|
|
Raises:
|
2016-05-31 23:12:10 +00:00
|
|
|
exceptions.HttpReadDisconnect: No bytes can be read from rfile.
|
|
|
|
exceptions.HttpSyntaxException: The input is malformed HTTP.
|
|
|
|
exceptions.HttpException: Any other error occured.
|
2015-09-15 17:12:15 +00:00
|
|
|
"""
|
|
|
|
timestamp_start = time.time()
|
|
|
|
if hasattr(rfile, "reset_timestamps"):
|
|
|
|
rfile.reset_timestamps()
|
|
|
|
|
|
|
|
form, method, scheme, host, port, path, http_version = _read_request_line(rfile)
|
|
|
|
headers = _read_headers(rfile)
|
|
|
|
|
|
|
|
if hasattr(rfile, "first_byte_timestamp"):
|
|
|
|
# more accurate timestamp_start
|
|
|
|
timestamp_start = rfile.first_byte_timestamp
|
|
|
|
|
2016-05-31 23:12:10 +00:00
|
|
|
return request.Request(
|
2015-09-15 17:12:15 +00:00
|
|
|
form, method, scheme, host, port, path, http_version, headers, None, timestamp_start
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
def read_response(rfile, request, body_size_limit=None):
|
|
|
|
response = read_response_head(rfile)
|
2015-09-15 22:04:23 +00:00
|
|
|
expected_body_size = expected_http_body_size(request, response)
|
2015-09-26 15:39:50 +00:00
|
|
|
response.data.content = b"".join(read_body(rfile, expected_body_size, body_size_limit))
|
2015-09-15 17:12:15 +00:00
|
|
|
response.timestamp_end = time.time()
|
|
|
|
return response
|
|
|
|
|
|
|
|
|
|
|
|
def read_response_head(rfile):
|
2015-09-15 22:04:23 +00:00
|
|
|
"""
|
|
|
|
Parse an HTTP response head (response line + headers) from an input stream
|
|
|
|
|
|
|
|
Args:
|
|
|
|
rfile: The input stream
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
The HTTP request object (without body)
|
|
|
|
|
|
|
|
Raises:
|
2016-05-31 23:12:10 +00:00
|
|
|
exceptions.HttpReadDisconnect: No bytes can be read from rfile.
|
|
|
|
exceptions.HttpSyntaxException: The input is malformed HTTP.
|
|
|
|
exceptions.HttpException: Any other error occured.
|
2015-09-15 22:04:23 +00:00
|
|
|
"""
|
|
|
|
|
2015-09-15 17:12:15 +00:00
|
|
|
timestamp_start = time.time()
|
|
|
|
if hasattr(rfile, "reset_timestamps"):
|
|
|
|
rfile.reset_timestamps()
|
|
|
|
|
|
|
|
http_version, status_code, message = _read_response_line(rfile)
|
|
|
|
headers = _read_headers(rfile)
|
|
|
|
|
|
|
|
if hasattr(rfile, "first_byte_timestamp"):
|
|
|
|
# more accurate timestamp_start
|
|
|
|
timestamp_start = rfile.first_byte_timestamp
|
|
|
|
|
2016-05-31 23:12:10 +00:00
|
|
|
return response.Response(http_version, status_code, message, headers, None, timestamp_start)
|
2015-09-15 17:12:15 +00:00
|
|
|
|
|
|
|
|
2015-09-15 22:04:23 +00:00
|
|
|
def read_body(rfile, expected_size, limit=None, max_chunk_size=4096):
|
2015-09-15 17:12:15 +00:00
|
|
|
"""
|
2015-09-15 22:04:23 +00:00
|
|
|
Read an HTTP message body
|
2015-09-15 17:12:15 +00:00
|
|
|
|
|
|
|
Args:
|
2015-09-15 22:04:23 +00:00
|
|
|
rfile: The input stream
|
|
|
|
expected_size: The expected body size (see :py:meth:`expected_body_size`)
|
|
|
|
limit: Maximum body size
|
|
|
|
max_chunk_size: Maximium chunk size that gets yielded
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
A generator that yields byte chunks of the content.
|
2015-09-15 17:12:15 +00:00
|
|
|
|
|
|
|
Raises:
|
2016-05-31 23:12:10 +00:00
|
|
|
exceptions.HttpException, if an error occurs
|
2015-09-15 17:12:15 +00:00
|
|
|
|
2015-09-15 22:04:23 +00:00
|
|
|
Caveats:
|
|
|
|
max_chunk_size is not considered if the transfer encoding is chunked.
|
|
|
|
"""
|
2015-09-15 17:12:15 +00:00
|
|
|
if not limit or limit < 0:
|
|
|
|
limit = sys.maxsize
|
|
|
|
if not max_chunk_size:
|
|
|
|
max_chunk_size = limit
|
|
|
|
|
|
|
|
if expected_size is None:
|
|
|
|
for x in _read_chunked(rfile, limit):
|
|
|
|
yield x
|
|
|
|
elif expected_size >= 0:
|
|
|
|
if limit is not None and expected_size > limit:
|
2016-05-31 23:12:10 +00:00
|
|
|
raise exceptions.HttpException(
|
2015-09-15 17:12:15 +00:00
|
|
|
"HTTP Body too large. "
|
|
|
|
"Limit is {}, content length was advertised as {}".format(limit, expected_size)
|
|
|
|
)
|
|
|
|
bytes_left = expected_size
|
|
|
|
while bytes_left:
|
|
|
|
chunk_size = min(bytes_left, max_chunk_size)
|
|
|
|
content = rfile.read(chunk_size)
|
2015-09-15 22:04:23 +00:00
|
|
|
if len(content) < chunk_size:
|
2016-05-31 23:12:10 +00:00
|
|
|
raise exceptions.HttpException("Unexpected EOF")
|
2015-09-15 17:12:15 +00:00
|
|
|
yield content
|
|
|
|
bytes_left -= chunk_size
|
|
|
|
else:
|
|
|
|
bytes_left = limit
|
|
|
|
while bytes_left:
|
|
|
|
chunk_size = min(bytes_left, max_chunk_size)
|
|
|
|
content = rfile.read(chunk_size)
|
|
|
|
if not content:
|
|
|
|
return
|
|
|
|
yield content
|
|
|
|
bytes_left -= chunk_size
|
|
|
|
not_done = rfile.read(1)
|
|
|
|
if not_done:
|
2016-05-31 23:12:10 +00:00
|
|
|
raise exceptions.HttpException("HTTP body too large. Limit is {}.".format(limit))
|
2015-09-15 17:12:15 +00:00
|
|
|
|
|
|
|
|
|
|
|
def connection_close(http_version, headers):
|
|
|
|
"""
|
|
|
|
Checks the message to see if the client connection should be closed
|
|
|
|
according to RFC 2616 Section 8.1.
|
|
|
|
"""
|
|
|
|
# At first, check if we have an explicit Connection header.
|
2015-09-21 23:48:35 +00:00
|
|
|
if "connection" in headers:
|
2016-05-31 06:54:42 +00:00
|
|
|
tokens = get_header_tokens(headers, "connection")
|
2015-09-21 23:48:35 +00:00
|
|
|
if "close" in tokens:
|
2015-09-15 17:12:15 +00:00
|
|
|
return True
|
2015-09-21 23:48:35 +00:00
|
|
|
elif "keep-alive" in tokens:
|
2015-09-15 17:12:15 +00:00
|
|
|
return False
|
|
|
|
|
|
|
|
# If we don't have a Connection header, HTTP 1.1 connections are assumed to
|
|
|
|
# be persistent
|
2015-09-25 22:39:04 +00:00
|
|
|
return http_version != "HTTP/1.1" and http_version != b"HTTP/1.1" # FIXME: Remove one case.
|
2015-09-15 17:12:15 +00:00
|
|
|
|
|
|
|
|
2015-09-16 16:43:24 +00:00
|
|
|
def expected_http_body_size(request, response=None):
|
2015-09-15 17:12:15 +00:00
|
|
|
"""
|
2015-09-15 22:04:23 +00:00
|
|
|
Returns:
|
|
|
|
The expected body length:
|
|
|
|
- a positive integer, if the size is known in advance
|
|
|
|
- None, if the size in unknown in advance (chunked encoding)
|
|
|
|
- -1, if all data should be read until end of stream.
|
2015-09-15 17:12:15 +00:00
|
|
|
|
|
|
|
Raises:
|
2016-05-31 23:12:10 +00:00
|
|
|
exceptions.HttpSyntaxException, if the content length header is invalid
|
2015-09-15 17:12:15 +00:00
|
|
|
"""
|
|
|
|
# Determine response size according to
|
|
|
|
# http://tools.ietf.org/html/rfc7230#section-3.3
|
2015-09-15 22:04:23 +00:00
|
|
|
if not response:
|
|
|
|
headers = request.headers
|
|
|
|
response_code = None
|
|
|
|
is_request = True
|
|
|
|
else:
|
|
|
|
headers = response.headers
|
|
|
|
response_code = response.status_code
|
|
|
|
is_request = False
|
2015-09-15 17:12:15 +00:00
|
|
|
|
2015-09-15 22:04:23 +00:00
|
|
|
if is_request:
|
2015-09-21 23:48:35 +00:00
|
|
|
if headers.get("expect", "").lower() == "100-continue":
|
2015-09-15 22:04:23 +00:00
|
|
|
return 0
|
|
|
|
else:
|
2015-09-25 22:39:04 +00:00
|
|
|
if request.method.upper() == "HEAD":
|
2015-09-15 22:04:23 +00:00
|
|
|
return 0
|
|
|
|
if 100 <= response_code <= 199:
|
|
|
|
return 0
|
2015-09-25 22:39:04 +00:00
|
|
|
if response_code == 200 and request.method.upper() == "CONNECT":
|
2015-09-15 22:04:23 +00:00
|
|
|
return 0
|
|
|
|
if response_code in (204, 304):
|
|
|
|
return 0
|
2015-09-15 17:12:15 +00:00
|
|
|
|
2015-09-21 23:48:35 +00:00
|
|
|
if "chunked" in headers.get("transfer-encoding", "").lower():
|
2015-09-15 17:12:15 +00:00
|
|
|
return None
|
2015-09-21 23:48:35 +00:00
|
|
|
if "content-length" in headers:
|
2015-09-15 17:12:15 +00:00
|
|
|
try:
|
2015-09-21 23:48:35 +00:00
|
|
|
size = int(headers["content-length"])
|
2015-09-15 17:12:15 +00:00
|
|
|
if size < 0:
|
|
|
|
raise ValueError()
|
|
|
|
return size
|
|
|
|
except ValueError:
|
2016-05-31 23:12:10 +00:00
|
|
|
raise exceptions.HttpSyntaxException("Unparseable Content Length")
|
2015-09-15 17:12:15 +00:00
|
|
|
if is_request:
|
|
|
|
return 0
|
|
|
|
return -1
|
|
|
|
|
|
|
|
|
|
|
|
def _get_first_line(rfile):
|
2015-09-16 16:43:24 +00:00
|
|
|
try:
|
2015-09-15 17:12:15 +00:00
|
|
|
line = rfile.readline()
|
2015-09-16 16:43:24 +00:00
|
|
|
if line == b"\r\n" or line == b"\n":
|
|
|
|
# Possible leftover from previous message
|
|
|
|
line = rfile.readline()
|
2016-05-31 23:12:10 +00:00
|
|
|
except exceptions.TcpDisconnect:
|
|
|
|
raise exceptions.HttpReadDisconnect("Remote disconnected")
|
2015-09-15 17:12:15 +00:00
|
|
|
if not line:
|
2016-05-31 23:12:10 +00:00
|
|
|
raise exceptions.HttpReadDisconnect("Remote disconnected")
|
2015-09-15 22:04:23 +00:00
|
|
|
return line.strip()
|
2015-09-15 17:12:15 +00:00
|
|
|
|
|
|
|
|
|
|
|
def _read_request_line(rfile):
|
2015-09-19 09:59:40 +00:00
|
|
|
try:
|
|
|
|
line = _get_first_line(rfile)
|
2016-05-31 23:12:10 +00:00
|
|
|
except exceptions.HttpReadDisconnect:
|
2015-09-19 09:59:40 +00:00
|
|
|
# We want to provide a better error message.
|
2016-05-31 23:12:10 +00:00
|
|
|
raise exceptions.HttpReadDisconnect("Client disconnected")
|
2015-09-15 17:12:15 +00:00
|
|
|
|
|
|
|
try:
|
2016-07-16 11:54:17 +00:00
|
|
|
method, path, http_version = line.split()
|
2015-09-15 17:12:15 +00:00
|
|
|
|
|
|
|
if path == b"*" or path.startswith(b"/"):
|
|
|
|
form = "relative"
|
|
|
|
scheme, host, port = None, None, None
|
|
|
|
elif method == b"CONNECT":
|
|
|
|
form = "authority"
|
|
|
|
host, port = _parse_authority_form(path)
|
|
|
|
scheme, path = None, None
|
|
|
|
else:
|
|
|
|
form = "absolute"
|
2016-05-31 06:46:19 +00:00
|
|
|
scheme, host, port, path = url.parse(path)
|
2015-09-15 17:12:15 +00:00
|
|
|
|
2015-09-15 22:04:23 +00:00
|
|
|
_check_http_version(http_version)
|
2015-09-15 17:12:15 +00:00
|
|
|
except ValueError:
|
2016-05-31 23:12:10 +00:00
|
|
|
raise exceptions.HttpSyntaxException("Bad HTTP request line: {}".format(line))
|
2015-09-15 17:12:15 +00:00
|
|
|
|
|
|
|
return form, method, scheme, host, port, path, http_version
|
|
|
|
|
|
|
|
|
|
|
|
def _parse_authority_form(hostport):
|
|
|
|
"""
|
|
|
|
Returns (host, port) if hostport is a valid authority-form host specification.
|
|
|
|
http://tools.ietf.org/html/draft-luotonen-web-proxy-tunneling-01 section 3.1
|
|
|
|
|
|
|
|
Raises:
|
|
|
|
ValueError, if the input is malformed
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
host, port = hostport.split(b":")
|
|
|
|
port = int(port)
|
|
|
|
if not utils.is_valid_host(host) or not utils.is_valid_port(port):
|
|
|
|
raise ValueError()
|
|
|
|
except ValueError:
|
2016-05-31 23:12:10 +00:00
|
|
|
raise exceptions.HttpSyntaxException("Invalid host specification: {}".format(hostport))
|
2015-09-15 17:12:15 +00:00
|
|
|
|
|
|
|
return host, port
|
|
|
|
|
|
|
|
|
|
|
|
def _read_response_line(rfile):
|
2015-09-19 09:59:40 +00:00
|
|
|
try:
|
|
|
|
line = _get_first_line(rfile)
|
2016-05-31 23:12:10 +00:00
|
|
|
except exceptions.HttpReadDisconnect:
|
2015-09-19 09:59:40 +00:00
|
|
|
# We want to provide a better error message.
|
2016-05-31 23:12:10 +00:00
|
|
|
raise exceptions.HttpReadDisconnect("Server disconnected")
|
2015-09-15 17:12:15 +00:00
|
|
|
|
|
|
|
try:
|
2016-07-16 11:54:17 +00:00
|
|
|
parts = line.split(None, 2)
|
2015-09-15 17:12:15 +00:00
|
|
|
if len(parts) == 2: # handle missing message gracefully
|
|
|
|
parts.append(b"")
|
|
|
|
|
|
|
|
http_version, status_code, message = parts
|
|
|
|
status_code = int(status_code)
|
|
|
|
_check_http_version(http_version)
|
|
|
|
|
|
|
|
except ValueError:
|
2016-05-31 23:12:10 +00:00
|
|
|
raise exceptions.HttpSyntaxException("Bad HTTP response line: {}".format(line))
|
2015-09-15 17:12:15 +00:00
|
|
|
|
|
|
|
return http_version, status_code, message
|
|
|
|
|
|
|
|
|
|
|
|
def _check_http_version(http_version):
|
2015-09-15 22:04:23 +00:00
|
|
|
if not re.match(br"^HTTP/\d\.\d$", http_version):
|
2016-05-31 23:12:10 +00:00
|
|
|
raise exceptions.HttpSyntaxException("Unknown HTTP version: {}".format(http_version))
|
2015-09-15 17:12:15 +00:00
|
|
|
|
|
|
|
|
|
|
|
def _read_headers(rfile):
|
|
|
|
"""
|
|
|
|
Read a set of headers.
|
|
|
|
Stop once a blank line is reached.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
A headers object
|
|
|
|
|
|
|
|
Raises:
|
2016-05-31 23:12:10 +00:00
|
|
|
exceptions.HttpSyntaxException
|
2015-09-15 17:12:15 +00:00
|
|
|
"""
|
|
|
|
ret = []
|
|
|
|
while True:
|
|
|
|
line = rfile.readline()
|
|
|
|
if not line or line == b"\r\n" or line == b"\n":
|
|
|
|
break
|
|
|
|
if line[0] in b" \t":
|
|
|
|
if not ret:
|
2016-05-31 23:12:10 +00:00
|
|
|
raise exceptions.HttpSyntaxException("Invalid headers")
|
2015-09-15 17:12:15 +00:00
|
|
|
# continued header
|
2016-05-19 01:46:42 +00:00
|
|
|
ret[-1] = (ret[-1][0], ret[-1][1] + b'\r\n ' + line.strip())
|
2015-09-15 17:12:15 +00:00
|
|
|
else:
|
|
|
|
try:
|
|
|
|
name, value = line.split(b":", 1)
|
|
|
|
value = value.strip()
|
2015-11-16 17:51:20 +00:00
|
|
|
if not name:
|
2015-09-16 16:43:24 +00:00
|
|
|
raise ValueError()
|
2016-05-19 01:46:42 +00:00
|
|
|
ret.append((name, value))
|
2015-09-15 17:12:15 +00:00
|
|
|
except ValueError:
|
2016-06-04 23:47:52 +00:00
|
|
|
raise exceptions.HttpSyntaxException(
|
|
|
|
"Invalid header line: %s" % repr(line)
|
|
|
|
)
|
2016-05-31 23:12:10 +00:00
|
|
|
return headers.Headers(ret)
|
2015-09-15 17:12:15 +00:00
|
|
|
|
|
|
|
|
2015-09-15 22:04:23 +00:00
|
|
|
def _read_chunked(rfile, limit=sys.maxsize):
|
2015-09-15 17:12:15 +00:00
|
|
|
"""
|
|
|
|
Read a HTTP body with chunked transfer encoding.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
rfile: the input file
|
|
|
|
limit: A positive integer
|
|
|
|
"""
|
|
|
|
total = 0
|
|
|
|
while True:
|
|
|
|
line = rfile.readline(128)
|
|
|
|
if line == b"":
|
2016-05-31 23:12:10 +00:00
|
|
|
raise exceptions.HttpException("Connection closed prematurely")
|
2015-09-15 17:12:15 +00:00
|
|
|
if line != b"\r\n" and line != b"\n":
|
|
|
|
try:
|
|
|
|
length = int(line, 16)
|
|
|
|
except ValueError:
|
2016-05-31 23:12:10 +00:00
|
|
|
raise exceptions.HttpSyntaxException("Invalid chunked encoding length: {}".format(line))
|
2015-09-15 17:12:15 +00:00
|
|
|
total += length
|
|
|
|
if total > limit:
|
2016-05-31 23:12:10 +00:00
|
|
|
raise exceptions.HttpException(
|
2015-09-15 17:12:15 +00:00
|
|
|
"HTTP Body too large. Limit is {}, "
|
|
|
|
"chunked content longer than {}".format(limit, total)
|
|
|
|
)
|
|
|
|
chunk = rfile.read(length)
|
|
|
|
suffix = rfile.readline(5)
|
|
|
|
if suffix != b"\r\n":
|
2016-05-31 23:12:10 +00:00
|
|
|
raise exceptions.HttpSyntaxException("Malformed chunked body")
|
2015-09-15 17:12:15 +00:00
|
|
|
if length == 0:
|
|
|
|
return
|
|
|
|
yield chunk
|