code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def _ip_or_dns_name(val: str) -> x509.GeneralName:
"""Convert a string into either an x509.IPAddress or x509.DNSName object."""
try:
ip = ipaddress.ip_address(val)
except ValueError:
return x509.DNSName(val.encode("idna").decode())
else:
return x509.IPAddress(ip) | Convert a string into either an x509.IPAddress or x509.DNSName object. | _ip_or_dns_name | python | mitmproxy/mitmproxy | mitmproxy/addons/tlsconfig.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/addons/tlsconfig.py | MIT |
def go(self, offset: int) -> None:
"""
Go to a specified offset. Positive offests are from the beginning of
the view, negative from the end of the view, so that 0 is the first
flow, -1 is the last flow.
"""
if len(self) == 0:
return
if offset < 0:
... |
Go to a specified offset. Positive offests are from the beginning of
the view, negative from the end of the view, so that 0 is the first
flow, -1 is the last flow.
| go | python | mitmproxy/mitmproxy | mitmproxy/addons/view.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/addons/view.py | MIT |
def focus_next(self) -> None:
"""
Set focus to the next flow.
"""
if self.focus.index is not None:
idx = self.focus.index + 1
if self.inbounds(idx):
self.focus.flow = self[idx]
else:
pass |
Set focus to the next flow.
| focus_next | python | mitmproxy/mitmproxy | mitmproxy/addons/view.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/addons/view.py | MIT |
def focus_prev(self) -> None:
"""
Set focus to the previous flow.
"""
if self.focus.index is not None:
idx = self.focus.index - 1
if self.inbounds(idx):
self.focus.flow = self[idx]
else:
pass |
Set focus to the previous flow.
| focus_prev | python | mitmproxy/mitmproxy | mitmproxy/addons/view.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/addons/view.py | MIT |
def clear(self) -> None:
"""
Clears both the store and view.
"""
self._store.clear()
self._view.clear()
self.sig_view_refresh.send()
self.sig_store_refresh.send() |
Clears both the store and view.
| clear | python | mitmproxy/mitmproxy | mitmproxy/addons/view.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/addons/view.py | MIT |
def setvalue_toggle(self, flows: Sequence[mitmproxy.flow.Flow], key: str) -> None:
"""
Toggle a boolean value in the settings store, setting the value to
the string "true" or "false".
"""
updated = []
for f in flows:
current = self.settings[f].get("key", "fals... |
Toggle a boolean value in the settings store, setting the value to
the string "true" or "false".
| setvalue_toggle | python | mitmproxy/mitmproxy | mitmproxy/addons/view.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/addons/view.py | MIT |
def setvalue(
self, flows: Sequence[mitmproxy.flow.Flow], key: str, value: str
) -> None:
"""
Set a value in the settings store for the specified flows.
"""
updated = []
for f in flows:
self.settings[f][key] = value
updated.append(f)
ct... |
Set a value in the settings store for the specified flows.
| setvalue | python | mitmproxy/mitmproxy | mitmproxy/addons/view.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/addons/view.py | MIT |
def duplicate(self, flows: Sequence[mitmproxy.flow.Flow]) -> None:
"""
Duplicates the specified flows, and sets the focus to the first
duplicate.
"""
dups = [f.copy() for f in flows]
if dups:
self.add(dups)
self.focus.flow = dups[0]
log... |
Duplicates the specified flows, and sets the focus to the first
duplicate.
| duplicate | python | mitmproxy/mitmproxy | mitmproxy/addons/view.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/addons/view.py | MIT |
def remove(self, flows: Sequence[mitmproxy.flow.Flow]) -> None:
"""
Removes the flow from the underlying store and the view.
"""
for f in flows:
if f.id in self._store:
if f.killable:
f.kill()
if f in self._view:
... |
Removes the flow from the underlying store and the view.
| remove | python | mitmproxy/mitmproxy | mitmproxy/addons/view.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/addons/view.py | MIT |
def resolve(self, flow_spec: str) -> Sequence[mitmproxy.flow.Flow]:
"""
Resolve a flow list specification to an actual list of flows.
"""
if flow_spec == "@all":
return [i for i in self._store.values()]
if flow_spec == "@focus":
return [self.focus.flow] if... |
Resolve a flow list specification to an actual list of flows.
| resolve | python | mitmproxy/mitmproxy | mitmproxy/addons/view.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/addons/view.py | MIT |
def load_file(self, path: mitmproxy.types.Path) -> None:
"""
Load flows into the view, without processing them with addons.
"""
try:
with open(path, "rb") as f:
for i in io.FlowReader(f).stream():
# Do this to get a new ID, so we can load t... |
Load flows into the view, without processing them with addons.
| load_file | python | mitmproxy/mitmproxy | mitmproxy/addons/view.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/addons/view.py | MIT |
def add(self, flows: Sequence[mitmproxy.flow.Flow]) -> None:
"""
Adds a flow to the state. If the flow already exists, it is
ignored.
"""
for f in flows:
if f.id not in self._store:
self._store[f.id] = f
if self.filter(f):
... |
Adds a flow to the state. If the flow already exists, it is
ignored.
| add | python | mitmproxy/mitmproxy | mitmproxy/addons/view.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/addons/view.py | MIT |
def update(self, flows: Sequence[mitmproxy.flow.Flow]) -> None:
"""
Updates a list of flows. If flow is not in the state, it's ignored.
"""
for f in flows:
if f.id in self._store:
if self.filter(f):
if f not in self._view:
... |
Updates a list of flows. If flow is not in the state, it's ignored.
| update | python | mitmproxy/mitmproxy | mitmproxy/addons/view.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/addons/view.py | MIT |
def format_pairs(items: Iterable[tuple[TTextType, TTextType]]) -> Iterator[TViewLine]:
"""
Helper function that accepts a list of (k,v) pairs into a list of
[
("key", key )
("value", value)
]
where key is padded to a uniform width
"""
max_key_len = max((len(k[0]) for k in... |
Helper function that accepts a list of (k,v) pairs into a list of
[
("key", key )
("value", value)
]
where key is padded to a uniform width
| format_pairs | python | mitmproxy/mitmproxy | mitmproxy/contentviews/base.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/contentviews/base.py | MIT |
def format_text(text: TTextType) -> Iterator[TViewLine]:
"""
Helper function that transforms bytes into the view output format.
"""
for line in text.splitlines():
yield [("text", line)] |
Helper function that transforms bytes into the view output format.
| format_text | python | mitmproxy/mitmproxy | mitmproxy/contentviews/base.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/contentviews/base.py | MIT |
def prettify(
self,
data: bytes,
metadata: Metadata,
) -> str:
"""
Transform raw data into human-readable output.
May raise an exception (e.g. `ValueError`) if data cannot be prettified.
""" |
Transform raw data into human-readable output.
May raise an exception (e.g. `ValueError`) if data cannot be prettified.
| prettify | python | mitmproxy/mitmproxy | mitmproxy/contentviews/_api.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/contentviews/_api.py | MIT |
def render_priority(
self,
data: bytes,
metadata: Metadata,
) -> float:
"""
Return the priority of this view for rendering `data`.
If no particular view is chosen by the user, the view with the highest priority is selected.
If this view does not support the gi... |
Return the priority of this view for rendering `data`.
If no particular view is chosen by the user, the view with the highest priority is selected.
If this view does not support the given data, return a float < 0.
| render_priority | python | mitmproxy/mitmproxy | mitmproxy/contentviews/_api.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/contentviews/_api.py | MIT |
def reencode(
self,
prettified: str,
metadata: Metadata,
) -> bytes:
"""
Reencode the given (modified) `prettified` output into the original data format.
May raise an exception (e.g. `ValueError`) if reencoding failed.
""" |
Reencode the given (modified) `prettified` output into the original data format.
May raise an exception (e.g. `ValueError`) if reencoding failed.
| reencode | python | mitmproxy/mitmproxy | mitmproxy/contentviews/_api.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/contentviews/_api.py | MIT |
def get_view(
self, data: bytes, metadata: Metadata, view_name: str = "auto"
) -> Contentview:
"""
Get the best contentview for the given data and metadata.
If `view_name` is "auto" or the provided view not found,
the best matching contentview based on `render_priority` will... |
Get the best contentview for the given data and metadata.
If `view_name` is "auto" or the provided view not found,
the best matching contentview based on `render_priority` will be returned.
| get_view | python | mitmproxy/mitmproxy | mitmproxy/contentviews/_registry.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/contentviews/_registry.py | MIT |
def merge_repeated_keys(items: Iterable[tuple[str, str]]) -> dict[str, str | list[str]]:
"""
Helper function that takes a list of pairs and merges repeated keys.
"""
ret: dict[str, str | list[str]] = {}
for key, value in items:
if existing := ret.get(key):
if isinstance(existing,... |
Helper function that takes a list of pairs and merges repeated keys.
| merge_repeated_keys | python | mitmproxy/mitmproxy | mitmproxy/contentviews/_utils.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/contentviews/_utils.py | MIT |
def what(file, h=None):
"""Return the type of image contained in a file or byte stream."""
f = None
try:
if h is None:
if isinstance(file, (str, PathLike)):
f = open(file, 'rb')
h = f.read(32)
else:
location = file.tell()
... | Return the type of image contained in a file or byte stream. | what | python | mitmproxy/mitmproxy | mitmproxy/contrib/imghdr.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/contrib/imghdr.py | MIT |
def test_jpeg(h, f):
"""Test for JPEG data with JFIF or Exif markers; and raw JPEG."""
if h[6:10] in (b'JFIF', b'Exif'):
return 'jpeg'
elif h[:4] == b'\xff\xd8\xff\xdb':
return 'jpeg' | Test for JPEG data with JFIF or Exif markers; and raw JPEG. | test_jpeg | python | mitmproxy/mitmproxy | mitmproxy/contrib/imghdr.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/contrib/imghdr.py | MIT |
def test_pbm(h, f):
"""Verify if the image is a PBM (portable bitmap)."""
if len(h) >= 3 and \
h[0] == ord(b'P') and h[1] in b'14' and h[2] in b' \t\n\r':
return 'pbm' | Verify if the image is a PBM (portable bitmap). | test_pbm | python | mitmproxy/mitmproxy | mitmproxy/contrib/imghdr.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/contrib/imghdr.py | MIT |
def test_pgm(h, f):
"""Verify if the image is a PGM (portable graymap)."""
if len(h) >= 3 and \
h[0] == ord(b'P') and h[1] in b'25' and h[2] in b' \t\n\r':
return 'pgm' | Verify if the image is a PGM (portable graymap). | test_pgm | python | mitmproxy/mitmproxy | mitmproxy/contrib/imghdr.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/contrib/imghdr.py | MIT |
def test_ppm(h, f):
"""Verify if the image is a PPM (portable pixmap)."""
if len(h) >= 3 and \
h[0] == ord(b'P') and h[1] in b'36' and h[2] in b' \t\n\r':
return 'ppm' | Verify if the image is a PPM (portable pixmap). | test_ppm | python | mitmproxy/mitmproxy | mitmproxy/contrib/imghdr.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/contrib/imghdr.py | MIT |
def style(
text: t.Any,
fg: t.Optional[t.Union[int, t.Tuple[int, int, int], str]] = None,
bg: t.Optional[t.Union[int, t.Tuple[int, int, int], str]] = None,
bold: t.Optional[bool] = None,
dim: t.Optional[bool] = None,
underline: t.Optional[bool] = None,
overline: t.Optional[bool] = None,
... | Styles a text with ANSI styles and returns the new string. By
default the styling is self contained which means that at the end
of the string a reset code is issued. This can be prevented by
passing ``reset=False``.
Examples::
click.echo(click.style('Hello World!', fg='green'))
click.e... | style | python | mitmproxy/mitmproxy | mitmproxy/contrib/click/__init__.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/contrib/click/__init__.py | MIT |
def wire_type(self):
""""Wire type" is a part of the "key" that carries enough
information to parse value from the wire, i.e. read correct
amount of bytes, but there's not enough informaton to
interprete in unambiguously. For example, one can't clearly
disting... | "Wire type" is a part of the "key" that carries enough
information to parse value from the wire, i.e. read correct
amount of bytes, but there's not enough informaton to
interprete in unambiguously. For example, one can't clearly
distinguish 64-bit fixed-sized integers fro... | wire_type | python | mitmproxy/mitmproxy | mitmproxy/contrib/kaitaistruct/google_protobuf.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/contrib/kaitaistruct/google_protobuf.py | MIT |
def field_tag(self):
"""Identifies a field of protocol. One can look up symbolic
field name in a `.proto` file by this field tag.
"""
if hasattr(self, '_m_field_tag'):
return self._m_field_tag
self._m_field_tag = (self.key.value >> 3)
... | Identifies a field of protocol. One can look up symbolic
field name in a `.proto` file by this field tag.
| field_tag | python | mitmproxy/mitmproxy | mitmproxy/contrib/kaitaistruct/google_protobuf.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/contrib/kaitaistruct/google_protobuf.py | MIT |
def img(self):
"""Raw image data. Use `is_png` to determine whether this is an
embedded PNG file (true) or a DIB bitmap (false) and call a
relevant parser, if needed to parse image data further.
"""
if hasattr(self, '_m_img'):
return self._m_im... | Raw image data. Use `is_png` to determine whether this is an
embedded PNG file (true) or a DIB bitmap (false) and call a
relevant parser, if needed to parse image data further.
| img | python | mitmproxy/mitmproxy | mitmproxy/contrib/kaitaistruct/ico.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/contrib/kaitaistruct/ico.py | MIT |
def png_header(self):
"""Pre-reads first 8 bytes of the image to determine if it's an
embedded PNG file.
"""
if hasattr(self, '_m_png_header'):
return self._m_png_header
_pos = self._io.pos()
self._io.seek(self.ofs_img)
... | Pre-reads first 8 bytes of the image to determine if it's an
embedded PNG file.
| png_header | python | mitmproxy/mitmproxy | mitmproxy/contrib/kaitaistruct/ico.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/contrib/kaitaistruct/ico.py | MIT |
def is_png(self):
"""True if this image is in PNG format."""
if hasattr(self, '_m_is_png'):
return self._m_is_png
self._m_is_png = self.png_header == b"\x89\x50\x4E\x47\x0D\x0A\x1A\x0A"
return getattr(self, '_m_is_png', None) | True if this image is in PNG format. | is_png | python | mitmproxy/mitmproxy | mitmproxy/contrib/kaitaistruct/ico.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/contrib/kaitaistruct/ico.py | MIT |
def delay(self):
"""Time to display this frame, in seconds."""
if hasattr(self, '_m_delay'):
return self._m_delay
self._m_delay = (self.delay_num / (100.0 if self.delay_den == 0 else self.delay_den))
return getattr(self, '_m_delay', None) | Time to display this frame, in seconds. | delay | python | mitmproxy/mitmproxy | mitmproxy/contrib/kaitaistruct/png.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/contrib/kaitaistruct/png.py | MIT |
def has_next(self):
"""If true, then we have more bytes to read."""
if hasattr(self, '_m_has_next'):
return self._m_has_next
self._m_has_next = (self.b & 128) != 0
return getattr(self, '_m_has_next', None) | If true, then we have more bytes to read. | has_next | python | mitmproxy/mitmproxy | mitmproxy/contrib/kaitaistruct/vlq_base128_le.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/contrib/kaitaistruct/vlq_base128_le.py | MIT |
def value(self):
"""The 7-bit (base128) numeric value chunk of this group."""
if hasattr(self, '_m_value'):
return self._m_value
self._m_value = (self.b & 127)
return getattr(self, '_m_value', None) | The 7-bit (base128) numeric value chunk of this group. | value | python | mitmproxy/mitmproxy | mitmproxy/contrib/kaitaistruct/vlq_base128_le.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/contrib/kaitaistruct/vlq_base128_le.py | MIT |
def value(self):
"""Resulting unsigned value as normal integer."""
if hasattr(self, '_m_value'):
return self._m_value
self._m_value = (((((((self.groups[0].value + ((self.groups[1].value << 7) if self.len >= 2 else 0)) + ((self.groups[2].value << 14) if self.len >= 3 else 0)) + ((se... | Resulting unsigned value as normal integer. | value | python | mitmproxy/mitmproxy | mitmproxy/contrib/kaitaistruct/vlq_base128_le.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/contrib/kaitaistruct/vlq_base128_le.py | MIT |
def value_signed(self):
"""
.. seealso::
Source - https://graphics.stanford.edu/~seander/bithacks.html#VariableSignExtend
"""
if hasattr(self, '_m_value_signed'):
return self._m_value_signed
self._m_value_signed = ((self.value ^ self.sign_bit) - self.sign_... |
.. seealso::
Source - https://graphics.stanford.edu/~seander/bithacks.html#VariableSignExtend
| value_signed | python | mitmproxy/mitmproxy | mitmproxy/contrib/kaitaistruct/vlq_base128_le.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/contrib/kaitaistruct/vlq_base128_le.py | MIT |
def _reduce_values(values: Sequence[VT]) -> VT:
"""
If a user accesses multidict["foo"], this method
reduces all values for "foo" to a single value that is returned.
For example, HTTP headers are folded, whereas we will just take
the first cookie we found with that name.
... |
If a user accesses multidict["foo"], this method
reduces all values for "foo" to a single value that is returned.
For example, HTTP headers are folded, whereas we will just take
the first cookie we found with that name.
| _reduce_values | python | mitmproxy/mitmproxy | mitmproxy/coretypes/multidict.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/coretypes/multidict.py | MIT |
def _kconv(key: KT) -> KT:
"""
This method converts a key to its canonical representation.
For example, HTTP headers are case-insensitive, so this method returns key.lower().
""" |
This method converts a key to its canonical representation.
For example, HTTP headers are case-insensitive, so this method returns key.lower().
| _kconv | python | mitmproxy/mitmproxy | mitmproxy/coretypes/multidict.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/coretypes/multidict.py | MIT |
def get_all(self, key: KT) -> list[VT]:
"""
Return the list of all values for a given key.
If that key is not in the MultiDict, the return value will be an empty list.
"""
key = self._kconv(key)
return [value for k, value in self.fields if self._kconv(k) == key] |
Return the list of all values for a given key.
If that key is not in the MultiDict, the return value will be an empty list.
| get_all | python | mitmproxy/mitmproxy | mitmproxy/coretypes/multidict.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/coretypes/multidict.py | MIT |
def set_all(self, key: KT, values: list[VT]) -> None:
"""
Remove the old values for a key and add new ones.
"""
key_kconv = self._kconv(key)
new_fields: list[tuple[KT, VT]] = []
for field in self.fields:
if self._kconv(field[0]) == key_kconv:
... |
Remove the old values for a key and add new ones.
| set_all | python | mitmproxy/mitmproxy | mitmproxy/coretypes/multidict.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/coretypes/multidict.py | MIT |
def insert(self, index: int, key: KT, value: VT) -> None:
"""
Insert an additional value for the given key at the specified position.
"""
item = (key, value)
self.fields = self.fields[:index] + (item,) + self.fields[index:] |
Insert an additional value for the given key at the specified position.
| insert | python | mitmproxy/mitmproxy | mitmproxy/coretypes/multidict.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/coretypes/multidict.py | MIT |
def items(self, multi: bool = False):
"""
Get all (key, value) tuples.
If `multi` is True, all `(key, value)` pairs will be returned.
If False, only one tuple per key is returned.
"""
if multi:
return self.fields
else:
return super().items... |
Get all (key, value) tuples.
If `multi` is True, all `(key, value)` pairs will be returned.
If False, only one tuple per key is returned.
| items | python | mitmproxy/mitmproxy | mitmproxy/coretypes/multidict.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/coretypes/multidict.py | MIT |
def convert_unicode(data: dict) -> dict:
"""
This method converts between Python 3 and Python 2 dumpfiles.
"""
data = _convert_dict_keys(data)
data = _convert_dict_vals(
data,
{
"type": True,
"id": True,
"request": {"first_line_format": True},
... |
This method converts between Python 3 and Python 2 dumpfiles.
| convert_unicode | python | mitmproxy/mitmproxy | mitmproxy/io/compat.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/io/compat.py | MIT |
def fix_headers(
request_headers: list[dict[str, str]] | list[tuple[str, str]],
) -> http.Headers:
"""Converts provided headers into (b"header-name", b"header-value") tuples"""
flow_headers: list[tuple[bytes, bytes]] = []
for header in request_headers:
# Applications that use the {"name":item,"v... | Converts provided headers into (b"header-name", b"header-value") tuples | fix_headers | python | mitmproxy/mitmproxy | mitmproxy/io/har.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/io/har.py | MIT |
def request_to_flow(request_json: dict) -> http.HTTPFlow:
"""
Creates a HTTPFlow object from a given entry in HAR file
"""
timestamp_start = datetime.fromisoformat(
request_json["startedDateTime"].replace("Z", "+00:00")
).timestamp()
timestamp_end = timestamp_start + request_json["time"... |
Creates a HTTPFlow object from a given entry in HAR file
| request_to_flow | python | mitmproxy/mitmproxy | mitmproxy/io/har.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/io/har.py | MIT |
def stream(self) -> Iterable[flow.Flow]:
"""
Yields Flow objects from the dump.
"""
if self.peek(4).startswith(
b"\xef\xbb\xbf{"
): # skip BOM, usually added by Fiddler
self.fo.read(3)
if self.peek(1).startswith(b"{"):
try:
... |
Yields Flow objects from the dump.
| stream | python | mitmproxy/mitmproxy | mitmproxy/io/io.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/io/io.py | MIT |
def read_flows_from_paths(paths) -> list[flow.Flow]:
"""
Given a list of filepaths, read all flows and return a list of them.
From a performance perspective, streaming would be advisable -
however, if there's an error with one of the files, we want it to be raised immediately.
Raises:
FlowR... |
Given a list of filepaths, read all flows and return a list of them.
From a performance perspective, streaming would be advisable -
however, if there's an error with one of the files, we want it to be raised immediately.
Raises:
FlowReadException, if any error occurs.
| read_flows_from_paths | python | mitmproxy/mitmproxy | mitmproxy/io/io.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/io/io.py | MIT |
def dumps(value: TSerializable) -> bytes:
"""
This function dumps a python object as a tnetstring.
"""
# This uses a deque to collect output fragments in reverse order,
# then joins them together at the end. It's measurably faster
# than creating all the intermediate strings.
q: collecti... |
This function dumps a python object as a tnetstring.
| dumps | python | mitmproxy/mitmproxy | mitmproxy/io/tnetstring.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/io/tnetstring.py | MIT |
def _rdumpq(q: collections.deque, size: int, value: TSerializable) -> int:
"""
Dump value as a tnetstring, to a deque instance, last chunks first.
This function generates the tnetstring representation of the given value,
pushing chunks of the output onto the given deque instance. It pushes
the las... |
Dump value as a tnetstring, to a deque instance, last chunks first.
This function generates the tnetstring representation of the given value,
pushing chunks of the output onto the given deque instance. It pushes
the last chunk first, then recursively generates more chunks.
When passed in the cur... | _rdumpq | python | mitmproxy/mitmproxy | mitmproxy/io/tnetstring.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/io/tnetstring.py | MIT |
def load(file_handle: BinaryIO) -> TSerializable:
"""load(file) -> object
This function reads a tnetstring from a file and parses it into a
python object. The file must support the read() method, and this
function promises not to read more data than necessary.
"""
# Read the length prefix one... | load(file) -> object
This function reads a tnetstring from a file and parses it into a
python object. The file must support the read() method, and this
function promises not to read more data than necessary.
| load | python | mitmproxy/mitmproxy | mitmproxy/io/tnetstring.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/io/tnetstring.py | MIT |
def pop(data: memoryview) -> tuple[TSerializable, memoryview]:
"""
This function parses a tnetstring into a python object.
It returns a tuple giving the parsed object and a string
containing any unparsed data from the end of the string.
"""
# Parse out data length, type and remaining string.
... |
This function parses a tnetstring into a python object.
It returns a tuple giving the parsed object and a string
containing any unparsed data from the end of the string.
| pop | python | mitmproxy/mitmproxy | mitmproxy/io/tnetstring.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/io/tnetstring.py | MIT |
def is_valid_host(host: AnyStr) -> bool:
"""
Checks if the passed bytes are a valid DNS hostname or an IPv4/IPv6 address.
"""
if isinstance(host, str):
try:
host_bytes = host.encode("idna")
except UnicodeError:
return False
else:
host_bytes = host
... |
Checks if the passed bytes are a valid DNS hostname or an IPv4/IPv6 address.
| is_valid_host | python | mitmproxy/mitmproxy | mitmproxy/net/check.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/check.py | MIT |
def decode(
encoded: None | str | bytes, encoding: str, errors: str = "strict"
) -> None | str | bytes:
"""
Decode the given input object
Returns:
The decoded value
Raises:
ValueError, if decoding fails.
"""
if encoded is None:
return None
encoding = encoding.lo... |
Decode the given input object
Returns:
The decoded value
Raises:
ValueError, if decoding fails.
| decode | python | mitmproxy/mitmproxy | mitmproxy/net/encoding.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/encoding.py | MIT |
def encode(
decoded: None | str | bytes, encoding, errors="strict"
) -> None | str | bytes:
"""
Encode the given input object
Returns:
The encoded value
Raises:
ValueError, if encoding fails.
"""
if decoded is None:
return None
encoding = encoding.lower()
g... |
Encode the given input object
Returns:
The encoded value
Raises:
ValueError, if encoding fails.
| encode | python | mitmproxy/mitmproxy | mitmproxy/net/encoding.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/encoding.py | MIT |
def get_free_port() -> int:
"""
Get a port that's free for both TCP and UDP.
This method never raises. If no free port can be found, 0 is returned.
"""
for _ in range(10):
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
... |
Get a port that's free for both TCP and UDP.
This method never raises. If no free port can be found, 0 is returned.
| get_free_port | python | mitmproxy/mitmproxy | mitmproxy/net/free_port.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/free_port.py | MIT |
def get_local_ip(reachable: str = "8.8.8.8") -> str | None:
"""
Get the default local outgoing IPv4 address without sending any packets.
This will fail if the target address is known to be unreachable.
We use Google DNS's IPv4 address as the default.
"""
# https://stackoverflow.com/questions/166... |
Get the default local outgoing IPv4 address without sending any packets.
This will fail if the target address is known to be unreachable.
We use Google DNS's IPv4 address as the default.
| get_local_ip | python | mitmproxy/mitmproxy | mitmproxy/net/local_ip.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/local_ip.py | MIT |
def get_local_ip6(reachable: str = "2001:4860:4860::8888") -> str | None:
"""
Get the default local outgoing IPv6 address without sending any packets.
This will fail if the target address is known to be unreachable.
We use Google DNS's IPv6 address as the default.
"""
s = None
try:
s... |
Get the default local outgoing IPv6 address without sending any packets.
This will fail if the target address is known to be unreachable.
We use Google DNS's IPv6 address as the default.
| get_local_ip6 | python | mitmproxy/mitmproxy | mitmproxy/net/local_ip.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/local_ip.py | MIT |
def parse(server_spec: str, default_scheme: str) -> ServerSpec:
"""
Parses a server mode specification, e.g.:
- http://example.com/
- example.org
- example.com:443
*Raises:*
- ValueError, if the server specification is invalid.
"""
m = server_spec_re.match(server_spec)
if n... |
Parses a server mode specification, e.g.:
- http://example.com/
- example.org
- example.com:443
*Raises:*
- ValueError, if the server specification is invalid.
| parse | python | mitmproxy/mitmproxy | mitmproxy/net/server_spec.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/server_spec.py | MIT |
def starts_like_tls_record(d: bytes) -> bool:
"""
Returns:
True, if the passed bytes could be the start of a TLS record
False, otherwise.
"""
# TLS ClientHello magic, works for SSLv3, TLSv1.0, TLSv1.1, TLSv1.2, and TLSv1.3
# http://www.moserware.com/2009/06/first-few-milliseconds-of-... |
Returns:
True, if the passed bytes could be the start of a TLS record
False, otherwise.
| starts_like_tls_record | python | mitmproxy/mitmproxy | mitmproxy/net/tls.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/tls.py | MIT |
def starts_like_dtls_record(d: bytes) -> bool:
"""
Returns:
True, if the passed bytes could be the start of a DTLS record
False, otherwise.
"""
# TLS ClientHello magic, works for DTLS 1.1, DTLS 1.2, and DTLS 1.3.
# https://www.rfc-editor.org/rfc/rfc4347#section-4.1
# https://www.... |
Returns:
True, if the passed bytes could be the start of a DTLS record
False, otherwise.
| starts_like_dtls_record | python | mitmproxy/mitmproxy | mitmproxy/net/tls.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/tls.py | MIT |
def unpack_from(buffer: bytes, offset: int) -> tuple[str, int]:
"""Converts RDATA into a domain name without pointer compression from a given offset and also returns the binary size."""
labels: list[str] = []
while True:
(size,) = _LABEL_SIZE.unpack_from(buffer, offset)
if size & _POINTER_IN... | Converts RDATA into a domain name without pointer compression from a given offset and also returns the binary size. | unpack_from | python | mitmproxy/mitmproxy | mitmproxy/net/dns/domain_names.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/dns/domain_names.py | MIT |
def unpack(buffer: bytes) -> str:
"""Converts RDATA into a domain name without pointer compression."""
name, length = unpack_from(buffer, 0)
if length != len(buffer):
raise struct.error(f"unpack requires a buffer of {length} bytes")
return name | Converts RDATA into a domain name without pointer compression. | unpack | python | mitmproxy/mitmproxy | mitmproxy/net/dns/domain_names.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/dns/domain_names.py | MIT |
def pack(name: str) -> bytes:
"""Converts a domain name into RDATA without pointer compression."""
buffer = bytearray()
if len(name) > 0:
for part in name.split("."):
label = part.encode("idna")
size = len(label)
if size == 0:
raise ValueError(f"do... | Converts a domain name into RDATA without pointer compression. | pack | python | mitmproxy/mitmproxy | mitmproxy/net/dns/domain_names.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/dns/domain_names.py | MIT |
def _unpack_params(data: bytes, offset: int) -> dict[int, bytes]:
"""Unpacks the service parameters from the given offset."""
params = {}
while offset < len(data):
param_type = struct.unpack("!H", data[offset : offset + 2])[0]
offset += 2
param_length = struct.unpack("!H", data[offse... | Unpacks the service parameters from the given offset. | _unpack_params | python | mitmproxy/mitmproxy | mitmproxy/net/dns/https_records.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/dns/https_records.py | MIT |
def unpack(data: bytes) -> HTTPSRecord:
"""
Unpacks HTTPS RDATA from byte data.
Raises:
struct.error if the record is malformed.
"""
offset = 0
# Priority (2 bytes)
priority = struct.unpack("!h", data[offset : offset + 2])[0]
offset += 2
# TargetName (variable length)
... |
Unpacks HTTPS RDATA from byte data.
Raises:
struct.error if the record is malformed.
| unpack | python | mitmproxy/mitmproxy | mitmproxy/net/dns/https_records.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/dns/https_records.py | MIT |
def _pack_params(params: dict[int, bytes]) -> bytes:
"""Converts the service parameters into the raw byte format"""
buffer = bytearray()
for k, v in params.items():
buffer.extend(struct.pack("!H", k))
buffer.extend(struct.pack("!H", len(v)))
buffer.extend(v)
return bytes(buffer... | Converts the service parameters into the raw byte format | _pack_params | python | mitmproxy/mitmproxy | mitmproxy/net/dns/https_records.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/dns/https_records.py | MIT |
def pack(record: HTTPSRecord) -> bytes:
"""Packs the HTTPS record into its bytes form."""
buffer = bytearray()
buffer.extend(struct.pack("!h", record.priority))
buffer.extend(domain_names.pack(record.target_name))
buffer.extend(_pack_params(record.params))
return bytes(buffer) | Packs the HTTPS record into its bytes form. | pack | python | mitmproxy/mitmproxy | mitmproxy/net/dns/https_records.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/dns/https_records.py | MIT |
def _read_until(s, start, term):
"""
Read until one of the characters in term is reached.
"""
if start == len(s):
return "", start + 1
for i in range(start, len(s)):
if s[i] in term:
return s[start:i], i
return s[start : i + 1], i + 1 |
Read until one of the characters in term is reached.
| _read_until | python | mitmproxy/mitmproxy | mitmproxy/net/http/cookies.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/cookies.py | MIT |
def _read_quoted_string(s, start):
"""
start: offset to the first quote of the string to be read
A sort of loose super-set of the various quoted string specifications.
RFC6265 disallows backslashes or double quotes within quoted strings.
Prior RFCs use backslashes to escape. This leaves us free to... |
start: offset to the first quote of the string to be read
A sort of loose super-set of the various quoted string specifications.
RFC6265 disallows backslashes or double quotes within quoted strings.
Prior RFCs use backslashes to escape. This leaves us free to apply
backslash escaping by default a... | _read_quoted_string | python | mitmproxy/mitmproxy | mitmproxy/net/http/cookies.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/cookies.py | MIT |
def _read_value(s, start, delims):
"""
Reads a value - the RHS of a token/value pair in a cookie.
"""
if start >= len(s):
return "", start
elif s[start] == '"':
return _read_quoted_string(s, start)
else:
return _read_until(s, start, delims) |
Reads a value - the RHS of a token/value pair in a cookie.
| _read_value | python | mitmproxy/mitmproxy | mitmproxy/net/http/cookies.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/cookies.py | MIT |
def _read_cookie_pairs(s, off=0):
"""
Read pairs of lhs=rhs values from Cookie headers.
off: start offset
"""
pairs = []
while True:
lhs, off = _read_key(s, off)
lhs = lhs.lstrip()
rhs = ""
if off < len(s) and s[off] == "=":
rhs, off = _read_value(s... |
Read pairs of lhs=rhs values from Cookie headers.
off: start offset
| _read_cookie_pairs | python | mitmproxy/mitmproxy | mitmproxy/net/http/cookies.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/cookies.py | MIT |
def _read_set_cookie_pairs(s: str, off=0) -> tuple[list[TPairs], int]:
"""
Read pairs of lhs=rhs values from SetCookie headers while handling multiple cookies.
off: start offset
specials: attributes that are treated specially
"""
cookies: list[TPairs] = []
pairs: TPairs = []
while True... |
Read pairs of lhs=rhs values from SetCookie headers while handling multiple cookies.
off: start offset
specials: attributes that are treated specially
| _read_set_cookie_pairs | python | mitmproxy/mitmproxy | mitmproxy/net/http/cookies.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/cookies.py | MIT |
def _format_pairs(pairs, specials=(), sep="; "):
"""
specials: A lower-cased list of keys that will not be quoted.
"""
vals = []
for k, v in pairs:
if v is None:
val = k
elif k.lower() not in specials and _has_special(v):
v = ESCAPE.sub(r"\\\1", v)
... |
specials: A lower-cased list of keys that will not be quoted.
| _format_pairs | python | mitmproxy/mitmproxy | mitmproxy/net/http/cookies.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/cookies.py | MIT |
def parse_set_cookie_header(line: str) -> list[TSetCookie]:
"""
Parse a Set-Cookie header value
Returns:
A list of (name, value, attrs) tuples, where attrs is a
CookieAttrs dict of attributes. No attempt is made to parse attribute
values - they are treated purely as strings.
"""... |
Parse a Set-Cookie header value
Returns:
A list of (name, value, attrs) tuples, where attrs is a
CookieAttrs dict of attributes. No attempt is made to parse attribute
values - they are treated purely as strings.
| parse_set_cookie_header | python | mitmproxy/mitmproxy | mitmproxy/net/http/cookies.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/cookies.py | MIT |
def refresh_set_cookie_header(c: str, delta: int) -> str:
"""
Args:
c: A Set-Cookie string
delta: Time delta in seconds
Returns:
A refreshed Set-Cookie string
Raises:
ValueError, if the cookie is invalid.
"""
cookies = parse_set_cookie_header(c)
for cookie in ... |
Args:
c: A Set-Cookie string
delta: Time delta in seconds
Returns:
A refreshed Set-Cookie string
Raises:
ValueError, if the cookie is invalid.
| refresh_set_cookie_header | python | mitmproxy/mitmproxy | mitmproxy/net/http/cookies.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/cookies.py | MIT |
def get_expiration_ts(cookie_attrs):
"""
Determines the time when the cookie will be expired.
Considering both 'expires' and 'max-age' parameters.
Returns: timestamp of when the cookie will expire.
None, if no expiration time is set.
"""
if "expires" in cookie_attrs:
e = e... |
Determines the time when the cookie will be expired.
Considering both 'expires' and 'max-age' parameters.
Returns: timestamp of when the cookie will expire.
None, if no expiration time is set.
| get_expiration_ts | python | mitmproxy/mitmproxy | mitmproxy/net/http/cookies.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/cookies.py | MIT |
def is_expired(cookie_attrs):
"""
Determines whether a cookie has expired.
Returns: boolean
"""
exp_ts = get_expiration_ts(cookie_attrs)
now_ts = time.time()
# If no expiration information was provided with the cookie
if exp_ts is None:
return False
else:
return ex... |
Determines whether a cookie has expired.
Returns: boolean
| is_expired | python | mitmproxy/mitmproxy | mitmproxy/net/http/cookies.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/cookies.py | MIT |
def group_cookies(pairs):
"""
Converts a list of pairs to a (name, value, attrs) for each cookie.
"""
if not pairs:
return []
cookie_list = []
# First pair is always a new cookie
name, value = pairs[0]
attrs = []
for k, v in pairs[1:]:
if k.lower() in _cookie_para... |
Converts a list of pairs to a (name, value, attrs) for each cookie.
| group_cookies | python | mitmproxy/mitmproxy | mitmproxy/net/http/cookies.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/cookies.py | MIT |
def parse_content_type(c: str) -> tuple[str, str, dict[str, str]] | None:
"""
A simple parser for content-type values. Returns a (type, subtype,
parameters) tuple, where type and subtype are strings, and parameters
is a dict. If the string could not be parsed, return None.
E.g. the following string... |
A simple parser for content-type values. Returns a (type, subtype,
parameters) tuple, where type and subtype are strings, and parameters
is a dict. If the string could not be parsed, return None.
E.g. the following string:
text/html; charset=UTF-8
Returns:
("text", "html", {"cha... | parse_content_type | python | mitmproxy/mitmproxy | mitmproxy/net/http/headers.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/headers.py | MIT |
def infer_content_encoding(content_type: str, content: bytes = b"") -> str:
"""
Infer the encoding of content from the content-type header.
"""
# Use the charset from the header if possible
parsed_content_type = parse_content_type(content_type)
enc = parsed_content_type[2].get("charset") if pars... |
Infer the encoding of content from the content-type header.
| infer_content_encoding | python | mitmproxy/mitmproxy | mitmproxy/net/http/headers.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/headers.py | MIT |
def decode_multipart(
content_type: str | None, content: bytes
) -> list[tuple[bytes, bytes]]:
"""
Takes a multipart boundary encoded string and returns list of (key, value) tuples.
"""
if content_type:
ct = headers.parse_content_type(content_type)
if not ct:
return []
... |
Takes a multipart boundary encoded string and returns list of (key, value) tuples.
| decode_multipart | python | mitmproxy/mitmproxy | mitmproxy/net/http/multipart.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/multipart.py | MIT |
def parse(url: str | bytes) -> tuple[bytes, bytes, int, bytes]:
"""
URL-parsing function that checks that
- port is an integer 0-65535
- host is a valid IDNA-encoded hostname with no null-bytes
- path is valid ASCII
Args:
A URL (as bytes or as unicode)
Returns:
... |
URL-parsing function that checks that
- port is an integer 0-65535
- host is a valid IDNA-encoded hostname with no null-bytes
- path is valid ASCII
Args:
A URL (as bytes or as unicode)
Returns:
A (scheme, host, port, path) tuple
Raises:
ValueError, if ... | parse | python | mitmproxy/mitmproxy | mitmproxy/net/http/url.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/url.py | MIT |
def unparse(scheme, host, port, path):
"""
Returns a URL string, constructed from the specified components.
"""
authority = hostport(scheme, host, port)
if isinstance(scheme, str):
return f"{scheme}://{authority}{path}"
else:
return b"%s://%s%s" % (scheme, authority, path) |
Returns a URL string, constructed from the specified components.
| unparse | python | mitmproxy/mitmproxy | mitmproxy/net/http/url.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/url.py | MIT |
def encode(s: Sequence[tuple[str, str]], similar_to: str | None = None) -> str:
"""
Takes a list of (key, value) tuples and returns a urlencoded string.
If similar_to is passed, the output is formatted similar to the provided urlencoded string.
"""
remove_trailing_equal = False
if similar_to:
... |
Takes a list of (key, value) tuples and returns a urlencoded string.
If similar_to is passed, the output is formatted similar to the provided urlencoded string.
| encode | python | mitmproxy/mitmproxy | mitmproxy/net/http/url.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/url.py | MIT |
def hostport(scheme: AnyStr, host: AnyStr, port: int) -> AnyStr:
"""
Returns the host component, with a port specification if needed.
"""
if default_port(scheme) == port:
return host
else:
if isinstance(host, bytes):
return b"%s:%d" % (host, port)
else:
... |
Returns the host component, with a port specification if needed.
| hostport | python | mitmproxy/mitmproxy | mitmproxy/net/http/url.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/url.py | MIT |
def parse_authority(authority: AnyStr, check: bool) -> tuple[str, int | None]:
"""Extract the host and port from host header/authority information
Raises:
ValueError, if check is True and the authority information is malformed.
"""
try:
if isinstance(authority, bytes):
m = _... | Extract the host and port from host header/authority information
Raises:
ValueError, if check is True and the authority information is malformed.
| parse_authority | python | mitmproxy/mitmproxy | mitmproxy/net/http/url.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/url.py | MIT |
def get_by_shortcut(s):
"""
Retrieve a user agent entry by shortcut.
"""
for i in UASTRINGS:
if s == i[1]:
return i |
Retrieve a user agent entry by shortcut.
| get_by_shortcut | python | mitmproxy/mitmproxy | mitmproxy/net/http/user_agents.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/user_agents.py | MIT |
def parse_content_length(value: str | bytes) -> int:
"""Parse a content-length header value, or raise a ValueError if it is invalid."""
if isinstance(value, str):
valid = bool(_valid_content_length_str.match(value))
else:
valid = bool(_valid_content_length.match(value))
if not valid:
... | Parse a content-length header value, or raise a ValueError if it is invalid. | parse_content_length | python | mitmproxy/mitmproxy | mitmproxy/net/http/validate.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/validate.py | MIT |
def parse_transfer_encoding(value: str | bytes) -> TransferEncoding:
"""Parse a transfer-encoding header value, or raise a ValueError if it is invalid or unknown."""
# guard against .lower() transforming non-ascii to ascii
if not value.isascii():
raise ValueError(f"invalid transfer-encoding header: ... | Parse a transfer-encoding header value, or raise a ValueError if it is invalid or unknown. | parse_transfer_encoding | python | mitmproxy/mitmproxy | mitmproxy/net/http/validate.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/validate.py | MIT |
def validate_headers(message: Message) -> None:
"""
Validate HTTP message headers to avoid request smuggling attacks.
Raises a ValueError if they are malformed.
"""
te = []
cl = []
for name, value in message.headers.fields:
if not _valid_header_name.match(name):
raise ... |
Validate HTTP message headers to avoid request smuggling attacks.
Raises a ValueError if they are malformed.
| validate_headers | python | mitmproxy/mitmproxy | mitmproxy/net/http/validate.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/validate.py | MIT |
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].... |
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.
| get_header_tokens | python | mitmproxy/mitmproxy | mitmproxy/net/http/http1/read.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/http1/read.py | MIT |
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.
If we don't have a Connection header, HTTP 1.1 connections are assumed
to be persistent.
"""
if "connection" in headers:
tokens = ge... |
Checks the message to see if the client connection should be closed
according to RFC 2616 Section 8.1.
If we don't have a Connection header, HTTP 1.1 connections are assumed
to be persistent.
| connection_close | python | mitmproxy/mitmproxy | mitmproxy/net/http/http1/read.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/http1/read.py | MIT |
def expected_http_body_size(
request: Request, response: Response | None = None
) -> int | None:
"""
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 ... |
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.
Raises:
ValueError, if the content-length or transfer-encoding hea... | expected_http_body_size | python | mitmproxy/mitmproxy | mitmproxy/net/http/http1/read.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/http1/read.py | MIT |
def _read_headers(lines: Iterable[bytes]) -> Headers:
"""
Read a set of headers.
Stop once a blank line is reached.
Returns:
A headers object
Raises:
exceptions.HttpSyntaxException
"""
ret: list[tuple[bytes, bytes]] = []
for line in lines:
if line[0] in b" \t":
... |
Read a set of headers.
Stop once a blank line is reached.
Returns:
A headers object
Raises:
exceptions.HttpSyntaxException
| _read_headers | python | mitmproxy/mitmproxy | mitmproxy/net/http/http1/read.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/http1/read.py | MIT |
def read_request_head(lines: list[bytes]) -> Request:
"""
Parse an HTTP request head (request line + headers) from an iterable of lines
Args:
lines: The input lines
Returns:
The HTTP request object (without body)
Raises:
ValueError: The input is malformed.
"""
host... |
Parse an HTTP request head (request line + headers) from an iterable of lines
Args:
lines: The input lines
Returns:
The HTTP request object (without body)
Raises:
ValueError: The input is malformed.
| read_request_head | python | mitmproxy/mitmproxy | mitmproxy/net/http/http1/read.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/http1/read.py | MIT |
def read_response_head(lines: list[bytes]) -> Response:
"""
Parse an HTTP response head (response line + headers) from an iterable of lines
Args:
lines: The input lines
Returns:
The HTTP response object (without body)
Raises:
ValueError: The input is malformed.
"""
... |
Parse an HTTP response head (response line + headers) from an iterable of lines
Args:
lines: The input lines
Returns:
The HTTP response object (without body)
Raises:
ValueError: The input is malformed.
| read_response_head | python | mitmproxy/mitmproxy | mitmproxy/net/http/http1/read.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/net/http/http1/read.py | MIT |
def lookup(address, port, s):
"""
Parse the pfctl state output s, to look up the destination host
matching the client (address, port).
Returns an (address, port) tuple, or None.
"""
# We may get an ipv4-mapped ipv6 address here, e.g. ::ffff:127.0.0.1.
# Those still appear as "127.0.0.1" in ... |
Parse the pfctl state output s, to look up the destination host
matching the client (address, port).
Returns an (address, port) tuple, or None.
| lookup | python | mitmproxy/mitmproxy | mitmproxy/platform/pf.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/platform/pf.py | MIT |
def recv(self) -> pydivert.Packet | None:
"""
Convenience function that receives a packet from the passed handler and handles error codes.
If the process has been shut down, None is returned.
"""
try:
return self.windivert.recv()
except OSError as e:
... |
Convenience function that receives a packet from the passed handler and handles error codes.
If the process has been shut down, None is returned.
| recv | python | mitmproxy/mitmproxy | mitmproxy/platform/windows.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/platform/windows.py | MIT |
def redirect_response(self, packet: pydivert.Packet):
"""
If the proxy responds to the client, let the client believe the target server sent the
packets.
"""
# print(" * Adjust proxy -> client")
client = (packet.dst_addr, packet.dst_port)
try:
packet.s... |
If the proxy responds to the client, let the client believe the target server sent the
packets.
| redirect_response | python | mitmproxy/mitmproxy | mitmproxy/platform/windows.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/platform/windows.py | MIT |
def connections():
"""List all TCP connections and the associated PIDs."""
connections = TcpConnectionTable()
connections.refresh()
for (ip, port), pid in connections.items():
print(f"{ip}:{port} -> {pid}") | List all TCP connections and the associated PIDs. | connections | python | mitmproxy/mitmproxy | mitmproxy/platform/windows.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/platform/windows.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.