From 20fb97df97cdfcbc1d98a0b1f7d94806d996e274 Mon Sep 17 00:00:00 2001 From: Dan Prince Date: Fri, 15 Feb 2013 10:41:30 -0500 Subject: Updates to OSAPI sizelimit middleware. Updates the OSAPI sizelimit middleware so that we use avoid calling len on a request body which could cause a really large request to get buffered into memory. Also updates the middleware to return HTTP 413 which is a more correct error code in this case (previously it returned just 400). Fixes LP Bug #1131857. Change-Id: Id8bc5eeb0fba9482809edd12543a75163e1227e9 --- nova/api/sizelimit.py | 41 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 36 insertions(+), 5 deletions(-) (limited to 'nova/api') diff --git a/nova/api/sizelimit.py b/nova/api/sizelimit.py index 67d459583..1e88f183e 100644 --- a/nova/api/sizelimit.py +++ b/nova/api/sizelimit.py @@ -37,6 +37,35 @@ CONF.register_opt(max_request_body_size_opt) LOG = logging.getLogger(__name__) +class LimitingReader(object): + """Reader to limit the size of an incoming request.""" + def __init__(self, data, limit): + """ + :param data: Underlying data object + :param limit: maximum number of bytes the reader should allow + """ + self.data = data + self.limit = limit + self.bytes_read = 0 + + def __iter__(self): + for chunk in self.data: + self.bytes_read += len(chunk) + if self.bytes_read > self.limit: + msg = _("Request is too large.") + raise webob.exc.HTTPRequestEntityTooLarge(explanation=msg) + else: + yield chunk + + def read(self, i=None): + result = self.data.read(i) + self.bytes_read += len(result) + if self.bytes_read > self.limit: + msg = _("Request is too large.") + raise webob.exc.HTTPRequestEntityTooLarge(explanation=msg) + return result + + class RequestBodySizeLimiter(wsgi.Middleware): """Limit the size of incoming requests.""" @@ -45,9 +74,11 @@ class RequestBodySizeLimiter(wsgi.Middleware): @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): - if (req.content_length > CONF.osapi_max_request_body_size - or len(req.body) > CONF.osapi_max_request_body_size): + if req.content_length > CONF.osapi_max_request_body_size: msg = _("Request is too large.") - raise webob.exc.HTTPBadRequest(explanation=msg) - else: - return self.application + raise webob.exc.HTTPRequestEntityTooLarge(explanation=msg) + if req.content_length is None and req.is_body_readable: + limiter = LimitingReader(req.body_file, + CONF.osapi_max_request_body_size) + req.body_file = limiter + return self.application -- cgit