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 test_clear_cache(test_cache): """Make sure that we can clear the cache.""" import outlines store = list() @test_cache def f(x): store.append(1) return x # The size of `store` does not increase since # `f` is cached after the first run. f(1) store_size = len(sto...
Make sure that we can clear the cache.
test_clear_cache
python
dottxt-ai/outlines
tests/test_cache.py
https://github.com/dottxt-ai/outlines/blob/master/tests/test_cache.py
Apache-2.0
def test_version_upgrade_cache_invalidate(test_cache, mocker): """Ensure we can change the signature of a cached function if we upgrade the version""" import outlines.caching def simulate_restart_outlines(): # clearing in-memory lru_cache which returns the diskcache in # order to simulate ...
Ensure we can change the signature of a cached function if we upgrade the version
test_version_upgrade_cache_invalidate
python
dottxt-ai/outlines
tests/test_cache.py
https://github.com/dottxt-ai/outlines/blob/master/tests/test_cache.py
Apache-2.0
def test_cache_disabled_decorator(test_cache): """Ensure cache can be disabled in a local scope""" from outlines.caching import cache_disabled mock = unittest.mock.MagicMock() @test_cache def fn(): mock() return 1 # first call isn't cached fn() assert mock.call_count ...
Ensure cache can be disabled in a local scope
test_cache_disabled_decorator
python
dottxt-ai/outlines
tests/test_cache.py
https://github.com/dottxt-ai/outlines/blob/master/tests/test_cache.py
Apache-2.0
def test_render_jinja(): """Make sure that we can use basic Jinja2 syntax, and give examples of how we can use it for basic use cases. """ # Notice the newline after the end of the loop examples = ["one", "two"] prompt = render( """ {% for e in examples %} Example: {{e}}...
Make sure that we can use basic Jinja2 syntax, and give examples of how we can use it for basic use cases.
test_render_jinja
python
dottxt-ai/outlines
tests/test_templates.py
https://github.com/dottxt-ai/outlines/blob/master/tests/test_templates.py
Apache-2.0
def test_cfg_test_sample_valid_with_lark(sample_name): """assert the provided sample is valid (testing the test itself)""" from lark import Lark, UnexpectedToken grammar_name, grammar_str, sample = all_samples[sample_name] try: parser = Lark(grammar_str, parser="lalr", import_paths=[grammars.GR...
assert the provided sample is valid (testing the test itself)
test_cfg_test_sample_valid_with_lark
python
dottxt-ai/outlines
tests/fsm/test_cfg_guide.py
https://github.com/dottxt-ai/outlines/blob/master/tests/fsm/test_cfg_guide.py
Apache-2.0
def test_cfg_grammar_sample(request, sample_name, tokenizer_name, cleanup_lark_import): """Test whether CFG can generate the exact token sequence as tokenizer.encode(sample) produces""" # TODO: enable these tests once improvements are made if ( tokenizer_name != "tokenizer_character_level_byt5" ...
Test whether CFG can generate the exact token sequence as tokenizer.encode(sample) produces
test_cfg_grammar_sample
python
dottxt-ai/outlines
tests/fsm/test_cfg_guide.py
https://github.com/dottxt-ai/outlines/blob/master/tests/fsm/test_cfg_guide.py
Apache-2.0
def test_regex_final_state(): """Make sure that the FSM stays in the final state as we keep generating""" class MockTokenizer: vocabulary = {"`": 101, ".": 102, "\n": 103, "eos": 104} special_tokens = {"eos"} eos_token_id = 104 def convert_token_to_string(self, token): ...
Make sure that the FSM stays in the final state as we keep generating
test_regex_final_state
python
dottxt-ai/outlines
tests/fsm/test_guide.py
https://github.com/dottxt-ai/outlines/blob/master/tests/fsm/test_guide.py
Apache-2.0
def _reconstruct_fsms(fsm, fsms_to_trans_finals): """Reconstruct the original fsms for testing purposes""" reconstructed_fsms = [] for transitions, finals, state_map in fsms_to_trans_finals.values(): inv_state_map = {new: orig for orig, news in state_map.items() for new in news} states = set...
Reconstruct the original fsms for testing purposes
_reconstruct_fsms
python
dottxt-ai/outlines
tests/fsm/test_parsing.py
https://github.com/dottxt-ai/outlines/blob/master/tests/fsm/test_parsing.py
Apache-2.0
def test_fsm_to_trans_finals_reconstruction(): """Assert that _fsms_to_trans_finals is correct by reconstructing original fsms""" fsm0 = interegular.parse_pattern(r"abc").to_fsm() fsm1 = interegular.parse_pattern(r"XYZ").to_fsm() fsm2 = interegular.parse_pattern(r"12345").to_fsm() fsm, _fsms_to_tra...
Assert that _fsms_to_trans_finals is correct by reconstructing original fsms
test_fsm_to_trans_finals_reconstruction
python
dottxt-ai/outlines
tests/fsm/test_parsing.py
https://github.com/dottxt-ai/outlines/blob/master/tests/fsm/test_parsing.py
Apache-2.0
def pytest_collection_modifyitems(config, items): """ If mlxlm and Metal aren't available, skip mlxlm tests If CUDA isn't available, skip vllm and transformers_vision """ if not torch.cuda.is_available(): skip_marker = pytest.mark.skip( reason="Skipping test because CUDA is not a...
If mlxlm and Metal aren't available, skip mlxlm tests If CUDA isn't available, skip vllm and transformers_vision
pytest_collection_modifyitems
python
dottxt-ai/outlines
tests/generate/conftest.py
https://github.com/dottxt-ai/outlines/blob/master/tests/generate/conftest.py
Apache-2.0
def enforce_not_implemented(model_fixture, *task_names): """ Per `NOT_IMPLEMENTED`, mapping, if a model hasn't implemented a task, assert an NotImplementedError is raised. Otherwise, run normally """ NOT_IMPLEMENTED = { "stream": ["model_transformers_vision", "model_vllm"], "batch": ...
Per `NOT_IMPLEMENTED`, mapping, if a model hasn't implemented a task, assert an NotImplementedError is raised. Otherwise, run normally
enforce_not_implemented
python
dottxt-ai/outlines
tests/generate/test_generate.py
https://github.com/dottxt-ai/outlines/blob/master/tests/generate/test_generate.py
Apache-2.0
def get_inputs(fixture_name, batch_size=None): """Get generator kwargs, just the prompt by default, but include images for transformers_visian""" from io import BytesIO from urllib.request import urlopen from PIL import Image # type: ignore prompts = ["abcd", "efgh", "1234", "5678", "foo", "bar",...
Get generator kwargs, just the prompt by default, but include images for transformers_visian
get_inputs
python
dottxt-ai/outlines
tests/generate/test_generate.py
https://github.com/dottxt-ai/outlines/blob/master/tests/generate/test_generate.py
Apache-2.0
def test_generate_regex_batch(request, model_fixture, pattern): """Ensure batch requests work and fsm order is maintained""" model = request.getfixturevalue(model_fixture) generator = generate.regex(model, pattern) with enforce_not_implemented(model_fixture, "batch"): outputs = generator(**get_i...
Ensure batch requests work and fsm order is maintained
test_generate_regex_batch
python
dottxt-ai/outlines
tests/generate/test_generate.py
https://github.com/dottxt-ai/outlines/blob/master/tests/generate/test_generate.py
Apache-2.0
def test_byte_tokenizer_regression(repo, model_path, hf_tokenizer_uri): """Reproduce https://github.com/dottxt-ai/outlines/issues/820""" import llama_cpp model = models.llamacpp( repo, model_path, tokenizer=llama_cpp.llama_tokenizer.LlamaHFTokenizer.from_pretrained( hf_t...
Reproduce https://github.com/dottxt-ai/outlines/issues/820
test_byte_tokenizer_regression
python
dottxt-ai/outlines
tests/generate/test_integration_llamacpp.py
https://github.com/dottxt-ai/outlines/blob/master/tests/generate/test_integration_llamacpp.py
Apache-2.0
def test_llama_cpp_pre_tokenizer_remains_broken(): """If fails, llama.cpp pre-tokenizer is fixed -> revert #892, remove `with pytest.raises`""" repo = "Qwen/Qwen1.5-0.5B-Chat-GGUF" model_path = "*q2*.gguf" model = models.llamacpp(repo, model_path) with pytest.raises(RuntimeError): generate....
If fails, llama.cpp pre-tokenizer is fixed -> revert #892, remove `with pytest.raises`
test_llama_cpp_pre_tokenizer_remains_broken
python
dottxt-ai/outlines
tests/generate/test_integration_llamacpp.py
https://github.com/dottxt-ai/outlines/blob/master/tests/generate/test_integration_llamacpp.py
Apache-2.0
def test_tokenizer_vocabulary_decode_sanity(): """Assert the decoded newline token (198) is the same as the normalized vocab token""" import llama_cpp model = models.llamacpp( "bartowski/Meta-Llama-3-8B-Instruct-GGUF", "Meta-Llama-3-8B-Instruct-IQ1_M.gguf", tokenizer=llama_cpp.llama...
Assert the decoded newline token (198) is the same as the normalized vocab token
test_tokenizer_vocabulary_decode_sanity
python
dottxt-ai/outlines
tests/generate/test_integration_llamacpp.py
https://github.com/dottxt-ai/outlines/blob/master/tests/generate/test_integration_llamacpp.py
Apache-2.0
def test_no_length_constraint_when_unset(): """Assert that models.llamacpp doesn't have an implicit max_tokens preventing full sequence generation""" import llama_cpp model = models.llamacpp( repo_id="M4-ai/TinyMistral-248M-v2-Instruct-GGUF", filename="TinyMistral-248M-v2-Instruct.Q4_K_M.gg...
Assert that models.llamacpp doesn't have an implicit max_tokens preventing full sequence generation
test_no_length_constraint_when_unset
python
dottxt-ai/outlines
tests/generate/test_integration_llamacpp.py
https://github.com/dottxt-ai/outlines/blob/master/tests/generate/test_integration_llamacpp.py
Apache-2.0
def test_multi_image_text_gen(model, processor): """If the length of image tags and number of images we pass are > 1 and equal, we should yield a successful generation. """ conversation = [ { "role": "user", "content": [ {"type": "text", "text": "What do a...
If the length of image tags and number of images we pass are > 1 and equal, we should yield a successful generation.
test_multi_image_text_gen
python
dottxt-ai/outlines
tests/generate/test_integration_transformers_vision.py
https://github.com/dottxt-ai/outlines/blob/master/tests/generate/test_integration_transformers_vision.py
Apache-2.0
def test_mismatched_image_text_gen(model, processor): """If the length of image tags and number of images we pass are unequal, we should raise an error. """ conversation = [ { "role": "user", "content": [ {"type": "text", "text": "I'm passing 3 images, but...
If the length of image tags and number of images we pass are unequal, we should raise an error.
test_mismatched_image_text_gen
python
dottxt-ai/outlines
tests/generate/test_integration_transformers_vision.py
https://github.com/dottxt-ai/outlines/blob/master/tests/generate/test_integration_transformers_vision.py
Apache-2.0
def module_patch(path): """Patch functions that have the same name as the module in which they're implemented.""" target = path components = target.split(".") for i in range(len(components), 0, -1): try: # attempt to import the module imported = importlib.import_module("....
Patch functions that have the same name as the module in which they're implemented.
module_patch
python
dottxt-ai/outlines
tests/models/test_openai.py
https://github.com/dottxt-ai/outlines/blob/master/tests/models/test_openai.py
Apache-2.0
def patched_openai(completion, **oai_config): """Create a patched openai whose chat completions always returns `completion`""" with module_patch("outlines.models.openai.generate_chat") as mocked_generate_chat: mocked_generate_chat.return_value = completion, 1, 2 async_client = MagicMock(spec=Asy...
Create a patched openai whose chat completions always returns `completion`
patched_openai
python
dottxt-ai/outlines
tests/models/test_openai.py
https://github.com/dottxt-ai/outlines/blob/master/tests/models/test_openai.py
Apache-2.0
def load_images(img_names): """loads user images from given file(s)""" if img_names[0] == '': return {} for image_name in img_names: with open(image_name) as img: loaded_imgs = {} img_list = '' img_line = ' ' name = img.readline().replace('\n'...
loads user images from given file(s)
load_images
python
gelstudios/gitfiti
gitfiti.py
https://github.com/gelstudios/gitfiti/blob/master/gitfiti.py
MIT
def parse_contributions_calendar(contributions_calendar): """Yield daily counts extracted from the embedded contributions SVG.""" for line in contributions_calendar.splitlines(): # a valid line looks like this: # <rect width="11" height="11" x="-31" y="0" class="ContributionCalendar-day" data-da...
Yield daily counts extracted from the embedded contributions SVG.
parse_contributions_calendar
python
gelstudios/gitfiti
gitfiti.py
https://github.com/gelstudios/gitfiti/blob/master/gitfiti.py
MIT
def get_start_date(): """returns a datetime object for the first sunday after one year ago today at 12:00 noon""" today = datetime.today() date = datetime(today.year - 1, today.month, today.day, 12) weekday = datetime.weekday(date) while weekday < 6: date = date + timedelta(1) w...
returns a datetime object for the first sunday after one year ago today at 12:00 noon
get_start_date
python
gelstudios/gitfiti
gitfiti.py
https://github.com/gelstudios/gitfiti/blob/master/gitfiti.py
MIT
def generate_next_dates(start_date, offset=0): """generator that returns the next date, requires a datetime object as input. The offset is in weeks""" start = offset * 7 for i in itertools.count(start): yield start_date + timedelta(i)
generator that returns the next date, requires a datetime object as input. The offset is in weeks
generate_next_dates
python
gelstudios/gitfiti
gitfiti.py
https://github.com/gelstudios/gitfiti/blob/master/gitfiti.py
MIT
def save(output, filename): """Saves the list to a given filename""" with open(filename, 'w') as f: f.write(output) os.chmod(filename, 0o755) # add execute permissions
Saves the list to a given filename
save
python
gelstudios/gitfiti
gitfiti.py
https://github.com/gelstudios/gitfiti/blob/master/gitfiti.py
MIT
def align( transcript: Iterable[SingleSegment], model: torch.nn.Module, align_model_metadata: dict, audio: Union[str, np.ndarray, torch.Tensor], device: str, interpolate_method: str = "nearest", return_char_alignments: bool = False, print_progress: bool = False, combined_progress: bo...
Align phoneme recognition predictions to known transcription.
align
python
m-bain/whisperX
whisperx/alignment.py
https://github.com/m-bain/whisperX/blob/master/whisperx/alignment.py
BSD-2-Clause
def get_wildcard_emission(frame_emission, tokens, blank_id): """Processing token emission scores containing wildcards (vectorized version) Args: frame_emission: Emission probability vector for the current frame tokens: List of token indices blank_id: ID of the blank token Returns: ...
Processing token emission scores containing wildcards (vectorized version) Args: frame_emission: Emission probability vector for the current frame tokens: List of token indices blank_id: ID of the blank token Returns: tensor: Maximum probability score for each token position ...
get_wildcard_emission
python
m-bain/whisperX
whisperx/alignment.py
https://github.com/m-bain/whisperX/blob/master/whisperx/alignment.py
BSD-2-Clause
def backtrack_beam(trellis, emission, tokens, blank_id=0, beam_width=5): """Standard CTC beam search backtracking implementation. Args: trellis (torch.Tensor): The trellis (or lattice) of shape (T, N), where T is the number of time steps and N is the number of tokens (in...
Standard CTC beam search backtracking implementation. Args: trellis (torch.Tensor): The trellis (or lattice) of shape (T, N), where T is the number of time steps and N is the number of tokens (including the blank token). emission (torch.Tensor): The emission probabil...
backtrack_beam
python
m-bain/whisperX
whisperx/alignment.py
https://github.com/m-bain/whisperX/blob/master/whisperx/alignment.py
BSD-2-Clause
def load_audio(file: str, sr: int = SAMPLE_RATE) -> np.ndarray: """ Open an audio file and read as mono waveform, resampling as necessary Parameters ---------- file: str The audio file to open sr: int The sample rate to resample the audio if necessary Returns ------- ...
Open an audio file and read as mono waveform, resampling as necessary Parameters ---------- file: str The audio file to open sr: int The sample rate to resample the audio if necessary Returns ------- A NumPy array containing the audio waveform, in float32 dtype.
load_audio
python
m-bain/whisperX
whisperx/audio.py
https://github.com/m-bain/whisperX/blob/master/whisperx/audio.py
BSD-2-Clause
def pad_or_trim(array, length: int = N_SAMPLES, *, axis: int = -1): """ Pad or trim the audio array to N_SAMPLES, as expected by the encoder. """ if torch.is_tensor(array): if array.shape[axis] > length: array = array.index_select( dim=axis, index=torch.arange(length,...
Pad or trim the audio array to N_SAMPLES, as expected by the encoder.
pad_or_trim
python
m-bain/whisperX
whisperx/audio.py
https://github.com/m-bain/whisperX/blob/master/whisperx/audio.py
BSD-2-Clause
def mel_filters(device, n_mels: int) -> torch.Tensor: """ load the mel filterbank matrix for projecting STFT into a Mel spectrogram. Allows decoupling librosa dependency; saved using: np.savez_compressed( "mel_filters.npz", mel_80=librosa.filters.mel(sr=16000, n_fft=400, n_m...
load the mel filterbank matrix for projecting STFT into a Mel spectrogram. Allows decoupling librosa dependency; saved using: np.savez_compressed( "mel_filters.npz", mel_80=librosa.filters.mel(sr=16000, n_fft=400, n_mels=80), )
mel_filters
python
m-bain/whisperX
whisperx/audio.py
https://github.com/m-bain/whisperX/blob/master/whisperx/audio.py
BSD-2-Clause
def log_mel_spectrogram( audio: Union[str, np.ndarray, torch.Tensor], n_mels: int, padding: int = 0, device: Optional[Union[str, torch.device]] = None, ): """ Compute the log-Mel spectrogram of Parameters ---------- audio: Union[str, np.ndarray, torch.Tensor], shape = (*) Th...
Compute the log-Mel spectrogram of Parameters ---------- audio: Union[str, np.ndarray, torch.Tensor], shape = (*) The path to audio or either a NumPy array or Tensor containing the audio waveform in 16 kHz n_mels: int The number of Mel-frequency filters, only 80 is supported ...
log_mel_spectrogram
python
m-bain/whisperX
whisperx/audio.py
https://github.com/m-bain/whisperX/blob/master/whisperx/audio.py
BSD-2-Clause
def transcribe_task(args: dict, parser: argparse.ArgumentParser): """Transcription task to be called from CLI. Args: args: Dictionary of command-line arguments. parser: argparse.ArgumentParser object. """ # fmt: off model_name: str = args.pop("model") batch_size: int = args.pop...
Transcription task to be called from CLI. Args: args: Dictionary of command-line arguments. parser: argparse.ArgumentParser object.
transcribe_task
python
m-bain/whisperX
whisperx/transcribe.py
https://github.com/m-bain/whisperX/blob/master/whisperx/transcribe.py
BSD-2-Clause
def __call__(self, scores: SlidingWindowFeature) -> Annotation: """Binarize detection scores Parameters ---------- scores : SlidingWindowFeature Detection scores. Returns ------- active : Annotation Binarized scores. """ nu...
Binarize detection scores Parameters ---------- scores : SlidingWindowFeature Detection scores. Returns ------- active : Annotation Binarized scores.
__call__
python
m-bain/whisperX
whisperx/vads/pyannote.py
https://github.com/m-bain/whisperX/blob/master/whisperx/vads/pyannote.py
BSD-2-Clause
def apply(self, file: AudioFile, hook: Optional[Callable] = None) -> Annotation: """Apply voice activity detection Parameters ---------- file : AudioFile Processed file. hook : callable, optional Hook called after each major step of the pipeline with the ...
Apply voice activity detection Parameters ---------- file : AudioFile Processed file. hook : callable, optional Hook called after each major step of the pipeline with the following signature: hook("step_name", step_artefact, file=file) Return...
apply
python
m-bain/whisperX
whisperx/vads/pyannote.py
https://github.com/m-bain/whisperX/blob/master/whisperx/vads/pyannote.py
BSD-2-Clause
def __call__(self, audio: AudioFile, **kwargs): """use silero to get segments of speech""" # Only accept 16000 Hz for now. # Note: Silero models support both 8000 and 16000 Hz. Although other values are not directly supported, # multiples of 16000 (e.g. 32000 or 48000) are cast to 16000 ...
use silero to get segments of speech
__call__
python
m-bain/whisperX
whisperx/vads/silero.py
https://github.com/m-bain/whisperX/blob/master/whisperx/vads/silero.py
BSD-2-Clause
def all_markers(): "Create a new flow showing all marker values" for marker in emoji.emoji: ctx.master.commands.call( "view.flows.create", "get", f"https://example.com/{marker}" ) ctx.master.commands.call("flow.mark", [ctx.master.view[-1]], marker)
Create a new flow showing all marker values
all_markers
python
mitmproxy/mitmproxy
examples/contrib/all_markers.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/all_markers.py
MIT
def stringify_cookies(cookies: list[dict[str, str | None]]) -> str: """ Creates a cookie string from a list of cookie dicts. """ return "; ".join( [ f"{c['name']}={c['value']}" if c.get("value", None) is not None else f"{c['name']}" for c in cookie...
Creates a cookie string from a list of cookie dicts.
stringify_cookies
python
mitmproxy/mitmproxy
examples/contrib/http_manipulate_cookies.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/http_manipulate_cookies.py
MIT
def parse_cookies(cookie_string: str) -> list[dict[str, str | None]]: """ Parses a cookie string into a list of cookie dicts. """ return [ {"name": g[0], "value": g[1]} if len(g) == 2 else {"name": g[0], "value": None} for g in [ k.split("=", 1) for k in [c.strip() for c in c...
Parses a cookie string into a list of cookie dicts.
parse_cookies
python
mitmproxy/mitmproxy
examples/contrib/http_manipulate_cookies.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/http_manipulate_cookies.py
MIT
def request(flow: http.HTTPFlow) -> None: """Add a specific set of cookies to every request.""" # obtain any cookies from the request _req_cookies_str = flow.request.headers.get("cookie", "") req_cookies = parse_cookies(_req_cookies_str) # add our cookies to the original cookies from the request ...
Add a specific set of cookies to every request.
request
python
mitmproxy/mitmproxy
examples/contrib/http_manipulate_cookies.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/http_manipulate_cookies.py
MIT
def response(flow: http.HTTPFlow) -> None: """Remove a specific cookie from every response.""" set_cookies_str = flow.response.headers.get_all("set-cookie") # NOTE: According to docs, for use with the "Set-Cookie" and "Cookie" headers, either use `Response.cookies` or see `Headers.get_all`. set_cookies_...
Remove a specific cookie from every response.
response
python
mitmproxy/mitmproxy
examples/contrib/http_manipulate_cookies.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/http_manipulate_cookies.py
MIT
def transform_field(obj, path, func): """ Apply a transformation function `func` to a value under the specified `path` in the `obj` dictionary. """ for key in path[:-1]: if not (key in obj and obj[key]): return obj = obj[key] if pat...
Apply a transformation function `func` to a value under the specified `path` in the `obj` dictionary.
transform_field
python
mitmproxy/mitmproxy
examples/contrib/jsondump.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/jsondump.py
MIT
def convert_to_strings(cls, obj): """ Recursively convert all list/dict elements of type `bytes` into strings. """ if isinstance(obj, dict): return { cls.convert_to_strings(key): cls.convert_to_strings(value) for key, value in obj.items() ...
Recursively convert all list/dict elements of type `bytes` into strings.
convert_to_strings
python
mitmproxy/mitmproxy
examples/contrib/jsondump.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/jsondump.py
MIT
def dump(self, frame): """ Transform and dump (write / send) a data frame. """ for tfm in self.transformations: for field in tfm["fields"]: self.transform_field(frame, field, tfm["func"]) frame = self.convert_to_strings(frame) if self.outfile:...
Transform and dump (write / send) a data frame.
dump
python
mitmproxy/mitmproxy
examples/contrib/jsondump.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/jsondump.py
MIT
def configure(self, _): """ Determine the destination type and path, initialize the output transformation rules. """ self.encode = ctx.options.dump_encodecontent if ctx.options.dump_destination.startswith("http"): self.outfile = None self.url = ct...
Determine the destination type and path, initialize the output transformation rules.
configure
python
mitmproxy/mitmproxy
examples/contrib/jsondump.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/jsondump.py
MIT
def _search(self, flows: Sequence[flow.Flow], regex: str) -> None: """ Defines a command named "search" that matches the given regular expression against most parts of each request/response included in the selected flows. Usage: from the flow list view, type ":search" followed b...
Defines a command named "search" that matches the given regular expression against most parts of each request/response included in the selected flows. Usage: from the flow list view, type ":search" followed by a space, then a flow selection expression; e.g., "@shown", t...
_search
python
mitmproxy/mitmproxy
examples/contrib/search.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/search.py
MIT
def find_unclaimed_URLs(body, requestUrl): """Look for unclaimed URLs in script tags and log them if found""" def getValue(attrs: list[tuple[str, str]], attrName: str) -> str | None: for name, value in attrs: if attrName == name: return value return None class S...
Look for unclaimed URLs in script tags and log them if found
find_unclaimed_URLs
python
mitmproxy/mitmproxy
examples/contrib/xss_scanner.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/xss_scanner.py
MIT
def test_end_of_URL_injection( original_body: str, request_URL: str, cookies: Cookies ) -> VulnData: """Test the given URL for XSS via injection onto the end of the URL and log the XSS if found""" parsed_URL = urlparse(request_URL) path = parsed_URL.path if path != "" and path[-1] != "/": # ens...
Test the given URL for XSS via injection onto the end of the URL and log the XSS if found
test_end_of_URL_injection
python
mitmproxy/mitmproxy
examples/contrib/xss_scanner.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/xss_scanner.py
MIT
def test_referer_injection( original_body: str, request_URL: str, cookies: Cookies ) -> VulnData: """Test the given URL for XSS via injection into the referer and log the XSS if found""" body = requests.get( request_URL, headers={"referer": FULL_PAYLOAD}, cookies=cookies ).text.lower() x...
Test the given URL for XSS via injection into the referer and log the XSS if found
test_referer_injection
python
mitmproxy/mitmproxy
examples/contrib/xss_scanner.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/xss_scanner.py
MIT
def test_user_agent_injection( original_body: str, request_URL: str, cookies: Cookies ) -> VulnData: """Test the given URL for XSS via injection into the user agent and log the XSS if found""" body = requests.get( request_URL, headers={"User-Agent": FULL_PAYLOAD}, cookies=cookies ).text.lowe...
Test the given URL for XSS via injection into the user agent and log the XSS if found
test_user_agent_injection
python
mitmproxy/mitmproxy
examples/contrib/xss_scanner.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/xss_scanner.py
MIT
def test_query_injection(original_body: str, request_URL: str, cookies: Cookies): """Test the given URL for XSS via injection into URL queries and log the XSS if found""" parsed_URL = urlparse(request_URL) query_string = parsed_URL.query # queries is a list of parameters where each parameter is set ...
Test the given URL for XSS via injection into URL queries and log the XSS if found
test_query_injection
python
mitmproxy/mitmproxy
examples/contrib/xss_scanner.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/xss_scanner.py
MIT
def get_SQLi_data( new_body: str, original_body: str, request_URL: str, injection_point: str ) -> SQLiData | None: """Return a SQLiDict if there is a SQLi otherwise return None String String URL String -> (SQLiDict or None)""" # Regexes taken from Damn Small SQLi Scanner: https://github.com/stamparm/DSS...
Return a SQLiDict if there is a SQLi otherwise return None String String URL String -> (SQLiDict or None)
get_SQLi_data
python
mitmproxy/mitmproxy
examples/contrib/xss_scanner.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/xss_scanner.py
MIT
def inside_quote( qc: str, substring_bytes: bytes, text_index: int, body_bytes: bytes ) -> bool: """Whether the Numberth occurrence of the first string in the second string is inside quotes as defined by the supplied QuoteChar""" substring = substring_bytes.decode("utf-8") body = body_bytes.decode("...
Whether the Numberth occurrence of the first string in the second string is inside quotes as defined by the supplied QuoteChar
inside_quote
python
mitmproxy/mitmproxy
examples/contrib/xss_scanner.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/xss_scanner.py
MIT
def paths_to_text(html: str, string: str) -> list[str]: """Return list of Paths to a given str in the given HTML tree - Note that it does a BFS""" def remove_last_occurence_of_sub_string(string: str, substr: str) -> str: """Delete the last occurrence of substr from str String String -> Stri...
Return list of Paths to a given str in the given HTML tree - Note that it does a BFS
paths_to_text
python
mitmproxy/mitmproxy
examples/contrib/xss_scanner.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/xss_scanner.py
MIT
def remove_last_occurence_of_sub_string(string: str, substr: str) -> str: """Delete the last occurrence of substr from str String String -> String """ index = string.rfind(substr) return string[:index] + string[index + len(substr) :]
Delete the last occurrence of substr from str String String -> String
remove_last_occurence_of_sub_string
python
mitmproxy/mitmproxy
examples/contrib/xss_scanner.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/xss_scanner.py
MIT
def get_XSS_data( body: str | bytes, request_URL: str, injection_point: str ) -> XSSData | None: """Return a XSSDict if there is a XSS otherwise return None""" def in_script(text, index, body) -> bool: """Whether the Numberth occurrence of the first string in the second string is inside a s...
Return a XSSDict if there is a XSS otherwise return None
get_XSS_data
python
mitmproxy/mitmproxy
examples/contrib/xss_scanner.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/xss_scanner.py
MIT
def in_script(text, index, body) -> bool: """Whether the Numberth occurrence of the first string in the second string is inside a script tag""" paths = paths_to_text(body.decode("utf-8"), text.decode("utf-8")) try: path = paths[index] return "script" in path ...
Whether the Numberth occurrence of the first string in the second string is inside a script tag
in_script
python
mitmproxy/mitmproxy
examples/contrib/xss_scanner.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/xss_scanner.py
MIT
def in_HTML(text: bytes, index: int, body: bytes) -> bool: """Whether the Numberth occurrence of the first string in the second string is inside the HTML but not inside a script tag or part of a HTML attribute""" # if there is a < then lxml will interpret that as a tag, so only search fo...
Whether the Numberth occurrence of the first string in the second string is inside the HTML but not inside a script tag or part of a HTML attribute
in_HTML
python
mitmproxy/mitmproxy
examples/contrib/xss_scanner.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/xss_scanner.py
MIT
def inject_javascript_handler(html: str) -> bool: """Whether you can inject a Javascript:alert(0) as a link""" class injectJSHandlerHTMLParser(HTMLParser): injectJSHandler = False def handle_starttag(self, tag, attrs): for name, value in attrs: ...
Whether you can inject a Javascript:alert(0) as a link
inject_javascript_handler
python
mitmproxy/mitmproxy
examples/contrib/xss_scanner.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/xss_scanner.py
MIT
def __init__(self, filename: str, persistent: bool = False) -> None: """Initializes the mapping add-on Args: filename: str that provides the name of the file in which the urls and css selectors to mapped content is stored. persistent: bool that indicates whether ...
Initializes the mapping add-on Args: filename: str that provides the name of the file in which the urls and css selectors to mapped content is stored. persistent: bool that indicates whether to store all new content in the configuration file. Example: ...
__init__
python
mitmproxy/mitmproxy
examples/contrib/webscanner_helper/mapping.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/webscanner_helper/mapping.py
MIT
def replace( self, soup: BeautifulSoup, css_sel: str, replace: BeautifulSoup ) -> None: """Replaces the content of soup that matches the css selector with the given replace content.""" for content in soup.select(css_sel): self.logger.debug(f'replace "{content}" with "{replace}"')...
Replaces the content of soup that matches the css selector with the given replace content.
replace
python
mitmproxy/mitmproxy
examples/contrib/webscanner_helper/mapping.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/webscanner_helper/mapping.py
MIT
def apply_template( self, soup: BeautifulSoup, template: dict[str, BeautifulSoup] ) -> None: """Applies the given mapping template to the given soup.""" for css_sel, replace in template.items(): mapped = soup.select(css_sel) if not mapped: self.logger....
Applies the given mapping template to the given soup.
apply_template
python
mitmproxy/mitmproxy
examples/contrib/webscanner_helper/mapping.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/webscanner_helper/mapping.py
MIT
def response(self, flow: HTTPFlow) -> None: """If a response is received, check if we should replace some content.""" try: templates = self.mapping_templates[flow] res = flow.response if res is not None: encoding = res.headers.get("content-encoding", "...
If a response is received, check if we should replace some content.
response
python
mitmproxy/mitmproxy
examples/contrib/webscanner_helper/mapping.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/webscanner_helper/mapping.py
MIT
def done(self) -> None: """Dumps all new content into the configuration file if self.persistent is set.""" if self.persistent: # make sure that all items are strings and not soups. def value_dumper(value): store = {} if value is None: ...
Dumps all new content into the configuration file if self.persistent is set.
done
python
mitmproxy/mitmproxy
examples/contrib/webscanner_helper/mapping.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/webscanner_helper/mapping.py
MIT
def randomString(string_length=10): """Generate a random string of fixed length""" letters = string.ascii_lowercase return "".join(random.choice(letters) for i in range(string_length))
Generate a random string of fixed length
randomString
python
mitmproxy/mitmproxy
examples/contrib/webscanner_helper/proxyauth_selenium.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/webscanner_helper/proxyauth_selenium.py
MIT
def response(self, flow: HTTPFlow): """Checks if the response should be included in the URL based on the index_filter and adds it to the URL index if appropriate. """ if isinstance(self.index_filter, str) or self.index_filter is None: raise ValueError("Invalid filter expressi...
Checks if the response should be included in the URL based on the index_filter and adds it to the URL index if appropriate.
response
python
mitmproxy/mitmproxy
examples/contrib/webscanner_helper/urlindex.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/webscanner_helper/urlindex.py
MIT
def response(self, flow: HTTPFlow): """Checks if the response matches the filter and such should be injected. Injects the URL index if appropriate. """ if flow.response is not None: if self.flt is not None and self.flt(flow): self.injection_gen.inject(self.url...
Checks if the response matches the filter and such should be injected. Injects the URL index if appropriate.
response
python
mitmproxy/mitmproxy
examples/contrib/webscanner_helper/urlinjection.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/webscanner_helper/urlinjection.py
MIT
def __init__(self, event, outdir: pathlib.Path, timeout=None): """Initializes the Watchdog. Args: event: multiprocessing.Event that will be set if the watchdog is triggered. outdir: path to a directory in which the triggering requests will be saved (curl and raw). ti...
Initializes the Watchdog. Args: event: multiprocessing.Event that will be set if the watchdog is triggered. outdir: path to a directory in which the triggering requests will be saved (curl and raw). timeout_conn: float that specifies the timeout for the server connection ...
__init__
python
mitmproxy/mitmproxy
examples/contrib/webscanner_helper/watchdog.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/webscanner_helper/watchdog.py
MIT
def not_in_timeout(cls, last_triggered, timeout): """Checks if current error lies not in timeout after last trigger (potential reset of connection).""" return ( last_triggered is None or timeout is None or (time.time() - last_triggered > timeout) )
Checks if current error lies not in timeout after last trigger (potential reset of connection).
not_in_timeout
python
mitmproxy/mitmproxy
examples/contrib/webscanner_helper/watchdog.py
https://github.com/mitmproxy/mitmproxy/blob/master/examples/contrib/webscanner_helper/watchdog.py
MIT
def cut_traceback(tb, func_name): """ Cut off a traceback at the function with the given name. The func_name's frame is excluded. Args: tb: traceback object, as returned by sys.exc_info()[2] func_name: function name Returns: Reduced traceback. """ tb_orig = tb f...
Cut off a traceback at the function with the given name. The func_name's frame is excluded. Args: tb: traceback object, as returned by sys.exc_info()[2] func_name: function name Returns: Reduced traceback.
cut_traceback
python
mitmproxy/mitmproxy
mitmproxy/addonmanager.py
https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/addonmanager.py
MIT
def register(self, addon): """ Register an addon, call its load event, and then register all its sub-addons. This should be used by addons that dynamically manage addons. If the calling addon is already running, it should follow with running and configure events. Must be...
Register an addon, call its load event, and then register all its sub-addons. This should be used by addons that dynamically manage addons. If the calling addon is already running, it should follow with running and configure events. Must be called within a current conte...
register
python
mitmproxy/mitmproxy
mitmproxy/addonmanager.py
https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/addonmanager.py
MIT
def remove(self, addon): """ Remove an addon and all its sub-addons. If the addon is not in the chain - that is, if it's managed by a parent addon - it's the parent's responsibility to remove it from its own addons attribute. """ for a in traverse([addon]): ...
Remove an addon and all its sub-addons. If the addon is not in the chain - that is, if it's managed by a parent addon - it's the parent's responsibility to remove it from its own addons attribute.
remove
python
mitmproxy/mitmproxy
mitmproxy/addonmanager.py
https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/addonmanager.py
MIT
def _iter_hooks(self, addon, event: hooks.Hook): """ Enumerate all hook callables belonging to the given addon """ assert isinstance(event, hooks.Hook) for a in traverse([addon]): func = getattr(a, event.name, None) if func: if callable(fun...
Enumerate all hook callables belonging to the given addon
_iter_hooks
python
mitmproxy/mitmproxy
mitmproxy/addonmanager.py
https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/addonmanager.py
MIT
async def invoke_addon(self, addon, event: hooks.Hook): """ Asynchronously invoke an event on an addon and all its children. """ for addon, func in self._iter_hooks(addon, event): res = func(*event.args()) # Support both async and sync hook functions i...
Asynchronously invoke an event on an addon and all its children.
invoke_addon
python
mitmproxy/mitmproxy
mitmproxy/addonmanager.py
https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/addonmanager.py
MIT
def invoke_addon_sync(self, addon, event: hooks.Hook): """ Invoke an event on an addon and all its children. """ for addon, func in self._iter_hooks(addon, event): if inspect.iscoroutinefunction(func): raise exceptions.AddonManagerError( f"...
Invoke an event on an addon and all its children.
invoke_addon_sync
python
mitmproxy/mitmproxy
mitmproxy/addonmanager.py
https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/addonmanager.py
MIT
async def trigger_event(self, event: hooks.Hook): """ Asynchronously trigger an event across all addons. """ for i in self.chain: try: with safecall(): await self.invoke_addon(i, event) except exceptions.AddonHalt: ...
Asynchronously trigger an event across all addons.
trigger_event
python
mitmproxy/mitmproxy
mitmproxy/addonmanager.py
https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/addonmanager.py
MIT
def trigger(self, event: hooks.Hook): """ Trigger an event across all addons. This API is discouraged and may be deprecated in the future. Use `trigger_event()` instead, which provides the same functionality but supports async hooks. """ for i in self.chain: ...
Trigger an event across all addons. This API is discouraged and may be deprecated in the future. Use `trigger_event()` instead, which provides the same functionality but supports async hooks.
trigger
python
mitmproxy/mitmproxy
mitmproxy/addonmanager.py
https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/addonmanager.py
MIT
def dummy_crl( privkey: rsa.RSAPrivateKey, cacert: x509.Certificate, ) -> bytes: """ Generates an empty CRL signed with the CA key privkey: CA private key cacert: CA certificate Returns a CRL DER encoded """ builder = x509.CertificateRevocationListBuilder() builder = builder.is...
Generates an empty CRL signed with the CA key privkey: CA private key cacert: CA certificate Returns a CRL DER encoded
dummy_crl
python
mitmproxy/mitmproxy
mitmproxy/certs.py
https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/certs.py
MIT
def umask_secret(): """ Context to temporarily set umask to its original value bitor 0o77. Useful when writing private keys to disk so that only the owner will be able to read them. """ original_umask = os.umask(0) os.umask(original_umask | 0o77) try: ...
Context to temporarily set umask to its original value bitor 0o77. Useful when writing private keys to disk so that only the owner will be able to read them.
umask_secret
python
mitmproxy/mitmproxy
mitmproxy/certs.py
https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/certs.py
MIT
def add_cert(self, entry: CertStoreEntry, *names: str) -> None: """ Adds a cert to the certstore. We register the CN in the cert plus any SANs, and also the list of names provided as an argument. """ if entry.cert.cn: self.certs[entry.cert.cn] = entry for i in...
Adds a cert to the certstore. We register the CN in the cert plus any SANs, and also the list of names provided as an argument.
add_cert
python
mitmproxy/mitmproxy
mitmproxy/certs.py
https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/certs.py
MIT
def get_cert( self, commonname: str | None, sans: Iterable[x509.GeneralName], organization: str | None = None, crl_url: str | None = None, ) -> CertStoreEntry: """ commonname: Common name for the generated certificate. Must be a valid, plain-ASCII, IDN...
commonname: Common name for the generated certificate. Must be a valid, plain-ASCII, IDNA-encoded domain name. sans: A list of Subject Alternate Names. organization: Organization name for the generated certificate. crl_url: URL of CRL distribution point
get_cert
python
mitmproxy/mitmproxy
mitmproxy/certs.py
https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/certs.py
MIT
def load_pem_private_key(data: bytes, password: bytes | None) -> rsa.RSAPrivateKey: """ like cryptography's load_pem_private_key, but silently falls back to not using a password if the private key is unencrypted. """ try: return serialization.load_pem_private_key(data, password) # type: ign...
like cryptography's load_pem_private_key, but silently falls back to not using a password if the private key is unencrypted.
load_pem_private_key
python
mitmproxy/mitmproxy
mitmproxy/certs.py
https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/certs.py
MIT
def typename(t: type) -> str: """ Translates a type to an explanatory string. """ if t == inspect._empty: # type: ignore raise exceptions.CommandError("missing type annotation") to = mitmproxy.types.CommandTypes.get(t, None) if not to: raise exceptions.CommandError( ...
Translates a type to an explanatory string.
typename
python
mitmproxy/mitmproxy
mitmproxy/command.py
https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/command.py
MIT
def call(self, args: Sequence[str]) -> Any: """ Call the command with a list of arguments. At this point, all arguments are strings. """ bound_args = self.prepare_args(args) ret = self.func(*bound_args.args, **bound_args.kwargs) if ret is None and self.return_type...
Call the command with a list of arguments. At this point, all arguments are strings.
call
python
mitmproxy/mitmproxy
mitmproxy/command.py
https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/command.py
MIT
def parse_partial( self, cmdstr: str ) -> tuple[Sequence[ParseResult], Sequence[CommandParameter]]: """ Parse a possibly partial command. Return a sequence of ParseResults and a sequence of remainder type help items. """ parts: pyparsing.ParseResults = command_lexer.expr.par...
Parse a possibly partial command. Return a sequence of ParseResults and a sequence of remainder type help items.
parse_partial
python
mitmproxy/mitmproxy
mitmproxy/command.py
https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/command.py
MIT
def call(self, command_name: str, *args: Any) -> Any: """ Call a command with native arguments. May raise CommandError. """ if command_name not in self.commands: raise exceptions.CommandError("Unknown command: %s" % command_name) return self.commands[command_name].fun...
Call a command with native arguments. May raise CommandError.
call
python
mitmproxy/mitmproxy
mitmproxy/command.py
https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/command.py
MIT
def call_strings(self, command_name: str, args: Sequence[str]) -> Any: """ Call a command using a list of string arguments. May raise CommandError. """ if command_name not in self.commands: raise exceptions.CommandError("Unknown command: %s" % command_name) return se...
Call a command using a list of string arguments. May raise CommandError.
call_strings
python
mitmproxy/mitmproxy
mitmproxy/command.py
https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/command.py
MIT
def execute(self, cmdstr: str) -> Any: """ Execute a command string. May raise CommandError. """ parts, _ = self.parse_partial(cmdstr) if not parts: raise exceptions.CommandError(f"Invalid command: {cmdstr!r}") command_name, *args = ( unquote(part....
Execute a command string. May raise CommandError.
execute
python
mitmproxy/mitmproxy
mitmproxy/command.py
https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/command.py
MIT
def parsearg(manager: CommandManager, spec: str, argtype: type) -> Any: """ Convert a string to a argument to the appropriate type. """ t = mitmproxy.types.CommandTypes.get(argtype, None) if not t: raise exceptions.CommandError(f"Unsupported argument type: {argtype}") try: return...
Convert a string to a argument to the appropriate type.
parsearg
python
mitmproxy/mitmproxy
mitmproxy/command.py
https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/command.py
MIT
def alpn_proto_negotiated(self) -> bytes | None: # pragma: no cover """*Deprecated:* An outdated alias for Connection.alpn.""" warnings.warn( "Connection.alpn_proto_negotiated is deprecated, use Connection.alpn instead.", DeprecationWarning, stacklevel=2, ) ...
*Deprecated:* An outdated alias for Connection.alpn.
alpn_proto_negotiated
python
mitmproxy/mitmproxy
mitmproxy/connection.py
https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/connection.py
MIT
def address(self): # pragma: no cover """*Deprecated:* An outdated alias for Client.peername.""" warnings.warn( "Client.address is deprecated, use Client.peername instead.", DeprecationWarning, stacklevel=2, ) return self.peername
*Deprecated:* An outdated alias for Client.peername.
address
python
mitmproxy/mitmproxy
mitmproxy/connection.py
https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/connection.py
MIT
def cipher_name(self) -> str | None: # pragma: no cover """*Deprecated:* An outdated alias for Connection.cipher.""" warnings.warn( "Client.cipher_name is deprecated, use Client.cipher instead.", DeprecationWarning, stacklevel=2, ) return self.cipher
*Deprecated:* An outdated alias for Connection.cipher.
cipher_name
python
mitmproxy/mitmproxy
mitmproxy/connection.py
https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/connection.py
MIT
def clientcert(self) -> certs.Cert | None: # pragma: no cover """*Deprecated:* An outdated alias for Connection.certificate_list[0].""" warnings.warn( "Client.clientcert is deprecated, use Client.certificate_list instead.", DeprecationWarning, stacklevel=2, )...
*Deprecated:* An outdated alias for Connection.certificate_list[0].
clientcert
python
mitmproxy/mitmproxy
mitmproxy/connection.py
https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/connection.py
MIT
def ip_address(self) -> Address | None: # pragma: no cover """*Deprecated:* An outdated alias for `Server.peername`.""" warnings.warn( "Server.ip_address is deprecated, use Server.peername instead.", DeprecationWarning, stacklevel=2, ) return self.pee...
*Deprecated:* An outdated alias for `Server.peername`.
ip_address
python
mitmproxy/mitmproxy
mitmproxy/connection.py
https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/connection.py
MIT
def cert(self) -> certs.Cert | None: # pragma: no cover """*Deprecated:* An outdated alias for `Connection.certificate_list[0]`.""" warnings.warn( "Server.cert is deprecated, use Server.certificate_list instead.", DeprecationWarning, stacklevel=2, ) i...
*Deprecated:* An outdated alias for `Connection.certificate_list[0]`.
cert
python
mitmproxy/mitmproxy
mitmproxy/connection.py
https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/connection.py
MIT
def CNAME( cls, alias: str, canonical: str, *, ttl: int = DEFAULT_TTL ) -> ResourceRecord: """Create a canonical internet name resource record.""" return cls(alias, types.CNAME, classes.IN, ttl, domain_names.pack(canonical))
Create a canonical internet name resource record.
CNAME
python
mitmproxy/mitmproxy
mitmproxy/dns.py
https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/dns.py
MIT
def question(self) -> Question | None: """DNS practically only supports a single question at the same time, so this is a shorthand for this.""" if len(self.questions) == 1: return self.questions[0] return None
DNS practically only supports a single question at the same time, so this is a shorthand for this.
question
python
mitmproxy/mitmproxy
mitmproxy/dns.py
https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/dns.py
MIT
def size(self) -> int: """Returns the cumulative data size of all resource record sections.""" return sum( len(x.data) for x in itertools.chain.from_iterable( [self.answers, self.authorities, self.additionals] ) )
Returns the cumulative data size of all resource record sections.
size
python
mitmproxy/mitmproxy
mitmproxy/dns.py
https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/dns.py
MIT
def unpack(cls, buffer: bytes, timestamp: float | None = None) -> DNSMessage: """Converts the entire given buffer into a DNS message.""" length, msg = cls.unpack_from(buffer, 0, timestamp) if length != len(buffer): raise struct.error(f"unpack requires a buffer of {length} bytes") ...
Converts the entire given buffer into a DNS message.
unpack
python
mitmproxy/mitmproxy
mitmproxy/dns.py
https://github.com/mitmproxy/mitmproxy/blob/master/mitmproxy/dns.py
MIT