Source code for onbasca.onbasca.util

# SPDX-FileCopyrightText: 2022 The Tor Project, Inc.
#
# SPDX-License-Identifier: BSD-3-Clause

import logging
import os
import random
from copy import deepcopy

import requests
from django.conf import settings

from onbasca.onbasca import constants

logger = logging.getLogger(__name__)


[docs] def modify_logging(config, scan=True, generate=False, log_level=None): custom_logging = deepcopy(settings.LOGGING) if scan: custom_logging["handlers"]["file"]["filename"] = config.SCAN_LOG_PATH elif generate: custom_logging["handlers"]["file"][ "filename" ] = config.GENERATE_LOG_PATH else: custom_logging["handlers"]["file"]["filename"] = config.CLEAN_LOG_PATH logger.info( "Modifying logging with file handler path: %s", custom_logging["handlers"]["file"]["filename"], ) os.makedirs(config.LOGS_DIR, mode=0o750, exist_ok=True) if log_level: custom_logging["loggers"]["onbasca"]["level"] = log_level.upper() logging.config.dictConfig(custom_logging)
[docs] def validate_recent_log(key1, value1, key2, value2): logger.warning("%s (%s) is less than %s (%s).", key1, value1, key2, value2)
[docs] def bytes_range_from_head( head=None, content_length=constants.MAX_DL_BYTES, size=constants.INITIAL_DL_BYTES, ): """ Returns a random range of bytes of length **size** taking either the head content-length header or ``content_length`` argument into account. For example, for content_length of 100 and size 10, this function will return one of the following: '0-9', '1-10', '2-11', [...] '89-98', '90-99' """ if head: if head.status_code != requests.codes.ok: return "" content_length = int(head.headers["content-length"]) # Start can be anywhere in the content_length as long as it is **size** # bytes away from the end or more. Because range is [start, end) (doesn't # include the end value), add 1 to the end. start = random.SystemRandom().choice(range(0, content_length - size + 1)) # Unlike range, the byte range in an http header is [start, end] (does # include the end value), so we subtract one end = start + size - 1 bytes_range = "bytes={}-{}".format(start, end) return bytes_range