func_code_string
stringlengths
52
1.94M
func_documentation_string
stringlengths
1
47.2k
def create_signature(secret, value, digestmod='sha256', encoding='utf-8'): if isinstance(secret, str): secret = secret.encode(encoding) if isinstance(value, str): value = value.encode(encoding) if isinstance(digestmod, str): digestmod = getattr(hashlib, digestmod, hashlib.sha1) ...
Create HMAC Signature from secret for value.
def check_signature(signature, *args, **kwargs): return hmac.compare_digest(signature, create_signature(*args, **kwargs))
Check for the signature is correct.
def generate_password_hash(password, digestmod='sha256', salt_length=8): salt = ''.join(random.sample(SALT_CHARS, salt_length)) signature = create_signature(salt, password, digestmod=digestmod) return '$'.join((digestmod, salt, signature))
Hash a password with given method and salt length.
def import_submodules(package_name, *submodules): package = sys.modules[package_name] return { name: importlib.import_module(package_name + '.' + name) for _, name, _ in pkgutil.walk_packages(package.__path__) if not submodules or name in submodules }
Import all submodules by package name.
def register(*paths, methods=None, name=None, handler=None): def wrapper(method): method = to_coroutine(method) setattr(method, ROUTE_PARAMS_ATTR, (paths, methods, name)) if handler and not hasattr(handler, method.__name__): setattr(handler, method.__name__, method)...
Mark Handler.method to aiohttp handler. It uses when registration of the handler with application is postponed. :: class AwesomeHandler(Handler): def get(self, request): return "I'm awesome!" @register('/awesome/best') def best(self, request): ...
def from_view(cls, view, *methods, name=None): docs = getattr(view, '__doc__', None) view = to_coroutine(view) methods = methods or ['GET'] if METH_ANY in methods: methods = METH_ALL def proxy(self, *args, **kwargs): return view(*args, **kwargs) ...
Create a handler class from function or coroutine.
def bind(cls, app, *paths, methods=None, name=None, router=None, view=None): cls.app = app if cls.app is not None: for _, m in inspect.getmembers(cls, predicate=inspect.isfunction): if not hasattr(m, ROUTE_PARAMS_ATTR): continue pa...
Bind to the given application.
def register(cls, *args, **kwargs): if cls.app is None: return register(*args, handler=cls, **kwargs) return cls.app.register(*args, handler=cls, **kwargs)
Register view to handler.
async def dispatch(self, request, view=None, **kwargs): if view is None and request.method not in self.methods: raise HTTPMethodNotAllowed(request.method, self.methods) method = getattr(self, view or request.method.lower()) response = await method(request, **kwargs) ...
Dispatch request.
async def make_response(self, request, response): while iscoroutine(response): response = await response if isinstance(response, StreamResponse): return response if isinstance(response, str): return Response(text=response, content_type='text/html') ...
Convert a handler result to web response.
async def parse(self, request): if request.content_type in {'application/x-www-form-urlencoded', 'multipart/form-data'}: return await request.post() if request.content_type == 'application/json': return await request.json() return await request.text()
Return a coroutine which parses data from request depends on content-type. Usage: :: def post(self, request): data = await self.parse(request) # ...
def setup(self, app): self.app = app for name, ptype in self.dependencies.items(): if name not in app.ps or not isinstance(app.ps[name], ptype): raise PluginException( 'Plugin `%s` requires for plugin `%s` to be installed to the application.' % ( ...
Initialize the plugin. Fill the plugin's options from application.
def _exc_middleware_factory(app): @web.middleware async def middleware(request, handler): try: return await handler(request) except Exception as exc: for cls in type(exc).mro(): if cls in app._error_handlers: request.exception = ex...
Handle exceptions. Route exceptions to handlers if they are registered in application.
def register(self, *paths, methods=None, name=None, handler=None): if isinstance(methods, str): methods = [methods] def wrapper(view): if handler is None: handler_ = view methods_ = methods or [METH_ANY] if isfunction(handl...
Register function/coroutine/muffin.Handler with the application. Usage example: .. code-block:: python @app.register('/hello') def hello(request): return 'Hello World!'
def cfg(self): config = LStruct(self.defaults) module = config['CONFIG'] = os.environ.get( CONFIGURATION_ENVIRON_VARIABLE, config['CONFIG']) if module: try: module = import_module(module) config.update({ name: g...
Load the application configuration. This method loads configuration from python module.
def install(self, plugin, name=None, **opts): source = plugin if isinstance(plugin, str): module, _, attr = plugin.partition(':') module = import_module(module) plugin = getattr(module, attr or 'Plugin', None) if isinstance(plugin, types.ModuleType): ...
Install plugin to the application.
async def startup(self): if self.frozen: return False if self._error_handlers: self.middlewares.append(_exc_middleware_factory(self)) # Register static paths for path in self.cfg.STATIC_FOLDERS: self.router.register_resource(SafeStaticResource...
Start the application. Support for start-callbacks and lock the application's configuration and plugins.
def middleware(self, func): self.middlewares.append(web.middleware(to_coroutine(func)))
Register given middleware (v1).
def parse( html, transport_encoding=None, namespace_elements=False, treebuilder='lxml', fallback_encoding=None, keep_doctype=True, maybe_xhtml=False, return_root=True, line_number_attr=None, sanitize_names=True, stack_size=16 * 1024 ): data = as_utf8(html or b'', tra...
Parse the specified :attr:`html` and return the parsed representation. :param html: The HTML to be parsed. Can be either bytes or a unicode string. :param transport_encoding: If specified, assume the passed in bytes are in this encoding. Ignored if :attr:`html` is unicode. :param namespace_elemen...
def honeypot_equals(val): expected = getattr(settings, 'HONEYPOT_VALUE', '') if callable(expected): expected = expected() return val == expected
Default verifier used if HONEYPOT_VERIFIER is not specified. Ensures val == HONEYPOT_VALUE or HONEYPOT_VALUE() if it's a callable.
def verify_honeypot_value(request, field_name): verifier = getattr(settings, 'HONEYPOT_VERIFIER', honeypot_equals) if request.method == 'POST': field = field_name or settings.HONEYPOT_FIELD_NAME if field not in request.POST or not verifier(request.POST[field]): resp = render_to_...
Verify that request.POST[field_name] is a valid honeypot. Ensures that the field exists and passes verification according to HONEYPOT_VERIFIER.
def check_honeypot(func=None, field_name=None): # hack to reverse arguments if called with str param if isinstance(func, six.string_types): func, field_name = field_name, func def decorated(func): def inner(request, *args, **kwargs): response = verify_honeypot_value(request,...
Check request.POST for valid honeypot field. Takes an optional field_name that defaults to HONEYPOT_FIELD_NAME if not specified.
def honeypot_exempt(view_func): # borrowing liberally from django's csrf_exempt def wrapped(*args, **kwargs): return view_func(*args, **kwargs) wrapped.honeypot_exempt = True return wraps(view_func, assigned=available_attrs(view_func))(wrapped)
Mark view as exempt from honeypot validation
def render_honeypot_field(field_name=None): if not field_name: field_name = settings.HONEYPOT_FIELD_NAME value = getattr(settings, 'HONEYPOT_VALUE', '') if callable(value): value = value() return {'fieldname': field_name, 'value': value}
Renders honeypot field named field_name (defaults to HONEYPOT_FIELD_NAME).
def parse_args(): import argparse import textwrap parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description=textwrap.dedent()) parser.add_argument('-l', '--label', type=str, help='The badge label.') parser.add_argumen...
Parse the command line arguments.
def main(): # Parse command line arguments args = parse_args() label = args.label threshold_text = args.args suffix = args.suffix # Check whether thresholds were sent as one word, and is in the # list of templates. If so, swap in the template. if len(args.args) == 1 and args.args[0...
Generate a badge based on command line arguments.
def value_is_int(self): try: a = float(self.value) b = int(a) except ValueError: return False else: return a == b
Identify whether the value text is an int.
def font_width(self): return self.get_font_width(font_name=self.font_name, font_size=self.font_size)
Return the badge font width.
def color_split_position(self): return self.get_text_width(' ') + self.label_width + \ int(float(self.font_width) * float(self.num_padding_chars))
The SVG x position where the color split should occur.
def badge_width(self): return self.get_text_width(' ' + ' ' * int(float(self.num_padding_chars) * 2.0)) \ + self.label_width + self.value_width
The total width of badge. >>> badge = Badge('pylint', '5', font_name='DejaVu Sans,Verdana,Geneva,sans-serif', ... font_size=11) >>> badge.badge_width 91
def badge_svg_text(self): # Identify whether template is a file or the actual template text if len(self.template.split('\n')) == 1: with open(self.template, mode='r') as file_handle: badge_text = file_handle.read() else: badge_text = self.template...
The badge SVG text.
def get_text_width(self, text): return len(text) * self.get_font_width(self.font_name, self.font_size)
Return the width of text. This implementation assumes a fixed font of: font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="11" >>> badge = Badge('x', 1, font_name='DejaVu Sans,Verdana,Geneva,sans-serif', font_size=11) >>> badge.get_text_width('pylint') 42
def badge_color(self): # If no thresholds were passed then return the default color if not self.thresholds: return self.default_color if self.value_type == str: if self.value in self.thresholds: return self.thresholds[self.value] else:...
Find the badge color based on the thresholds.
def write_badge(self, file_path, overwrite=False): # Validate path (part 1) if file_path.endswith('/'): raise Exception('File location may not be a directory.') # Get absolute filepath path = os.path.abspath(file_path) if not path.lower().endswith('.svg'): ...
Write badge to file.
def main(): global DEFAULT_SERVER_PORT, DEFAULT_SERVER_LISTEN_ADDRESS, DEFAULT_LOGGING_LEVEL # Check for environment variables if 'ANYBADGE_PORT' in environ: DEFAULT_SERVER_PORT = environ['ANYBADGE_PORT'] if 'ANYBADGE_LISTEN_ADDRESS' in environ: DEFAULT_SERVER_LISTEN_ADDRESS = envir...
Run server.
def get_object_name(obj): name_dispatch = { ast.Name: "id", ast.Attribute: "attr", ast.Call: "func", ast.FunctionDef: "name", ast.ClassDef: "name", ast.Subscript: "value", } # This is a new ast type in Python 3 if hasattr(ast, "arg"): name_dis...
Return the name of a given object
def get_attribute_name_id(attr): return attr.value.id if isinstance(attr.value, ast.Name) else None
Return the attribute name identifier
def is_class_method_bound(method, arg_name=BOUND_METHOD_ARGUMENT_NAME): if not method.args.args: return False first_arg = method.args.args[0] first_arg_name = get_object_name(first_arg) return first_arg_name == arg_name
Return whether a class method is bound to the class
def get_class_methods(cls): return [ node for node in cls.body if isinstance(node, ast.FunctionDef) ]
Return methods associated with a given class
def get_class_variables(cls): return [ target for node in cls.body if isinstance(node, ast.Assign) for target in node.targets ]
Return class variables associated with a given class
def get_instance_variables(node, bound_name_classifier=BOUND_METHOD_ARGUMENT_NAME): node_attributes = [ child for child in ast.walk(node) if isinstance(child, ast.Attribute) and get_attribute_name_id(child) == bound_name_classifier ] node_function_call_names = [ ...
Return instance variables used in an AST node
def get_module_classes(node): return [ child for child in ast.walk(node) if isinstance(child, ast.ClassDef) ]
Return classes associated with a given module
def recursively_get_files_from_directory(directory): return [ os.path.join(root, filename) for root, directories, filenames in os.walk(directory) for filename in filenames ]
Return all filenames under recursively found in a directory
def get(key, default=-1): if isinstance(key, int): return SeedID(key) if key not in SeedID._member_map_: extend_enum(SeedID, key, default) return SeedID[key]
Backport support for original codes.
def get(key, default=-1): if isinstance(key, int): return PriorityLevel(key) if key not in PriorityLevel._member_map_: extend_enum(PriorityLevel, key, default) return PriorityLevel[key]
Backport support for original codes.
def get(key, default=-1): if isinstance(key, int): return TOS_THR(key) if key not in TOS_THR._member_map_: extend_enum(TOS_THR, key, default) return TOS_THR[key]
Backport support for original codes.
def _missing_(cls, value): if not (isinstance(value, int) and 0 <= value <= 1): raise ValueError('%r is not a valid %s' % (value, cls.__name__)) extend_enum(cls, 'Unassigned [%d]' % value, value) return cls(value) super()._missing_(value)
Lookup function used when value is not found.
def get(key, default=-1): if isinstance(key, int): return Registration(key) if key not in Registration._member_map_: extend_enum(Registration, key, default) return Registration[key]
Backport support for original codes.
def get(key, default=-1): if isinstance(key, int): return ErrorCode(key) if key not in ErrorCode._member_map_: extend_enum(ErrorCode, key, default) return ErrorCode[key]
Backport support for original codes.
def count(self, value): from pcapkit.protocols.protocol import Protocol try: flag = issubclass(value, Protocol) except TypeError: flag = issubclass(type(value), Protocol) if flag or isinstance(value, Protocol): value = value.__index__() ...
S.count(value) -> integer -- return number of occurrences of value
def index(self, value, start=0, stop=None): if start is not None and start < 0: start = max(len(self) + start, 0) if stop is not None and stop < 0: stop += len(self) try: if not isinstance(start, numbers.Integral): start = self.index(s...
S.index(value, [start, [stop]]) -> integer -- return first index of value. Raises ValueError if the value is not present. Supporting start and stop arguments is optional, but recommended.
def index(self, value, start=None, stop=None): return self.__alias__.index(value, start, stop)
Return first index of value.
def get(key, default=-1): if isinstance(key, int): return NAT_Traversal(key) if key not in NAT_Traversal._member_map_: extend_enum(NAT_Traversal, key, default) return NAT_Traversal[key]
Backport support for original codes.
def read_ospf(self, length): if length is None: length = len(self) _vers = self._read_unpack(1) _type = self._read_unpack(1) _tlen = self._read_unpack(2) _rtid = self._read_id_numbers() _area = self._read_id_numbers() _csum = self._read_fileng...
Read Open Shortest Path First. Structure of OSPF header [RFC 2328]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | V...
def _read_id_numbers(self): _byte = self._read_fileng(4) _addr = '.'.join([str(_) for _ in _byte]) return _addr
Read router and area IDs.
def _read_encrypt_auth(self): _resv = self._read_fileng(2) _keys = self._read_unpack(1) _alen = self._read_unpack(1) _seqn = self._read_unpack(4) auth = dict( key_id=_keys, len=_alen, seq=_seqn, ) return auth
Read Authentication field when Cryptographic Authentication is employed. Structure of Cryptographic Authentication [RFC 2328]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+...
def int_check(*args, func=None): func = func or inspect.stack()[2][3] for var in args: if not isinstance(var, numbers.Integral): name = type(var).__name__ raise ComplexError( f'Function {func} expected integral number, {name} got instead.')
Check if arguments are integrals.
def real_check(*args, func=None): func = func or inspect.stack()[2][3] for var in args: if not isinstance(var, numbers.Real): name = type(var).__name__ raise ComplexError( f'Function {func} expected real number, {name} got instead.')
Check if arguments are real numbers.
def complex_check(*args, func=None): func = func or inspect.stack()[2][3] for var in args: if not isinstance(var, numbers.Complex): name = type(var).__name__ raise ComplexError( f'Function {func} expected complex number, {name} got instead.')
Check if arguments are complex numbers.
def number_check(*args, func=None): func = func or inspect.stack()[2][3] for var in args: if not isinstance(var, numbers.Number): name = type(var).__name__ raise DigitError( f'Function {func} expected number, {name} got instead.')
Check if arguments are numbers.
def bytes_check(*args, func=None): func = func or inspect.stack()[2][3] for var in args: if not isinstance(var, (bytes, collections.abc.ByteString)): name = type(var).__name__ raise BytesError( f'Function {func} expected bytes, {name} got instead.')
Check if arguments are bytes type.
def bytearray_check(*args, func=None): func = func or inspect.stack()[2][3] for var in args: if not isinstance(var, (bytearray, collections.abc.ByteString, collections.abc.MutableSequence)): name = type(var).__name__ raise BytearrayError( f'Function {func} ex...
Check if arguments are bytearray type.
def str_check(*args, func=None): func = func or inspect.stack()[2][3] for var in args: if not isinstance(var, (str, collections.UserString, collections.abc.Sequence)): name = type(var).__name__ raise StringError( f'Function {func} expected str, {name} got ins...
Check if arguments are str type.
def bool_check(*args, func=None): func = func or inspect.stack()[2][3] for var in args: if not isinstance(var, bool): name = type(var).__name__ raise BoolError( f'Function {func} expected bool, {name} got instead.')
Check if arguments are bytes type.
def list_check(*args, func=None): func = func or inspect.stack()[2][3] for var in args: if not isinstance(var, (list, collections.UserList, collections.abc.MutableSequence)): name = type(var).__name__ raise ListError( f'Function {func} expected list, {name} g...
Check if arguments are list type.
def dict_check(*args, func=None): func = func or inspect.stack()[2][3] for var in args: if not isinstance(var, (dict, collections.UserDict, collections.abc.MutableMapping)): name = type(var).__name__ raise DictError( f'Function {func} expected dict, {name} go...
Check if arguments are dict type.
def tuple_check(*args, func=None): func = func or inspect.stack()[2][3] for var in args: if not isinstance(var, (tuple, collections.abc.Sequence)): name = type(var).__name__ raise TupleError( f'Function {func} expected tuple, {name} got instead.')
Check if arguments are tuple type.
def io_check(*args, func=None): func = func or inspect.stack()[2][3] for var in args: if not isinstance(var, io.IOBase): name = type(var).__name__ raise IOObjError( f'Function {func} expected file-like object, {name} got instead.')
Check if arguments are file-like object.
def info_check(*args, func=None): from pcapkit.corekit.infoclass import Info func = func or inspect.stack()[2][3] for var in args: if not isinstance(var, Info): name = type(var).__name__ raise InfoError( f'Function {func} expected Info instance, {name} go...
Check if arguments are Info instance.
def ip_check(*args, func=None): func = func or inspect.stack()[2][3] for var in args: if not isinstance(var, ipaddress._IPAddressBase): name = type(var).__name__ raise IPError( f'Function {func} expected IP address, {name} got instead.')
Check if arguments are IP addresses.
def enum_check(*args, func=None): func = func or inspect.stack()[2][3] for var in args: if not isinstance(var, (enum.EnumMeta, aenum.EnumMeta)): name = type(var).__name__ raise EnumError( f'Function {func} expected enumeration, {name} got instead.')
Check if arguments are of protocol type.
def frag_check(*args, protocol, func=None): func = func or inspect.stack()[2][3] if 'IP' in protocol: _ip_frag_check(*args, func=func) elif 'TCP' in protocol: _tcp_frag_check(*args, func=func) else: raise FragmentError(f'Unknown fragmented protocol {protocol}.')
Check if arguments are valid fragments.
def _ip_frag_check(*args, func=None): func = func or inspect.stack()[2][3] for var in args: dict_check(var, func=func) bufid = var.get('bufid') str_check(bufid[3], func=func) bool_check(var.get('mf'), func=func) ip_check(bufid[0], bufid[1], func=func) bytearr...
Check if arguments are valid IP fragments.
def pkt_check(*args, func=None): func = func or inspect.stack()[2][3] for var in args: dict_check(var, func=func) dict_check(var.get('frame'), func=func) enum_check(var.get('protocol'), func=func) real_check(var.get('timestamp'), func=func) ip_check(var.get('src'), v...
Check if arguments are valid packets.
def fetch(self): if self._newflg: self._newflg = False temp_dtgram = copy.deepcopy(self._dtgram) for (bufid, buffer) in self._buffer.items(): temp_dtgram += self.submit(buffer, bufid=bufid) return tuple(temp_dtgram) return tuple(se...
Fetch datagram.
def index(self, pkt_num): int_check(pkt_num) for counter, datagram in enumerate(self.datagram): if pkt_num in datagram.index: return counter return None
Return datagram index.
def run(self, packets): for packet in packets: frag_check(packet, protocol=self.protocol) info = Info(packet) self.reassembly(info) self._newflg = True
Run automatically. Positional arguments: * packets -- list<dict>, list of packet dicts to be reassembled
def read_mh(self, length, extension): if length is None: length = len(self) _next = self._read_protos(1) _hlen = self._read_unpack(1) _type = self._read_unpack(1) _temp = self._read_fileng(1) _csum = self._read_fileng(2) # _data = self._read_f...
Read Mobility Header. Structure of MH header [RFC 6275]: +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Payload Proto | Header Len | MH Type | Reserved | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | ...
def get(key, default=-1): if isinstance(key, int): return DI(key) if key not in DI._member_map_: extend_enum(DI, key, default) return DI[key]
Backport support for original codes.
def get(key, default=-1): if isinstance(key, int): return Certificate(key) if key not in Certificate._member_map_: extend_enum(Certificate, key, default) return Certificate[key]
Backport support for original codes.
def read_udp(self, length): if length is None: length = len(self) _srcp = self._read_unpack(2) _dstp = self._read_unpack(2) _tlen = self._read_unpack(2) _csum = self._read_fileng(2) udp = dict( srcport=_srcp, dstport=_dstp, ...
Read User Datagram Protocol (UDP). Structure of UDP header [RFC 768]: 0 7 8 15 16 23 24 31 +--------+--------+--------+--------+ | Source | Destination | | Port | Port | +--------+--------+--------+--...
def read_ipx(self, length): if length is None: length = len(self) _csum = self._read_fileng(2) _tlen = self._read_unpack(2) _ctrl = self._read_unpack(1) _type = self._read_unpack(1) _dsta = self._read_ipx_address() _srca = self._read_ipx_addre...
Read Internetwork Packet Exchange. Structure of IPX header [RFC 1132]: Octets Bits Name Description 0 0 ipx.cksum Checksum 2 16 ipx.len Packet Length (header includes) 4...
def _read_ipx_address(self): # Address Number _byte = self._read_fileng(4) _ntwk = ':'.join(textwrap.wrap(_byte.hex(), 2)) # Node Number (MAC) _byte = self._read_fileng(6) _node = ':'.join(textwrap.wrap(_byte.hex(), 2)) _maca = '-'.join(textwrap.wrap(_byt...
Read IPX address field. Structure of IPX address: Octets Bits Name Description 0 0 ipx.addr.network Network Number 4 32 ipx.addr.node Node Number 10 80 ipx.addr.socket ...
def get(key, default=-1): if isinstance(key, int): return Group(key) if key not in Group._member_map_: extend_enum(Group, key, default) return Group[key]
Backport support for original codes.
def read_arp(self, length): if length is None: length = len(self) _hwty = self._read_unpack(2) _ptty = self._read_unpack(2) _hlen = self._read_unpack(1) _plen = self._read_unpack(1) _oper = self._read_unpack(2) _shwa = self._read_addr_resolve(...
Read Address Resolution Protocol. Structure of ARP header [RFC 826]: Octets Bits Name Description 0 0 arp.htype Hardware Type 2 16 arp.ptype Protocol Type 4 32 ...
def _read_addr_resolve(self, length, htype): if htype == 1: # Ethernet _byte = self._read_fileng(6) _addr = '-'.join(textwrap.wrap(_byte.hex(), 2)) else: _addr = self._read_fileng(length) return _addr
Resolve MAC address according to protocol. Positional arguments: * length -- int, hardware address length * htype -- int, hardware type Returns: * str -- MAC address
def _read_proto_resolve(self, length, ptype): # if ptype == '0800': # IPv4 # _byte = self._read_fileng(4) # _addr = '.'.join([str(_) for _ in _byte]) # elif ptype == '86dd': # IPv6 # adlt = [] # list of IPv6 hexadecimal address # ctr_ ...
Resolve IP address according to protocol. Positional arguments: * length -- int, protocol address length * ptype -- int, protocol type Returns: * str -- IP address
def get(key, default=-1): if isinstance(key, int): return Setting(key) if key not in Setting._member_map_: extend_enum(Setting, key, default) return Setting[key]
Backport support for original codes.
def get(key, default=-1): if isinstance(key, int): return Transport(key) if key not in Transport._member_map_: extend_enum(Transport, key, default) return Transport[key]
Backport support for original codes.
def get(key, default=-1): if isinstance(key, int): return TOS_DEL(key) if key not in TOS_DEL._member_map_: extend_enum(TOS_DEL, key, default) return TOS_DEL[key]
Backport support for original codes.
def get(key, default=-1): if isinstance(key, int): return EtherType(key) if key not in EtherType._member_map_: extend_enum(EtherType, key, default) return EtherType[key]
Backport support for original codes.
def _missing_(cls, value): if not (isinstance(value, int) and 0x0000 <= value <= 0xFFFF): raise ValueError('%r is not a valid %s' % (value, cls.__name__)) if 0x0000 <= value <= 0x05DC: # [Neil_Sembower] extend_enum(cls, 'IEEE802.3 Length Field [0x%s]' % hex(v...
Lookup function used when value is not found.
def get(key, default=-1): if isinstance(key, int): return TOS_ECN(key) if key not in TOS_ECN._member_map_: extend_enum(TOS_ECN, key, default) return TOS_ECN[key]
Backport support for original codes.
def get(key, default=-1): if isinstance(key, int): return Frame(key) if key not in Frame._member_map_: extend_enum(Frame, key, default) return Frame[key]
Backport support for original codes.
def _missing_(cls, value): if not (isinstance(value, int) and 0x00 <= value <= 0xFF): raise ValueError('%r is not a valid %s' % (value, cls.__name__)) if 0x0D <= value <= 0xEF: extend_enum(cls, 'Unassigned [0x%s]' % hex(value)[2:].upper().zfill(2), value) ret...
Lookup function used when value is not found.
def ipv4_reassembly(frame): if 'IPv4' in frame: ipv4 = frame['IPv4'].info if ipv4.flags.df: # dismiss not fragmented frame return False, None data = dict( bufid=( ipv4.src, # source IP address ...
Make data for IPv4 reassembly.
def ipv6_reassembly(frame): if 'IPv6' in frame: ipv6 = frame['IPv6'].info if 'frag' not in ipv6: # dismiss not fragmented frame return False, None data = dict( bufid=( ipv6.src, # source IP address ...
Make data for IPv6 reassembly.
def tcp_reassembly(frame): if 'TCP' in frame: ip = (frame['IPv4'] if 'IPv4' in frame else frame['IPv6']).info tcp = frame['TCP'].info data = dict( bufid=( ip.src, # source IP address ip.dst, ...
Make data for TCP reassembly.
def tcp_traceflow(frame, *, data_link): if 'TCP' in frame: ip = (frame['IPv4'] if 'IPv4' in frame else frame['IPv6']).info tcp = frame['TCP'].info data = dict( protocol=data_link, # data link type from global header index=frame.info.number, ...
Trace packet flow for TCP.
def get(key, default=-1): if isinstance(key, int): return TOS_REL(key) if key not in TOS_REL._member_map_: extend_enum(TOS_REL, key, default) return TOS_REL[key]
Backport support for original codes.