from __future__ import annotations import logging import os import shutil import sys import tempfile from email.message import Message from enum import IntEnum from io import BytesIO from numbers import Number from typing import TYPE_CHECKING from .decoders import Base64Decoder, QuotedPrintableDecoder from .exceptions import FileError, FormParserError, MultipartParseError, QuerystringParseError if TYPE_CHECKING: # pragma: no cover from typing import Callable, TypedDict class QuerystringCallbacks(TypedDict, total=False): on_field_start: Callable[[], None] on_field_name: Callable[[bytes, int, int], None] on_field_data: Callable[[bytes, int, int], None] on_field_end: Callable[[], None] on_end: Callable[[], None] class OctetStreamCallbacks(TypedDict, total=False): on_start: Callable[[], None] on_data: Callable[[bytes, int, int], None] on_end: Callable[[], None] class MultipartCallbacks(TypedDict, total=False): on_part_begin: Callable[[], None] on_part_data: Callable[[bytes, int, int], None] on_part_end: Callable[[], None] on_headers_begin: Callable[[], None] on_header_field: Callable[[bytes, int, int], None] on_header_value: Callable[[bytes, int, int], None] on_header_end: Callable[[], None] on_headers_finished: Callable[[], None] on_end: Callable[[], None] class FormParserConfig(TypedDict, total=False): UPLOAD_DIR: str | None UPLOAD_KEEP_FILENAME: bool UPLOAD_KEEP_EXTENSIONS: bool UPLOAD_ERROR_ON_BAD_CTE: bool MAX_MEMORY_FILE_SIZE: int MAX_BODY_SIZE: float class FileConfig(TypedDict, total=False): UPLOAD_DIR: str | None UPLOAD_DELETE_TMP: bool UPLOAD_KEEP_FILENAME: bool UPLOAD_KEEP_EXTENSIONS: bool MAX_MEMORY_FILE_SIZE: int # Unique missing object. _missing = object() class QuerystringState(IntEnum): """Querystring parser states. These are used to keep track of the state of the parser, and are used to determine what to do when new data is encountered. """ BEFORE_FIELD = 0 FIELD_NAME = 1 FIELD_DATA = 2 class MultipartState(IntEnum): """Multipart parser states. These are used to keep track of the state of the parser, and are used to determine what to do when new data is encountered. """ START = 0 START_BOUNDARY = 1 HEADER_FIELD_START = 2 HEADER_FIELD = 3 HEADER_VALUE_START = 4 HEADER_VALUE = 5 HEADER_VALUE_ALMOST_DONE = 6 HEADERS_ALMOST_DONE = 7 PART_DATA_START = 8 PART_DATA = 9 PART_DATA_END = 10 END = 11 # Flags for the multipart parser. FLAG_PART_BOUNDARY = 1 FLAG_LAST_BOUNDARY = 2 # Get constants. Since iterating over a str on Python 2 gives you a 1-length # string, but iterating over a bytes object on Python 3 gives you an integer, # we need to save these constants. CR = b"\r"[0] LF = b"\n"[0] COLON = b":"[0] SPACE = b" "[0] HYPHEN = b"-"[0] AMPERSAND = b"&"[0] SEMICOLON = b";"[0] LOWER_A = b"a"[0] LOWER_Z = b"z"[0] NULL = b"\x00"[0] # Lower-casing a character is different, because of the difference between # str on Py2, and bytes on Py3. Same with getting the ordinal value of a byte, # and joining a list of bytes together. # These functions abstract that. def lower_char(c): return c | 0x20 def ord_char(c): return c def join_bytes(b): return bytes(list(b)) def parse_options_header(value: str | bytes) -> tuple[bytes, dict[bytes, bytes]]: """ Parses a Content-Type header into a value in the following format: (content_type, {parameters}) """ # Uses email.message.Message to parse the header as described in PEP 594. # Ref: https://peps.python.org/pep-0594/#cgi if not value: return (b"", {}) # If we are passed bytes, we assume that it conforms to WSGI, encoding in latin-1. if isinstance(value, bytes): # pragma: no cover value = value.decode("latin-1") # For types assert isinstance(value, str), "Value should be a string by now" # If we have no options, return the string as-is. if ";" not in value: return (value.lower().strip().encode("latin-1"), {}) # Split at the first semicolon, to get our value and then options. # ctype, rest = value.split(b';', 1) message = Message() message["content-type"] = value params = message.get_params() # If there were no parameters, this would have already returned above assert params, "At least the content type value should be present" ctype = params.pop(0)[0].encode("latin-1") options = {} for param in params: key, value = param # If the value returned from get_params() is a 3-tuple, the last # element corresponds to the value. # See: https://docs.python.org/3/library/email.compat32-message.html if isinstance(value, tuple): value = value[-1] # If the value is a filename, we need to fix a bug on IE6 that sends # the full file path instead of the filename. if key == "filename": if value[1:3] == ":\\" or value[:2] == "\\\\": value = value.split("\\")[-1] options[key.encode("latin-1")] = value.encode("latin-1") return ctype, options class Field: """A Field object represents a (parsed) form field. It represents a single field with a corresponding name and value. The name that a :class:`Field` will be instantiated with is the same name that would be found in the following HTML:: This class defines two methods, :meth:`on_data` and :meth:`on_end`, that will be called when data is written to the Field, and when the Field is finalized, respectively. :param name: the name of the form field """ def __init__(self, name: str): self._name = name self._value: list[bytes] = [] # We cache the joined version of _value for speed. self._cache = _missing @classmethod def from_value(cls, name: str, value: bytes | None) -> Field: """Create an instance of a :class:`Field`, and set the corresponding value - either None or an actual value. This method will also finalize the Field itself. :param name: the name of the form field :param value: the value of the form field - either a bytestring or None """ f = cls(name) if value is None: f.set_none() else: f.write(value) f.finalize() return f def write(self, data: bytes) -> int: """Write some data into the form field. :param data: a bytestring """ return self.on_data(data) def on_data(self, data: bytes) -> int: """This method is a callback that will be called whenever data is written to the Field. :param data: a bytestring """ self._value.append(data) self._cache = _missing return len(data) def on_end(self) -> None: """This method is called whenever the Field is finalized.""" if self._cache is _missing: self._cache = b"".join(self._value) def finalize(self) -> None: """Finalize the form field.""" self.on_end() def close(self) -> None: """Close the Field object. This will free any underlying cache.""" # Free our value array. if self._cache is _missing: self._cache = b"".join(self._value) del self._value def set_none(self) -> None: """Some fields in a querystring can possibly have a value of None - for example, the string "foo&bar=&baz=asdf" will have a field with the name "foo" and value None, one with name "bar" and value "", and one with name "baz" and value "asdf". Since the write() interface doesn't support writing None, this function will set the field value to None. """ self._cache = None @property def field_name(self) -> str: """This property returns the name of the field.""" return self._name @property def value(self): """This property returns the value of the form field.""" if self._cache is _missing: self._cache = b"".join(self._value) return self._cache def __eq__(self, other: object) -> bool: if isinstance(other, Field): return self.field_name == other.field_name and self.value == other.value else: return NotImplemented def __repr__(self) -> str: if len(self.value) > 97: # We get the repr, and then insert three dots before the final # quote. v = repr(self.value[:97])[:-1] + "...'" else: v = repr(self.value) return "{}(field_name={!r}, value={})".format(self.__class__.__name__, self.field_name, v) class File: """This class represents an uploaded file. It handles writing file data to either an in-memory file or a temporary file on-disk, if the optional threshold is passed. There are some options that can be passed to the File to change behavior of the class. Valid options are as follows: .. list-table:: :widths: 15 5 5 30 :header-rows: 1 * - Name - Type - Default - Description * - UPLOAD_DIR - `str` - None - The directory to store uploaded files in. If this is None, a temporary file will be created in the system's standard location. * - UPLOAD_DELETE_TMP - `bool` - True - Delete automatically created TMP file * - UPLOAD_KEEP_FILENAME - `bool` - False - Whether or not to keep the filename of the uploaded file. If True, then the filename will be converted to a safe representation (e.g. by removing any invalid path segments), and then saved with the same name). Otherwise, a temporary name will be used. * - UPLOAD_KEEP_EXTENSIONS - `bool` - False - Whether or not to keep the uploaded file's extension. If False, the file will be saved with the default temporary extension (usually ".tmp"). Otherwise, the file's extension will be maintained. Note that this will properly combine with the UPLOAD_KEEP_FILENAME setting. * - MAX_MEMORY_FILE_SIZE - `int` - 1 MiB - The maximum number of bytes of a File to keep in memory. By default, the contents of a File are kept into memory until a certain limit is reached, after which the contents of the File are written to a temporary file. This behavior can be disabled by setting this value to an appropriately large value (or, for example, infinity, such as `float('inf')`. :param file_name: The name of the file that this :class:`File` represents :param field_name: The field name that uploaded this file. Note that this can be None, if, for example, the file was uploaded with Content-Type application/octet-stream :param config: The configuration for this File. See above for valid configuration keys and their corresponding values. """ def __init__(self, file_name: bytes | None, field_name: bytes | None = None, config: FileConfig = {}): # Save configuration, set other variables default. self.logger = logging.getLogger(__name__) self._config = config self._in_memory = True self._bytes_written = 0 self._fileobj = BytesIO() # Save the provided field/file name. self._field_name = field_name self._file_name = file_name # Our actual file name is None by default, since, depending on our # config, we may not actually use the provided name. self._actual_file_name = None # Split the extension from the filename. if file_name is not None: base, ext = os.path.splitext(file_name) self._file_base = base self._ext = ext @property def field_name(self) -> bytes | None: """The form field associated with this file. May be None if there isn't one, for example when we have an application/octet-stream upload. """ return self._field_name @property def file_name(self) -> bytes | None: """The file name given in the upload request.""" return self._file_name @property def actual_file_name(self): """The file name that this file is saved as. Will be None if it's not currently saved on disk. """ return self._actual_file_name @property def file_object(self): """The file object that we're currently writing to. Note that this will either be an instance of a :class:`io.BytesIO`, or a regular file object. """ return self._fileobj @property def size(self): """The total size of this file, counted as the number of bytes that currently have been written to the file. """ return self._bytes_written @property def in_memory(self) -> bool: """A boolean representing whether or not this file object is currently stored in-memory or on-disk. """ return self._in_memory def flush_to_disk(self) -> None: """If the file is already on-disk, do nothing. Otherwise, copy from the in-memory buffer to a disk file, and then reassign our internal file object to this new disk file. Note that if you attempt to flush a file that is already on-disk, a warning will be logged to this module's logger. """ if not self._in_memory: self.logger.warning("Trying to flush to disk when we're not in memory") return # Go back to the start of our file. self._fileobj.seek(0) # Open a new file. new_file = self._get_disk_file() # Copy the file objects. shutil.copyfileobj(self._fileobj, new_file) # Seek to the new position in our new file. new_file.seek(self._bytes_written) # Reassign the fileobject. old_fileobj = self._fileobj self._fileobj = new_file # We're no longer in memory. self._in_memory = False # Close the old file object. old_fileobj.close() def _get_disk_file(self): """This function is responsible for getting a file object on-disk for us.""" self.logger.info("Opening a file on disk") file_dir = self._config.get("UPLOAD_DIR") keep_filename = self._config.get("UPLOAD_KEEP_FILENAME", False) keep_extensions = self._config.get("UPLOAD_KEEP_EXTENSIONS", False) delete_tmp = self._config.get("UPLOAD_DELETE_TMP", True) # If we have a directory and are to keep the filename... if file_dir is not None and keep_filename: self.logger.info("Saving with filename in: %r", file_dir) # Build our filename. # TODO: what happens if we don't have a filename? fname = self._file_base if keep_extensions: fname = fname + self._ext path = os.path.join(file_dir, fname) try: self.logger.info("Opening file: %r", path) tmp_file = open(path, "w+b") except OSError: tmp_file = None self.logger.exception("Error opening temporary file") raise FileError("Error opening temporary file: %r" % path) else: # Build options array. # Note that on Python 3, tempfile doesn't support byte names. We # encode our paths using the default filesystem encoding. options = {} if keep_extensions: ext = self._ext if isinstance(ext, bytes): ext = ext.decode(sys.getfilesystemencoding()) options["suffix"] = ext if file_dir is not None: d = file_dir if isinstance(d, bytes): d = d.decode(sys.getfilesystemencoding()) options["dir"] = d options["delete"] = delete_tmp # Create a temporary (named) file with the appropriate settings. self.logger.info("Creating a temporary file with options: %r", options) try: tmp_file = tempfile.NamedTemporaryFile(**options) except OSError: self.logger.exception("Error creating named temporary file") raise FileError("Error creating named temporary file") fname = tmp_file.name # Encode filename as bytes. if isinstance(fname, str): fname = fname.encode(sys.getfilesystemencoding()) self._actual_file_name = fname return tmp_file def write(self, data: bytes): """Write some data to the File. :param data: a bytestring """ return self.on_data(data) def on_data(self, data: bytes): """This method is a callback that will be called whenever data is written to the File. :param data: a bytestring """ pos = self._fileobj.tell() bwritten = self._fileobj.write(data) # true file objects write returns None if bwritten is None: bwritten = self._fileobj.tell() - pos # If the bytes written isn't the same as the length, just return. if bwritten != len(data): self.logger.warning("bwritten != len(data) (%d != %d)", bwritten, len(data)) return bwritten # Keep track of how many bytes we've written. self._bytes_written += bwritten # If we're in-memory and are over our limit, we create a file. if ( self._in_memory and self._config.get("MAX_MEMORY_FILE_SIZE") is not None and (self._bytes_written > self._config.get("MAX_MEMORY_FILE_SIZE")) ): self.logger.info("Flushing to disk") self.flush_to_disk() # Return the number of bytes written. return bwritten def on_end(self) -> None: """This method is called whenever the Field is finalized.""" # Flush the underlying file object self._fileobj.flush() def finalize(self) -> None: """Finalize the form file. This will not close the underlying file, but simply signal that we are finished writing to the File. """ self.on_end() def close(self) -> None: """Close the File object. This will actually close the underlying file object (whether it's a :class:`io.BytesIO` or an actual file object). """ self._fileobj.close() def __repr__(self) -> str: return "{}(file_name={!r}, field_name={!r})".format(self.__class__.__name__, self.file_name, self.field_name) class BaseParser: """This class is the base class for all parsers. It contains the logic for calling and adding callbacks. A callback can be one of two different forms. "Notification callbacks" are callbacks that are called when something happens - for example, when a new part of a multipart message is encountered by the parser. "Data callbacks" are called when we get some sort of data - for example, part of the body of a multipart chunk. Notification callbacks are called with no parameters, whereas data callbacks are called with three, as follows:: data_callback(data, start, end) The "data" parameter is a bytestring (i.e. "foo" on Python 2, or b"foo" on Python 3). "start" and "end" are integer indexes into the "data" string that represent the data of interest. Thus, in a data callback, the slice `data[start:end]` represents the data that the callback is "interested in". The callback is not passed a copy of the data, since copying severely hurts performance. """ def __init__(self): self.logger = logging.getLogger(__name__) def callback(self, name: str, data=None, start=None, end=None): """This function calls a provided callback with some data. If the callback is not set, will do nothing. :param name: The name of the callback to call (as a string). :param data: Data to pass to the callback. If None, then it is assumed that the callback is a notification callback, and no parameters are given. :param end: An integer that is passed to the data callback. :param start: An integer that is passed to the data callback. """ name = "on_" + name func = self.callbacks.get(name) if func is None: return # Depending on whether we're given a buffer... if data is not None: # Don't do anything if we have start == end. if start is not None and start == end: return self.logger.debug("Calling %s with data[%d:%d]", name, start, end) func(data, start, end) else: self.logger.debug("Calling %s with no data", name) func() def set_callback(self, name: str, new_func): """Update the function for a callback. Removes from the callbacks dict if new_func is None. :param name: The name of the callback to call (as a string). :param new_func: The new function for the callback. If None, then the callback will be removed (with no error if it does not exist). """ if new_func is None: self.callbacks.pop("on_" + name, None) else: self.callbacks["on_" + name] = new_func def close(self): pass # pragma: no cover def finalize(self): pass # pragma: no cover def __repr__(self): return "%s()" % self.__class__.__name__ class OctetStreamParser(BaseParser): """This parser parses an octet-stream request body and calls callbacks when incoming data is received. Callbacks are as follows: .. list-table:: :widths: 15 10 30 :header-rows: 1 * - Callback Name - Parameters - Description * - on_start - None - Called when the first data is parsed. * - on_data - data, start, end - Called for each data chunk that is parsed. * - on_end - None - Called when the parser is finished parsing all data. :param callbacks: A dictionary of callbacks. See the documentation for :class:`BaseParser`. :param max_size: The maximum size of body to parse. Defaults to infinity - i.e. unbounded. """ def __init__(self, callbacks: OctetStreamCallbacks = {}, max_size=float("inf")): super().__init__() self.callbacks = callbacks self._started = False if not isinstance(max_size, Number) or max_size < 1: raise ValueError("max_size must be a positive number, not %r" % max_size) self.max_size = max_size self._current_size = 0 def write(self, data: bytes): """Write some data to the parser, which will perform size verification, and then pass the data to the underlying callback. :param data: a bytestring """ if not self._started: self.callback("start") self._started = True # Truncate data length. data_len = len(data) if (self._current_size + data_len) > self.max_size: # We truncate the length of data that we are to process. new_size = int(self.max_size - self._current_size) self.logger.warning( "Current size is %d (max %d), so truncating data length from %d to %d", self._current_size, self.max_size, data_len, new_size, ) data_len = new_size # Increment size, then callback, in case there's an exception. self._current_size += data_len self.callback("data", data, 0, data_len) return data_len def finalize(self) -> None: """Finalize this parser, which signals to that we are finished parsing, and sends the on_end callback. """ self.callback("end") def __repr__(self) -> str: return "%s()" % self.__class__.__name__ class QuerystringParser(BaseParser): """This is a streaming querystring parser. It will consume data, and call the callbacks given when it has data. .. list-table:: :widths: 15 10 30 :header-rows: 1 * - Callback Name - Parameters - Description * - on_field_start - None - Called when a new field is encountered. * - on_field_name - data, start, end - Called when a portion of a field's name is encountered. * - on_field_data - data, start, end - Called when a portion of a field's data is encountered. * - on_field_end - None - Called when the end of a field is encountered. * - on_end - None - Called when the parser is finished parsing all data. :param callbacks: A dictionary of callbacks. See the documentation for :class:`BaseParser`. :param strict_parsing: Whether or not to parse the body strictly. Defaults to False. If this is set to True, then the behavior of the parser changes as the following: if a field has a value with an equal sign (e.g. "foo=bar", or "foo="), it is always included. If a field has no equals sign (e.g. "...&name&..."), it will be treated as an error if 'strict_parsing' is True, otherwise included. If an error is encountered, then a :class:`multipart.exceptions.QuerystringParseError` will be raised. :param max_size: The maximum size of body to parse. Defaults to infinity - i.e. unbounded. """ state: QuerystringState def __init__(self, callbacks: QuerystringCallbacks = {}, strict_parsing: bool =