Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
"""
Called when data is received.
This is the bulk of the processing.
"""
# Feed the data to the parser.
try:
self.parser.feed_data(data)
except httptools.HttpParserInvalidMethodError as e:
ctx = HTTPRequestContext(None, self.app, self.parent_context)
# Transform it into a 405.
exc = exc_from(e)
exc.code = 405
self.loop.create_task(self._safe_handle_error(ctx, exc))
return
except httptools.HttpParserError as e:
ctx = HTTPRequestContext(None, self.app, self.parent_context)
# Transform it into a 400.
exc = exc_from(e)
exc.code = 400
self.loop.create_task(self._safe_handle_error(ctx, exc))
return
# Wait on the event.
if self.waiter is None:
self.waiter = self.loop.create_task(self._wait())
return
def handle_parser_exception(self, exc: Exception):
"""
Handles an exception when parsing.
This will not call into the app (hence why it is a normal function, and not a coroutine).
It will also close the connection when it's done.
:param exc: The exception to handle.
"""
if isinstance(exc, httptools.HttpParserInvalidMethodError):
# 405 method not allowed
r = MethodNotAllowed()
elif isinstance(exc, httptools.HttpParserError):
# 400 bad request
r = BadRequest()
elif isinstance(exc, httptools.HttpParserUpgrade):
r = BadRequest(description="Invalid upgrade header.")
else:
# internal server error
r = InternalServerError()
# Make a fake environment.
new_environ = to_wsgi_environment(headers=self.headers, method="", path="/",
http_version="1.0", body=None)
new_environ["SERVER_NAME"] = self.component.get_server_name()
new_environ["SERVER_PORT"] = str(self.server_port)
new_environ["REMOTE_ADDR"] = self.ip
self.raw_write(get_formatted_response(r, new_environ))
buffer += data
parser.feed_data(data)
if request.is_gzip:
request.ungzip()
response = await handler(request)
if response.is_gzip:
response.gzip()
client_writer.write(prepare_response(response))
except HandlerNotFoundError:
self.logger.info('No handler found: %s' % request)
except HttpParserError as e:
self.logger.warning('%s: %s' % (e, request))
else:
should_proxy = False
finally:
if should_proxy:
await self.not_found_handler(client_reader,
client_writer,
buffer)
if not self.loop.is_closed():
client_writer.close()
raised in the http parser must be reraised from __context__ because
they are caught by the MagicStack implementation"""
protocol = self.protocol()
server_socket = socket.socket()
buffer = dict(data=bytes())
exception = None
try:
self.server_connect(server_socket)
self.client_recv(client_socket, RequestHandler(protocol), buffer)
self.server_send(server_socket, protocol.request)
self.server_recv(server_socket, ResponseHandler(protocol))
ranks = self.model_rank(protocol.topk, protocol.query, protocol.choices)
protocol.on_rank(ranks)
except HttpParserError as exc:
exception = exc.__context__
except Exception as exc:
exception = exc
try:
log = '{}:{}: {}'.format(*address, protocol.request)
if exception is None:
self.logger.debug(log)
else:
self.logger.warning('%s: %s', type(exception).__name__, log)
raise exception
except StatusRequest:
protocol.response.body = json.dumps(self.status, indent=2).encode()
protocol.response.encode()
def data_received(self, data: bytes):
try:
self.parser.feed_data(data)
except HttpParserError:
# If the parsing failed before on_message_begin, we don't have a
# response.
self.response = self.app.Response(self.app)
self.response.status = HTTPStatus.BAD_REQUEST
self.response.body = b'Unparsable request'
self.write()
def feed(self, data: bytes):
"""feed data to the underlying parser. Exceptions raised in the http
parser must be reraised from __context__ because they are caught by
the MagicStack implementation."""
for hook in self._data_hooks:
hook(data)
try:
self._parser.feed_data(data)
except HttpParserError as exc:
raise exc.__context__ if exc.__context__ else exc
def data_received(self, data):
try:
self.data += data
self.http_parser.feed_data(data)
self.send_data_to_client()
except HttpParserError as e:
traceback.print_exc()
self.send_response(Response(status=HTTPStatus.BAD_REQUEST,
body=b'invalid HTTP',
headers={}))
import zlib
from collections import namedtuple
import httptools
from curio import timeout_after, TaskTimeout
from curio.io import StreamBase
from requests.structures import CaseInsensitiveDict
from requests import ReadTimeout as ReadTimeoutError
from urllib3.response import GzipDecoder as GzipDecoderBase
from urllib3.response import DeflateDecoder as DeflateDecoderBase
from urllib3.exceptions import DecodeError
class ProtocolError(httptools.HttpParserError):
"""ProtocolError"""
class _Decoder:
def decompress(self, *args, **kwargs):
try:
return super().decompress(*args, **kwargs)
except zlib.error as ex:
msg = 'failed to decode response with {}'.format(
type(self).__name__)
raise DecodeError(msg) from ex
class GzipDecoder(_Decoder, GzipDecoderBase):
"""GzipDecoder"""
def data_received(self, data):
try:
self.parser.feed_data(data)
except HttpParserCallbackError:
self.close()
raise
except HttpParserError as pex:
raise InvalidResponseFromServer(pex)