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 stack_pos(self) -> str:
"""repr() for this layer and all its parent layers, only useful for debugging."""
try:
idx = self.context.layers.index(self)
except ValueError:
return repr(self)
else:
return " >> ".join(repr(x) for x in self.context.layers[... | repr() for this layer and all its parent layers, only useful for debugging. | stack_pos | python | mitmproxy/mitmproxy | mitmproxy/proxy/layer.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layer.py | MIT |
def __process(self, command_generator: CommandGenerator, send=None):
"""
Yield commands from a generator.
If a command is blocking, execution is paused and this function returns without
processing any further commands.
"""
try:
# Run ._handle_event to the next... |
Yield commands from a generator.
If a command is blocking, execution is paused and this function returns without
processing any further commands.
| __process | python | mitmproxy/mitmproxy | mitmproxy/proxy/layer.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layer.py | MIT |
def __continue(self, event: events.CommandCompleted):
"""
Continue processing events after being paused.
The tricky part here is that events in the event queue may trigger commands which again pause the execution,
so we may not be able to process the entire queue.
"""
ass... |
Continue processing events after being paused.
The tricky part here is that events in the event queue may trigger commands which again pause the execution,
so we may not be able to process the entire queue.
| __continue | python | mitmproxy/mitmproxy | mitmproxy/proxy/layer.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layer.py | MIT |
def _ask(self):
"""
Manually trigger a next_layer hook.
The only use at the moment is to make sure that the top layer is initialized.
"""
yield NextLayerHook(self)
# Has an addon decided on the next layer yet?
if self.layer:
if self.debug:
... |
Manually trigger a next_layer hook.
The only use at the moment is to make sure that the top layer is initialized.
| _ask | python | mitmproxy/mitmproxy | mitmproxy/proxy/layer.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layer.py | MIT |
def __init_subclass__(cls, **kwargs):
"""Register all subclasses so that make() finds them."""
# extract mode from Generic[Mode].
mode = get_args(cls.__orig_bases__[0])[0] # type: ignore
if not isinstance(mode, TypeVar):
assert issubclass(mode, mode_specs.ProxyMode)
... | Register all subclasses so that make() finds them. | __init_subclass__ | python | mitmproxy/mitmproxy | mitmproxy/proxy/mode_servers.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/mode_servers.py | MIT |
def parse(cls, spec: str) -> Self:
"""
Parse a proxy mode specification and return the corresponding `ProxyMode` instance.
"""
head, _, listen_at = spec.rpartition("@")
if not head:
head = listen_at
listen_at = ""
mode, _, data = head.partition(":... |
Parse a proxy mode specification and return the corresponding `ProxyMode` instance.
| parse | python | mitmproxy/mitmproxy | mitmproxy/proxy/mode_specs.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/mode_specs.py | MIT |
def listen_host(self, default: str | None = None) -> str:
"""
Return the address a server for this mode should listen on. This can be either directly
specified in the spec or taken from a user-configured global default (`options.listen_host`).
By default, return an empty string to listen... |
Return the address a server for this mode should listen on. This can be either directly
specified in the spec or taken from a user-configured global default (`options.listen_host`).
By default, return an empty string to listen on all hosts.
| listen_host | python | mitmproxy/mitmproxy | mitmproxy/proxy/mode_specs.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/mode_specs.py | MIT |
def listen_port(self, default: int | None = None) -> int | None:
"""
Return the port a server for this mode should listen on. This can be either directly
specified in the spec, taken from a user-configured global default (`options.listen_port`),
or from `ProxyMode.default_port`.
... |
Return the port a server for this mode should listen on. This can be either directly
specified in the spec, taken from a user-configured global default (`options.listen_port`),
or from `ProxyMode.default_port`.
May be `None` for modes that don't bind to a specific address, e.g. local re... | listen_port | python | mitmproxy/mitmproxy | mitmproxy/proxy/mode_specs.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/mode_specs.py | MIT |
async def handle_connection(self, connection: Connection) -> None:
"""
Handle a connection for its entire lifetime.
This means we read until EOF,
but then possibly also keep on waiting for our side of the connection to be closed.
"""
cancelled = None
reader = self... |
Handle a connection for its entire lifetime.
This means we read until EOF,
but then possibly also keep on waiting for our side of the connection to be closed.
| handle_connection | python | mitmproxy/mitmproxy | mitmproxy/proxy/server.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/server.py | MIT |
async def drain_writers(self):
"""
Drain all writers to create some backpressure. We won't continue reading until there's space available in our
write buffers, so if we cannot write fast enough our own read buffers run full and the TCP recv stream is throttled.
"""
async with sel... |
Drain all writers to create some backpressure. We won't continue reading until there's space available in our
write buffers, so if we cannot write fast enough our own read buffers run full and the TCP recv stream is throttled.
| drain_writers | python | mitmproxy/mitmproxy | mitmproxy/proxy/server.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/server.py | MIT |
def expect(*event_types):
"""
Only allow the given event type.
If another event is passed, an AssertionError is raised.
"""
def decorator(f):
if __debug__ is True:
@functools.wraps(f)
def _check_event_type(self, event: events.Event):
if isinstance(ev... |
Only allow the given event type.
If another event is passed, an AssertionError is raised.
| expect | python | mitmproxy/mitmproxy | mitmproxy/proxy/utils.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/utils.py | MIT |
def handshake_record_contents(data: bytes) -> Iterator[bytes]:
"""
Returns a generator that yields the bytes contained in each handshake record.
This will raise an error on the first non-handshake record, so fully exhausting this
generator is a bad idea.
"""
offset = 0
while True:
if... |
Returns a generator that yields the bytes contained in each handshake record.
This will raise an error on the first non-handshake record, so fully exhausting this
generator is a bad idea.
| handshake_record_contents | python | mitmproxy/mitmproxy | mitmproxy/proxy/layers/tls.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layers/tls.py | MIT |
def get_client_hello(data: bytes) -> bytes | None:
"""
Read all TLS records that contain the initial ClientHello.
Returns the raw handshake packet bytes, without TLS record headers.
"""
client_hello = b""
for d in handshake_record_contents(data):
client_hello += d
if len(client_h... |
Read all TLS records that contain the initial ClientHello.
Returns the raw handshake packet bytes, without TLS record headers.
| get_client_hello | python | mitmproxy/mitmproxy | mitmproxy/proxy/layers/tls.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layers/tls.py | MIT |
def parse_client_hello(data: bytes) -> ClientHello | None:
"""
Check if the supplied bytes contain a full ClientHello message,
and if so, parse it.
Returns:
- A ClientHello object on success
- None, if the TLS record is not complete
Raises:
- A ValueError, if the passed Cli... |
Check if the supplied bytes contain a full ClientHello message,
and if so, parse it.
Returns:
- A ClientHello object on success
- None, if the TLS record is not complete
Raises:
- A ValueError, if the passed ClientHello is invalid
| parse_client_hello | python | mitmproxy/mitmproxy | mitmproxy/proxy/layers/tls.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layers/tls.py | MIT |
def get_dtls_client_hello(data: bytes) -> bytes | None:
"""
Read all DTLS records that contain the initial ClientHello.
Returns the raw handshake packet bytes, without TLS record headers.
"""
client_hello = b""
for d in dtls_handshake_record_contents(data):
client_hello += d
if l... |
Read all DTLS records that contain the initial ClientHello.
Returns the raw handshake packet bytes, without TLS record headers.
| get_dtls_client_hello | python | mitmproxy/mitmproxy | mitmproxy/proxy/layers/tls.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layers/tls.py | MIT |
def start_server_tls(self) -> layer.CommandGenerator[str | None]:
"""
We often need information from the upstream connection to establish TLS with the client.
For example, we need to check if the client does ALPN or not.
"""
if not self.server_tls_available:
return f"... |
We often need information from the upstream connection to establish TLS with the client.
For example, we need to check if the client does ALPN or not.
| start_server_tls | python | mitmproxy/mitmproxy | mitmproxy/proxy/layers/tls.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layers/tls.py | MIT |
def wait(self, event: events.Event) -> layer.CommandGenerator[None]:
"""
We wait for the current flow to be finished before parsing the next message,
as we may want to upgrade to WebSocket or plain TCP before that.
"""
assert self.stream_id
if isinstance(event, events.Dat... |
We wait for the current flow to be finished before parsing the next message,
as we may want to upgrade to WebSocket or plain TCP before that.
| wait | python | mitmproxy/mitmproxy | mitmproxy/proxy/layers/http/_http1.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layers/http/_http1.py | MIT |
def is_closed(self, stream_id: int) -> bool:
"""Check if a non-idle stream is closed"""
stream = self.h2_conn.streams.get(stream_id, None)
if (
stream is not None
and stream.state_machine.state is not h2.stream.StreamState.CLOSED
and self.h2_conn.state_machine... | Check if a non-idle stream is closed | is_closed | python | mitmproxy/mitmproxy | mitmproxy/proxy/layers/http/_http2.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layers/http/_http2.py | MIT |
def is_open_for_us(self, stream_id: int) -> bool:
"""Check if we can write to a non-idle stream."""
stream = self.h2_conn.streams.get(stream_id, None)
if (
stream is not None
and stream.state_machine.state
is not h2.stream.StreamState.HALF_CLOSED_LOCAL
... | Check if we can write to a non-idle stream. | is_open_for_us | python | mitmproxy/mitmproxy | mitmproxy/proxy/layers/http/_http2.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layers/http/_http2.py | MIT |
def handle_h2_event(self, event: h2.events.Event) -> CommandGenerator[bool]:
"""returns true if further processing should be stopped."""
if isinstance(event, h2.events.DataReceived):
state = self.streams.get(event.stream_id, None)
if state is StreamState.HEADERS_RECEIVED:
... | returns true if further processing should be stopped. | handle_h2_event | python | mitmproxy/mitmproxy | mitmproxy/proxy/layers/http/_http2.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layers/http/_http2.py | MIT |
def parse_h2_request_headers(
h2_headers: Sequence[tuple[bytes, bytes]],
) -> tuple[str, int, bytes, bytes, bytes, bytes, http.Headers]:
"""Split HTTP/2 pseudo-headers from the actual headers and parse them."""
pseudo_headers, headers = split_pseudo_headers(h2_headers)
try:
method: bytes = pseu... | Split HTTP/2 pseudo-headers from the actual headers and parse them. | parse_h2_request_headers | python | mitmproxy/mitmproxy | mitmproxy/proxy/layers/http/_http2.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layers/http/_http2.py | MIT |
def send_data(
self,
stream_id: int,
data: bytes,
end_stream: bool = False,
pad_length: None = None,
) -> None:
"""
Send data on a given stream.
In contrast to plain hyper-h2, this method will not raise if the data cannot be sent immediately.
... |
Send data on a given stream.
In contrast to plain hyper-h2, this method will not raise if the data cannot be sent immediately.
Data is split up and buffered internally.
| send_data | python | mitmproxy/mitmproxy | mitmproxy/proxy/layers/http/_http_h2.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layers/http/_http_h2.py | MIT |
def stream_window_updated(self, stream_id: int) -> bool:
"""
The window for a specific stream has updated. Send as much buffered data as possible.
"""
# If the stream has been reset in the meantime, we just clear the buffer.
try:
stream: h2.stream.H2Stream = self.stre... |
The window for a specific stream has updated. Send as much buffered data as possible.
| stream_window_updated | python | mitmproxy/mitmproxy | mitmproxy/proxy/layers/http/_http_h2.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layers/http/_http_h2.py | MIT |
def connection_window_updated(self) -> None:
"""
The connection window has updated. Send data from buffers in a round-robin fashion.
"""
sent_any_data = True
while sent_any_data:
sent_any_data = False
for stream_id in list(self.stream_buffers):
... |
The connection window has updated. Send data from buffers in a round-robin fashion.
| connection_window_updated | python | mitmproxy/mitmproxy | mitmproxy/proxy/layers/http/_http_h2.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layers/http/_http_h2.py | MIT |
def close_connection(
self,
error_code: int = QuicErrorCode.NO_ERROR,
frame_type: int | None = None,
reason_phrase: str = "",
) -> None:
"""Closes the underlying QUIC connection and ignores any incoming events."""
self._is_done = True
self._quic.close(error_c... | Closes the underlying QUIC connection and ignores any incoming events. | close_connection | python | mitmproxy/mitmproxy | mitmproxy/proxy/layers/http/_http_h3.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layers/http/_http_h3.py | MIT |
def end_stream(self, stream_id: int) -> None:
"""Ends the given stream if not already done so."""
stream = self._get_or_create_stream(stream_id)
if stream.headers_send_state != HeadersState.AFTER_TRAILERS:
super().send_data(stream_id, b"", end_stream=True)
stream.headers... | Ends the given stream if not already done so. | end_stream | python | mitmproxy/mitmproxy | mitmproxy/proxy/layers/http/_http_h3.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layers/http/_http_h3.py | MIT |
def get_open_stream_ids(self) -> Iterable[int]:
"""Iterates over all non-special open streams"""
return (
stream.stream_id
for stream in self._stream.values()
if (
stream.stream_type is None
and not (
stream.headers... | Iterates over all non-special open streams | get_open_stream_ids | python | mitmproxy/mitmproxy | mitmproxy/proxy/layers/http/_http_h3.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layers/http/_http_h3.py | MIT |
def has_sent_headers(self, stream_id: int) -> bool:
"""Indicates whether headers have been sent over the given stream."""
try:
return self._stream[stream_id].headers_send_state != HeadersState.INITIAL
except KeyError:
return False | Indicates whether headers have been sent over the given stream. | has_sent_headers | python | mitmproxy/mitmproxy | mitmproxy/proxy/layers/http/_http_h3.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layers/http/_http_h3.py | MIT |
def close_stream(
self, stream_id: int, error_code: int, stop_send: bool = True
) -> None:
"""Close a stream that hasn't been closed locally yet."""
if stream_id not in self._closed_streams:
self._closed_streams.add(stream_id)
stream = self._get_or_create_stream(stre... | Close a stream that hasn't been closed locally yet. | close_stream | python | mitmproxy/mitmproxy | mitmproxy/proxy/layers/http/_http_h3.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layers/http/_http_h3.py | MIT |
def send_headers(
self, stream_id: int, headers: Headers, end_stream: bool = False
) -> None:
"""Sends headers over the given stream."""
# ensure we haven't sent something before
stream = self._get_or_create_stream(stream_id)
if stream.headers_send_state != HeadersState.INIT... | Sends headers over the given stream. | send_headers | python | mitmproxy/mitmproxy | mitmproxy/proxy/layers/http/_http_h3.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layers/http/_http_h3.py | MIT |
def send_trailers(self, stream_id: int, trailers: Headers) -> None:
"""Sends trailers over the given stream and ends it."""
# ensure we got some headers first
stream = self._get_or_create_stream(stream_id)
if stream.headers_send_state != HeadersState.AFTER_HEADERS:
raise Fra... | Sends trailers over the given stream and ends it. | send_trailers | python | mitmproxy/mitmproxy | mitmproxy/proxy/layers/http/_http_h3.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layers/http/_http_h3.py | MIT |
def send_response(self, already_streamed: bool = False):
"""We have either consumed the entire response from the server or the response was set by an addon."""
assert self.flow.response
self.flow.response.timestamp_end = time.time()
is_websocket = (
self.flow.response.status... | We have either consumed the entire response from the server or the response was set by an addon. | send_response | python | mitmproxy/mitmproxy | mitmproxy/proxy/layers/http/__init__.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layers/http/__init__.py | MIT |
def quic_parse_client_hello_from_datagrams(
datagrams: list[bytes],
) -> Optional[ClientHello]:
"""
Check if the supplied bytes contain a full ClientHello message,
and if so, parse it.
Args:
- msgs: list of ClientHello fragments received from client
Returns:
- A ClientHello obj... |
Check if the supplied bytes contain a full ClientHello message,
and if so, parse it.
Args:
- msgs: list of ClientHello fragments received from client
Returns:
- A ClientHello object on success
- None, if the QUIC record is incomplete
Raises:
- A ValueError, if the... | quic_parse_client_hello_from_datagrams | python | mitmproxy/mitmproxy | mitmproxy/proxy/layers/quic/_client_hello_parser.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layers/quic/_client_hello_parser.py | MIT |
def close_stream_layer(
self, stream_layer: QuicStreamLayer, client: bool
) -> layer.CommandGenerator[None]:
"""Closes the incoming part of a connection."""
conn = stream_layer.client if client else stream_layer.server
conn.state &= ~connection.ConnectionState.CAN_READ
asser... | Closes the incoming part of a connection. | close_stream_layer | python | mitmproxy/mitmproxy | mitmproxy/proxy/layers/quic/_raw_layers.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layers/quic/_raw_layers.py | MIT |
def event_to_child(
self, child_layer: layer.Layer, event: events.Event
) -> layer.CommandGenerator[None]:
"""Forwards events to child layers and translates commands."""
for command in child_layer.handle_event(event):
# intercept commands for streams connections
if (... | Forwards events to child layers and translates commands. | event_to_child | python | mitmproxy/mitmproxy | mitmproxy/proxy/layers/quic/_raw_layers.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layers/quic/_raw_layers.py | MIT |
def _handle_command(
self, command: commands.Command
) -> layer.CommandGenerator[None]:
"""Turns stream commands into aioquic connection invocations."""
if isinstance(command, QuicStreamCommand) and command.connection is self.conn:
assert self.quic
if isinstance(comma... | Turns stream commands into aioquic connection invocations. | _handle_command | python | mitmproxy/mitmproxy | mitmproxy/proxy/layers/quic/_stream_layers.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layers/quic/_stream_layers.py | MIT |
def tls_interact(self) -> layer.CommandGenerator[None]:
"""Retrieves all pending outgoing packets from aioquic and sends the data."""
# send all queued datagrams
assert self.quic
now = self._time()
for data, addr in self.quic.datagrams_to_send(now=now):
assert addr ... | Retrieves all pending outgoing packets from aioquic and sends the data. | tls_interact | python | mitmproxy/mitmproxy | mitmproxy/proxy/layers/quic/_stream_layers.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layers/quic/_stream_layers.py | MIT |
def error_code_to_str(error_code: int) -> str:
"""Returns the corresponding name of the given error code or a string containing its numeric value."""
try:
return H3ErrorCode(error_code).name
except ValueError:
try:
return QuicErrorCode(error_code).name
except ValueError:... | Returns the corresponding name of the given error code or a string containing its numeric value. | error_code_to_str | python | mitmproxy/mitmproxy | mitmproxy/proxy/layers/quic/_stream_layers.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/proxy/layers/quic/_stream_layers.py | MIT |
async def cycle(self, addon, f):
"""
Cycles the flow through the events for the flow. Stops if the flow
is intercepted.
"""
for evt in eventsequence.iterate(f):
await self.master.addons.invoke_addon(addon, evt)
if f.intercepted:
return |
Cycles the flow through the events for the flow. Stops if the flow
is intercepted.
| cycle | python | mitmproxy/mitmproxy | mitmproxy/test/taddons.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/test/taddons.py | MIT |
def configure(self, addon, **kwargs):
"""
A helper for testing configure methods. Modifies the registered
Options object with the given keyword arguments, then calls the
configure method on the addon with the updated value.
"""
if addon not in self.master.addons:
... |
A helper for testing configure methods. Modifies the registered
Options object with the given keyword arguments, then calls the
configure method on the addon with the updated value.
| configure | python | mitmproxy/mitmproxy | mitmproxy/test/taddons.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/test/taddons.py | MIT |
def script(self, path):
"""
Loads a script from path, and returns the enclosed addon.
"""
sc = script.Script(path, False)
return sc.addons[0] if sc.addons else None |
Loads a script from path, and returns the enclosed addon.
| script | python | mitmproxy/mitmproxy | mitmproxy/test/taddons.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/test/taddons.py | MIT |
def run(
master_cls: type[T],
make_parser: Callable[[options.Options], argparse.ArgumentParser],
arguments: Sequence[str],
extra: Callable[[Any], dict] | None = None,
) -> T: # pragma: no cover
"""
extra: Extra argument processing callable which returns a dict of
options.
"""
async... |
extra: Extra argument processing callable which returns a dict of
options.
| run | python | mitmproxy/mitmproxy | mitmproxy/tools/main.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/main.py | MIT |
def format_keyvals(
entries: Iterable[tuple[str, None | str | urwid.Widget]],
key_format: str = "key",
value_format: str = "text",
indent: int = 0,
) -> list[urwid.Columns]:
"""
Format a list of (key, value) tuples.
Args:
entries: The list to format. keys must be strings, values can... |
Format a list of (key, value) tuples.
Args:
entries: The list to format. keys must be strings, values can also be None or urwid widgets.
The latter makes it possible to use the result of format_keyvals() as a value.
key_format: The display attribute for the key.
value_forma... | format_keyvals | python | mitmproxy/mitmproxy | mitmproxy/tools/console/common.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/common.py | MIT |
def rle_append_beginning_modify(rle, a_r):
"""
Append (a, r) (unpacked from *a_r*) to BEGINNING of rle.
Merge with first run when possible
MODIFIES rle parameter contents. Returns None.
"""
a, r = a_r
if not rle:
rle[:] = [(a, r)]
else:
al, run = rle[0]
if a == a... |
Append (a, r) (unpacked from *a_r*) to BEGINNING of rle.
Merge with first run when possible
MODIFIES rle parameter contents. Returns None.
| rle_append_beginning_modify | python | mitmproxy/mitmproxy | mitmproxy/tools/console/common.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/common.py | MIT |
def format_flow(
f: flow.Flow,
*,
render_mode: RenderMode,
hostheader: bool = False, # pass options directly if we need more stuff from them
focused: bool = True,
) -> urwid.Widget:
"""
This functions calls the proper renderer depending on the flow type.
We also want to cache the render... |
This functions calls the proper renderer depending on the flow type.
We also want to cache the renderer output, so we extract all attributes
relevant for display and call the render with only that. This assures that rows
are updated if the flow is changed.
| format_flow | python | mitmproxy/mitmproxy | mitmproxy/tools/console/common.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/common.py | MIT |
def layout_cycle(self) -> None:
"""
Cycle through the console layout options.
"""
opts = self.layout_options()
off = self.layout_options().index(ctx.options.console_layout)
ctx.options.update(console_layout=opts[(off + 1) % len(opts)]) |
Cycle through the console layout options.
| layout_cycle | python | mitmproxy/mitmproxy | mitmproxy/tools/console/consoleaddons.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/consoleaddons.py | MIT |
def options_reset_current(self) -> None:
"""
Reset the current option in the options editor.
"""
fv = self.master.window.current("options")
if not fv:
raise exceptions.CommandError("Not viewing options.")
self.master.commands.call_strings("options.reset.one", ... |
Reset the current option in the options editor.
| options_reset_current | python | mitmproxy/mitmproxy | mitmproxy/tools/console/consoleaddons.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/consoleaddons.py | MIT |
def console_choose(
self,
prompt: str,
choices: Sequence[str],
cmd: mitmproxy.types.Cmd,
*args: mitmproxy.types.CmdArgs,
) -> None:
"""
Prompt the user to choose from a specified list of strings, then
invoke another command with all occurrences of {cho... |
Prompt the user to choose from a specified list of strings, then
invoke another command with all occurrences of {choice} replaced by
the choice the user made.
| console_choose | python | mitmproxy/mitmproxy | mitmproxy/tools/console/consoleaddons.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/consoleaddons.py | MIT |
def console_choose_cmd(
self,
prompt: str,
choicecmd: mitmproxy.types.Cmd,
subcmd: mitmproxy.types.Cmd,
*args: mitmproxy.types.CmdArgs,
) -> None:
"""
Prompt the user to choose from a list of strings returned by a
command, then invoke another command w... |
Prompt the user to choose from a list of strings returned by a
command, then invoke another command with all occurrences of {choice}
replaced by the choice the user made.
| console_choose_cmd | python | mitmproxy/mitmproxy | mitmproxy/tools/console/consoleaddons.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/consoleaddons.py | MIT |
def console_command(self, *command_str: str) -> None:
"""
Prompt the user to edit a command with a (possibly empty) starting value.
"""
quoted = " ".join(command_lexer.quote(x) for x in command_str)
if quoted:
quoted += " "
signals.status_prompt_command.send(p... |
Prompt the user to edit a command with a (possibly empty) starting value.
| console_command | python | mitmproxy/mitmproxy | mitmproxy/tools/console/consoleaddons.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/consoleaddons.py | MIT |
def console_command_confirm(
self,
prompt: str,
cmd: mitmproxy.types.Cmd,
*args: mitmproxy.types.CmdArgs,
) -> None:
"""
Prompt the user before running the specified command.
"""
def callback(opt):
if opt == "n":
return
... |
Prompt the user before running the specified command.
| console_command_confirm | python | mitmproxy/mitmproxy | mitmproxy/tools/console/consoleaddons.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/consoleaddons.py | MIT |
def console_command_set(self, option_name: str) -> None:
"""
Prompt the user to set an option.
"""
option_value = getattr(self.master.options, option_name, None) or ""
set_command = f"set {option_name} {option_value!r}"
cursor = len(set_command) - 1
signals.status... |
Prompt the user to set an option.
| console_command_set | python | mitmproxy/mitmproxy | mitmproxy/tools/console/consoleaddons.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/consoleaddons.py | MIT |
def bodyview(self, flow: flow.Flow, part: str) -> None:
"""
Spawn an external viewer for a flow request or response body based
on the detected MIME type. We use the mailcap system to find the
correct viewer, and fall back to the programs in $PAGER or $EDITOR
if necessary.
... |
Spawn an external viewer for a flow request or response body based
on the detected MIME type. We use the mailcap system to find the
correct viewer, and fall back to the programs in $PAGER or $EDITOR
if necessary.
| bodyview | python | mitmproxy/mitmproxy | mitmproxy/tools/console/consoleaddons.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/consoleaddons.py | MIT |
def edit_focus_options(self) -> Sequence[str]:
"""
Possible components for console.edit.focus.
"""
flow = self.master.view.focus.flow
focus_options = []
try:
view_name = self.master.commands.call("console.flowview.mode")
except CommandError:
... |
Possible components for console.edit.focus.
| edit_focus_options | python | mitmproxy/mitmproxy | mitmproxy/tools/console/consoleaddons.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/consoleaddons.py | MIT |
def edit_focus(self, flow_part: str) -> None:
"""
Edit a component of the currently focused flow.
"""
flow = self.master.view.focus.flow
# This shouldn't be necessary once this command is "console.edit @focus",
# but for now it is.
if not flow:
raise e... |
Edit a component of the currently focused flow.
| edit_focus | python | mitmproxy/mitmproxy | mitmproxy/tools/console/consoleaddons.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/consoleaddons.py | MIT |
def grideditor_save(self, path: mitmproxy.types.Path) -> None:
"""
Save data to file as a CSV.
"""
rows = self._grideditor().value
try:
with open(path, "w", newline="", encoding="utf8") as fp:
writer = csv.writer(fp)
for row in rows:
... |
Save data to file as a CSV.
| grideditor_save | python | mitmproxy/mitmproxy | mitmproxy/tools/console/consoleaddons.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/consoleaddons.py | MIT |
def flowview_mode_set(self, mode: str) -> None:
"""
Set the display mode for the current flow view.
"""
fv = self.master.window.current_window("flowview")
if not fv:
raise exceptions.CommandError("Not viewing a flow.")
idx = fv.body.tab_offset
if mode... |
Set the display mode for the current flow view.
| flowview_mode_set | python | mitmproxy/mitmproxy | mitmproxy/tools/console/consoleaddons.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/consoleaddons.py | MIT |
def flowview_mode(self) -> str:
"""
Get the display mode for the current flow view.
"""
fv = self.master.window.current_window("flowview")
if not fv:
raise exceptions.CommandError("Not viewing a flow.")
idx = fv.body.tab_offset
return self.master.comm... |
Get the display mode for the current flow view.
| flowview_mode | python | mitmproxy/mitmproxy | mitmproxy/tools/console/consoleaddons.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/consoleaddons.py | MIT |
def key_unbind_focus(self) -> None:
"""
Un-bind the shortcut key currently focused in the key binding viewer.
"""
b = self._keyfocus()
try:
self.master.keymap.remove(b.key, b.contexts)
except ValueError as v:
raise exceptions.CommandError(v) |
Un-bind the shortcut key currently focused in the key binding viewer.
| key_unbind_focus | python | mitmproxy/mitmproxy | mitmproxy/tools/console/consoleaddons.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/consoleaddons.py | MIT |
def key_edit_focus(self) -> None:
"""
Execute the currently focused key binding.
"""
b = self._keyfocus()
self.console_command(
"console.key.bind",
",".join(b.contexts),
b.key,
b.command,
) |
Execute the currently focused key binding.
| key_edit_focus | python | mitmproxy/mitmproxy | mitmproxy/tools/console/consoleaddons.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/consoleaddons.py | MIT |
def add(self, key: str, command: str, contexts: Sequence[str], help="") -> None:
"""
Add a key to the key map.
"""
self._check_contexts(contexts)
for b in self.bindings:
if b.key == key and b.command.strip() == command.strip():
b.contexts = sorted(lis... |
Add a key to the key map.
| add | python | mitmproxy/mitmproxy | mitmproxy/tools/console/keymap.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/keymap.py | MIT |
def remove(self, key: str, contexts: Sequence[str]) -> None:
"""
Remove a key from the key map.
"""
self._check_contexts(contexts)
for c in contexts:
b = self.get(c, key)
if b:
self.unbind(b)
b.contexts = [x for x in b.conte... |
Remove a key from the key map.
| remove | python | mitmproxy/mitmproxy | mitmproxy/tools/console/keymap.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/keymap.py | MIT |
def unbind(self, binding: Binding) -> None:
"""
Unbind also removes the binding from the list.
"""
for c in binding.contexts:
del self.keys[c][binding.keyspec()]
self.bindings = [b for b in self.bindings if b != binding]
self._on_change() |
Unbind also removes the binding from the list.
| unbind | python | mitmproxy/mitmproxy | mitmproxy/tools/console/keymap.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/keymap.py | MIT |
def handle(self, context: str, key: str) -> str | None:
"""
Returns the key if it has not been handled, or None.
"""
b = self.get(context, key) or self.get("global", key)
if b:
self.executor(b.command)
return None
return key |
Returns the key if it has not been handled, or None.
| handle | python | mitmproxy/mitmproxy | mitmproxy/tools/console/keymap.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/keymap.py | MIT |
def handle_only(self, context: str, key: str) -> str | None:
"""
Like handle, but ignores global bindings. Returns the key if it has
not been handled, or None.
"""
b = self.get(context, key)
if b:
self.executor(b.command)
return None
return... |
Like handle, but ignores global bindings. Returns the key if it has
not been handled, or None.
| handle_only | python | mitmproxy/mitmproxy | mitmproxy/tools/console/keymap.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/keymap.py | MIT |
def focus_changed(self):
"""
The view focus has changed. Layout objects should implement the API
rather than directly subscribing to events.
""" |
The view focus has changed. Layout objects should implement the API
rather than directly subscribing to events.
| focus_changed | python | mitmproxy/mitmproxy | mitmproxy/tools/console/layoutwidget.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/layoutwidget.py | MIT |
def layout_popping(self):
"""
We are just about to pop a window off the stack, or exit an overlay.
""" |
We are just about to pop a window off the stack, or exit an overlay.
| layout_popping | python | mitmproxy/mitmproxy | mitmproxy/tools/console/layoutwidget.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/layoutwidget.py | MIT |
def layout_pushed(self, prev):
"""
We have just pushed a window onto the stack.
""" |
We have just pushed a window onto the stack.
| layout_pushed | python | mitmproxy/mitmproxy | mitmproxy/tools/console/layoutwidget.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/layoutwidget.py | MIT |
def __init__(self, master, name, vals, vspace):
"""
vspace: how much vertical space to keep clear
"""
cols, rows = master.ui.get_cols_rows()
self.ge = grideditor.OptionsEditor(master, name, vals)
super().__init__(
urwid.AttrMap(
urwid.LineBox(u... |
vspace: how much vertical space to keep clear
| __init__ | python | mitmproxy/mitmproxy | mitmproxy/tools/console/overlay.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/overlay.py | MIT |
def shorten_message(
msg: tuple[str, str] | str, max_width: int
) -> list[tuple[str, str]]:
"""
Shorten message so that it fits into a single line in the statusbar.
"""
if isinstance(msg, tuple):
disp_attr, msg_text = msg
elif isinstance(msg, str):
msg_text = msg
disp_att... |
Shorten message so that it fits into a single line in the statusbar.
| shorten_message | python | mitmproxy/mitmproxy | mitmproxy/tools/console/statusbar.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/statusbar.py | MIT |
def sig_prompt_onekey(
self, prompt: str, keys: list[tuple[str, str]], callback: Callable[[str], None]
) -> None:
"""
Keys are a set of (word, key) tuples. The appropriate key in the
word is highlighted.
"""
signals.focus.send(section="footer")
parts = [prompt... |
Keys are a set of (word, key) tuples. The appropriate key in the
word is highlighted.
| sig_prompt_onekey | python | mitmproxy/mitmproxy | mitmproxy/tools/console/statusbar.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/statusbar.py | MIT |
def __init__(self, offset, content, attr, onclick):
"""
onclick is called on click with the tab offset as argument
"""
p = urwid.Text(content, align="center")
p = urwid.Padding(p, align="center", width=("relative", 100))
p = urwid.AttrMap(p, attr)
urwid.WidgetWrap... |
onclick is called on click with the tab offset as argument
| __init__ | python | mitmproxy/mitmproxy | mitmproxy/tools/console/tabs.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/tabs.py | MIT |
def top_widget(self):
"""
The current top widget - either a window or the active overlay.
"""
if self.overlay:
return self.overlay
return self.top_window() |
The current top widget - either a window or the active overlay.
| top_widget | python | mitmproxy/mitmproxy | mitmproxy/tools/console/window.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/window.py | MIT |
def pop(self, *args, **kwargs):
"""
Pop off the stack, return True if we're already at the top.
"""
if not self.overlay and len(self.stack) == 1:
return True
self.call("layout_popping")
if self.overlay:
self.overlay = None
else:
... |
Pop off the stack, return True if we're already at the top.
| pop | python | mitmproxy/mitmproxy | mitmproxy/tools/console/window.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/window.py | MIT |
def call(self, name, *args, **kwargs):
"""
Call a function on both the top window, and the overlay if there is
one. If the widget has a key_responder, we call the function on the
responder instead.
"""
getattr(self.top_window(), name)(*args, **kwargs)
if self.over... |
Call a function on both the top window, and the overlay if there is
one. If the widget has a key_responder, we call the function on the
responder instead.
| call | python | mitmproxy/mitmproxy | mitmproxy/tools/console/window.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/window.py | MIT |
def push(self, wname):
"""
Push a window onto the currently focused stack.
"""
self.focus_stack().push(wname)
self.refresh()
self.view_changed()
self.focus_changed() |
Push a window onto the currently focused stack.
| push | python | mitmproxy/mitmproxy | mitmproxy/tools/console/window.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/window.py | MIT |
def pop(self) -> None:
"""
Pop a window from the currently focused stack. If there is only one
window on the stack, this prompts for exit.
"""
if self.focus_stack().pop():
self.master.prompt_for_exit()
else:
self.refresh()
self.view_cha... |
Pop a window from the currently focused stack. If there is only one
window on the stack, this prompts for exit.
| pop | python | mitmproxy/mitmproxy | mitmproxy/tools/console/window.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/window.py | MIT |
def stacks_sorted_by_focus(self):
"""
Returns:
self.stacks, with the focused stack first.
"""
stacks = self.stacks.copy()
stacks.insert(0, stacks.pop(self.pane))
return stacks |
Returns:
self.stacks, with the focused stack first.
| stacks_sorted_by_focus | python | mitmproxy/mitmproxy | mitmproxy/tools/console/window.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/window.py | MIT |
def current(self, keyctx):
"""
Returns the active widget with a matching key context, including overlays.
If multiple stacks have an active widget with a matching key context,
the currently focused stack is preferred.
"""
for s in self.stacks_sorted_by_focus():
... |
Returns the active widget with a matching key context, including overlays.
If multiple stacks have an active widget with a matching key context,
the currently focused stack is preferred.
| current | python | mitmproxy/mitmproxy | mitmproxy/tools/console/window.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/window.py | MIT |
def current_window(self, keyctx):
"""
Returns the active window with a matching key context, ignoring overlays.
If multiple stacks have an active widget with a matching key context,
the currently focused stack is preferred.
"""
for s in self.stacks_sorted_by_focus():
... |
Returns the active window with a matching key context, ignoring overlays.
If multiple stacks have an active widget with a matching key context,
the currently focused stack is preferred.
| current_window | python | mitmproxy/mitmproxy | mitmproxy/tools/console/window.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/console/window.py | MIT |
def __init_subclass__(cls, **kwargs):
"""Automatically wrap all request handlers with `_require_auth`."""
for method in cls.SUPPORTED_METHODS:
method = method.lower()
fn = getattr(cls, method)
if fn is not tornado.web.RequestHandler._unimplemented_method:
... | Automatically wrap all request handlers with `_require_auth`. | __init_subclass__ | python | mitmproxy/mitmproxy | mitmproxy/tools/web/app.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/web/app.py | MIT |
def auth_fail(self, invalid_password: bool) -> None:
"""
Will be called when returning a 403.
May write a login form as the response.
""" |
Will be called when returning a 403.
May write a login form as the response.
| auth_fail | python | mitmproxy/mitmproxy | mitmproxy/tools/web/app.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/web/app.py | MIT |
def filecontents(self):
"""
Accept either a multipart/form file upload or just take the plain request body.
"""
if self.request.files:
return next(iter(self.request.files.values()))[0].body
else:
return self.request.body |
Accept either a multipart/form file upload or just take the plain request body.
| filecontents | python | mitmproxy/mitmproxy | mitmproxy/tools/web/app.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/web/app.py | MIT |
def save_static(path: pathlib.Path) -> None:
"""
Save the files for the static web view.
"""
# We want to overwrite the static files to keep track of the update.
if (path / "static").exists():
shutil.rmtree(str(path / "static"))
shutil.copytree(str(web_dir / "static"), str(path / "static... |
Save the files for the static web view.
| save_static | python | mitmproxy/mitmproxy | mitmproxy/tools/web/static_viewer.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/tools/web/static_viewer.py | MIT |
def set_task_debug_info(
task: asyncio.Task,
*,
name: str,
client: tuple | None = None,
) -> None:
"""Set debug info for an externally-spawned task."""
task.created = time.time() # type: ignore
if __debug__ is True and (test := os.environ.get("PYTEST_CURRENT_TEST", None)):
name = f"... | Set debug info for an externally-spawned task. | set_task_debug_info | python | mitmproxy/mitmproxy | mitmproxy/utils/asyncio_utils.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/utils/asyncio_utils.py | MIT |
def set_current_task_debug_info(
*,
name: str,
client: tuple | None = None,
) -> None:
"""Set debug info for the current task."""
task = asyncio.current_task()
assert task
set_task_debug_info(task, name=name, client=client) | Set debug info for the current task. | set_current_task_debug_info | python | mitmproxy/mitmproxy | mitmproxy/utils/asyncio_utils.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/utils/asyncio_utils.py | MIT |
def task_repr(task: asyncio.Task) -> str:
"""Get a task representation with debug info."""
name = task.get_name()
a: float = getattr(task, "created", 0)
if a:
age = f" (age: {time.time() - a:.0f}s)"
else:
age = ""
client = getattr(task, "client", "")
if client:
client... | Get a task representation with debug info. | task_repr | python | mitmproxy/mitmproxy | mitmproxy/utils/asyncio_utils.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/utils/asyncio_utils.py | MIT |
def setbit(byte, offset, value):
"""
Set a bit in a byte to 1 if value is truthy, 0 if not.
"""
if value:
return byte | (1 << offset)
else:
return byte & ~(1 << offset) |
Set a bit in a byte to 1 if value is truthy, 0 if not.
| setbit | python | mitmproxy/mitmproxy | mitmproxy/utils/bits.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/utils/bits.py | MIT |
def push(self, subpath):
"""
Change the data object to a path relative to the module.
"""
dirname = os.path.normpath(os.path.join(self.dirname, subpath))
ret = Data(self.name)
ret.dirname = dirname
return ret |
Change the data object to a path relative to the module.
| push | python | mitmproxy/mitmproxy | mitmproxy/utils/data.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/utils/data.py | MIT |
def path(self, path):
"""
Returns a path to the package data housed at 'path' under this
module.Path can be a path to a file, or to a directory.
This function will raise ValueError if the path does not exist.
"""
fullpath = os.path.normpath(os.path.join(self.dirname, pat... |
Returns a path to the package data housed at 'path' under this
module.Path can be a path to a file, or to a directory.
This function will raise ValueError if the path does not exist.
| path | python | mitmproxy/mitmproxy | mitmproxy/utils/data.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/utils/data.py | MIT |
def pretty_size(size: int) -> str:
"""Convert a number of bytes into a human-readable string.
len(return value) <= 5 always holds true.
"""
s: float = size # type cast for mypy
if s < 1024:
return f"{s}b"
for suffix in ["k", "m", "g", "t"]:
s /= 1024
if s < 99.95:
... | Convert a number of bytes into a human-readable string.
len(return value) <= 5 always holds true.
| pretty_size | python | mitmproxy/mitmproxy | mitmproxy/utils/human.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/utils/human.py | MIT |
def parse_size(s: str | None) -> int | None:
"""
Parse a size with an optional k/m/... suffix.
Invalid values raise a ValueError. For added convenience, passing `None` returns `None`.
"""
if s is None:
return None
try:
return int(s)
except ValueError:
pass
for i i... |
Parse a size with an optional k/m/... suffix.
Invalid values raise a ValueError. For added convenience, passing `None` returns `None`.
| parse_size | python | mitmproxy/mitmproxy | mitmproxy/utils/human.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/utils/human.py | MIT |
def format_address(address: tuple | None) -> str:
"""
This function accepts IPv4/IPv6 tuples and
returns the formatted address string with port number
"""
if address is None:
return "<no address>"
try:
host = ipaddress.ip_address(address[0])
if host.is_unspecified:
... |
This function accepts IPv4/IPv6 tuples and
returns the formatted address string with port number
| format_address | python | mitmproxy/mitmproxy | mitmproxy/utils/human.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/utils/human.py | MIT |
def make_weak_ref(obj: Any) -> weakref.ReferenceType:
"""
Like weakref.ref(), but using weakref.WeakMethod for bound methods.
"""
if hasattr(obj, "__self__"):
return cast(weakref.ref, weakref.WeakMethod(obj))
else:
return weakref.ref(obj) |
Like weakref.ref(), but using weakref.WeakMethod for bound methods.
| make_weak_ref | python | mitmproxy/mitmproxy | mitmproxy/utils/signals.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/utils/signals.py | MIT |
def window(
iterator: Iterable[T], behind: int = 0, ahead: int = 0
) -> Iterator[tuple[T | None, ...]]:
"""
Sliding window for an iterator.
Example:
>>> for prev, i, nxt in window(range(10), 1, 1):
>>> print(prev, i, nxt)
None 0 1
0 1 2
1 2 3
2 3 Non... |
Sliding window for an iterator.
Example:
>>> for prev, i, nxt in window(range(10), 1, 1):
>>> print(prev, i, nxt)
None 0 1
0 1 2
1 2 3
2 3 None
| window | python | mitmproxy/mitmproxy | mitmproxy/utils/sliding_window.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/utils/sliding_window.py | MIT |
def parse_spec(option: str) -> tuple[flowfilter.TFilter, str, str]:
"""
Parse strings in the following format:
[/flow-filter]/subject/replacement
"""
sep, rem = option[0], option[1:]
parts = rem.split(sep, 2)
if len(parts) == 2:
subject, replacement = parts
return flowf... |
Parse strings in the following format:
[/flow-filter]/subject/replacement
| parse_spec | python | mitmproxy/mitmproxy | mitmproxy/utils/spec.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/utils/spec.py | MIT |
def escape_control_characters(text: str, keep_spacing=True) -> str:
"""
Replace all unicode C1 control characters from the given text with a single "."
Args:
keep_spacing: If True, tabs and newlines will not be replaced.
"""
if not isinstance(text, str):
raise ValueError(f"text type... |
Replace all unicode C1 control characters from the given text with a single "."
Args:
keep_spacing: If True, tabs and newlines will not be replaced.
| escape_control_characters | python | mitmproxy/mitmproxy | mitmproxy/utils/strutils.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/utils/strutils.py | MIT |
def bytes_to_escaped_str(
data: bytes, keep_spacing: bool = False, escape_single_quotes: bool = False
) -> str:
"""
Take bytes and return a safe string that can be displayed to the user.
Single quotes are always escaped, double quotes are never escaped:
"'" + bytes_to_escaped_str(...) + "'"
... |
Take bytes and return a safe string that can be displayed to the user.
Single quotes are always escaped, double quotes are never escaped:
"'" + bytes_to_escaped_str(...) + "'"
gives a valid Python string.
Args:
keep_spacing: If True, tabs and newlines will not be escaped.
| bytes_to_escaped_str | python | mitmproxy/mitmproxy | mitmproxy/utils/strutils.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/utils/strutils.py | MIT |
def escaped_str_to_bytes(data: str) -> bytes:
"""
Take an escaped string and return the unescaped bytes equivalent.
Raises:
ValueError, if the escape sequence is invalid.
"""
if not isinstance(data, str):
raise ValueError(f"data must be str, but is {data.__class__.__name__}")
#... |
Take an escaped string and return the unescaped bytes equivalent.
Raises:
ValueError, if the escape sequence is invalid.
| escaped_str_to_bytes | python | mitmproxy/mitmproxy | mitmproxy/utils/strutils.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/utils/strutils.py | MIT |
def clean_hanging_newline(t):
"""
Many editors will silently add a newline to the final line of a
document (I'm looking at you, Vim). This function fixes this common
problem at the risk of removing a hanging newline in the rare cases
where the user actually intends it.
"""
if t and t[-1] == ... |
Many editors will silently add a newline to the final line of a
document (I'm looking at you, Vim). This function fixes this common
problem at the risk of removing a hanging newline in the rare cases
where the user actually intends it.
| clean_hanging_newline | python | mitmproxy/mitmproxy | mitmproxy/utils/strutils.py | https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/utils/strutils.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.