repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_documentation_string
stringlengths 1
47.2k
| func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|
klen/muffin | muffin/utils.py | create_signature | def create_signature(secret, value, digestmod='sha256', encoding='utf-8'):
""" Create HMAC Signature from secret for value. """
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)
hm = hmac.new(secret, digestmod=digestmod)
hm.update(value)
return hm.hexdigest() | python | def create_signature(secret, value, digestmod='sha256', encoding='utf-8'):
""" Create HMAC Signature from secret for value. """
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)
hm = hmac.new(secret, digestmod=digestmod)
hm.update(value)
return hm.hexdigest() | Create HMAC Signature from secret for value. | https://github.com/klen/muffin/blob/7bc891e174e08b62d1ae232b5d45f8cd8bc82112/muffin/utils.py#L32-L45 |
klen/muffin | muffin/utils.py | check_signature | def check_signature(signature, *args, **kwargs):
""" Check for the signature is correct. """
return hmac.compare_digest(signature, create_signature(*args, **kwargs)) | python | def check_signature(signature, *args, **kwargs):
""" Check for the signature is correct. """
return hmac.compare_digest(signature, create_signature(*args, **kwargs)) | Check for the signature is correct. | https://github.com/klen/muffin/blob/7bc891e174e08b62d1ae232b5d45f8cd8bc82112/muffin/utils.py#L48-L50 |
klen/muffin | muffin/utils.py | generate_password_hash | def generate_password_hash(password, digestmod='sha256', salt_length=8):
""" Hash a password with given method and salt length. """
salt = ''.join(random.sample(SALT_CHARS, salt_length))
signature = create_signature(salt, password, digestmod=digestmod)
return '$'.join((digestmod, salt, signature)) | python | def generate_password_hash(password, digestmod='sha256', salt_length=8):
""" Hash a password with given method and salt length. """
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. | https://github.com/klen/muffin/blob/7bc891e174e08b62d1ae232b5d45f8cd8bc82112/muffin/utils.py#L53-L58 |
klen/muffin | muffin/utils.py | import_submodules | def import_submodules(package_name, *submodules):
"""Import all submodules by package name."""
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
} | python | def import_submodules(package_name, *submodules):
"""Import all submodules by package name."""
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. | https://github.com/klen/muffin/blob/7bc891e174e08b62d1ae232b5d45f8cd8bc82112/muffin/utils.py#L183-L190 |
klen/muffin | muffin/handler.py | register | def register(*paths, methods=None, name=None, handler=None):
"""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):
return "I'm best!"
"""
def wrapper(method):
"""Store route params into 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)
return method
return wrapper | python | def register(*paths, methods=None, name=None, handler=None):
"""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):
return "I'm best!"
"""
def wrapper(method):
"""Store route params into 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)
return method
return wrapper | 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):
return "I'm best!" | https://github.com/klen/muffin/blob/7bc891e174e08b62d1ae232b5d45f8cd8bc82112/muffin/handler.py#L17-L40 |
klen/muffin | muffin/handler.py | Handler.from_view | def from_view(cls, view, *methods, name=None):
"""Create a handler class from function or coroutine."""
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)
params = {m.lower(): proxy for m in methods}
params['methods'] = methods
if docs:
params['__doc__'] = docs
return type(name or view.__name__, (cls,), params) | python | def from_view(cls, view, *methods, name=None):
"""Create a handler class from function or coroutine."""
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)
params = {m.lower(): proxy for m in methods}
params['methods'] = methods
if docs:
params['__doc__'] = docs
return type(name or view.__name__, (cls,), params) | Create a handler class from function or coroutine. | https://github.com/klen/muffin/blob/7bc891e174e08b62d1ae232b5d45f8cd8bc82112/muffin/handler.py#L95-L112 |
klen/muffin | muffin/handler.py | Handler.bind | def bind(cls, app, *paths, methods=None, name=None, router=None, view=None):
"""Bind to the given application."""
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
paths_, methods_, name_ = getattr(m, ROUTE_PARAMS_ATTR)
name_ = name_ or ("%s.%s" % (cls.name, m.__name__))
delattr(m, ROUTE_PARAMS_ATTR)
cls.app.register(*paths_, methods=methods_, name=name_, handler=cls)(m)
@coroutine
@functools.wraps(cls)
def handler(request):
return cls().dispatch(request, view=view)
if not paths:
paths = ["/%s" % cls.__name__]
return routes_register(
app, handler, *paths, methods=methods, router=router, name=name or cls.name) | python | def bind(cls, app, *paths, methods=None, name=None, router=None, view=None):
"""Bind to the given application."""
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
paths_, methods_, name_ = getattr(m, ROUTE_PARAMS_ATTR)
name_ = name_ or ("%s.%s" % (cls.name, m.__name__))
delattr(m, ROUTE_PARAMS_ATTR)
cls.app.register(*paths_, methods=methods_, name=name_, handler=cls)(m)
@coroutine
@functools.wraps(cls)
def handler(request):
return cls().dispatch(request, view=view)
if not paths:
paths = ["/%s" % cls.__name__]
return routes_register(
app, handler, *paths, methods=methods, router=router, name=name or cls.name) | Bind to the given application. | https://github.com/klen/muffin/blob/7bc891e174e08b62d1ae232b5d45f8cd8bc82112/muffin/handler.py#L115-L136 |
klen/muffin | muffin/handler.py | Handler.register | def register(cls, *args, **kwargs):
"""Register view to handler."""
if cls.app is None:
return register(*args, handler=cls, **kwargs)
return cls.app.register(*args, handler=cls, **kwargs) | python | def register(cls, *args, **kwargs):
"""Register view to handler."""
if cls.app is None:
return register(*args, handler=cls, **kwargs)
return cls.app.register(*args, handler=cls, **kwargs) | Register view to handler. | https://github.com/klen/muffin/blob/7bc891e174e08b62d1ae232b5d45f8cd8bc82112/muffin/handler.py#L139-L143 |
klen/muffin | muffin/handler.py | Handler.dispatch | async def dispatch(self, request, view=None, **kwargs):
"""Dispatch request."""
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)
return await self.make_response(request, response) | python | async def dispatch(self, request, view=None, **kwargs):
"""Dispatch request."""
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)
return await self.make_response(request, response) | Dispatch request. | https://github.com/klen/muffin/blob/7bc891e174e08b62d1ae232b5d45f8cd8bc82112/muffin/handler.py#L145-L152 |
klen/muffin | muffin/handler.py | Handler.make_response | async def make_response(self, request, response):
"""Convert a handler result to web 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')
if isinstance(response, bytes):
return Response(body=response, content_type='text/html')
return Response(text=json.dumps(response), content_type='application/json') | python | async def make_response(self, request, response):
"""Convert a handler result to web 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')
if isinstance(response, bytes):
return Response(body=response, content_type='text/html')
return Response(text=json.dumps(response), content_type='application/json') | Convert a handler result to web response. | https://github.com/klen/muffin/blob/7bc891e174e08b62d1ae232b5d45f8cd8bc82112/muffin/handler.py#L156-L170 |
klen/muffin | muffin/handler.py | Handler.parse | async def parse(self, request):
"""Return a coroutine which parses data from request depends on content-type.
Usage: ::
def post(self, request):
data = await self.parse(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() | python | async def parse(self, request):
"""Return a coroutine which parses data from request depends on content-type.
Usage: ::
def post(self, request):
data = await self.parse(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)
# ... | https://github.com/klen/muffin/blob/7bc891e174e08b62d1ae232b5d45f8cd8bc82112/muffin/handler.py#L172-L187 |
klen/muffin | muffin/plugins.py | BasePlugin.setup | def setup(self, app):
"""Initialize the plugin.
Fill the plugin's options from application.
"""
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.' % (
self.name, ptype))
for oname, dvalue in self.defaults.items():
aname = ('%s_%s' % (self.name, oname)).upper()
self.cfg.setdefault(oname, app.cfg.get(aname, dvalue))
app.cfg.setdefault(aname, self.cfg[oname]) | python | def setup(self, app):
"""Initialize the plugin.
Fill the plugin's options from application.
"""
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.' % (
self.name, ptype))
for oname, dvalue in self.defaults.items():
aname = ('%s_%s' % (self.name, oname)).upper()
self.cfg.setdefault(oname, app.cfg.get(aname, dvalue))
app.cfg.setdefault(aname, self.cfg[oname]) | Initialize the plugin.
Fill the plugin's options from application. | https://github.com/klen/muffin/blob/7bc891e174e08b62d1ae232b5d45f8cd8bc82112/muffin/plugins.py#L60-L75 |
klen/muffin | muffin/app.py | _exc_middleware_factory | def _exc_middleware_factory(app):
"""Handle exceptions.
Route exceptions to handlers if they are registered in application.
"""
@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 = exc
response = await app._error_handlers[cls](request)
return response
raise
return middleware | python | def _exc_middleware_factory(app):
"""Handle exceptions.
Route exceptions to handlers if they are registered in application.
"""
@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 = exc
response = await app._error_handlers[cls](request)
return response
raise
return middleware | Handle exceptions.
Route exceptions to handlers if they are registered in application. | https://github.com/klen/muffin/blob/7bc891e174e08b62d1ae232b5d45f8cd8bc82112/muffin/app.py#L266-L284 |
klen/muffin | muffin/app.py | BaseApplication.register | def register(self, *paths, methods=None, name=None, handler=None):
"""Register function/coroutine/muffin.Handler with the application.
Usage example:
.. code-block:: python
@app.register('/hello')
def hello(request):
return 'Hello World!'
"""
if isinstance(methods, str):
methods = [methods]
def wrapper(view):
if handler is None:
handler_ = view
methods_ = methods or [METH_ANY]
if isfunction(handler_) or ismethod(handler_):
handler_ = Handler.from_view(view, *methods_, name=name)
handler_.bind(self, *paths, methods=methods_, name=name)
else:
view_name = view.__name__
if not hasattr(handler, view_name):
setattr(handler, view_name, to_coroutine(view))
name_ = name or view_name
handler.bind(self, *paths, methods=methods, name=name_, view=view_name)
return view
# Support for @app.register(func)
if len(paths) == 1 and callable(paths[0]):
view = paths[0]
if isclass(view) and issubclass(view, BaseException):
return wrapper
paths = []
return wrapper(view)
return wrapper | python | def register(self, *paths, methods=None, name=None, handler=None):
"""Register function/coroutine/muffin.Handler with the application.
Usage example:
.. code-block:: python
@app.register('/hello')
def hello(request):
return 'Hello World!'
"""
if isinstance(methods, str):
methods = [methods]
def wrapper(view):
if handler is None:
handler_ = view
methods_ = methods or [METH_ANY]
if isfunction(handler_) or ismethod(handler_):
handler_ = Handler.from_view(view, *methods_, name=name)
handler_.bind(self, *paths, methods=methods_, name=name)
else:
view_name = view.__name__
if not hasattr(handler, view_name):
setattr(handler, view_name, to_coroutine(view))
name_ = name or view_name
handler.bind(self, *paths, methods=methods, name=name_, view=view_name)
return view
# Support for @app.register(func)
if len(paths) == 1 and callable(paths[0]):
view = paths[0]
if isclass(view) and issubclass(view, BaseException):
return wrapper
paths = []
return wrapper(view)
return wrapper | Register function/coroutine/muffin.Handler with the application.
Usage example:
.. code-block:: python
@app.register('/hello')
def hello(request):
return 'Hello World!' | https://github.com/klen/muffin/blob/7bc891e174e08b62d1ae232b5d45f8cd8bc82112/muffin/app.py#L29-L76 |
klen/muffin | muffin/app.py | Application.cfg | def cfg(self):
"""Load the application configuration.
This method loads configuration from python module.
"""
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: getattr(module, name) for name in dir(module)
if name == name.upper() and not name.startswith('_')
})
except ImportError as exc:
config.CONFIG = None
self.logger.error("Error importing %s: %s", module, exc)
# Patch configuration from ENV
for name in config:
if name.startswith('_') or name != name.upper() or name not in os.environ:
continue
try:
config[name] = json.loads(os.environ[name])
except ValueError:
pass
return config | python | def cfg(self):
"""Load the application configuration.
This method loads configuration from python module.
"""
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: getattr(module, name) for name in dir(module)
if name == name.upper() and not name.startswith('_')
})
except ImportError as exc:
config.CONFIG = None
self.logger.error("Error importing %s: %s", module, exc)
# Patch configuration from ENV
for name in config:
if name.startswith('_') or name != name.upper() or name not in os.environ:
continue
try:
config[name] = json.loads(os.environ[name])
except ValueError:
pass
return config | Load the application configuration.
This method loads configuration from python module. | https://github.com/klen/muffin/blob/7bc891e174e08b62d1ae232b5d45f8cd8bc82112/muffin/app.py#L162-L192 |
klen/muffin | muffin/app.py | Application.install | def install(self, plugin, name=None, **opts):
"""Install plugin to the application."""
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):
plugin = getattr(module, 'Plugin', None)
if plugin is None:
raise MuffinException('Plugin is not found %r' % source)
name = name or plugin.name
if name in self.ps:
raise MuffinException('Plugin with name `%s` is already intalled.' % name)
if isinstance(plugin, type):
plugin = plugin(**opts)
if hasattr(plugin, 'setup'):
plugin.setup(self)
if hasattr(plugin, 'middleware') and plugin.middleware not in self.middlewares:
self.middlewares.append(plugin.middleware)
if hasattr(plugin, 'startup'):
self.on_startup.append(plugin.startup)
if hasattr(plugin, 'cleanup'):
self.on_cleanup.append(plugin.cleanup)
# Save plugin links
self.ps[name] = plugin
return plugin | python | def install(self, plugin, name=None, **opts):
"""Install plugin to the application."""
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):
plugin = getattr(module, 'Plugin', None)
if plugin is None:
raise MuffinException('Plugin is not found %r' % source)
name = name or plugin.name
if name in self.ps:
raise MuffinException('Plugin with name `%s` is already intalled.' % name)
if isinstance(plugin, type):
plugin = plugin(**opts)
if hasattr(plugin, 'setup'):
plugin.setup(self)
if hasattr(plugin, 'middleware') and plugin.middleware not in self.middlewares:
self.middlewares.append(plugin.middleware)
if hasattr(plugin, 'startup'):
self.on_startup.append(plugin.startup)
if hasattr(plugin, 'cleanup'):
self.on_cleanup.append(plugin.cleanup)
# Save plugin links
self.ps[name] = plugin
return plugin | Install plugin to the application. | https://github.com/klen/muffin/blob/7bc891e174e08b62d1ae232b5d45f8cd8bc82112/muffin/app.py#L194-L231 |
klen/muffin | muffin/app.py | Application.startup | async def startup(self):
"""Start the application.
Support for start-callbacks and lock the application's configuration and plugins.
"""
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(self.cfg.STATIC_PREFIX, path))
await super(Application, self).startup() | python | async def startup(self):
"""Start the application.
Support for start-callbacks and lock the application's configuration and plugins.
"""
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(self.cfg.STATIC_PREFIX, path))
await super(Application, self).startup() | Start the application.
Support for start-callbacks and lock the application's configuration and plugins. | https://github.com/klen/muffin/blob/7bc891e174e08b62d1ae232b5d45f8cd8bc82112/muffin/app.py#L233-L248 |
klen/muffin | muffin/app.py | Application.middleware | def middleware(self, func):
"""Register given middleware (v1)."""
self.middlewares.append(web.middleware(to_coroutine(func))) | python | def middleware(self, func):
"""Register given middleware (v1)."""
self.middlewares.append(web.middleware(to_coroutine(func))) | Register given middleware (v1). | https://github.com/klen/muffin/blob/7bc891e174e08b62d1ae232b5d45f8cd8bc82112/muffin/app.py#L261-L263 |
kovidgoyal/html5-parser | src/html5_parser/__init__.py | parse | 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
):
'''
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_elements:
Add XML namespaces when parsing so that the resulting tree is XHTML.
:param treebuilder:
The type of tree to return. Note that only the lxml treebuilder is fast, as all
other treebuilders are implemented in python, not C. Supported values are:
* `lxml <http://lxml.de>`_ -- the default, and fastest
* etree (the python stdlib :mod:`xml.etree.ElementTree`)
* dom (the python stdlib :mod:`xml.dom.minidom`)
* `soup <https://www.crummy.com/software/BeautifulSoup>`_ -- BeautifulSoup,
which must be installed or it will raise an :class:`ImportError`
:param fallback_encoding: If no encoding could be detected, then use this encoding.
Defaults to an encoding based on system locale.
:param keep_doctype: Keep the <DOCTYPE> (if any).
:param maybe_xhtml: Useful when it is unknown if the HTML to be parsed is
actually XHTML. Changes the HTML 5 parsing algorithm to be more
suitable for XHTML. In particular handles self-closed CDATA elements.
So a ``<title/>`` or ``<style/>`` in the HTML will not completely break
parsing. Also preserves namespaced tags and attributes even for namespaces
not supported by HTML 5 (this works only with the ``lxml`` treebuilder).
Note that setting this also implicitly sets ``namespace_elements``.
:param return_root: If True, return the root node of the document, otherwise
return the tree object for the document.
:param line_number_attr: The optional name of an attribute used to store the line number
of every element. If set, this attribute will be added to each element with the
element's line number.
:param sanitize_names: Ensure tag and attributes contain only ASCII alphanumeric
charactes, underscores, hyphens and periods. This ensures that the resulting
tree is also valid XML. Any characters outside this set are replaced by
underscores. Note that this is not strictly HTML 5 spec compliant, so turn it
off if you need strict spec compliance.
:param stack_size: The initial size (number of items) in the stack. The
default is sufficient to avoid memory allocations for all but the
largest documents.
'''
data = as_utf8(html or b'', transport_encoding, fallback_encoding)
treebuilder = normalize_treebuilder(treebuilder)
if treebuilder == 'soup':
from .soup import parse
return parse(
data, return_root=return_root, keep_doctype=keep_doctype, stack_size=stack_size)
if treebuilder not in NAMESPACE_SUPPORTING_BUILDERS:
namespace_elements = False
capsule = html_parser.parse(
data,
namespace_elements=namespace_elements or maybe_xhtml,
keep_doctype=keep_doctype,
maybe_xhtml=maybe_xhtml,
line_number_attr=line_number_attr,
sanitize_names=sanitize_names,
stack_size=stack_size)
ans = etree.adopt_external_document(capsule)
if treebuilder == 'lxml':
return ans.getroot() if return_root else ans
m = importlib.import_module('html5_parser.' + treebuilder)
return m.adapt(ans, return_root=return_root) | python | 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
):
'''
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_elements:
Add XML namespaces when parsing so that the resulting tree is XHTML.
:param treebuilder:
The type of tree to return. Note that only the lxml treebuilder is fast, as all
other treebuilders are implemented in python, not C. Supported values are:
* `lxml <http://lxml.de>`_ -- the default, and fastest
* etree (the python stdlib :mod:`xml.etree.ElementTree`)
* dom (the python stdlib :mod:`xml.dom.minidom`)
* `soup <https://www.crummy.com/software/BeautifulSoup>`_ -- BeautifulSoup,
which must be installed or it will raise an :class:`ImportError`
:param fallback_encoding: If no encoding could be detected, then use this encoding.
Defaults to an encoding based on system locale.
:param keep_doctype: Keep the <DOCTYPE> (if any).
:param maybe_xhtml: Useful when it is unknown if the HTML to be parsed is
actually XHTML. Changes the HTML 5 parsing algorithm to be more
suitable for XHTML. In particular handles self-closed CDATA elements.
So a ``<title/>`` or ``<style/>`` in the HTML will not completely break
parsing. Also preserves namespaced tags and attributes even for namespaces
not supported by HTML 5 (this works only with the ``lxml`` treebuilder).
Note that setting this also implicitly sets ``namespace_elements``.
:param return_root: If True, return the root node of the document, otherwise
return the tree object for the document.
:param line_number_attr: The optional name of an attribute used to store the line number
of every element. If set, this attribute will be added to each element with the
element's line number.
:param sanitize_names: Ensure tag and attributes contain only ASCII alphanumeric
charactes, underscores, hyphens and periods. This ensures that the resulting
tree is also valid XML. Any characters outside this set are replaced by
underscores. Note that this is not strictly HTML 5 spec compliant, so turn it
off if you need strict spec compliance.
:param stack_size: The initial size (number of items) in the stack. The
default is sufficient to avoid memory allocations for all but the
largest documents.
'''
data = as_utf8(html or b'', transport_encoding, fallback_encoding)
treebuilder = normalize_treebuilder(treebuilder)
if treebuilder == 'soup':
from .soup import parse
return parse(
data, return_root=return_root, keep_doctype=keep_doctype, stack_size=stack_size)
if treebuilder not in NAMESPACE_SUPPORTING_BUILDERS:
namespace_elements = False
capsule = html_parser.parse(
data,
namespace_elements=namespace_elements or maybe_xhtml,
keep_doctype=keep_doctype,
maybe_xhtml=maybe_xhtml,
line_number_attr=line_number_attr,
sanitize_names=sanitize_names,
stack_size=stack_size)
ans = etree.adopt_external_document(capsule)
if treebuilder == 'lxml':
return ans.getroot() if return_root else ans
m = importlib.import_module('html5_parser.' + treebuilder)
return m.adapt(ans, return_root=return_root) | 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_elements:
Add XML namespaces when parsing so that the resulting tree is XHTML.
:param treebuilder:
The type of tree to return. Note that only the lxml treebuilder is fast, as all
other treebuilders are implemented in python, not C. Supported values are:
* `lxml <http://lxml.de>`_ -- the default, and fastest
* etree (the python stdlib :mod:`xml.etree.ElementTree`)
* dom (the python stdlib :mod:`xml.dom.minidom`)
* `soup <https://www.crummy.com/software/BeautifulSoup>`_ -- BeautifulSoup,
which must be installed or it will raise an :class:`ImportError`
:param fallback_encoding: If no encoding could be detected, then use this encoding.
Defaults to an encoding based on system locale.
:param keep_doctype: Keep the <DOCTYPE> (if any).
:param maybe_xhtml: Useful when it is unknown if the HTML to be parsed is
actually XHTML. Changes the HTML 5 parsing algorithm to be more
suitable for XHTML. In particular handles self-closed CDATA elements.
So a ``<title/>`` or ``<style/>`` in the HTML will not completely break
parsing. Also preserves namespaced tags and attributes even for namespaces
not supported by HTML 5 (this works only with the ``lxml`` treebuilder).
Note that setting this also implicitly sets ``namespace_elements``.
:param return_root: If True, return the root node of the document, otherwise
return the tree object for the document.
:param line_number_attr: The optional name of an attribute used to store the line number
of every element. If set, this attribute will be added to each element with the
element's line number.
:param sanitize_names: Ensure tag and attributes contain only ASCII alphanumeric
charactes, underscores, hyphens and periods. This ensures that the resulting
tree is also valid XML. Any characters outside this set are replaced by
underscores. Note that this is not strictly HTML 5 spec compliant, so turn it
off if you need strict spec compliance.
:param stack_size: The initial size (number of items) in the stack. The
default is sufficient to avoid memory allocations for all but the
largest documents. | https://github.com/kovidgoyal/html5-parser/blob/65ce451652cbab71ed86a9b53ac8c8906f2a2d67/src/html5_parser/__init__.py#L121-L207 |
jamesturk/django-honeypot | honeypot/decorators.py | honeypot_equals | def honeypot_equals(val):
"""
Default verifier used if HONEYPOT_VERIFIER is not specified.
Ensures val == HONEYPOT_VALUE or HONEYPOT_VALUE() if it's a callable.
"""
expected = getattr(settings, 'HONEYPOT_VALUE', '')
if callable(expected):
expected = expected()
return val == expected | python | def honeypot_equals(val):
"""
Default verifier used if HONEYPOT_VERIFIER is not specified.
Ensures val == HONEYPOT_VALUE or HONEYPOT_VALUE() if it's a callable.
"""
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. | https://github.com/jamesturk/django-honeypot/blob/4b149bfca81828eaf418b5a6854e670d156f5e35/honeypot/decorators.py#L9-L17 |
jamesturk/django-honeypot | honeypot/decorators.py | verify_honeypot_value | def verify_honeypot_value(request, field_name):
"""
Verify that request.POST[field_name] is a valid honeypot.
Ensures that the field exists and passes verification according to
HONEYPOT_VERIFIER.
"""
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_string('honeypot/honeypot_error.html',
{'fieldname': field})
return HttpResponseBadRequest(resp) | python | def verify_honeypot_value(request, field_name):
"""
Verify that request.POST[field_name] is a valid honeypot.
Ensures that the field exists and passes verification according to
HONEYPOT_VERIFIER.
"""
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_string('honeypot/honeypot_error.html',
{'fieldname': field})
return HttpResponseBadRequest(resp) | Verify that request.POST[field_name] is a valid honeypot.
Ensures that the field exists and passes verification according to
HONEYPOT_VERIFIER. | https://github.com/jamesturk/django-honeypot/blob/4b149bfca81828eaf418b5a6854e670d156f5e35/honeypot/decorators.py#L20-L33 |
jamesturk/django-honeypot | honeypot/decorators.py | check_honeypot | def check_honeypot(func=None, field_name=None):
"""
Check request.POST for valid honeypot field.
Takes an optional field_name that defaults to HONEYPOT_FIELD_NAME if
not specified.
"""
# 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, field_name)
if response:
return response
else:
return func(request, *args, **kwargs)
return wraps(func, assigned=available_attrs(func))(inner)
if func is None:
def decorator(func):
return decorated(func)
return decorator
return decorated(func) | python | def check_honeypot(func=None, field_name=None):
"""
Check request.POST for valid honeypot field.
Takes an optional field_name that defaults to HONEYPOT_FIELD_NAME if
not specified.
"""
# 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, field_name)
if response:
return response
else:
return func(request, *args, **kwargs)
return wraps(func, assigned=available_attrs(func))(inner)
if func is None:
def decorator(func):
return decorated(func)
return decorator
return decorated(func) | Check request.POST for valid honeypot field.
Takes an optional field_name that defaults to HONEYPOT_FIELD_NAME if
not specified. | https://github.com/jamesturk/django-honeypot/blob/4b149bfca81828eaf418b5a6854e670d156f5e35/honeypot/decorators.py#L36-L60 |
jamesturk/django-honeypot | honeypot/decorators.py | honeypot_exempt | def honeypot_exempt(view_func):
"""
Mark view as exempt from honeypot validation
"""
# 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) | python | def honeypot_exempt(view_func):
"""
Mark view as exempt from honeypot validation
"""
# 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 | https://github.com/jamesturk/django-honeypot/blob/4b149bfca81828eaf418b5a6854e670d156f5e35/honeypot/decorators.py#L63-L71 |
jamesturk/django-honeypot | honeypot/templatetags/honeypot.py | render_honeypot_field | def render_honeypot_field(field_name=None):
"""
Renders honeypot field named field_name (defaults to HONEYPOT_FIELD_NAME).
"""
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} | python | def render_honeypot_field(field_name=None):
"""
Renders honeypot field named field_name (defaults to HONEYPOT_FIELD_NAME).
"""
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). | https://github.com/jamesturk/django-honeypot/blob/4b149bfca81828eaf418b5a6854e670d156f5e35/honeypot/templatetags/honeypot.py#L8-L17 |
jongracecox/anybadge | anybadge.py | parse_args | def parse_args():
"""Parse the command line arguments."""
import argparse
import textwrap
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,
description=textwrap.dedent('''\
Command line utility to generate .svg badges.
This utility can be used to generate .svg badge images, using configurable
thresholds for coloring. Values can be passed as string, integer or floating
point. The type will be detected automatically.
Running the utility with a --file option will result in the .svg image being
written to file. Without the --file option the .svg file content will be
written to stdout, so can be redirected to a file.
Some thresholds have been built in to save time. To use these thresholds you
can simply specify the template name instead of threshold value/color pairs.
examples:
Here are some usage specific examples that may save time on defining
thresholds.
Pylint
anybadge.py --value=2.22 --file=pylint.svg pylint
anybadge.py --label=pylint --value=2.22 --file=pylint.svg \\
2=red 4=orange 8=yellow 10=green
Coverage
anybadge.py --value=65 --file=coverage.svg coverage
anybadge.py --label=coverage --value=65 --suffix='%%' --file=coverage.svg \\
50=red 60=orange 80=yellow 100=green
CI Pipeline
anybadge.py --label=pipeline --value=passing --file=pipeline.svg \\
passing=green failing=red
'''))
parser.add_argument('-l', '--label', type=str, help='The badge label.')
parser.add_argument('-v', '--value', type=str, help='The badge value.', required=True)
parser.add_argument('-m', '--value-format', type=str, default=None,
help='Formatting string for value (e.g. "%%.2f" for 2dp floats)')
parser.add_argument('-c', '--color', type=str, help='For fixed color badges use --color'
'to specify the badge color.',
default=DEFAULT_COLOR)
parser.add_argument('-p', '--prefix', type=str, help='Optional prefix for value.',
default='')
parser.add_argument('-s', '--suffix', type=str, help='Optional suffix for value.',
default='')
parser.add_argument('-d', '--padding', type=int, help='Number of characters to pad on '
'either side of the badge text.',
default=NUM_PADDING_CHARS)
parser.add_argument('-n', '--font', type=str,
help='Font name. Supported fonts: '
','.join(['"%s"' % x for x in FONT_WIDTHS.keys()]),
default=DEFAULT_FONT)
parser.add_argument('-z', '--font-size', type=int, help='Font size.',
default=DEFAULT_FONT_SIZE)
parser.add_argument('-t', '--template', type=str, help='Location of alternative '
'template .svg file.',
default=TEMPLATE_SVG)
parser.add_argument('-u', '--use-max', action='store_true',
help='Use the maximum threshold color when the value exceeds the '
'maximum threshold.')
parser.add_argument('-f', '--file', type=str, help='Output file location.')
parser.add_argument('-o', '--overwrite', action='store_true',
help='Overwrite output file if it already exists.')
parser.add_argument('-r', '--text-color', type=str, help='Text color. Single value affects both label'
'and value colors. A comma separated pair '
'affects label and value text respectively.',
default=DEFAULT_TEXT_COLOR)
parser.add_argument('args', nargs=argparse.REMAINDER, help='Pairs of <upper>=<color>. '
'For example 2=red 4=orange 6=yellow 8=good. '
'Read this as "Less than 2 = red, less than 4 = orange...".')
return parser.parse_args() | python | def parse_args():
"""Parse the command line arguments."""
import argparse
import textwrap
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,
description=textwrap.dedent('''\
Command line utility to generate .svg badges.
This utility can be used to generate .svg badge images, using configurable
thresholds for coloring. Values can be passed as string, integer or floating
point. The type will be detected automatically.
Running the utility with a --file option will result in the .svg image being
written to file. Without the --file option the .svg file content will be
written to stdout, so can be redirected to a file.
Some thresholds have been built in to save time. To use these thresholds you
can simply specify the template name instead of threshold value/color pairs.
examples:
Here are some usage specific examples that may save time on defining
thresholds.
Pylint
anybadge.py --value=2.22 --file=pylint.svg pylint
anybadge.py --label=pylint --value=2.22 --file=pylint.svg \\
2=red 4=orange 8=yellow 10=green
Coverage
anybadge.py --value=65 --file=coverage.svg coverage
anybadge.py --label=coverage --value=65 --suffix='%%' --file=coverage.svg \\
50=red 60=orange 80=yellow 100=green
CI Pipeline
anybadge.py --label=pipeline --value=passing --file=pipeline.svg \\
passing=green failing=red
'''))
parser.add_argument('-l', '--label', type=str, help='The badge label.')
parser.add_argument('-v', '--value', type=str, help='The badge value.', required=True)
parser.add_argument('-m', '--value-format', type=str, default=None,
help='Formatting string for value (e.g. "%%.2f" for 2dp floats)')
parser.add_argument('-c', '--color', type=str, help='For fixed color badges use --color'
'to specify the badge color.',
default=DEFAULT_COLOR)
parser.add_argument('-p', '--prefix', type=str, help='Optional prefix for value.',
default='')
parser.add_argument('-s', '--suffix', type=str, help='Optional suffix for value.',
default='')
parser.add_argument('-d', '--padding', type=int, help='Number of characters to pad on '
'either side of the badge text.',
default=NUM_PADDING_CHARS)
parser.add_argument('-n', '--font', type=str,
help='Font name. Supported fonts: '
','.join(['"%s"' % x for x in FONT_WIDTHS.keys()]),
default=DEFAULT_FONT)
parser.add_argument('-z', '--font-size', type=int, help='Font size.',
default=DEFAULT_FONT_SIZE)
parser.add_argument('-t', '--template', type=str, help='Location of alternative '
'template .svg file.',
default=TEMPLATE_SVG)
parser.add_argument('-u', '--use-max', action='store_true',
help='Use the maximum threshold color when the value exceeds the '
'maximum threshold.')
parser.add_argument('-f', '--file', type=str, help='Output file location.')
parser.add_argument('-o', '--overwrite', action='store_true',
help='Overwrite output file if it already exists.')
parser.add_argument('-r', '--text-color', type=str, help='Text color. Single value affects both label'
'and value colors. A comma separated pair '
'affects label and value text respectively.',
default=DEFAULT_TEXT_COLOR)
parser.add_argument('args', nargs=argparse.REMAINDER, help='Pairs of <upper>=<color>. '
'For example 2=red 4=orange 6=yellow 8=good. '
'Read this as "Less than 2 = red, less than 4 = orange...".')
return parser.parse_args() | Parse the command line arguments. | https://github.com/jongracecox/anybadge/blob/1850a9580697e019c601d09f5de490056fed2bab/anybadge.py#L360-L437 |
jongracecox/anybadge | anybadge.py | main | def main():
"""Generate a badge based on command line arguments."""
# 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] in BADGE_TEMPLATES:
template_name = args.args[0]
template_dict = BADGE_TEMPLATES[template_name]
threshold_text = template_dict['threshold'].split(' ')
if not args.label:
label = template_dict['label']
if not args.suffix and 'suffix' in template_dict:
suffix = template_dict['suffix']
if not label:
raise ValueError('Label has not been set. Please use --label argument.')
# Create threshold list from args
threshold_list = [x.split('=') for x in threshold_text]
threshold_dict = {x[0]: x[1] for x in threshold_list}
# Create badge object
badge = Badge(label, args.value, value_prefix=args.prefix, value_suffix=suffix,
default_color=args.color, num_padding_chars=args.padding, font_name=args.font,
font_size=args.font_size, template=args.template,
use_max_when_value_exceeds=args.use_max, thresholds=threshold_dict,
value_format=args.value_format, text_color=args.text_color)
if args.file:
# Write badge SVG to file
badge.write_badge(args.file, overwrite=args.overwrite)
else:
print(badge.badge_svg_text) | python | def main():
"""Generate a badge based on command line arguments."""
# 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] in BADGE_TEMPLATES:
template_name = args.args[0]
template_dict = BADGE_TEMPLATES[template_name]
threshold_text = template_dict['threshold'].split(' ')
if not args.label:
label = template_dict['label']
if not args.suffix and 'suffix' in template_dict:
suffix = template_dict['suffix']
if not label:
raise ValueError('Label has not been set. Please use --label argument.')
# Create threshold list from args
threshold_list = [x.split('=') for x in threshold_text]
threshold_dict = {x[0]: x[1] for x in threshold_list}
# Create badge object
badge = Badge(label, args.value, value_prefix=args.prefix, value_suffix=suffix,
default_color=args.color, num_padding_chars=args.padding, font_name=args.font,
font_size=args.font_size, template=args.template,
use_max_when_value_exceeds=args.use_max, thresholds=threshold_dict,
value_format=args.value_format, text_color=args.text_color)
if args.file:
# Write badge SVG to file
badge.write_badge(args.file, overwrite=args.overwrite)
else:
print(badge.badge_svg_text) | Generate a badge based on command line arguments. | https://github.com/jongracecox/anybadge/blob/1850a9580697e019c601d09f5de490056fed2bab/anybadge.py#L440-L478 |
jongracecox/anybadge | anybadge.py | Badge.value_is_int | def value_is_int(self):
"""Identify whether the value text is an int."""
try:
a = float(self.value)
b = int(a)
except ValueError:
return False
else:
return a == b | python | def value_is_int(self):
"""Identify whether the value text is an int."""
try:
a = float(self.value)
b = int(a)
except ValueError:
return False
else:
return a == b | Identify whether the value text is an int. | https://github.com/jongracecox/anybadge/blob/1850a9580697e019c601d09f5de490056fed2bab/anybadge.py#L183-L191 |
jongracecox/anybadge | anybadge.py | Badge.font_width | def font_width(self):
"""Return the badge font width."""
return self.get_font_width(font_name=self.font_name, font_size=self.font_size) | python | def font_width(self):
"""Return the badge font width."""
return self.get_font_width(font_name=self.font_name, font_size=self.font_size) | Return the badge font width. | https://github.com/jongracecox/anybadge/blob/1850a9580697e019c601d09f5de490056fed2bab/anybadge.py#L214-L216 |
jongracecox/anybadge | anybadge.py | Badge.color_split_position | def color_split_position(self):
"""The SVG x position where the color split should occur."""
return self.get_text_width(' ') + self.label_width + \
int(float(self.font_width) * float(self.num_padding_chars)) | python | def color_split_position(self):
"""The SVG x position where the color split should occur."""
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. | https://github.com/jongracecox/anybadge/blob/1850a9580697e019c601d09f5de490056fed2bab/anybadge.py#L219-L222 |
jongracecox/anybadge | anybadge.py | Badge.badge_width | def badge_width(self):
"""The total width of badge.
>>> badge = Badge('pylint', '5', font_name='DejaVu Sans,Verdana,Geneva,sans-serif',
... font_size=11)
>>> badge.badge_width
91
"""
return self.get_text_width(' ' + ' ' * int(float(self.num_padding_chars) * 2.0)) \
+ self.label_width + self.value_width | python | def badge_width(self):
"""The total width of badge.
>>> badge = Badge('pylint', '5', font_name='DejaVu Sans,Verdana,Geneva,sans-serif',
... font_size=11)
>>> badge.badge_width
91
"""
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 | https://github.com/jongracecox/anybadge/blob/1850a9580697e019c601d09f5de490056fed2bab/anybadge.py#L245-L254 |
jongracecox/anybadge | anybadge.py | Badge.badge_svg_text | def badge_svg_text(self):
"""The badge SVG text."""
# 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
return badge_text.replace('{{ badge width }}', str(self.badge_width)) \
.replace('{{ font name }}', self.font_name) \
.replace('{{ font size }}', str(self.font_size)) \
.replace('{{ label }}', self.label) \
.replace('{{ value }}', self.value_text) \
.replace('{{ label anchor }}', str(self.label_anchor)) \
.replace('{{ label anchor shadow }}', str(self.label_anchor_shadow)) \
.replace('{{ value anchor }}', str(self.value_anchor)) \
.replace('{{ value anchor shadow }}', str(self.value_anchor_shadow)) \
.replace('{{ color }}', self.badge_color_code) \
.replace('{{ label text color }}', self.label_text_color) \
.replace('{{ value text color }}', self.value_text_color) \
.replace('{{ color split x }}', str(self.color_split_position)) \
.replace('{{ value width }}', str(self.badge_width - self.color_split_position)) | python | def badge_svg_text(self):
"""The badge SVG text."""
# 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
return badge_text.replace('{{ badge width }}', str(self.badge_width)) \
.replace('{{ font name }}', self.font_name) \
.replace('{{ font size }}', str(self.font_size)) \
.replace('{{ label }}', self.label) \
.replace('{{ value }}', self.value_text) \
.replace('{{ label anchor }}', str(self.label_anchor)) \
.replace('{{ label anchor shadow }}', str(self.label_anchor_shadow)) \
.replace('{{ value anchor }}', str(self.value_anchor)) \
.replace('{{ value anchor shadow }}', str(self.value_anchor_shadow)) \
.replace('{{ color }}', self.badge_color_code) \
.replace('{{ label text color }}', self.label_text_color) \
.replace('{{ value text color }}', self.value_text_color) \
.replace('{{ color split x }}', str(self.color_split_position)) \
.replace('{{ value width }}', str(self.badge_width - self.color_split_position)) | The badge SVG text. | https://github.com/jongracecox/anybadge/blob/1850a9580697e019c601d09f5de490056fed2bab/anybadge.py#L257-L280 |
jongracecox/anybadge | anybadge.py | Badge.get_text_width | def get_text_width(self, text):
"""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
"""
return len(text) * self.get_font_width(self.font_name, self.font_size) | python | def get_text_width(self, text):
"""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
"""
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 | https://github.com/jongracecox/anybadge/blob/1850a9580697e019c601d09f5de490056fed2bab/anybadge.py#L291-L301 |
jongracecox/anybadge | anybadge.py | Badge.badge_color | def badge_color(self):
"""Find the badge color based on the thresholds."""
# 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:
return self.default_color
# Convert the threshold dictionary into a sorted list of lists
threshold_list = [[self.value_type(i[0]), i[1]] for i in self.thresholds.items()]
threshold_list.sort(key=lambda x: x[0])
color = None
for threshold, color in threshold_list:
if float(self.value) < float(threshold):
return color
# If we drop out the top of the range then return the last max color
if color and self.use_max_when_value_exceeds:
return color
else:
return self.default_color | python | def badge_color(self):
"""Find the badge color based on the thresholds."""
# 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:
return self.default_color
# Convert the threshold dictionary into a sorted list of lists
threshold_list = [[self.value_type(i[0]), i[1]] for i in self.thresholds.items()]
threshold_list.sort(key=lambda x: x[0])
color = None
for threshold, color in threshold_list:
if float(self.value) < float(threshold):
return color
# If we drop out the top of the range then return the last max color
if color and self.use_max_when_value_exceeds:
return color
else:
return self.default_color | Find the badge color based on the thresholds. | https://github.com/jongracecox/anybadge/blob/1850a9580697e019c601d09f5de490056fed2bab/anybadge.py#L304-L330 |
jongracecox/anybadge | anybadge.py | Badge.write_badge | def write_badge(self, file_path, overwrite=False):
"""Write badge to file."""
# 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'):
path += '.svg'
# Validate path (part 2)
if not overwrite and os.path.exists(path):
raise Exception('File "{}" already exists.'.format(path))
with open(path, mode='w') as file_handle:
file_handle.write(self.badge_svg_text) | python | def write_badge(self, file_path, overwrite=False):
"""Write badge to file."""
# 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'):
path += '.svg'
# Validate path (part 2)
if not overwrite and os.path.exists(path):
raise Exception('File "{}" already exists.'.format(path))
with open(path, mode='w') as file_handle:
file_handle.write(self.badge_svg_text) | Write badge to file. | https://github.com/jongracecox/anybadge/blob/1850a9580697e019c601d09f5de490056fed2bab/anybadge.py#L340-L357 |
jongracecox/anybadge | anybadge_server.py | main | def main():
"""Run server."""
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 = environ['ANYBADGE_LISTEN_ADDRESS']
if 'ANYBADGE_LOG_LEVEL' in environ:
DEFAULT_LOGGING_LEVEL = logging.getLevelName(environ['ANYBADGE_LOG_LEVEL'])
# Parse command line args
args = parse_args()
# Set logging level
logging_level = DEFAULT_LOGGING_LEVEL
if args.debug:
logging_level = logging.DEBUG
logging.basicConfig(format='%(asctime)-15s %(levelname)s:%(filename)s(%(lineno)d):%(funcName)s: %(message)s',
level=logging_level)
logger.info('Starting up anybadge server.')
run(listen_address=args.listen_address, port=args.port) | python | def main():
"""Run server."""
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 = environ['ANYBADGE_LISTEN_ADDRESS']
if 'ANYBADGE_LOG_LEVEL' in environ:
DEFAULT_LOGGING_LEVEL = logging.getLevelName(environ['ANYBADGE_LOG_LEVEL'])
# Parse command line args
args = parse_args()
# Set logging level
logging_level = DEFAULT_LOGGING_LEVEL
if args.debug:
logging_level = logging.DEBUG
logging.basicConfig(format='%(asctime)-15s %(levelname)s:%(filename)s(%(lineno)d):%(funcName)s: %(message)s',
level=logging_level)
logger.info('Starting up anybadge server.')
run(listen_address=args.listen_address, port=args.port) | Run server. | https://github.com/jongracecox/anybadge/blob/1850a9580697e019c601d09f5de490056fed2bab/anybadge_server.py#L129-L156 |
mschwager/cohesion | lib/cohesion/parser.py | get_object_name | def get_object_name(obj):
"""
Return the name of a given object
"""
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_dispatch[ast.arg] = "arg"
while not isinstance(obj, str):
assert type(obj) in name_dispatch
obj = getattr(obj, name_dispatch[type(obj)])
return obj | python | def get_object_name(obj):
"""
Return the name of a given object
"""
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_dispatch[ast.arg] = "arg"
while not isinstance(obj, str):
assert type(obj) in name_dispatch
obj = getattr(obj, name_dispatch[type(obj)])
return obj | Return the name of a given object | https://github.com/mschwager/cohesion/blob/b242ad59770940f3a0904931f27755ede009f491/lib/cohesion/parser.py#L8-L29 |
mschwager/cohesion | lib/cohesion/parser.py | get_attribute_name_id | def get_attribute_name_id(attr):
"""
Return the attribute name identifier
"""
return attr.value.id if isinstance(attr.value, ast.Name) else None | python | def get_attribute_name_id(attr):
"""
Return the attribute name identifier
"""
return attr.value.id if isinstance(attr.value, ast.Name) else None | Return the attribute name identifier | https://github.com/mschwager/cohesion/blob/b242ad59770940f3a0904931f27755ede009f491/lib/cohesion/parser.py#L32-L36 |
mschwager/cohesion | lib/cohesion/parser.py | is_class_method_bound | def is_class_method_bound(method, arg_name=BOUND_METHOD_ARGUMENT_NAME):
"""
Return whether a class method is bound to the class
"""
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 | python | def is_class_method_bound(method, arg_name=BOUND_METHOD_ARGUMENT_NAME):
"""
Return whether a class method is bound to the class
"""
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 | https://github.com/mschwager/cohesion/blob/b242ad59770940f3a0904931f27755ede009f491/lib/cohesion/parser.py#L39-L50 |
mschwager/cohesion | lib/cohesion/parser.py | get_class_methods | def get_class_methods(cls):
"""
Return methods associated with a given class
"""
return [
node
for node in cls.body
if isinstance(node, ast.FunctionDef)
] | python | def get_class_methods(cls):
"""
Return methods associated with a given class
"""
return [
node
for node in cls.body
if isinstance(node, ast.FunctionDef)
] | Return methods associated with a given class | https://github.com/mschwager/cohesion/blob/b242ad59770940f3a0904931f27755ede009f491/lib/cohesion/parser.py#L74-L82 |
mschwager/cohesion | lib/cohesion/parser.py | get_class_variables | def get_class_variables(cls):
"""
Return class variables associated with a given class
"""
return [
target
for node in cls.body
if isinstance(node, ast.Assign)
for target in node.targets
] | python | def get_class_variables(cls):
"""
Return class variables associated with a given class
"""
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 | https://github.com/mschwager/cohesion/blob/b242ad59770940f3a0904931f27755ede009f491/lib/cohesion/parser.py#L85-L94 |
mschwager/cohesion | lib/cohesion/parser.py | get_instance_variables | def get_instance_variables(node, bound_name_classifier=BOUND_METHOD_ARGUMENT_NAME):
"""
Return instance variables used in an AST node
"""
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 = [
get_object_name(child)
for child in ast.walk(node)
if isinstance(child, ast.Call)
]
node_instance_variables = [
attribute
for attribute in node_attributes
if get_object_name(attribute) not in node_function_call_names
]
return node_instance_variables | python | def get_instance_variables(node, bound_name_classifier=BOUND_METHOD_ARGUMENT_NAME):
"""
Return instance variables used in an AST node
"""
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 = [
get_object_name(child)
for child in ast.walk(node)
if isinstance(child, ast.Call)
]
node_instance_variables = [
attribute
for attribute in node_attributes
if get_object_name(attribute) not in node_function_call_names
]
return node_instance_variables | Return instance variables used in an AST node | https://github.com/mschwager/cohesion/blob/b242ad59770940f3a0904931f27755ede009f491/lib/cohesion/parser.py#L97-L117 |
mschwager/cohesion | lib/cohesion/parser.py | get_module_classes | def get_module_classes(node):
"""
Return classes associated with a given module
"""
return [
child
for child in ast.walk(node)
if isinstance(child, ast.ClassDef)
] | python | def get_module_classes(node):
"""
Return classes associated with a given module
"""
return [
child
for child in ast.walk(node)
if isinstance(child, ast.ClassDef)
] | Return classes associated with a given module | https://github.com/mschwager/cohesion/blob/b242ad59770940f3a0904931f27755ede009f491/lib/cohesion/parser.py#L149-L157 |
mschwager/cohesion | lib/cohesion/filesystem.py | recursively_get_files_from_directory | def recursively_get_files_from_directory(directory):
"""
Return all filenames under recursively found in a directory
"""
return [
os.path.join(root, filename)
for root, directories, filenames in os.walk(directory)
for filename in filenames
] | python | def recursively_get_files_from_directory(directory):
"""
Return all filenames under recursively found in a 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 | https://github.com/mschwager/cohesion/blob/b242ad59770940f3a0904931f27755ede009f491/lib/cohesion/filesystem.py#L21-L29 |
JarryShaw/PyPCAPKit | src/const/ipv6/seed_id.py | SeedID.get | def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return SeedID(key)
if key not in SeedID._member_map_:
extend_enum(SeedID, key, default)
return SeedID[key] | python | def get(key, default=-1):
"""Backport support for original codes."""
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. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/ipv6/seed_id.py#L18-L24 |
JarryShaw/PyPCAPKit | src/const/vlan/priority_level.py | PriorityLevel.get | def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return PriorityLevel(key)
if key not in PriorityLevel._member_map_:
extend_enum(PriorityLevel, key, default)
return PriorityLevel[key] | python | def get(key, default=-1):
"""Backport support for original codes."""
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. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/vlan/priority_level.py#L22-L28 |
JarryShaw/PyPCAPKit | src/const/ipv4/tos_thr.py | TOS_THR.get | def get(key, default=-1):
"""Backport support for original codes."""
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] | python | def get(key, default=-1):
"""Backport support for original codes."""
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. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/ipv4/tos_thr.py#L16-L22 |
JarryShaw/PyPCAPKit | src/const/ipv4/tos_thr.py | TOS_THR._missing_ | def _missing_(cls, value):
"""Lookup function used when value is not found."""
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) | python | def _missing_(cls, value):
"""Lookup function used when value is not found."""
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. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/ipv4/tos_thr.py#L25-L31 |
JarryShaw/PyPCAPKit | src/const/hip/registration.py | Registration.get | def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Registration(key)
if key not in Registration._member_map_:
extend_enum(Registration, key, default)
return Registration[key] | python | def get(key, default=-1):
"""Backport support for original codes."""
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. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/hip/registration.py#L17-L23 |
JarryShaw/PyPCAPKit | src/const/http/error_code.py | ErrorCode.get | def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return ErrorCode(key)
if key not in ErrorCode._member_map_:
extend_enum(ErrorCode, key, default)
return ErrorCode[key] | python | def get(key, default=-1):
"""Backport support for original codes."""
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. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/http/error_code.py#L28-L34 |
JarryShaw/PyPCAPKit | src/corekit/protochain.py | _AliasList.count | def count(self, value):
"""S.count(value) -> integer -- return number of occurrences of 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__()
if isinstance(value, tuple):
value = r'|'.join(value)
with contextlib.suppress(Exception):
return sum(1 for data in self.__data__ if re.fullmatch(value, data, re.IGNORECASE) is not None)
return 0 | python | def count(self, value):
"""S.count(value) -> integer -- return number of occurrences of 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__()
if isinstance(value, tuple):
value = r'|'.join(value)
with contextlib.suppress(Exception):
return sum(1 for data in self.__data__ if re.fullmatch(value, data, re.IGNORECASE) is not None)
return 0 | S.count(value) -> integer -- return number of occurrences of value | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/corekit/protochain.py#L116-L130 |
JarryShaw/PyPCAPKit | src/corekit/protochain.py | _AliasList.index | def index(self, value, start=0, stop=None):
"""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.
"""
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(start)
if not isinstance(stop, numbers.Integral):
stop = self.index(stop)
except IndexNotFound:
raise IntError('slice indices must be integers or have an __index__ method') from None
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__()
if isinstance(value, tuple):
value = r'|'.join(value)
try:
for index, data in enumerate(self.__data__[start:stop]):
if re.fullmatch(value, data, re.IGNORECASE):
return index
except Exception:
raise IndexNotFound(f'{value!r} is not in {self.__class__.__name__!r}') | python | def index(self, value, start=0, stop=None):
"""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.
"""
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(start)
if not isinstance(stop, numbers.Integral):
stop = self.index(stop)
except IndexNotFound:
raise IntError('slice indices must be integers or have an __index__ method') from None
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__()
if isinstance(value, tuple):
value = r'|'.join(value)
try:
for index, data in enumerate(self.__data__[start:stop]):
if re.fullmatch(value, data, re.IGNORECASE):
return index
except Exception:
raise IndexNotFound(f'{value!r} is not in {self.__class__.__name__!r}') | 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. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/corekit/protochain.py#L133-L168 |
JarryShaw/PyPCAPKit | src/corekit/protochain.py | ProtoChain.index | def index(self, value, start=None, stop=None):
"""Return first index of value."""
return self.__alias__.index(value, start, stop) | python | def index(self, value, start=None, stop=None):
"""Return first index of value."""
return self.__alias__.index(value, start, stop) | Return first index of value. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/corekit/protochain.py#L213-L215 |
JarryShaw/PyPCAPKit | src/const/hip/nat_traversal.py | NAT_Traversal.get | def get(key, default=-1):
"""Backport support for original codes."""
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] | python | def get(key, default=-1):
"""Backport support for original codes."""
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. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/hip/nat_traversal.py#L17-L23 |
JarryShaw/PyPCAPKit | src/protocols/link/ospf.py | OSPF.read_ospf | def read_ospf(self, length):
"""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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Version # | Type | Packet length |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Router ID |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Area ID |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Checksum | AuType |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Authentication |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Authentication |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 ospf.version Version #
1 8 ospf.type Type (0/1)
2 16 ospf.len Packet Length (header includes)
4 32 ospf.router_id Router ID
8 64 ospf.area_id Area ID
12 96 ospf.chksum Checksum
14 112 ospf.autype AuType
16 128 ospf.auth Authentication
"""
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(2)
_autp = self._read_unpack(2)
ospf = dict(
version=_vers,
type=TYPE.get(_type),
len=_tlen,
router_id=_rtid,
area_id=_area,
chksum=_csum,
autype=AUTH.get(_autp) or 'Reserved',
)
if _autp == 2:
ospf['auth'] = self._read_encrypt_auth()
else:
ospf['auth'] = self._read_fileng(8)
length = ospf['len'] - 24
ospf['packet'] = self._read_packet(header=24, payload=length)
return self._decode_next_layer(ospf, length) | python | def read_ospf(self, length):
"""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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Version # | Type | Packet length |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Router ID |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Area ID |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Checksum | AuType |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Authentication |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Authentication |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 ospf.version Version #
1 8 ospf.type Type (0/1)
2 16 ospf.len Packet Length (header includes)
4 32 ospf.router_id Router ID
8 64 ospf.area_id Area ID
12 96 ospf.chksum Checksum
14 112 ospf.autype AuType
16 128 ospf.auth Authentication
"""
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(2)
_autp = self._read_unpack(2)
ospf = dict(
version=_vers,
type=TYPE.get(_type),
len=_tlen,
router_id=_rtid,
area_id=_area,
chksum=_csum,
autype=AUTH.get(_autp) or 'Reserved',
)
if _autp == 2:
ospf['auth'] = self._read_encrypt_auth()
else:
ospf['auth'] = self._read_fileng(8)
length = ospf['len'] - 24
ospf['packet'] = self._read_packet(header=24, payload=length)
return self._decode_next_layer(ospf, length) | 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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Version # | Type | Packet length |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Router ID |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Area ID |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Checksum | AuType |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Authentication |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Authentication |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 ospf.version Version #
1 8 ospf.type Type (0/1)
2 16 ospf.len Packet Length (header includes)
4 32 ospf.router_id Router ID
8 64 ospf.area_id Area ID
12 96 ospf.chksum Checksum
14 112 ospf.autype AuType
16 128 ospf.auth Authentication | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/link/ospf.py#L95-L155 |
JarryShaw/PyPCAPKit | src/protocols/link/ospf.py | OSPF._read_id_numbers | def _read_id_numbers(self):
"""Read router and area IDs."""
_byte = self._read_fileng(4)
_addr = '.'.join([str(_) for _ in _byte])
return _addr | python | def _read_id_numbers(self):
"""Read router and area IDs."""
_byte = self._read_fileng(4)
_addr = '.'.join([str(_) for _ in _byte])
return _addr | Read router and area IDs. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/link/ospf.py#L172-L176 |
JarryShaw/PyPCAPKit | src/protocols/link/ospf.py | OSPF._read_encrypt_auth | def _read_encrypt_auth(self):
"""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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| 0 | Key ID | Auth Data Len |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Cryptographic sequence number |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 - Reserved (must be zero)
2 16 ospf.auth.key_id Key ID
3 24 ospf.auth.len Auth Data Length
4 32 ospf.auth.seq Cryptographic Sequence Number
"""
_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 | python | def _read_encrypt_auth(self):
"""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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| 0 | Key ID | Auth Data Len |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Cryptographic sequence number |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 - Reserved (must be zero)
2 16 ospf.auth.key_id Key ID
3 24 ospf.auth.len Auth Data Length
4 32 ospf.auth.seq Cryptographic Sequence Number
"""
_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
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| 0 | Key ID | Auth Data Len |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Cryptographic sequence number |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 - Reserved (must be zero)
2 16 ospf.auth.key_id Key ID
3 24 ospf.auth.len Auth Data Length
4 32 ospf.auth.seq Cryptographic Sequence Number | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/link/ospf.py#L178-L209 |
JarryShaw/PyPCAPKit | src/utilities/validations.py | int_check | def int_check(*args, func=None):
"""Check if arguments are integrals."""
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.') | python | def int_check(*args, func=None):
"""Check if arguments are integrals."""
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. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/utilities/validations.py#L36-L43 |
JarryShaw/PyPCAPKit | src/utilities/validations.py | real_check | def real_check(*args, func=None):
"""Check if arguments are real numbers."""
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.') | python | def real_check(*args, func=None):
"""Check if arguments are real numbers."""
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. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/utilities/validations.py#L46-L53 |
JarryShaw/PyPCAPKit | src/utilities/validations.py | complex_check | def complex_check(*args, func=None):
"""Check if arguments are complex numbers."""
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.') | python | def complex_check(*args, func=None):
"""Check if arguments are complex numbers."""
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. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/utilities/validations.py#L56-L63 |
JarryShaw/PyPCAPKit | src/utilities/validations.py | number_check | def number_check(*args, func=None):
"""Check if arguments are numbers."""
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.') | python | def number_check(*args, func=None):
"""Check if arguments are numbers."""
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. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/utilities/validations.py#L66-L73 |
JarryShaw/PyPCAPKit | src/utilities/validations.py | bytes_check | def bytes_check(*args, func=None):
"""Check if arguments are bytes type."""
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.') | python | def bytes_check(*args, func=None):
"""Check if arguments are bytes type."""
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. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/utilities/validations.py#L76-L83 |
JarryShaw/PyPCAPKit | src/utilities/validations.py | bytearray_check | def bytearray_check(*args, func=None):
"""Check if arguments are bytearray type."""
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} expected bytearray, {name} got instead.') | python | def bytearray_check(*args, func=None):
"""Check if arguments are bytearray type."""
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} expected bytearray, {name} got instead.') | Check if arguments are bytearray type. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/utilities/validations.py#L86-L93 |
JarryShaw/PyPCAPKit | src/utilities/validations.py | str_check | def str_check(*args, func=None):
"""Check if arguments are str type."""
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 instead.') | python | def str_check(*args, func=None):
"""Check if arguments are str type."""
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 instead.') | Check if arguments are str type. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/utilities/validations.py#L96-L103 |
JarryShaw/PyPCAPKit | src/utilities/validations.py | bool_check | def bool_check(*args, func=None):
"""Check if arguments are bytes type."""
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.') | python | def bool_check(*args, func=None):
"""Check if arguments are bytes type."""
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. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/utilities/validations.py#L106-L113 |
JarryShaw/PyPCAPKit | src/utilities/validations.py | list_check | def list_check(*args, func=None):
"""Check if arguments are list type."""
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} got instead.') | python | def list_check(*args, func=None):
"""Check if arguments are list type."""
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} got instead.') | Check if arguments are list type. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/utilities/validations.py#L116-L123 |
JarryShaw/PyPCAPKit | src/utilities/validations.py | dict_check | def dict_check(*args, func=None):
"""Check if arguments are dict type."""
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} got instead.') | python | def dict_check(*args, func=None):
"""Check if arguments are dict type."""
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} got instead.') | Check if arguments are dict type. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/utilities/validations.py#L126-L133 |
JarryShaw/PyPCAPKit | src/utilities/validations.py | tuple_check | def tuple_check(*args, func=None):
"""Check if arguments are tuple type."""
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.') | python | def tuple_check(*args, func=None):
"""Check if arguments are tuple type."""
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. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/utilities/validations.py#L136-L143 |
JarryShaw/PyPCAPKit | src/utilities/validations.py | io_check | def io_check(*args, func=None):
"""Check if arguments are file-like object."""
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.') | python | def io_check(*args, func=None):
"""Check if arguments are file-like object."""
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. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/utilities/validations.py#L146-L153 |
JarryShaw/PyPCAPKit | src/utilities/validations.py | info_check | def info_check(*args, func=None):
"""Check if arguments are Info instance."""
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} got instead.') | python | def info_check(*args, func=None):
"""Check if arguments are Info instance."""
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} got instead.') | Check if arguments are Info instance. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/utilities/validations.py#L156-L165 |
JarryShaw/PyPCAPKit | src/utilities/validations.py | ip_check | def ip_check(*args, func=None):
"""Check if arguments are IP addresses."""
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.') | python | def ip_check(*args, func=None):
"""Check if arguments are IP addresses."""
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. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/utilities/validations.py#L168-L175 |
JarryShaw/PyPCAPKit | src/utilities/validations.py | enum_check | def enum_check(*args, func=None):
"""Check if arguments are of protocol type."""
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.') | python | def enum_check(*args, func=None):
"""Check if arguments are of protocol type."""
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. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/utilities/validations.py#L178-L185 |
JarryShaw/PyPCAPKit | src/utilities/validations.py | frag_check | def frag_check(*args, protocol, func=None):
"""Check if arguments are valid fragments."""
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}.') | python | def frag_check(*args, protocol, func=None):
"""Check if arguments are valid fragments."""
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. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/utilities/validations.py#L188-L196 |
JarryShaw/PyPCAPKit | src/utilities/validations.py | _ip_frag_check | def _ip_frag_check(*args, func=None):
"""Check if arguments are valid IP fragments."""
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)
bytearray_check(var.get('header'), var.get('payload'), func=func)
int_check(bufid[2], var.get('num'), var.get('fo'),
var.get('ihl'), var.get('tl'), func=func) | python | def _ip_frag_check(*args, func=None):
"""Check if arguments are valid IP fragments."""
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)
bytearray_check(var.get('header'), var.get('payload'), func=func)
int_check(bufid[2], var.get('num'), var.get('fo'),
var.get('ihl'), var.get('tl'), func=func) | Check if arguments are valid IP fragments. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/utilities/validations.py#L199-L210 |
JarryShaw/PyPCAPKit | src/utilities/validations.py | pkt_check | def pkt_check(*args, func=None):
"""Check if arguments are valid packets."""
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'), var.get('dst'), func=func)
bool_check(var.get('syn'), var.get('fin'), func=func)
int_check(var.get('srcport'), var.get('dstport'), var.get('index'), func=func) | python | def pkt_check(*args, func=None):
"""Check if arguments are valid packets."""
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'), var.get('dst'), func=func)
bool_check(var.get('syn'), var.get('fin'), func=func)
int_check(var.get('srcport'), var.get('dstport'), var.get('index'), func=func) | Check if arguments are valid packets. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/utilities/validations.py#L226-L236 |
JarryShaw/PyPCAPKit | src/reassembly/reassembly.py | Reassembly.fetch | def fetch(self):
"""Fetch datagram."""
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(self._dtgram) | python | def fetch(self):
"""Fetch datagram."""
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(self._dtgram) | Fetch datagram. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/reassembly/reassembly.py#L108-L116 |
JarryShaw/PyPCAPKit | src/reassembly/reassembly.py | Reassembly.index | def index(self, pkt_num):
"""Return datagram index."""
int_check(pkt_num)
for counter, datagram in enumerate(self.datagram):
if pkt_num in datagram.index:
return counter
return None | python | def index(self, pkt_num):
"""Return datagram index."""
int_check(pkt_num)
for counter, datagram in enumerate(self.datagram):
if pkt_num in datagram.index:
return counter
return None | Return datagram index. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/reassembly/reassembly.py#L119-L125 |
JarryShaw/PyPCAPKit | src/reassembly/reassembly.py | Reassembly.run | def run(self, packets):
"""Run automatically.
Positional arguments:
* packets -- list<dict>, list of packet dicts to be reassembled
"""
for packet in packets:
frag_check(packet, protocol=self.protocol)
info = Info(packet)
self.reassembly(info)
self._newflg = True | python | def run(self, packets):
"""Run automatically.
Positional arguments:
* packets -- list<dict>, list of packet dicts to be reassembled
"""
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 | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/reassembly/reassembly.py#L128-L139 |
JarryShaw/PyPCAPKit | src/protocols/internet/mh.py | MH.read_mh | def read_mh(self, length, extension):
"""Read Mobility Header.
Structure of MH header [RFC 6275]:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Payload Proto | Header Len | MH Type | Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Checksum | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |
| |
. .
. Message Data .
. .
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 mh.next Next Header
1 8 mh.length Header Length
2 16 mh.type Mobility Header Type
3 24 - Reserved
4 32 mh.chksum Checksum
6 48 mh.data Message Data
"""
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_fileng((_hlen+1)*8)
mh = dict(
next=_next,
length=(_hlen + 1) * 8,
type=_MOBILITY_TYPE.get(_type, 'Unassigned'),
chksum=_csum,
)
length -= mh['length']
mh['packet'] = self._read_packet(header=mh['length'], payload=length)
if extension:
self._protos = None
return mh
return self._decode_next_layer(mh, _next, length) | python | def read_mh(self, length, extension):
"""Read Mobility Header.
Structure of MH header [RFC 6275]:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Payload Proto | Header Len | MH Type | Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Checksum | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |
| |
. .
. Message Data .
. .
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 mh.next Next Header
1 8 mh.length Header Length
2 16 mh.type Mobility Header Type
3 24 - Reserved
4 32 mh.chksum Checksum
6 48 mh.data Message Data
"""
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_fileng((_hlen+1)*8)
mh = dict(
next=_next,
length=(_hlen + 1) * 8,
type=_MOBILITY_TYPE.get(_type, 'Unassigned'),
chksum=_csum,
)
length -= mh['length']
mh['packet'] = self._read_packet(header=mh['length'], payload=length)
if extension:
self._protos = None
return mh
return self._decode_next_layer(mh, _next, length) | Read Mobility Header.
Structure of MH header [RFC 6275]:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Payload Proto | Header Len | MH Type | Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Checksum | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |
| |
. .
. Message Data .
. .
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Octets Bits Name Description
0 0 mh.next Next Header
1 8 mh.length Header Length
2 16 mh.type Mobility Header Type
3 24 - Reserved
4 32 mh.chksum Checksum
6 48 mh.data Message Data | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/mh.py#L91-L139 |
JarryShaw/PyPCAPKit | src/const/hip/di.py | DI.get | def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return DI(key)
if key not in DI._member_map_:
extend_enum(DI, key, default)
return DI[key] | python | def get(key, default=-1):
"""Backport support for original codes."""
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. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/hip/di.py#L17-L23 |
JarryShaw/PyPCAPKit | src/const/hip/certificate.py | Certificate.get | def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Certificate(key)
if key not in Certificate._member_map_:
extend_enum(Certificate, key, default)
return Certificate[key] | python | def get(key, default=-1):
"""Backport support for original codes."""
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. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/hip/certificate.py#L23-L29 |
JarryShaw/PyPCAPKit | src/protocols/transport/udp.py | UDP.read_udp | def read_udp(self, length):
"""Read User Datagram Protocol (UDP).
Structure of UDP header [RFC 768]:
0 7 8 15 16 23 24 31
+--------+--------+--------+--------+
| Source | Destination |
| Port | Port |
+--------+--------+--------+--------+
| | |
| Length | Checksum |
+--------+--------+--------+--------+
|
| data octets ...
+---------------- ...
Octets Bits Name Description
0 0 udp.srcport Source Port
2 16 udp.dstport Destination Port
4 32 udp.len Length (header includes)
6 48 udp.checksum Checksum
"""
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,
len=_tlen,
checksum=_csum,
)
length = udp['len'] - 8
udp['packet'] = self._read_packet(header=8, payload=length)
return self._decode_next_layer(udp, None, length) | python | def read_udp(self, length):
"""Read User Datagram Protocol (UDP).
Structure of UDP header [RFC 768]:
0 7 8 15 16 23 24 31
+--------+--------+--------+--------+
| Source | Destination |
| Port | Port |
+--------+--------+--------+--------+
| | |
| Length | Checksum |
+--------+--------+--------+--------+
|
| data octets ...
+---------------- ...
Octets Bits Name Description
0 0 udp.srcport Source Port
2 16 udp.dstport Destination Port
4 32 udp.len Length (header includes)
6 48 udp.checksum Checksum
"""
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,
len=_tlen,
checksum=_csum,
)
length = udp['len'] - 8
udp['packet'] = self._read_packet(header=8, payload=length)
return self._decode_next_layer(udp, None, length) | Read User Datagram Protocol (UDP).
Structure of UDP header [RFC 768]:
0 7 8 15 16 23 24 31
+--------+--------+--------+--------+
| Source | Destination |
| Port | Port |
+--------+--------+--------+--------+
| | |
| Length | Checksum |
+--------+--------+--------+--------+
|
| data octets ...
+---------------- ...
Octets Bits Name Description
0 0 udp.srcport Source Port
2 16 udp.dstport Destination Port
4 32 udp.len Length (header includes)
6 48 udp.checksum Checksum | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/transport/udp.py#L87-L128 |
JarryShaw/PyPCAPKit | src/protocols/internet/ipx.py | IPX.read_ipx | def read_ipx(self, length):
"""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 32 ipx.count Transport Control (hop count)
5 40 ipx.type Packet Type
6 48 ipx.dst Destination Address
18 144 ipx.src Source Address
"""
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_address()
ipx = dict(
chksum=_csum,
len=_tlen,
count=_ctrl,
type=TYPE.get(_type),
dst=_dsta,
src=_srca,
)
proto = ipx['type']
length = ipx['len'] - 30
ipx['packet'] = self._read_packet(header=30, payload=length)
return self._decode_next_layer(ipx, proto, length) | python | def read_ipx(self, length):
"""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 32 ipx.count Transport Control (hop count)
5 40 ipx.type Packet Type
6 48 ipx.dst Destination Address
18 144 ipx.src Source Address
"""
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_address()
ipx = dict(
chksum=_csum,
len=_tlen,
count=_ctrl,
type=TYPE.get(_type),
dst=_dsta,
src=_srca,
)
proto = ipx['type']
length = ipx['len'] - 30
ipx['packet'] = self._read_packet(header=30, payload=length)
return self._decode_next_layer(ipx, proto, length) | 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 32 ipx.count Transport Control (hop count)
5 40 ipx.type Packet Type
6 48 ipx.dst Destination Address
18 144 ipx.src Source Address | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/ipx.py#L93-L129 |
JarryShaw/PyPCAPKit | src/protocols/internet/ipx.py | IPX._read_ipx_address | def _read_ipx_address(self):
"""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 Socket Number
"""
# 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(_byte.hex(), 2))
# Socket Number
_sock = self._read_fileng(2)
# Whole Address
_list = [_ntwk, _node, _sock.hex()]
_addr = ':'.join(_list)
addr = dict(
network=_ntwk,
node=_maca,
socket=SOCK.get(int(_sock.hex(), base=16)) or _sock,
addr=_addr,
)
return addr | python | def _read_ipx_address(self):
"""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 Socket Number
"""
# 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(_byte.hex(), 2))
# Socket Number
_sock = self._read_fileng(2)
# Whole Address
_list = [_ntwk, _node, _sock.hex()]
_addr = ':'.join(_list)
addr = dict(
network=_ntwk,
node=_maca,
socket=SOCK.get(int(_sock.hex(), base=16)) or _sock,
addr=_addr,
)
return addr | 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 Socket Number | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/internet/ipx.py#L146-L179 |
JarryShaw/PyPCAPKit | src/const/hip/group.py | Group.get | def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Group(key)
if key not in Group._member_map_:
extend_enum(Group, key, default)
return Group[key] | python | def get(key, default=-1):
"""Backport support for original codes."""
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. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/hip/group.py#L26-L32 |
JarryShaw/PyPCAPKit | src/protocols/link/arp.py | ARP.read_arp | def read_arp(self, length):
"""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 arp.hlen Hardware Address Length
5 40 arp.plen Protocol Address Length
6 48 arp.oper Operation
8 64 arp.sha Sender Hardware Address
14 112 arp.spa Sender Protocol Address
18 144 arp.tha Target Hardware Address
24 192 arp.tpa Target Protocol Address
"""
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(_hlen, _hwty)
_spta = self._read_proto_resolve(_plen, _ptty)
_thwa = self._read_addr_resolve(_hlen, _hwty)
_tpta = self._read_proto_resolve(_plen, _ptty)
if _oper in (5, 6, 7):
self._acnm = 'DRARP'
self._name = 'Dynamic Reverse Address Resolution Protocol'
elif _oper in (8, 9):
self._acnm = 'InARP'
self._name = 'Inverse Address Resolution Protocol'
elif _oper in (3, 4):
self._acnm = 'RARP'
self._name = 'Reverse Address Resolution Protocol'
else:
self._acnm = 'ARP'
self._name = 'Address Resolution Protocol'
_htype = HRD.get(_hwty)
if re.match(r'.*Ethernet.*', _htype, re.IGNORECASE):
_ptype = ETHERTYPE.get(_ptty)
else:
_ptype = f'Unknown [{_ptty}]'
arp = dict(
htype=_htype,
ptype=_ptype,
hlen=_hlen,
plen=_plen,
oper=OPER.get(_oper),
sha=_shwa,
spa=_spta,
tha=_thwa,
tpa=_tpta,
len=8 + _hlen * 2 + _plen * 2,
)
length -= arp['len']
arp['packet'] = self._read_packet(header=arp['len'], payload=length)
return self._decode_next_layer(arp, None, length) | python | def read_arp(self, length):
"""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 arp.hlen Hardware Address Length
5 40 arp.plen Protocol Address Length
6 48 arp.oper Operation
8 64 arp.sha Sender Hardware Address
14 112 arp.spa Sender Protocol Address
18 144 arp.tha Target Hardware Address
24 192 arp.tpa Target Protocol Address
"""
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(_hlen, _hwty)
_spta = self._read_proto_resolve(_plen, _ptty)
_thwa = self._read_addr_resolve(_hlen, _hwty)
_tpta = self._read_proto_resolve(_plen, _ptty)
if _oper in (5, 6, 7):
self._acnm = 'DRARP'
self._name = 'Dynamic Reverse Address Resolution Protocol'
elif _oper in (8, 9):
self._acnm = 'InARP'
self._name = 'Inverse Address Resolution Protocol'
elif _oper in (3, 4):
self._acnm = 'RARP'
self._name = 'Reverse Address Resolution Protocol'
else:
self._acnm = 'ARP'
self._name = 'Address Resolution Protocol'
_htype = HRD.get(_hwty)
if re.match(r'.*Ethernet.*', _htype, re.IGNORECASE):
_ptype = ETHERTYPE.get(_ptty)
else:
_ptype = f'Unknown [{_ptty}]'
arp = dict(
htype=_htype,
ptype=_ptype,
hlen=_hlen,
plen=_plen,
oper=OPER.get(_oper),
sha=_shwa,
spa=_spta,
tha=_thwa,
tpa=_tpta,
len=8 + _hlen * 2 + _plen * 2,
)
length -= arp['len']
arp['packet'] = self._read_packet(header=arp['len'], payload=length)
return self._decode_next_layer(arp, None, length) | 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 arp.hlen Hardware Address Length
5 40 arp.plen Protocol Address Length
6 48 arp.oper Operation
8 64 arp.sha Sender Hardware Address
14 112 arp.spa Sender Protocol Address
18 144 arp.tha Target Hardware Address
24 192 arp.tpa Target Protocol Address | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/link/arp.py#L116-L180 |
JarryShaw/PyPCAPKit | src/protocols/link/arp.py | ARP._read_addr_resolve | def _read_addr_resolve(self, length, htype):
"""Resolve MAC address according to protocol.
Positional arguments:
* length -- int, hardware address length
* htype -- int, hardware type
Returns:
* str -- MAC address
"""
if htype == 1: # Ethernet
_byte = self._read_fileng(6)
_addr = '-'.join(textwrap.wrap(_byte.hex(), 2))
else:
_addr = self._read_fileng(length)
return _addr | python | def _read_addr_resolve(self, length, htype):
"""Resolve MAC address according to protocol.
Positional arguments:
* length -- int, hardware address length
* htype -- int, hardware type
Returns:
* str -- MAC address
"""
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 | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/link/arp.py#L201-L217 |
JarryShaw/PyPCAPKit | src/protocols/link/arp.py | ARP._read_proto_resolve | def _read_proto_resolve(self, length, ptype):
"""Resolve IP address according to protocol.
Positional arguments:
* length -- int, protocol address length
* ptype -- int, protocol type
Returns:
* str -- IP address
"""
# 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_ = collections.defaultdict(int)
# # counter for consecutive groups of zero value
# ptr_ = 0 # start pointer of consecutive groups of zero value
# last = False # if last hextet/group is zero value
# omit = False # omitted flag, since IPv6 address can omit to `::` only once
# for index in range(8):
# hex_ = self._read_fileng(2).hex().lstrip('0')
# if hex_: # if hextet is not '', directly append
# adlt.append(hex_)
# last = False
# else: # if hextet is '', append '0'
# adlt.append('0')
# if last: # if last hextet is '', ascend counter
# ctr_[ptr_] += 1
# else: # if last hextet is not '', record pointer
# ptr_ = index
# last = True
# ctr_[ptr_] = 1
# ptr_ = max(ctr_, key=ctr_.get) if ctr_ else 0 # fetch start pointer with longest zero values
# end_ = ptr_ + ctr_[ptr_] # calculate end pointer
# if ctr_[ptr_] > 1: # only omit if zero values are in a consecutive group
# del adlt[ptr_:end_] # remove zero values
# if ptr_ == 0 and end_ == 8: # insert `::` if IPv6 unspecified address (::)
# adlt.insert(ptr_, '::')
# elif ptr_ == 0 or end_ == 8: # insert `:` if zero values are from start or at end
# adlt.insert(ptr_, ':')
# else: # insert '' otherwise
# adlt.insert(ptr_, '')
# _addr = ':'.join(adlt)
# else:
# _addr = self._read_fileng(length)
# return _addr
if ptype == '0800': # IPv4
return ipaddress.ip_address(self._read_fileng(4))
elif ptype == '86dd': # IPv6
return ipaddress.ip_address(self._read_fileng(16))
else:
return self._read_fileng(length) | python | def _read_proto_resolve(self, length, ptype):
"""Resolve IP address according to protocol.
Positional arguments:
* length -- int, protocol address length
* ptype -- int, protocol type
Returns:
* str -- IP address
"""
# 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_ = collections.defaultdict(int)
# # counter for consecutive groups of zero value
# ptr_ = 0 # start pointer of consecutive groups of zero value
# last = False # if last hextet/group is zero value
# omit = False # omitted flag, since IPv6 address can omit to `::` only once
# for index in range(8):
# hex_ = self._read_fileng(2).hex().lstrip('0')
# if hex_: # if hextet is not '', directly append
# adlt.append(hex_)
# last = False
# else: # if hextet is '', append '0'
# adlt.append('0')
# if last: # if last hextet is '', ascend counter
# ctr_[ptr_] += 1
# else: # if last hextet is not '', record pointer
# ptr_ = index
# last = True
# ctr_[ptr_] = 1
# ptr_ = max(ctr_, key=ctr_.get) if ctr_ else 0 # fetch start pointer with longest zero values
# end_ = ptr_ + ctr_[ptr_] # calculate end pointer
# if ctr_[ptr_] > 1: # only omit if zero values are in a consecutive group
# del adlt[ptr_:end_] # remove zero values
# if ptr_ == 0 and end_ == 8: # insert `::` if IPv6 unspecified address (::)
# adlt.insert(ptr_, '::')
# elif ptr_ == 0 or end_ == 8: # insert `:` if zero values are from start or at end
# adlt.insert(ptr_, ':')
# else: # insert '' otherwise
# adlt.insert(ptr_, '')
# _addr = ':'.join(adlt)
# else:
# _addr = self._read_fileng(length)
# return _addr
if ptype == '0800': # IPv4
return ipaddress.ip_address(self._read_fileng(4))
elif ptype == '86dd': # IPv6
return ipaddress.ip_address(self._read_fileng(16))
else:
return self._read_fileng(length) | Resolve IP address according to protocol.
Positional arguments:
* length -- int, protocol address length
* ptype -- int, protocol type
Returns:
* str -- IP address | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/protocols/link/arp.py#L219-L278 |
JarryShaw/PyPCAPKit | src/const/http/setting.py | Setting.get | def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Setting(key)
if key not in Setting._member_map_:
extend_enum(Setting, key, default)
return Setting[key] | python | def get(key, default=-1):
"""Backport support for original codes."""
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. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/http/setting.py#L23-L29 |
JarryShaw/PyPCAPKit | src/const/hip/transport.py | Transport.get | def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Transport(key)
if key not in Transport._member_map_:
extend_enum(Transport, key, default)
return Transport[key] | python | def get(key, default=-1):
"""Backport support for original codes."""
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. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/hip/transport.py#L18-L24 |
JarryShaw/PyPCAPKit | src/const/ipv4/tos_del.py | TOS_DEL.get | def get(key, default=-1):
"""Backport support for original codes."""
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] | python | def get(key, default=-1):
"""Backport support for original codes."""
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. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/ipv4/tos_del.py#L16-L22 |
JarryShaw/PyPCAPKit | src/const/misc/ethertype.py | EtherType.get | def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return EtherType(key)
if key not in EtherType._member_map_:
extend_enum(EtherType, key, default)
return EtherType[key] | python | def get(key, default=-1):
"""Backport support for original codes."""
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. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/misc/ethertype.py#L175-L181 |
JarryShaw/PyPCAPKit | src/const/misc/ethertype.py | EtherType._missing_ | def _missing_(cls, value):
"""Lookup function used when value is not found."""
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(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x0101 <= value <= 0x01FF:
# [Neil_Sembower]
extend_enum(cls, 'Experimental [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x0888 <= value <= 0x088A:
# [Neil_Sembower]
extend_enum(cls, 'Xyplex [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x1001 <= value <= 0x100F:
# [Neil_Sembower]
extend_enum(cls, 'Berkeley Trailer encap/IP [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x6008 <= value <= 0x6009:
# [Neil_Sembower]
extend_enum(cls, 'DEC Unassigned [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x6010 <= value <= 0x6014:
# [Neil_Sembower]
extend_enum(cls, '3Com Corporation [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x7020 <= value <= 0x7029:
# [Neil_Sembower]
extend_enum(cls, 'LRT [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8039 <= value <= 0x803C:
# [Neil_Sembower]
extend_enum(cls, 'DEC Unassigned [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8040 <= value <= 0x8042:
# [Neil_Sembower]
extend_enum(cls, 'DEC Unassigned [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x806E <= value <= 0x8077:
# [Neil_Sembower]
extend_enum(cls, 'Landmark Graphics Corp. [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x807D <= value <= 0x807F:
# [Neil_Sembower]
extend_enum(cls, 'Vitalink Communications [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8081 <= value <= 0x8083:
# [Neil_Sembower]
extend_enum(cls, 'Counterpoint Computers [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x809C <= value <= 0x809E:
# [Neil_Sembower]
extend_enum(cls, 'Datability [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x80A4 <= value <= 0x80B3:
# [Neil_Sembower]
extend_enum(cls, 'Siemens Gammasonics Inc. [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x80C0 <= value <= 0x80C3:
# [Neil_Sembower]
extend_enum(cls, 'DCA Data Exchange Cluster [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x80C8 <= value <= 0x80CC:
# [Neil_Sembower]
extend_enum(cls, 'Intergraph Corporation [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x80CD <= value <= 0x80CE:
# [Neil_Sembower]
extend_enum(cls, 'Harris Corporation [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x80CF <= value <= 0x80D2:
# [Neil_Sembower]
extend_enum(cls, 'Taylor Instrument [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x80D3 <= value <= 0x80D4:
# [Neil_Sembower]
extend_enum(cls, 'Rosemount Corporation [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x80DE <= value <= 0x80DF:
# [Neil_Sembower]
extend_enum(cls, 'Integrated Solutions TRFS [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x80E0 <= value <= 0x80E3:
# [Neil_Sembower]
extend_enum(cls, 'Allen-Bradley [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x80E4 <= value <= 0x80F0:
# [Neil_Sembower]
extend_enum(cls, 'Datability [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x80F4 <= value <= 0x80F5:
# [Neil_Sembower]
extend_enum(cls, 'Kinetics [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8101 <= value <= 0x8103:
# [Neil_Sembower]
extend_enum(cls, 'Wellfleet Communications [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8107 <= value <= 0x8109:
# [Neil_Sembower]
extend_enum(cls, 'Symbolics Private [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8132 <= value <= 0x8136:
# [Neil_Sembower]
extend_enum(cls, 'Bridge Communications [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8137 <= value <= 0x8138:
# [Neil_Sembower]
extend_enum(cls, 'Novell, Inc. [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8139 <= value <= 0x813D:
# [Neil_Sembower]
extend_enum(cls, 'KTI [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8151 <= value <= 0x8153:
# [Neil_Sembower]
extend_enum(cls, 'Qualcomm [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x815C <= value <= 0x815E:
# [Neil_Sembower]
extend_enum(cls, 'Computer Protocol Pty Ltd [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8164 <= value <= 0x8166:
# [Neil_Sembower]
extend_enum(cls, 'Charles River Data System [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8184 <= value <= 0x818C:
# [Neil_Sembower]
extend_enum(cls, 'Silicon Graphics prop. [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x819A <= value <= 0x81A3:
# [Neil_Sembower]
extend_enum(cls, 'Qualcomm [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x81A5 <= value <= 0x81AE:
# [Neil_Sembower]
extend_enum(cls, 'RAD Network Devices [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x81B7 <= value <= 0x81B9:
# [Neil_Sembower]
extend_enum(cls, 'Xyplex [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x81CC <= value <= 0x81D5:
# [Neil_Sembower]
extend_enum(cls, 'Apricot Computers [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x81D6 <= value <= 0x81DD:
# [Neil_Sembower]
extend_enum(cls, 'Artisoft [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x81E6 <= value <= 0x81EF:
# [Neil_Sembower]
extend_enum(cls, 'Polygon [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x81F0 <= value <= 0x81F2:
# [Neil_Sembower]
extend_enum(cls, 'Comsat Labs [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x81F3 <= value <= 0x81F5:
# [Neil_Sembower]
extend_enum(cls, 'SAIC [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x81F6 <= value <= 0x81F8:
# [Neil_Sembower]
extend_enum(cls, 'VG Analytical [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8203 <= value <= 0x8205:
# [Neil_Sembower]
extend_enum(cls, 'Quantum Software [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8221 <= value <= 0x8222:
# [Neil_Sembower]
extend_enum(cls, 'Ascom Banking Systems [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x823E <= value <= 0x8240:
# [Neil_Sembower]
extend_enum(cls, 'Advanced Encryption Syste [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x827F <= value <= 0x8282:
# [Neil_Sembower]
extend_enum(cls, 'Athena Programming [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8263 <= value <= 0x826A:
# [Neil_Sembower]
extend_enum(cls, 'Charles River Data System [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x829A <= value <= 0x829B:
# [Neil_Sembower]
extend_enum(cls, 'Inst Ind Info Tech [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x829C <= value <= 0x82AB:
# [Neil_Sembower]
extend_enum(cls, 'Taurus Controls [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x82AC <= value <= 0x8693:
# [Neil_Sembower]
extend_enum(cls, 'Walker Richer & Quinn [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8694 <= value <= 0x869D:
# [Neil_Sembower]
extend_enum(cls, 'Idea Courier [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x869E <= value <= 0x86A1:
# [Neil_Sembower]
extend_enum(cls, 'Computer Network Tech [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x86A3 <= value <= 0x86AC:
# [Neil_Sembower]
extend_enum(cls, 'Gateway Communications [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x86E0 <= value <= 0x86EF:
# [Neil_Sembower]
extend_enum(cls, 'Landis & Gyr Powers [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8700 <= value <= 0x8710:
# [Neil_Sembower]
extend_enum(cls, 'Motorola [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8A96 <= value <= 0x8A97:
# [Neil_Sembower]
extend_enum(cls, 'Invisible Software [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0xFF00 <= value <= 0xFF0F:
# [Neil_Sembower]
extend_enum(cls, 'ISC Bunker Ramo [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
super()._missing_(value) | python | def _missing_(cls, value):
"""Lookup function used when value is not found."""
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(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x0101 <= value <= 0x01FF:
# [Neil_Sembower]
extend_enum(cls, 'Experimental [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x0888 <= value <= 0x088A:
# [Neil_Sembower]
extend_enum(cls, 'Xyplex [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x1001 <= value <= 0x100F:
# [Neil_Sembower]
extend_enum(cls, 'Berkeley Trailer encap/IP [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x6008 <= value <= 0x6009:
# [Neil_Sembower]
extend_enum(cls, 'DEC Unassigned [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x6010 <= value <= 0x6014:
# [Neil_Sembower]
extend_enum(cls, '3Com Corporation [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x7020 <= value <= 0x7029:
# [Neil_Sembower]
extend_enum(cls, 'LRT [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8039 <= value <= 0x803C:
# [Neil_Sembower]
extend_enum(cls, 'DEC Unassigned [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8040 <= value <= 0x8042:
# [Neil_Sembower]
extend_enum(cls, 'DEC Unassigned [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x806E <= value <= 0x8077:
# [Neil_Sembower]
extend_enum(cls, 'Landmark Graphics Corp. [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x807D <= value <= 0x807F:
# [Neil_Sembower]
extend_enum(cls, 'Vitalink Communications [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8081 <= value <= 0x8083:
# [Neil_Sembower]
extend_enum(cls, 'Counterpoint Computers [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x809C <= value <= 0x809E:
# [Neil_Sembower]
extend_enum(cls, 'Datability [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x80A4 <= value <= 0x80B3:
# [Neil_Sembower]
extend_enum(cls, 'Siemens Gammasonics Inc. [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x80C0 <= value <= 0x80C3:
# [Neil_Sembower]
extend_enum(cls, 'DCA Data Exchange Cluster [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x80C8 <= value <= 0x80CC:
# [Neil_Sembower]
extend_enum(cls, 'Intergraph Corporation [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x80CD <= value <= 0x80CE:
# [Neil_Sembower]
extend_enum(cls, 'Harris Corporation [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x80CF <= value <= 0x80D2:
# [Neil_Sembower]
extend_enum(cls, 'Taylor Instrument [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x80D3 <= value <= 0x80D4:
# [Neil_Sembower]
extend_enum(cls, 'Rosemount Corporation [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x80DE <= value <= 0x80DF:
# [Neil_Sembower]
extend_enum(cls, 'Integrated Solutions TRFS [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x80E0 <= value <= 0x80E3:
# [Neil_Sembower]
extend_enum(cls, 'Allen-Bradley [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x80E4 <= value <= 0x80F0:
# [Neil_Sembower]
extend_enum(cls, 'Datability [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x80F4 <= value <= 0x80F5:
# [Neil_Sembower]
extend_enum(cls, 'Kinetics [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8101 <= value <= 0x8103:
# [Neil_Sembower]
extend_enum(cls, 'Wellfleet Communications [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8107 <= value <= 0x8109:
# [Neil_Sembower]
extend_enum(cls, 'Symbolics Private [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8132 <= value <= 0x8136:
# [Neil_Sembower]
extend_enum(cls, 'Bridge Communications [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8137 <= value <= 0x8138:
# [Neil_Sembower]
extend_enum(cls, 'Novell, Inc. [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8139 <= value <= 0x813D:
# [Neil_Sembower]
extend_enum(cls, 'KTI [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8151 <= value <= 0x8153:
# [Neil_Sembower]
extend_enum(cls, 'Qualcomm [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x815C <= value <= 0x815E:
# [Neil_Sembower]
extend_enum(cls, 'Computer Protocol Pty Ltd [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8164 <= value <= 0x8166:
# [Neil_Sembower]
extend_enum(cls, 'Charles River Data System [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8184 <= value <= 0x818C:
# [Neil_Sembower]
extend_enum(cls, 'Silicon Graphics prop. [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x819A <= value <= 0x81A3:
# [Neil_Sembower]
extend_enum(cls, 'Qualcomm [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x81A5 <= value <= 0x81AE:
# [Neil_Sembower]
extend_enum(cls, 'RAD Network Devices [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x81B7 <= value <= 0x81B9:
# [Neil_Sembower]
extend_enum(cls, 'Xyplex [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x81CC <= value <= 0x81D5:
# [Neil_Sembower]
extend_enum(cls, 'Apricot Computers [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x81D6 <= value <= 0x81DD:
# [Neil_Sembower]
extend_enum(cls, 'Artisoft [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x81E6 <= value <= 0x81EF:
# [Neil_Sembower]
extend_enum(cls, 'Polygon [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x81F0 <= value <= 0x81F2:
# [Neil_Sembower]
extend_enum(cls, 'Comsat Labs [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x81F3 <= value <= 0x81F5:
# [Neil_Sembower]
extend_enum(cls, 'SAIC [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x81F6 <= value <= 0x81F8:
# [Neil_Sembower]
extend_enum(cls, 'VG Analytical [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8203 <= value <= 0x8205:
# [Neil_Sembower]
extend_enum(cls, 'Quantum Software [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8221 <= value <= 0x8222:
# [Neil_Sembower]
extend_enum(cls, 'Ascom Banking Systems [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x823E <= value <= 0x8240:
# [Neil_Sembower]
extend_enum(cls, 'Advanced Encryption Syste [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x827F <= value <= 0x8282:
# [Neil_Sembower]
extend_enum(cls, 'Athena Programming [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8263 <= value <= 0x826A:
# [Neil_Sembower]
extend_enum(cls, 'Charles River Data System [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x829A <= value <= 0x829B:
# [Neil_Sembower]
extend_enum(cls, 'Inst Ind Info Tech [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x829C <= value <= 0x82AB:
# [Neil_Sembower]
extend_enum(cls, 'Taurus Controls [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x82AC <= value <= 0x8693:
# [Neil_Sembower]
extend_enum(cls, 'Walker Richer & Quinn [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8694 <= value <= 0x869D:
# [Neil_Sembower]
extend_enum(cls, 'Idea Courier [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x869E <= value <= 0x86A1:
# [Neil_Sembower]
extend_enum(cls, 'Computer Network Tech [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x86A3 <= value <= 0x86AC:
# [Neil_Sembower]
extend_enum(cls, 'Gateway Communications [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x86E0 <= value <= 0x86EF:
# [Neil_Sembower]
extend_enum(cls, 'Landis & Gyr Powers [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8700 <= value <= 0x8710:
# [Neil_Sembower]
extend_enum(cls, 'Motorola [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0x8A96 <= value <= 0x8A97:
# [Neil_Sembower]
extend_enum(cls, 'Invisible Software [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
if 0xFF00 <= value <= 0xFF0F:
# [Neil_Sembower]
extend_enum(cls, 'ISC Bunker Ramo [0x%s]' % hex(value)[2:].upper().zfill(4), value)
return cls(value)
super()._missing_(value) | Lookup function used when value is not found. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/misc/ethertype.py#L184-L412 |
JarryShaw/PyPCAPKit | src/const/ipv4/tos_ecn.py | TOS_ECN.get | def get(key, default=-1):
"""Backport support for original codes."""
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] | python | def get(key, default=-1):
"""Backport support for original codes."""
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. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/ipv4/tos_ecn.py#L18-L24 |
JarryShaw/PyPCAPKit | src/const/http/frame.py | Frame.get | def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Frame(key)
if key not in Frame._member_map_:
extend_enum(Frame, key, default)
return Frame[key] | python | def get(key, default=-1):
"""Backport support for original codes."""
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. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/http/frame.py#L27-L33 |
JarryShaw/PyPCAPKit | src/const/http/frame.py | Frame._missing_ | def _missing_(cls, value):
"""Lookup function used when value is not found."""
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)
return cls(value)
if 0xF0 <= value <= 0xFF:
# [RFC 7540]
extend_enum(cls, 'Reserved for Experimental Use [0x%s]' % hex(value)[2:].upper().zfill(2), value)
return cls(value)
super()._missing_(value) | python | def _missing_(cls, value):
"""Lookup function used when value is not found."""
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)
return cls(value)
if 0xF0 <= value <= 0xFF:
# [RFC 7540]
extend_enum(cls, 'Reserved for Experimental Use [0x%s]' % hex(value)[2:].upper().zfill(2), value)
return cls(value)
super()._missing_(value) | Lookup function used when value is not found. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/http/frame.py#L36-L47 |
JarryShaw/PyPCAPKit | src/toolkit/default.py | ipv4_reassembly | def ipv4_reassembly(frame):
"""Make data for IPv4 reassembly."""
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
ipv4.dst, # destination IP address
ipv4.id, # identification
ipv4.proto.name, # payload protocol type
),
num=frame.info.number, # original packet range number
fo=ipv4.frag_offset, # fragment offset
ihl=ipv4.hdr_len, # internet header length
mf=ipv4.flags.mf, # more fragment flag
tl=ipv4.len, # total length, header includes
header=bytearray(ipv4.packet.header), # raw bytearray type header
payload=bytearray(ipv4.packet.payload or b''), # raw bytearray type payload
)
return True, data
return False, None | python | def ipv4_reassembly(frame):
"""Make data for IPv4 reassembly."""
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
ipv4.dst, # destination IP address
ipv4.id, # identification
ipv4.proto.name, # payload protocol type
),
num=frame.info.number, # original packet range number
fo=ipv4.frag_offset, # fragment offset
ihl=ipv4.hdr_len, # internet header length
mf=ipv4.flags.mf, # more fragment flag
tl=ipv4.len, # total length, header includes
header=bytearray(ipv4.packet.header), # raw bytearray type header
payload=bytearray(ipv4.packet.payload or b''), # raw bytearray type payload
)
return True, data
return False, None | Make data for IPv4 reassembly. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/toolkit/default.py#L12-L34 |
JarryShaw/PyPCAPKit | src/toolkit/default.py | ipv6_reassembly | def ipv6_reassembly(frame):
"""Make data for IPv6 reassembly."""
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
ipv6.dst, # destination IP address
ipv6.label, # label
ipv6.ipv6_frag.next.name, # next header field in IPv6 Fragment Header
),
num=frame.info.number, # original packet range number
fo=ipv6.ipv6_frag.offset, # fragment offset
ihl=ipv6.hdr_len, # header length, only headers before IPv6-Frag
mf=ipv6.ipv6_frag.mf, # more fragment flag
tl=ipv6.hdr_len + ipv6.raw_len, # total length, header includes
header=bytearray(ipv6.fragment.header), # raw bytearray type header before IPv6-Frag
payload=bytearray(ipv6.fragment.payload or b''), # raw bytearray type payload after IPv6-Frag
)
return True, data
return False, None | python | def ipv6_reassembly(frame):
"""Make data for IPv6 reassembly."""
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
ipv6.dst, # destination IP address
ipv6.label, # label
ipv6.ipv6_frag.next.name, # next header field in IPv6 Fragment Header
),
num=frame.info.number, # original packet range number
fo=ipv6.ipv6_frag.offset, # fragment offset
ihl=ipv6.hdr_len, # header length, only headers before IPv6-Frag
mf=ipv6.ipv6_frag.mf, # more fragment flag
tl=ipv6.hdr_len + ipv6.raw_len, # total length, header includes
header=bytearray(ipv6.fragment.header), # raw bytearray type header before IPv6-Frag
payload=bytearray(ipv6.fragment.payload or b''), # raw bytearray type payload after IPv6-Frag
)
return True, data
return False, None | Make data for IPv6 reassembly. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/toolkit/default.py#L37-L59 |
JarryShaw/PyPCAPKit | src/toolkit/default.py | tcp_reassembly | def tcp_reassembly(frame):
"""Make data for TCP reassembly."""
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, # destination IP address
tcp.srcport, # source port
tcp.dstport, # destination port
),
num=frame.info.number, # original packet range number
ack=tcp.ack, # acknowledgement
dsn=tcp.seq, # data sequence number
syn=tcp.flags.syn, # synchronise flag
fin=tcp.flags.fin, # finish flag
rst=tcp.flags.rst, # reset connection flag
payload=bytearray(tcp.packet.payload or b''), # raw bytearray type payload
)
raw_len = len(data['payload']) # payload length, header excludes
data['first'] = tcp.seq # this sequence number
data['last'] = tcp.seq + raw_len # next (wanted) sequence number
data['len'] = raw_len # payload length, header excludes
return True, data
return False, None | python | def tcp_reassembly(frame):
"""Make data for TCP reassembly."""
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, # destination IP address
tcp.srcport, # source port
tcp.dstport, # destination port
),
num=frame.info.number, # original packet range number
ack=tcp.ack, # acknowledgement
dsn=tcp.seq, # data sequence number
syn=tcp.flags.syn, # synchronise flag
fin=tcp.flags.fin, # finish flag
rst=tcp.flags.rst, # reset connection flag
payload=bytearray(tcp.packet.payload or b''), # raw bytearray type payload
)
raw_len = len(data['payload']) # payload length, header excludes
data['first'] = tcp.seq # this sequence number
data['last'] = tcp.seq + raw_len # next (wanted) sequence number
data['len'] = raw_len # payload length, header excludes
return True, data
return False, None | Make data for TCP reassembly. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/toolkit/default.py#L62-L87 |
JarryShaw/PyPCAPKit | src/toolkit/default.py | tcp_traceflow | def tcp_traceflow(frame, *, data_link):
"""Trace packet flow for TCP."""
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, # frame number
frame=frame.info, # extracted frame info
syn=tcp.flags.syn, # TCP synchronise (SYN) flag
fin=tcp.flags.fin, # TCP finish (FIN) flag
src=ip.src, # source IP
dst=ip.dst, # destination IP
srcport=tcp.srcport, # TCP source port
dstport=tcp.dstport, # TCP destination port
timestamp=frame.info.time_epoch, # frame timestamp
)
return True, data
return False, None | python | def tcp_traceflow(frame, *, data_link):
"""Trace packet flow for TCP."""
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, # frame number
frame=frame.info, # extracted frame info
syn=tcp.flags.syn, # TCP synchronise (SYN) flag
fin=tcp.flags.fin, # TCP finish (FIN) flag
src=ip.src, # source IP
dst=ip.dst, # destination IP
srcport=tcp.srcport, # TCP source port
dstport=tcp.dstport, # TCP destination port
timestamp=frame.info.time_epoch, # frame timestamp
)
return True, data
return False, None | Trace packet flow for TCP. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/toolkit/default.py#L90-L108 |
JarryShaw/PyPCAPKit | src/const/ipv4/tos_rel.py | TOS_REL.get | def get(key, default=-1):
"""Backport support for original codes."""
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] | python | def get(key, default=-1):
"""Backport support for original codes."""
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. | https://github.com/JarryShaw/PyPCAPKit/blob/c7f0da9aebc2cf210bf8f8b912f7d3cbb98ca10e/src/const/ipv4/tos_rel.py#L16-L22 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.