Ejemplo n.º 1
0
def get_input_data():
    content_length = request.headers.get('content-length', type=int)
    if content_length > 0:
        stream = LimitedStream(request.environ['wsgi.input'], content_length)
        old_msg = stream.read()
        msg = utils.parse_txt(old_msg)
    else:
        text = request.values.get('text', '')
        msg = {'Content': text, 'MsgType': 'text'}
    return msg
Ejemplo n.º 2
0
 def replace_wsgi_input(self, environ):
     content_length = self.headers.get('content-length', type=int)
     limited_stream = LimitedStream(environ['wsgi.input'], content_length)
     if content_length is not None and content_length > 1024 * 500:
         wsgi_input = TemporaryFile('wb+')
     else:
         wsgi_input = StringIO()
     wsgi_input.write(limited_stream.read())
     wsgi_input.seek(0)
     environ['wsgi.input'] = wsgi_input
     return environ['wsgi.input']
Ejemplo n.º 3
0
 def __call__(self, environ, start_response):
     stream = LimitedStream(environ["wsgi.input"], int(environ["CONTENT_LENGTH"] or 0))
     environ["wsgi.input"] = stream
     app_iter = self.app(environ, start_response)
     try:
         stream.exhaust()
         for event in app_iter:
             yield event
     finally:
         if hasattr(app_iter, "close"):
             app_iter.close()
Ejemplo n.º 4
0
 def __call__(self, environ, start_response):
     stream = LimitedStream(environ['wsgi.input'], 512 * 1024 * 1024)
     environ['wsgi.input'] = stream
     app_iter = self.app(environ, start_response)
     try:
         stream.exhaust()
         for event in app_iter:
             yield event
     finally:
         if hasattr(app_iter, 'close'):
             app_iter.close()
Ejemplo n.º 5
0
 def __call__(self, environ, start_response):
     stream = LimitedStream(environ['wsgi.input'], int(environ.get('CONTENT_LENGTH') or 0))
     environ['wsgi.input'] = stream
     app_iter = self.app(environ, start_response)
     try:
         stream.exhaust()
         for event in app_iter:
             yield event
     finally:
         if hasattr(app_iter, 'close'):
             app_iter.close()
Ejemplo n.º 6
0
 def __call__(self, environ, start_response):
     stream = LimitedStream(environ['wsgi.input'],
                            int(environ.get('CONTENT_LENGTH', 0) or 0))
     environ['wsgi.input'] = stream
     app_iter = self.app(environ, start_response)
     try:
         stream.exhaust()
         for event in app_iter:
             yield event
     finally:
         if hasattr(app_iter, 'close'):
             app_iter.close()
Ejemplo n.º 7
0
    def __call__(self, environ, start_response):
        content_length = environ.get('CONTENT_LENGTH',0)
        content_length = 0 if content_length is '' else content_length

        stream = LimitedStream(environ.get('wsgi.input'),
                               int(content_length))
        environ['wsgi.input'] = stream
        app_iter = self.app(environ, start_response)
        try:
            stream.exhaust()
            for event in app_iter:
                yield event
        finally:
            if hasattr(app_iter, 'close'):
                app_iter.close()
Ejemplo n.º 8
0
def deserialize(src, backend):
    while True:
        meta_size_bytes = src.read(4)
        if not len(meta_size_bytes):
            return  # end of file
        meta_size = struct.unpack('!i', meta_size_bytes)[0]
        if not meta_size:
            continue  # end of store
        meta_str = src.read(meta_size)
        text = meta_str.decode('utf-8')
        meta = json.loads(text)
        name = meta.get(NAME)
        if isinstance(name, str):
            # if we encounter single names, make a list of names:
            meta[NAME] = [
                name,
            ]
        if ITEMTYPE not in meta:
            # temporary hack to upgrade serialized item files:
            meta[ITEMTYPE] = ITEMTYPE_DEFAULT
        data_size = meta[SIZE]
        curr_pos = src.tell()
        limited = LimitedStream(src, data_size)
        backend.store(meta, limited)
        if not limited.is_exhausted:
            # if we already have the DATAID in the backend, the backend code
            # does not read from the limited stream:
            assert limited._pos == 0
            # but we must seek to get forward to the next item:
            src.seek(curr_pos + data_size)
Ejemplo n.º 9
0
def parse_form_data(environ, stream_factory = None, charset = 'utf-8', errors = 'ignore', max_form_memory_size = None, max_content_length = None, cls = None, silent = True):
    content_type, extra = parse_options_header(environ.get('CONTENT_TYPE', ''))
    try:
        content_length = int(environ['CONTENT_LENGTH'])
    except (KeyError, ValueError):
        content_length = 0

    if cls is None:
        cls = MultiDict
    if max_content_length is not None and content_length > max_content_length:
        raise RequestEntityTooLarge()
    stream = _empty_stream
    files = ()
    if content_type == 'multipart/form-data':
        try:
            form, files = parse_multipart(environ['wsgi.input'], extra.get('boundary'), content_length, stream_factory, charset, errors, max_form_memory_size=max_form_memory_size)
        except ValueError as e:
            if not silent:
                raise 
            form = cls()
        else:
            form = cls(form)

    elif content_type == 'application/x-www-form-urlencoded' or content_type == 'application/x-url-encoded':
        if max_form_memory_size is not None and content_length > max_form_memory_size:
            raise RequestEntityTooLarge()
        form = url_decode(environ['wsgi.input'].read(content_length), charset, errors=errors, cls=cls)
    else:
        form = cls()
        stream = LimitedStream(environ['wsgi.input'], content_length)
    return (stream, form, cls(files))
Ejemplo n.º 10
0
    def parse(self, stream, mimetype, content_length, options=None):
        """Parses the information from the given stream, mimetype,
        content length and mimetype parameters.

        :param stream: an input stream
        :param mimetype: the mimetype of the data
        :param content_length: the content length of the incoming data
        :param options: optional mimetype parameters (used for
                        the multipart boundary for instance)
        :return: A tuple in the form ``(stream, form, files)``.
        """
        if self.max_content_length is not None and \
           content_length > self.max_content_length:
            raise RequestEntityTooLarge()
        if options is None:
            options = {}
        input_stream = LimitedStream(stream, content_length)

        parse_func = self.get_parse_func(mimetype, options)
        if parse_func is not None:
            try:
                return parse_func(self, input_stream, mimetype,
                                  content_length, options)
            except ValueError:
                if not self.silent:
                    raise
        return input_stream, self.cls(), self.cls()
Ejemplo n.º 11
0
    def __call__(self, environ, start_response):
        length = 0
        if 'CONTENT_LENGTH' in environ:
            try:
                length = int(environ['CONTENT_LENGTH'])
            except ValueError:
                pass
        stream = LimitedStream(environ['wsgi.input'], length)

        environ['wsgi.input'] = stream
        app_iter = self.app(environ, start_response)
        try:
            stream.exhaust()
            for event in app_iter:
                yield event
        finally:
            if hasattr(app_iter, 'close'):
                app_iter.close()
Ejemplo n.º 12
0
def deserialize(src, backend):
    while True:
        meta_size_bytes = src.read(4)
        meta_size = struct.unpack('!i', meta_size_bytes)[0]
        if not meta_size:
            return
        meta_str = src.read(meta_size)
        text = meta_str.decode('utf-8')
        meta = json.loads(text)
        data_size = meta[u'size']

        limited = LimitedStream(src, data_size)
        backend.store(meta, limited)
        assert limited.is_exhausted
Ejemplo n.º 13
0
def deserialize(src, backend, new_ns=None, old_ns=None, kill_ns=None):
    """
    Normal usage is to restore an empty wiki with data from a backup.

    If new_ns and old_ns are passed, then all items in the old_ns are renamed into the new_ns.
    If kill_ns is passed, then all items in that namespace are not loaded.
    """
    assert bool(new_ns is None) == bool(
        old_ns is None), 'new_ns and old_ns are co-dependent options'
    while True:
        meta_size_bytes = src.read(4)
        if not len(meta_size_bytes):
            return  # end of file
        meta_size = struct.unpack('!i', meta_size_bytes)[0]
        if not meta_size:
            continue  # end of store
        meta_str = src.read(meta_size)
        text = meta_str.decode('utf-8')
        meta = json.loads(text)
        name = meta.get(NAME)
        if isinstance(name, str):
            # if we encounter single names, make a list of names:
            meta[NAME] = [
                name,
            ]
        if ITEMTYPE not in meta:
            # temporary hack to upgrade serialized item files:
            meta[ITEMTYPE] = ITEMTYPE_DEFAULT
        data_size = meta[SIZE]
        curr_pos = src.tell()
        limited = LimitedStream(src, data_size)

        if kill_ns and kill_ns == meta[NAMESPACE]:
            continue
        if new_ns is not None and old_ns == meta[NAMESPACE]:
            meta[NAMESPACE] = new_ns

        backend.store(meta, limited)
        if not limited.is_exhausted:
            # if we already have the DATAID in the backend, the backend code
            # does not read from the limited stream:
            assert limited._pos == 0
            # but we must seek to get forward to the next item:
            src.seek(curr_pos + data_size)
Ejemplo n.º 14
0
def test_simple_put_get():
    swift = FakeSwiftStorage(**base_args)
    assert not swift.exists("somepath")

    swift.put_content("somepath", b"hello world!")
    assert swift.exists("somepath")
    assert swift.get_content("somepath") == b"hello world!"

    swift.put_content("someotherpath", LimitedStream(io.BytesIO(b"hello world2"), 12))
    assert swift.exists("someotherpath")
    assert swift.get_content("someotherpath") == b"hello world2"

    swift.put_content("yetsomeotherpath", ReadableToIterable(b"hello world3"))
    assert swift.exists("yetsomeotherpath")
    assert swift.get_content("yetsomeotherpath") == b"hello world3"

    swift.put_content("againsomeotherpath", io.BytesIO(b"hello world4"))
    assert swift.exists("againsomeotherpath")
    assert swift.get_content("againsomeotherpath") == b"hello world4"
Ejemplo n.º 15
0
def get_stream(stream: t.BinaryIO,
               headers: t.Dict[str, str],
               safe_fallback: bool = True) -> t.BinaryIO:
    """

    :param stream:
        File like object
    :param headers:
        HTTP headers
    :param safe_fallback:
        When no conditions are satisfied, return raw stream binary io
    :return:
    """

    content_length = get_content_length(headers)
    if 'Transfer-Encoding' in headers:
        return DechunkedInput(stream)
    if content_length is None:
        return io.BytesIO if safe_fallback else stream
    return t.cast(t.BinaryIO, LimitedStream(stream, content_length))
Ejemplo n.º 16
0
    def _load_form_data(self):
        if 'stream' in self.__dict__:
            return
        if self.shallow:
            raise RuntimeError('A shallow request tried to consume form data.  If you really want to do that, set `shallow` to False.')
        data = None
        stream = _empty_stream
        if self.environ['REQUEST_METHOD'] in ('POST', 'PUT'):
            try:
                data = parse_form_data(self.environ, self._get_file_stream, self.charset, self.encoding_errors, self.max_form_memory_size, self.max_content_length, cls=self.parameter_storage_class, silent=False)
            except ValueError as e:
                self._form_parsing_failed(e)

        else:
            content_length = self.headers.get('content-length', type=int)
            if content_length is not None:
                stream = LimitedStream(self.environ['wsgi.input'], content_length)
        if data is None:
            data = (stream, self.parameter_storage_class(), self.parameter_storage_class())
        d = self.__dict__
        d['stream'], d['form'], d['files'] = data
Ejemplo n.º 17
0
def test_limited_stream():
    """Test the LimitedStream"""
    io = StringIO('123456')
    stream = RaisingLimitedStream(io, 3)
    assert stream.read() == '123'
    assert_raises(BadRequest, stream.read)

    io = StringIO('123456')
    stream = RaisingLimitedStream(io, 3)
    assert stream.read(1) == '1'
    assert stream.read(1) == '2'
    assert stream.read(1) == '3'
    assert_raises(BadRequest, stream.read)

    io = StringIO('123456\nabcdefg')
    stream = LimitedStream(io, 9)
    assert stream.readline() == '123456\n'
    assert stream.readline() == 'ab'

    io = StringIO('123456\nabcdefg')
    stream = LimitedStream(io, 9)
    assert stream.readlines() == ['123456\n', 'ab']

    io = StringIO('123456\nabcdefg')
    stream = LimitedStream(io, 9)
    assert stream.readlines(2) == ['12']
    assert stream.readlines(2) == ['34']
    assert stream.readlines() == ['56\n', 'ab']

    io = StringIO('123456\nabcdefg')
    stream = LimitedStream(io, 9)
    assert stream.readline(100) == '123456\n'

    io = StringIO('123456\nabcdefg')
    stream = LimitedStream(io, 9)
    assert stream.readlines(100) == ['123456\n', 'ab']

    io = StringIO('123456')
    stream = LimitedStream(io, 3)
    assert stream.read(1) == '1'
    assert stream.read(1) == '2'
    assert stream.read() == '3'
    assert stream.read() == ''
Ejemplo n.º 18
0
def parse_form_data(environ,
                    stream_factory=None,
                    charset='utf-8',
                    errors='ignore',
                    max_form_memory_size=None,
                    max_content_length=None,
                    cls=None,
                    silent=True):
    """Parse the form data in the environ and return it as tuple in the form
    ``(stream, form, files)``.  You should only call this method if the
    transport method is `POST` or `PUT`.
    
    If the mimetype of the data transmitted is `multipart/form-data` the
    files multidict will be filled with `FileStorage` objects.  If the
    mimetype is unknown the input stream is wrapped and returned as first
    argument, else the stream is empty.
    
    This function does not raise exceptions, even if the input data is
    malformed.
    
    Have a look at :ref:`dealing-with-request-data` for more details.
    
    .. versionadded:: 0.5
       The `max_form_memory_size`, `max_content_length` and
       `cls` parameters were added.
    
    .. versionadded:: 0.5.1
       The optional `silent` flag was added.
    
    :param environ: the WSGI environment to be used for parsing.
    :param stream_factory: An optional callable that returns a new read and
                           writeable file descriptor.  This callable works
                           the same as :meth:`~BaseResponse._get_file_stream`.
    :param charset: The character set for URL and url encoded form data.
    :param errors: The encoding error behavior.
    :param max_form_memory_size: the maximum number of bytes to be accepted for
                           in-memory stored form data.  If the data
                           exceeds the value specified an
                           :exc:`~exceptions.RequestURITooLarge`
                           exception is raised.
    :param max_content_length: If this is provided and the transmitted data
                               is longer than this value an
                               :exc:`~exceptions.RequestEntityTooLarge`
                               exception is raised.
    :param cls: an optional dict class to use.  If this is not specified
                       or `None` the default :class:`MultiDict` is used.
    :param silent: If set to False parsing errors will not be caught.
    :return: A tuple in the form ``(stream, form, files)``.
    """
    content_type, extra = parse_options_header(environ.get('CONTENT_TYPE', ''))
    try:
        content_length = int(environ['CONTENT_LENGTH'])
    except (KeyError, ValueError):
        content_length = 0

    if cls is None:
        cls = MultiDict
    if max_content_length is not None and content_length > max_content_length:
        raise RequestEntityTooLarge()
    stream = _empty_stream
    files = ()
    if content_type == 'multipart/form-data':
        try:
            form, files = parse_multipart(
                environ['wsgi.input'],
                extra.get('boundary'),
                content_length,
                stream_factory,
                charset,
                errors,
                max_form_memory_size=max_form_memory_size)
        except ValueError as e:
            if not silent:
                raise
            form = cls()
        else:
            form = cls(form)

    elif content_type == 'application/x-www-form-urlencoded' or content_type == 'application/x-url-encoded':
        if max_form_memory_size is not None and content_length > max_form_memory_size:
            raise RequestEntityTooLarge()
        form = url_decode(environ['wsgi.input'].read(content_length),
                          charset,
                          errors=errors,
                          cls=cls)
    else:
        form = cls()
        stream = LimitedStream(environ['wsgi.input'], content_length)
    return (stream, form, cls(files))
Ejemplo n.º 19
0
                raise
            form = cls()
        else:
            form = cls(form)
    elif content_type == 'application/x-www-form-urlencoded' or \
         content_type == 'application/x-url-encoded':
        if max_form_memory_size is not None and \
           content_length > max_form_memory_size:
            raise RequestEntityTooLarge()
        form = url_decode(environ['wsgi.input'].read(content_length),
                          charset,
                          errors=errors,
                          cls=cls)
    else:
        form = cls()
        stream = LimitedStream(environ['wsgi.input'], content_length)

    return stream, form, cls(files)


def _fix_ie_filename(filename):
    """Internet Explorer 6 transmits the full file name if a file is
    uploaded.  This function strips the full path if it thinks the
    filename is Windows-like absolute.
    """
    if filename[1:3] == ':\\' or filename[:2] == '\\\\':
        return filename.split('\\')[-1]
    return filename


def _line_parse(line):
Ejemplo n.º 20
0
def parse_multipart(file,
                    boundary,
                    content_length,
                    stream_factory=None,
                    charset='utf-8',
                    errors='ignore',
                    buffer_size=10 * 1024,
                    max_form_memory_size=None):
    """Parse a multipart/form-data stream.  This is invoked by
    :func:`utils.parse_form_data` if the content type matches.  Currently it
    exists for internal usage only, but could be exposed as separate
    function if it turns out to be useful and if we consider the API stable.
    """
    # XXX: this function does not support multipart/mixed.  I don't know of
    #      any browser that supports this, but it should be implemented
    #      nonetheless.

    # make sure the buffer size is divisible by four so that we can base64
    # decode chunk by chunk
    assert buffer_size % 4 == 0, 'buffer size has to be divisible by 4'
    # also the buffer size has to be at least 1024 bytes long or long headers
    # will freak out the system
    assert buffer_size >= 1024, 'buffer size has to be at least 1KB'

    if stream_factory is None:
        stream_factory = default_stream_factory

    if not boundary:
        raise ValueError('Missing boundary')
    if not is_valid_multipart_boundary(boundary):
        raise ValueError('Invalid boundary: %s' % boundary)
    if len(boundary) > buffer_size:
        raise ValueError('Boundary longer than buffer size')

    total_content_length = content_length
    next_part = '--' + boundary
    last_part = next_part + '--'

    form = []
    files = []
    in_memory = 0

    # convert the file into a limited stream with iteration capabilities
    file = LimitedStream(file, content_length)
    iterator = chain(make_line_iter(file, buffer_size=buffer_size),
                     _empty_string_iter)

    try:
        terminator = _find_terminator(iterator)
        if terminator != next_part:
            raise ValueError('Expected boundary at start of multipart data')

        while terminator != last_part:
            headers = parse_multipart_headers(iterator)
            disposition = headers.get('content-disposition')
            if disposition is None:
                raise ValueError('Missing Content-Disposition header')
            disposition, extra = parse_options_header(disposition)
            name = extra.get('name')

            transfer_encoding = headers.get('content-transfer-encoding')
            try_decode = transfer_encoding is not None and \
                         transfer_encoding in _supported_multipart_encodings

            filename = extra.get('filename')

            # if no content type is given we stream into memory.  A list is
            # used as a temporary container.
            if filename is None:
                is_file = False
                container = []
                _write = container.append
                guard_memory = max_form_memory_size is not None

            # otherwise we parse the rest of the headers and ask the stream
            # factory for something we can write in.
            else:
                content_type = headers.get('content-type')
                content_type = parse_options_header(content_type)[0] \
                    or 'text/plain'
                is_file = True
                guard_memory = False
                if filename is not None:
                    filename = _fix_ie_filename(
                        _decode_unicode(filename, charset, errors))
                try:
                    content_length = int(headers['content-length'])
                except (KeyError, ValueError):
                    content_length = 0
                container = stream_factory(total_content_length, content_type,
                                           filename, content_length)
                _write = container.write

            buf = ''
            for line in iterator:
                if not line:
                    raise ValueError('unexpected end of stream')

                if line[:2] == '--':
                    terminator = line.rstrip()
                    if terminator in (next_part, last_part):
                        break

                if try_decode:
                    try:
                        line = line.decode(transfer_encoding)
                    except:
                        raise ValueError('could not decode transfer '
                                         'encoded chunk')

                # we have something in the buffer from the last iteration.
                # this is usually a newline delimiter.
                if buf:
                    _write(buf)
                    buf = ''

                # If the line ends with windows CRLF we write everything except
                # the last two bytes.  In all other cases however we write
                # everything except the last byte.  If it was a newline, that's
                # fine, otherwise it does not matter because we will write it
                # the next iteration.  this ensures we do not write the
                # final newline into the stream.  That way we do not have to
                # truncate the stream.
                if line[-2:] == '\r\n':
                    buf = '\r\n'
                    cutoff = -2
                else:
                    buf = line[-1]
                    cutoff = -1
                _write(line[:cutoff])

                # if we write into memory and there is a memory size limit we
                # count the number of bytes in memory and raise an exception if
                # there is too much data in memory.
                if guard_memory:
                    in_memory += len(line)
                    if in_memory > max_form_memory_size:
                        from werkzeug.exceptions import RequestEntityTooLarge
                        raise RequestEntityTooLarge()
            else:
                raise ValueError('unexpected end of part')

            if is_file:
                container.seek(0)
                files.append(
                    (name,
                     FileStorage(container, filename, name, content_type,
                                 content_length, headers)))
            else:
                form.append(
                    (name, _decode_unicode(''.join(container), charset,
                                           errors)))
    finally:
        # make sure the whole input stream is read
        file.exhaust()

    return form, files
Ejemplo n.º 21
0
def parse_multipart(file, boundary, content_length, stream_factory = None, charset = 'utf-8', errors = 'ignore', buffer_size = 10240, max_form_memory_size = None):
    if stream_factory is None:
        stream_factory = default_stream_factory
    if not boundary:
        raise ValueError('Missing boundary')
    if not is_valid_multipart_boundary(boundary):
        raise ValueError('Invalid boundary: %s' % boundary)
    if len(boundary) > buffer_size:
        raise ValueError('Boundary longer than buffer size')
    total_content_length = content_length
    next_part = '--' + boundary
    last_part = next_part + '--'
    form = []
    files = []
    in_memory = 0
    file = LimitedStream(file, content_length)
    iterator = chain(make_line_iter(file, buffer_size=buffer_size), _empty_string_iter)
    try:
        terminator = _find_terminator(iterator)
        if terminator != next_part:
            raise ValueError('Expected boundary at start of multipart data')
        while terminator != last_part:
            headers = parse_multipart_headers(iterator)
            disposition = headers.get('content-disposition')
            if disposition is None:
                raise ValueError('Missing Content-Disposition header')
            disposition, extra = parse_options_header(disposition)
            name = extra.get('name')
            transfer_encoding = headers.get('content-transfer-encoding')
            try_decode = transfer_encoding is not None and transfer_encoding in _supported_multipart_encodings
            filename = extra.get('filename')
            if filename is None:
                is_file = False
                container = []
                _write = container.append
                guard_memory = max_form_memory_size is not None
            else:
                content_type = headers.get('content-type')
                content_type = parse_options_header(content_type)[0] or 'text/plain'
                is_file = True
                guard_memory = False
                if filename is not None:
                    filename = _fix_ie_filename(_decode_unicode(filename, charset, errors))
                try:
                    content_length = int(headers['content-length'])
                except (KeyError, ValueError):
                    content_length = 0

                container = stream_factory(total_content_length, content_type, filename, content_length)
                _write = container.write
            buf = ''
            for line in iterator:
                if not line:
                    raise ValueError('unexpected end of stream')
                if line[:2] == '--':
                    terminator = line.rstrip()
                    if terminator in (next_part, last_part):
                        break
                if try_decode:
                    try:
                        line = line.decode(transfer_encoding)
                    except:
                        raise ValueError('could not decode transfer encoded chunk')

                if buf:
                    _write(buf)
                    buf = ''
                if line[-2:] == '\r\n':
                    buf = '\r\n'
                    cutoff = -2
                else:
                    buf = line[-1]
                    cutoff = -1
                _write(line[:cutoff])
                if guard_memory:
                    in_memory += len(line)
                    if in_memory > max_form_memory_size:
                        from werkzeug.exceptions import RequestEntityTooLarge
                        raise RequestEntityTooLarge()
            else:
                raise ValueError('unexpected end of part')

            if is_file:
                container.seek(0)
                files.append((name, FileStorage(container, filename, name, content_type, content_length, headers)))
            else:
                form.append((name, _decode_unicode(''.join(container), charset, errors)))

    finally:
        file.exhaust()

    return (form, files)
Ejemplo n.º 22
0
def parse_multipart(
    file,
    boundary,
    content_length,
    stream_factory=None,
    charset="utf-8",
    errors="ignore",
    buffer_size=10 * 1024,
    max_form_memory_size=None,
):
    """Parse a multipart/form-data stream.  This is invoked by
    :func:`utils.parse_form_data` if the content type matches.  Currently it
    exists for internal usage only, but could be exposed as separate
    function if it turns out to be useful and if we consider the API stable.
    """
    # XXX: this function does not support multipart/mixed.  I don't know of
    #      any browser that supports this, but it should be implemented
    #      nonetheless.

    # make sure the buffer size is divisible by four so that we can base64
    # decode chunk by chunk
    assert buffer_size % 4 == 0, "buffer size has to be divisible by 4"
    # also the buffer size has to be at least 1024 bytes long or long headers
    # will freak out the system
    assert buffer_size >= 1024, "buffer size has to be at least 1KB"

    if stream_factory is None:
        stream_factory = default_stream_factory

    if not boundary:
        raise ValueError("Missing boundary")
    if not is_valid_multipart_boundary(boundary):
        raise ValueError("Invalid boundary: %s" % boundary)
    if len(boundary) > buffer_size:  # pragma: no cover
        # this should never happen because we check for a minimum size
        # of 1024 and boundaries may not be longer than 200.  The only
        # situation when this happen is for non debug builds where
        # the assert i skipped.
        raise ValueError("Boundary longer than buffer size")

    total_content_length = content_length
    next_part = "--" + boundary
    last_part = next_part + "--"

    form = []
    files = []
    in_memory = 0

    # convert the file into a limited stream with iteration capabilities
    file = LimitedStream(file, content_length)
    iterator = chain(make_line_iter(file, buffer_size=buffer_size), _empty_string_iter)

    try:
        terminator = _find_terminator(iterator)
        if terminator != next_part:
            raise ValueError("Expected boundary at start of multipart data")

        while terminator != last_part:
            headers = parse_multipart_headers(iterator)
            disposition = headers.get("content-disposition")
            if disposition is None:
                raise ValueError("Missing Content-Disposition header")
            disposition, extra = parse_options_header(disposition)
            name = extra.get("name")

            transfer_encoding = headers.get("content-transfer-encoding")
            try_decode = transfer_encoding is not None and transfer_encoding in _supported_multipart_encodings

            filename = extra.get("filename")

            # if no content type is given we stream into memory.  A list is
            # used as a temporary container.
            if filename is None:
                is_file = False
                container = []
                _write = container.append
                guard_memory = max_form_memory_size is not None

            # otherwise we parse the rest of the headers and ask the stream
            # factory for something we can write in.
            else:
                content_type = headers.get("content-type")
                content_type = parse_options_header(content_type)[0] or "text/plain"
                is_file = True
                guard_memory = False
                if filename is not None:
                    filename = _fix_ie_filename(_decode_unicode(filename, charset, errors))
                try:
                    content_length = int(headers["content-length"])
                except (KeyError, ValueError):
                    content_length = 0
                container = stream_factory(total_content_length, content_type, filename, content_length)
                _write = container.write

            buf = ""
            for line in iterator:
                if not line:
                    raise ValueError("unexpected end of stream")

                if line[:2] == "--":
                    terminator = line.rstrip()
                    if terminator in (next_part, last_part):
                        break

                if try_decode:
                    try:
                        line = line.decode(transfer_encoding)
                    except:
                        raise ValueError("could not decode transfer " "encoded chunk")

                # we have something in the buffer from the last iteration.
                # this is usually a newline delimiter.
                if buf:
                    _write(buf)
                    buf = ""

                # If the line ends with windows CRLF we write everything except
                # the last two bytes.  In all other cases however we write
                # everything except the last byte.  If it was a newline, that's
                # fine, otherwise it does not matter because we will write it
                # the next iteration.  this ensures we do not write the
                # final newline into the stream.  That way we do not have to
                # truncate the stream.
                if line[-2:] == "\r\n":
                    buf = "\r\n"
                    cutoff = -2
                else:
                    buf = line[-1]
                    cutoff = -1
                _write(line[:cutoff])

                # if we write into memory and there is a memory size limit we
                # count the number of bytes in memory and raise an exception if
                # there is too much data in memory.
                if guard_memory:
                    in_memory += len(line)
                    if in_memory > max_form_memory_size:
                        from werkzeug.exceptions import RequestEntityTooLarge

                        raise RequestEntityTooLarge()
            else:  # pragma: no cover
                raise ValueError("unexpected end of part")

            if is_file:
                container.seek(0)
                files.append((name, FileStorage(container, filename, name, content_type, content_length, headers)))
            else:
                form.append((name, _decode_unicode("".join(container), charset, errors)))
    finally:
        # make sure the whole input stream is read
        file.exhaust()

    return form, files
Ejemplo n.º 23
0
 def __call__(self, environ, start_response):
     limit = min(self.maximum_size, int(environ.get('CONTENT_LENGTH') or 0))
     environ['wsgi.input'] = LimitedStream(environ['wsgi.input'], limit)
     return self.app(environ, start_response)
Ejemplo n.º 24
0
def parse_multipart(file,
                    boundary,
                    content_length,
                    stream_factory=None,
                    charset='utf-8',
                    errors='ignore',
                    buffer_size=10240,
                    max_form_memory_size=None):
    if stream_factory is None:
        stream_factory = default_stream_factory
    if not boundary:
        raise ValueError('Missing boundary')
    if not is_valid_multipart_boundary(boundary):
        raise ValueError('Invalid boundary: %s' % boundary)
    if len(boundary) > buffer_size:
        raise ValueError('Boundary longer than buffer size')
    total_content_length = content_length
    next_part = '--' + boundary
    last_part = next_part + '--'
    form = []
    files = []
    in_memory = 0
    file = LimitedStream(file, content_length)
    iterator = chain(make_line_iter(file, buffer_size=buffer_size),
                     _empty_string_iter)
    try:
        terminator = _find_terminator(iterator)
        if terminator != next_part:
            raise ValueError('Expected boundary at start of multipart data')
        while terminator != last_part:
            headers = parse_multipart_headers(iterator)
            disposition = headers.get('content-disposition')
            if disposition is None:
                raise ValueError('Missing Content-Disposition header')
            disposition, extra = parse_options_header(disposition)
            name = extra.get('name')
            transfer_encoding = headers.get('content-transfer-encoding')
            try_decode = transfer_encoding is not None and transfer_encoding in _supported_multipart_encodings
            filename = extra.get('filename')
            if filename is None:
                is_file = False
                container = []
                _write = container.append
                guard_memory = max_form_memory_size is not None
            else:
                content_type = headers.get('content-type')
                content_type = parse_options_header(
                    content_type)[0] or 'text/plain'
                is_file = True
                guard_memory = False
                if filename is not None:
                    filename = _fix_ie_filename(
                        _decode_unicode(filename, charset, errors))
                try:
                    content_length = int(headers['content-length'])
                except (KeyError, ValueError):
                    content_length = 0

                container = stream_factory(total_content_length, content_type,
                                           filename, content_length)
                _write = container.write
            buf = ''
            for line in iterator:
                if not line:
                    raise ValueError('unexpected end of stream')
                if line[:2] == '--':
                    terminator = line.rstrip()
                    if terminator in (next_part, last_part):
                        break
                if try_decode:
                    try:
                        line = line.decode(transfer_encoding)
                    except:
                        raise ValueError(
                            'could not decode transfer encoded chunk')

                if buf:
                    _write(buf)
                    buf = ''
                if line[-2:] == '\r\n':
                    buf = '\r\n'
                    cutoff = -2
                else:
                    buf = line[-1]
                    cutoff = -1
                _write(line[:cutoff])
                if guard_memory:
                    in_memory += len(line)
                    if in_memory > max_form_memory_size:
                        from werkzeug.exceptions import RequestEntityTooLarge
                        raise RequestEntityTooLarge()
            else:
                raise ValueError('unexpected end of part')

            if is_file:
                container.seek(0)
                files.append(
                    (name,
                     FileStorage(container, filename, name, content_type,
                                 content_length, headers)))
            else:
                form.append(
                    (name, _decode_unicode(''.join(container), charset,
                                           errors)))

    finally:
        file.exhaust()

    return (form, files)