code stringlengths 52 7.75k | docs stringlengths 1 5.85k |
|---|---|
def nlmsg_for_each_attr(nlh, hdrlen, rem):
return nla_for_each_attr(nlmsg_attrdata(nlh, hdrlen), nlmsg_attrlen(nlh, hdrlen), rem) | Iterate over a stream of attributes in a message.
https://github.com/thom311/libnl/blob/libnl3_2_25/include/netlink/msg.h#L123
Positional arguments:
nlh -- Netlink message header (nlmsghdr class instance).
hdrlen -- length of family header (integer).
rem -- initialized to len, holds bytes currentl... |
def nlmsg_attrdata(nlh, hdrlen):
data = nlmsg_data(nlh)
return libnl.linux_private.netlink.nlattr(bytearray_ptr(data, libnl.linux_private.netlink.NLMSG_ALIGN(hdrlen))) | Head of attributes data.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L143
Positional arguments:
nlh -- Netlink message header (nlmsghdr class instance).
hdrlen -- length of family specific header (integer).
Returns:
First attribute (nlattr class instance with others in its pay... |
def nlmsg_attrlen(nlh, hdrlen):
return max(nlmsg_len(nlh) - libnl.linux_private.netlink.NLMSG_ALIGN(hdrlen), 0) | Length of attributes data.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L154
nlh -- Netlink message header (nlmsghdr class instance).
hdrlen -- length of family specific header (integer).
Returns:
Integer. |
def nlmsg_ok(nlh, remaining):
sizeof = libnl.linux_private.netlink.nlmsghdr.SIZEOF
return remaining.value >= sizeof and sizeof <= nlh.nlmsg_len <= remaining.value | Check if the Netlink message fits into the remaining bytes.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L179
Positional arguments:
nlh -- Netlink message header (nlmsghdr class instance).
remaining -- number of bytes remaining in message stream (c_int).
Returns:
Boolean. |
def nlmsg_next(nlh, remaining):
totlen = libnl.linux_private.netlink.NLMSG_ALIGN(nlh.nlmsg_len)
remaining.value -= totlen
return libnl.linux_private.netlink.nlmsghdr(bytearray_ptr(nlh.bytearray, totlen)) | Next Netlink message in message stream.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L194
Positional arguments:
nlh -- Netlink message header (nlmsghdr class instance).
remaining -- number of bytes remaining in message stream (c_int).
Returns:
The next Netlink message in the me... |
def nlmsg_parse(nlh, hdrlen, tb, maxtype, policy):
if not nlmsg_valid_hdr(nlh, hdrlen):
return -NLE_MSG_TOOSHORT
return nla_parse(tb, maxtype, nlmsg_attrdata(nlh, hdrlen), nlmsg_attrlen(nlh, hdrlen), policy) | Parse attributes of a Netlink message.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L213
Positional arguments:
nlh -- Netlink message header (nlmsghdr class instance).
hdrlen -- length of family specific header (integer).
tb -- dictionary of nlattr instances (length of maxtype+1).
... |
def nlmsg_find_attr(nlh, hdrlen, attrtype):
return nla_find(nlmsg_attrdata(nlh, hdrlen), nlmsg_attrlen(nlh, hdrlen), attrtype) | Find a specific attribute in a Netlink message.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L231
Positional arguments:
nlh -- Netlink message header (nlmsghdr class instance).
hdrlen -- length of family specific header (integer).
attrtype -- type of attribute to look for (integer).... |
def nlmsg_alloc(len_=default_msg_size):
len_ = max(libnl.linux_private.netlink.nlmsghdr.SIZEOF, len_)
nm = nl_msg()
nm.nm_refcnt = 1
nm.nm_nlh = libnl.linux_private.netlink.nlmsghdr(bytearray(b'\0') * len_)
nm.nm_protocol = -1
nm.nm_size = len_
nm.nm_nlh.nlmsg_len = nlmsg_total_size(0)
... | Allocate a new Netlink message with maximum payload size specified.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L299
Allocates a new Netlink message without any further payload. The maximum payload size defaults to
resource.getpagesize() or as otherwise specified with nlmsg_set_default_siz... |
def nlmsg_inherit(hdr=None):
nm = nlmsg_alloc()
if hdr:
new = nm.nm_nlh
new.nlmsg_type = hdr.nlmsg_type
new.nlmsg_flags = hdr.nlmsg_flags
new.nlmsg_seq = hdr.nlmsg_seq
new.nlmsg_pid = hdr.nlmsg_pid
return nm | Allocate a new Netlink message and inherit Netlink message header.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L322
Allocates a new Netlink message and inherits the original message header. If `hdr` is not None it will be used as a
template for the Netlink message header, otherwise the hea... |
def nlmsg_alloc_simple(nlmsgtype, flags):
nlh = libnl.linux_private.netlink.nlmsghdr(nlmsg_type=nlmsgtype, nlmsg_flags=flags)
msg = nlmsg_inherit(nlh)
_LOGGER.debug('msg 0x%x: Allocated new simple message', id(msg))
return msg | Allocate a new Netlink message.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L346
Positional arguments:
nlmsgtype -- Netlink message type (integer).
flags -- message flags (integer).
Returns:
Newly allocated Netlink message (nl_msg class instance) or None. |
def nlmsg_convert(hdr):
nm = nlmsg_alloc(hdr.nlmsg_len)
if not nm:
return None
nm.nm_nlh.bytearray = hdr.bytearray.copy()[:hdr.nlmsg_len]
return nm | Convert a Netlink message received from a Netlink socket to an nl_msg.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L382
Allocates a new Netlink message and copies all of the data in `hdr` into the new message object.
Positional arguments:
hdr -- Netlink message received from netlink s... |
def nlmsg_reserve(n, len_, pad):
nlmsg_len_ = n.nm_nlh.nlmsg_len
tlen = len_ if not pad else ((len_ + (pad - 1)) & ~(pad - 1))
if tlen + nlmsg_len_ > n.nm_size:
return None
buf = bytearray_ptr(n.nm_nlh.bytearray, nlmsg_len_)
n.nm_nlh.nlmsg_len += tlen
if tlen > len_:
bytea... | Reserve room for additional data in a Netlink message.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L407
Reserves room for additional data at the tail of the an existing netlink message. Eventual padding required will be
zeroed out.
bytearray_ptr() at the start of additional data or No... |
def nlmsg_append(n, data, len_, pad):
tmp = nlmsg_reserve(n, len_, pad)
if tmp is None:
return -NLE_NOMEM
tmp[:len_] = data.bytearray[:len_]
_LOGGER.debug('msg 0x%x: Appended %d bytes with padding %d', id(n), len_, pad)
return 0 | Append data to tail of a Netlink message.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L442
Extends the Netlink message as needed and appends the data of given length to the message.
Positional arguments:
n -- Netlink message (nl_msg class instance).
data -- data to add.
len_ -... |
def nlmsg_put(n, pid, seq, type_, payload, flags):
if n.nm_nlh.nlmsg_len < libnl.linux_private.netlink.NLMSG_HDRLEN:
raise BUG
nlh = n.nm_nlh
nlh.nlmsg_type = type_
nlh.nlmsg_flags = flags
nlh.nlmsg_pid = pid
nlh.nlmsg_seq = seq
_LOGGER.debug('msg 0x%x: Added netlink header ty... | Add a Netlink message header to a Netlink message.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L503
Adds or overwrites the Netlink message header in an existing message object.
Positional arguments:
n -- Netlink message (nl_msg class instance).
pid -- Netlink process id or NL_AUTO... |
def nl_nlmsg_flags2str(flags, buf, _=None):
del buf[:]
all_flags = (
('REQUEST', libnl.linux_private.netlink.NLM_F_REQUEST),
('MULTI', libnl.linux_private.netlink.NLM_F_MULTI),
('ACK', libnl.linux_private.netlink.NLM_F_ACK),
('ECHO', libnl.linux_private.netlink.NLM_F_ECHO),
... | Netlink Message Flags Translations.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L664
Positional arguments:
flags -- integer.
buf -- bytearray().
Keyword arguments:
_ -- unused.
Returns:
Reference to `buf`. |
def dump_hex(ofd, start, len_, prefix=0):
prefix_whitespaces = ' ' * prefix
limit = 16 - (prefix * 2)
start_ = start[:len_]
for line in (start_[i:i + limit] for i in range(0, len(start_), limit)): # stackoverflow.com/a/9475354/1198943
hex_lines, ascii_lines = list(), list()
for c ... | Convert `start` to hex and logs it, 16 bytes per log statement.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L760
Positional arguments:
ofd -- function to call with arguments similar to `logging.debug`.
start -- bytearray() or bytearray_ptr() instance.
len_ -- size of `start` (integ... |
def print_hdr(ofd, msg):
nlh = nlmsg_hdr(msg)
buf = bytearray()
ofd(' .nlmsg_len = %d', nlh.nlmsg_len)
ops = nl_cache_ops_associate_safe(msg.nm_protocol, nlh.nlmsg_type)
if ops:
mt = nl_msgtype_lookup(ops, nlh.nlmsg_type)
if not mt:
raise BUG
buf.extend(... | https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L793.
Positional arguments:
ofd -- function to call with arguments similar to `logging.debug`.
msg -- message to print (nl_msg class instance). |
def print_genl_hdr(ofd, start):
ghdr = genlmsghdr(start)
ofd(' [GENERIC NETLINK HEADER] %d octets', GENL_HDRLEN)
ofd(' .cmd = %d', ghdr.cmd)
ofd(' .version = %d', ghdr.version)
ofd(' .unused = %#d', ghdr.reserved) | https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L821.
Positional arguments:
ofd -- function to call with arguments similar to `logging.debug`.
start -- bytearray() or bytearray_ptr() instance. |
def print_genl_msg(_, ofd, hdr, ops, payloadlen):
data = nlmsg_data(hdr)
if payloadlen.value < GENL_HDRLEN:
return data
print_genl_hdr(ofd, data)
payloadlen.value -= GENL_HDRLEN
data = bytearray_ptr(data, GENL_HDRLEN)
if ops:
hdrsize = ops.co_hdrsize - GENL_HDRLEN
... | https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L831.
Positional arguments:
_ -- unused.
ofd -- function to call with arguments similar to `logging.debug`.
hdr -- Netlink message header (nlmsghdr class instance).
ops -- cache operations (nl_cache_ops class instance).
payloadlen -- l... |
def dump_attr(ofd, attr, prefix=0):
dump_hex(ofd, nla_data(attr), nla_len(attr), prefix) | https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L862.
Positional arguments:
ofd -- function to call with arguments similar to `logging.debug`.
attr -- nlattr class instance.
Keyword arguments:
prefix -- additional number of whitespace pairs to prefix each log statement with. |
def dump_attrs(ofd, attrs, attrlen, prefix=0):
prefix_whitespaces = ' ' * prefix
rem = c_int()
for nla in nla_for_each_attr(attrs, attrlen, rem):
alen = nla_len(nla)
if nla.nla_type == 0:
ofd('%s [ATTR PADDING] %d octets', prefix_whitespaces, alen)
else:
... | https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L869.
Positional arguments:
ofd -- function to call with arguments similar to `logging.debug`.
attrs -- nlattr class instance.
attrlen -- length of payload (integer).
Keyword arguments:
prefix -- additional number of whitespace pairs ... |
def dump_error_msg(msg, ofd=_LOGGER.debug):
hdr = nlmsg_hdr(msg)
err = libnl.linux_private.netlink.nlmsgerr(nlmsg_data(hdr))
ofd(' [ERRORMSG] %d octets', err.SIZEOF)
if nlmsg_len(hdr) >= err.SIZEOF:
ofd(' .error = %d "%s"', err.error, os.strerror(-err.error))
ofd(' [ORIGINAL ... | https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L908.
Positional arguments:
msg -- message to print (nl_msg class instance).
Keyword arguments:
ofd -- function to call with arguments similar to `logging.debug`. |
def print_msg(msg, ofd, hdr):
payloadlen = c_int(nlmsg_len(hdr))
attrlen = 0
data = nlmsg_data(hdr)
ops = nl_cache_ops_associate_safe(msg.nm_protocol, hdr.nlmsg_type)
if ops:
attrlen = nlmsg_attrlen(hdr, ops.co_hdrsize)
payloadlen.value -= attrlen
if msg.nm_protocol == libnl... | https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L929.
Positional arguments:
msg -- Netlink message (nl_msg class instance).
ofd -- function to call with arguments similar to `logging.debug`.
hdr -- Netlink message header (nlmsghdr class instance). |
def nl_msg_dump(msg, ofd=_LOGGER.debug):
hdr = nlmsg_hdr(msg)
ofd('-------------------------- BEGIN NETLINK MESSAGE ---------------------------')
ofd(' [NETLINK HEADER] %d octets', hdr.SIZEOF)
print_hdr(ofd, msg)
if hdr.nlmsg_type == libnl.linux_private.netlink.NLMSG_ERROR:
dump_e... | Dump message in human readable format to callable.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L970
Positional arguments:
msg -- message to print (nl_msg class instance).
Keyword arguments:
ofd -- function to call with arguments similar to `logging.debug`. |
def setChecked(src, ids=[], dpth = 0, key = ''):
#tabs = lambda n: ' ' * n * 4 # or 2 or 8 or...
#brace = lambda s, n: '%s%s%s' % ('['*n, s, ']'*n)
if isinstance(src, dict):
for key, value in src.iteritems():
setChecked(value, ids, dpth + 1, key)
elif isinstance(src, list):
... | Recursively find checked item. |
def setThirdStateChecked(src, ids=[], dpth = 0, key = ''):
#tabs = lambda n: ' ' * n * 4 # or 2 or 8 or...
#brace = lambda s, n: '%s%s%s' % ('['*n, s, ']'*n)
#print('third state nodes: ', third_state_nodes)
if isinstance(src, dict):
#print "DICT: ", src
if 'children' in src and type... | Recursively find checked item. |
def nl_object_alloc(ops):
new = nl_object()
nl_init_list_head(new.ce_list)
new.ce_ops = ops
if ops.oo_constructor:
ops.oo_constructor(new)
_LOGGER.debug('Allocated new object 0x%x', id(new))
return new | Allocate a new object of kind specified by the operations handle.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/object.c#L54
Positional arguments:
ops -- cache operations handle (nl_object_ops class instance).
Returns:
New nl_object class instance or None. |
def lookup_cmd(ops, cmd_id):
for i in range(ops.o_ncmds):
cmd = ops.o_cmds[i]
if cmd.c_id == cmd_id:
return cmd
return None | https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/mngt.c#L33.
Positional arguments:
ops -- genl_ops class instance.
cmd_id -- integer.
Returns:
genl_cmd class instance or None. |
def cmd_msg_parser(who, nlh, ops, cache_ops, arg):
ghdr = genlmsg_hdr(nlh)
cmd = lookup_cmd(ops, ghdr.cmd)
if not cmd:
return -NLE_MSGTYPE_NOSUPPORT
if cmd.c_msg_parser is None:
return -NLE_OPNOTSUPP
tb = dict((i, None) for i in range(cmd.c_maxattr + 1))
info = genl_info(wh... | https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/mngt.c#L47.
Positional arguments:
who -- sockaddr_nl class instance.
nlh -- nlmsghdr class instance.
ops -- genl_ops class instance.
cache_ops -- nl_cache_ops class instance.
arg -- to be passed along to .c_msg_parser().
Returns:
... |
def genl_msg_parser(ops, who, nlh, pp):
if ops.co_genl is None:
raise BUG
return int(cmd_msg_parser(who, nlh, ops.co_genl, ops, pp)) | https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/mngt.c#L85.
Positional arguments:
ops -- nl_cache_ops class instance.
who -- sockaddr_nl class instance.
nlh -- nlmsghdr class instance.
pp -- nl_parser_param class instance.
Returns:
Integer, cmd_msg_parser() output. |
def lookup_family(family):
for ops in nl_list_for_each_entry(genl_ops(), genl_ops_list, 'o_list'):
if ops.o_id == family:
return ops
return None | https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/mngt.c#L94.
Positional arguments:
family -- integer.
Returns:
genl_ops class instance or None. |
def lookup_family_by_name(name):
for ops in nl_list_for_each_entry(genl_ops(), genl_ops_list, 'o_list'):
if ops.o_name == name:
return ops
return None | https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/mngt.c#L106.
Positional arguments:
name -- string.
Returns:
genl_ops class instance or None. |
def genl_register_family(ops):
if not ops.o_name or (ops.o_cmds and ops.o_ncmds <= 0):
return -NLE_INVAL
if ops.o_id and lookup_family(ops.o_id):
return -NLE_EXIST
if lookup_family_by_name(ops.o_name):
return -NLE_EXIST
nl_list_add_tail(ops.o_list, genl_ops_list)
ret... | Register Generic Netlink family and associated commands.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/mngt.c#L164
Registers the specified Generic Netlink family definition together with all associated commands. After registration,
received Generic Netlink messages can be passed to genl_handl... |
def genl_register(ops):
if ops.co_protocol != NETLINK_GENERIC:
return -NLE_PROTO_MISMATCH
if ops.co_hdrsize < GENL_HDRSIZE(0):
return -NLE_INVAL
if ops.co_genl is None:
return -NLE_INVAL
ops.co_genl.o_cache_ops = ops
ops.co_genl.o_hdrsize = ops.co_hdrsize - GENL_HDRLEN
... | Register Generic Netlink family backed cache.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/mngt.c#L241
Same as genl_register_family() but additionally registers the specified cache operations using
nl_cache_mngt_register() and associates it with the Generic Netlink family.
Positional ar... |
def __setup_connection(self):
if self.payload != None and type(self.payload) is dict and 'settings' in self.payload:
config.plugin_client_settings = self.payload['settings']
config.offline = self.args.offline
config.connection = PluginConnection(
client=self.... | each operation requested represents a session
the session holds information about the plugin running it
and establishes a project object |
def execute(self):
try:
self.__setup_connection()
#if the arg switch argument is included, the request is to launch the out of box
#MavensMate UI, so we generate the HTML for the UI and launch the process
#example: mm -o new_project --ui
if s... | Executes requested command |
def nl_syserr2nlerr(error_):
error_ = abs(error_)
legend = {
errno.EBADF: libnl.errno_.NLE_BAD_SOCK,
errno.EADDRINUSE: libnl.errno_.NLE_EXIST,
errno.EEXIST: libnl.errno_.NLE_EXIST,
errno.EADDRNOTAVAIL: libnl.errno_.NLE_NOADDR,
errno.ESRCH: libnl.errno_.NLE_OBJ_NOTFOU... | https://github.com/thom311/libnl/blob/libnl3_2_25/lib/error.c#L84. |
def get_alert(self, alert):
if alert > self.alerts_count() or self.alerts_count() is None:
return None
else:
return self.get()[alert-1] | Recieves a day as an argument and returns the prediction for that alert
if is available. If not, function will return None. |
def get_forecast(self, latitude, longitude):
reply = self.http_get(self.url_builder(latitude, longitude))
self.forecast = json.loads(reply)
for item in self.forecast.keys():
setattr(self, item, self.forecast[item]) | Gets the weather data from darksky api and stores it in
the respective dictionaries if available.
This function should be used to fetch weather information. |
def get_forecast_fromstr(self, reply):
self.forecast = json.loads(reply)
for item in self.forecast.keys():
setattr(self, item, self.forecast[item]) | Gets the weather data from a darksky api response string
and stores it in the respective dictionaries if available.
This function should be used to fetch weather information. |
def url_builder(self, latitude, longitude):
try:
float(latitude)
float(longitude)
except TypeError:
raise TypeError('Latitude (%s) and Longitude (%s) must be a float number' % (latitude, longitude))
url = self._darksky_url + self.forecast_io_api_key +... | This function is used to build the correct url to make the request
to the forecast.io api.
Recieves the latitude and the longitude.
Return a string with the url. |
def http_get(self, request_url):
try:
headers = {'Accept-Encoding': 'gzip, deflate'}
response = requests.get(request_url, headers=headers)
except requests.exceptions.Timeout as ext:
log.error('Error: Timeout', ext)
except requests.exceptions.TooManyRe... | This function recieves the request url and it is used internally to get
the information via http.
Returns the response content.
Raises Timeout, TooManyRedirects, RequestException.
Raises KeyError if headers are not present.
Raises HTTPError if responde code is not 200. |
def _deprecated_kwargs(kwargs, arg_newarg):
warn_for = []
for (arg, new_kw) in arg_newarg:
if arg in kwargs.keys():
val = kwargs.pop(arg)
kwargs[new_kw] = val
warn_for.append((arg, new_kw))
if len(warn_for) > 0:
if len(warn_for) == 1:
warn... | arg_newarg is a list of tuples, where each tuple has a pair of strings.
('old_arg', 'new_arg')
A DeprecationWarning is raised for the arguments that need to be
replaced. |
def _map_or_starmap(function, iterable, args, kwargs, map_or_starmap):
arg_newarg = (("parallel", "pm_parallel"), ("chunksize", "pm_chunksize"),
("pool", "pm_pool"), ("processes", "pm_processes"),
("parmap_progress", "pm_pbar"))
kwargs = _deprecated_kwargs(kwargs, arg_ne... | Shared function between parmap.map and parmap.starmap.
Refer to those functions for details. |
def map(function, iterable, *args, **kwargs):
return _map_or_starmap(function, iterable, args, kwargs, "map") | This function is equivalent to:
>>> [function(x, args[0], args[1],...) for x in iterable]
:param pm_parallel: Force parallelization on/off
:type pm_parallel: bool
:param pm_chunksize: see :py:class:`multiprocessing.pool.Pool`
:type pm_chunksize: int
:param pm_pool: Pass an e... |
def starmap(function, iterables, *args, **kwargs):
return _map_or_starmap(function, iterables, args, kwargs, "starmap") | Equivalent to:
>>> return ([function(x1,x2,x3,..., args[0], args[1],...) for
>>> (x1,x2,x3...) in iterable])
:param pm_parallel: Force parallelization on/off
:type pm_parallel: bool
:param pm_chunksize: see :py:class:`multiprocessing.pool.Pool`
:type pm_chun... |
def _map_or_starmap_async(function, iterable, args, kwargs, map_or_starmap):
arg_newarg = (("parallel", "pm_parallel"), ("chunksize", "pm_chunksize"),
("pool", "pm_pool"), ("processes", "pm_processes"),
("callback", "pm_callback"),
("error_callback", "pm_er... | Shared function between parmap.map_async and parmap.starmap_async.
Refer to those functions for details. |
def map_async(function, iterable, *args, **kwargs):
return _map_or_starmap_async(function, iterable, args, kwargs, "map") | This function is the multiprocessing.Pool.map_async version that
supports multiple arguments.
>>> [function(x, args[0], args[1],...) for x in iterable]
:param pm_parallel: Force parallelization on/off. If False, the
function won't be asynchronous.
:type pm_paral... |
def starmap_async(function, iterables, *args, **kwargs):
return _map_or_starmap_async(function, iterables, args, kwargs, "starmap") | This function is the multiprocessing.Pool.starmap_async version that
supports multiple arguments.
>>> return ([function(x1,x2,x3,..., args[0], args[1],...) for
>>> (x1,x2,x3...) in iterable])
:param pm_parallel: Force parallelization on/off. If False, the
... |
def lookup_domain(domain, nameservers=[], rtype="A",
exclude_nameservers=[], timeout=2):
dns_exp = DNSQuery(domains=[domain], nameservers=nameservers, rtype=rtype,
exclude_nameservers=exclude_nameservers, timeout=timeout)
return dns_exp.lookup_domain(domain) | Wrapper for DNSQuery method |
def parse_out_ips(message):
ips = []
for entry in message.answer:
for rdata in entry.items:
ips.append(rdata.to_text())
return ips | Given a message, parse out the ips in the answer |
def send_chaos_queries(self):
names = ["HOSTNAME.BIND", "VERSION.BIND", "ID.SERVER"]
self.results = {'exp-name': "chaos-queries"}
for name in names:
self.results[name] = {}
for nameserver in self.nameservers:
sock = socket.socket(socket.AF_INET, s... | Send chaos queries to identify the DNS server and its manufacturer
Note: we send 2 queries for BIND stuff per RFC 4892 and 1
query per RFC 6304
Note: we are not waiting on a second response because we
shouldn't be getting injected packets here |
def lookup_domains(self):
thread_error = False
thread_wait_timeout = 200
ind = 1
total_item_count = len(self.domains)
for domain in self.domains:
for nameserver in self.nameservers:
wait_time = 0
while threading.active_count() ... | More complex DNS primitive that looks up domains concurrently
Note: if you want to lookup multiple domains, you should use
this function |
def start(self, timeout=None):
self.thread.start()
start_time = time.time()
if not timeout:
timeout = self.timeout
# every second, check the condition of the thread and return
# control to the user if appropriate
while start_time + timeout > time.tim... | Start running the command |
def stop(self, timeout=None):
if not timeout:
timeout = self.timeout
self.kill_switch()
# Send the signal to all the process groups
self.process.kill()
self.thread.join(timeout)
try:
os.killpg(os.getpgid(self.process.pid), signal.SIGTERM)... | Stop the given command |
def _traceroute_callback(self, line, kill_switch):
line = line.lower()
if "traceroute to" in line:
self.started = True
# need to run as root but not running as root.
# usually happens when doing TCP and ICMP traceroute.
if "enough privileges" in line:
self.error = True
... | Callback function to handle traceroute.
:param self:
:param line:
:param kill_switch:
:return: |
def output_callback(self, line, kill_switch):
self.notifications += line + "\n"
if "Initialization Sequence Completed" in line:
self.started = True
if "ERROR:" in line or "Cannot resolve host address:" in line:
self.error = True
if "process exiting" in l... | Set status of openvpn according to what we process |
def start(self, timeout=None):
if not timeout:
timeout = self.timeout
self.thread.start()
start_time = time.time()
while start_time + timeout > time.time():
self.thread.join(1)
if self.error or self.started:
break
if se... | Start OpenVPN and block until the connection is opened or there is
an error
:param timeout: time in seconds to wait for process to start
:return: |
def stop(self, timeout=None):
if not timeout:
timeout = self.timeout
os.killpg(os.getpgid(self.process.pid), signal.SIGTERM)
self.thread.join(timeout)
if self.stopped:
logging.info("OpenVPN stopped")
if self in OpenVPN.connected_instances:
... | Stop OpenVPN process group
:param timeout: time in seconds to wait for process to stop
:return: |
def load_experiments(self):
logging.debug("Loading experiments.")
# look for experiments in experiments directory
exp_dir = self.config['dirs']['experiments_dir']
for path in glob.glob(os.path.join(exp_dir, '[!_]*.py')):
# get name of file and path
name, ... | This function will return the list of experiments. |
def get_meta(self):
# get the normalized IP if we don't already have it
if self._meta is None:
external_ip = get_external_ip()
if external_ip:
self._meta = get_meta(self.config, external_ip)
else:
raise Exception("Unable to get... | we only want to get the meta information (our normalized IP) once,
so we are going to do lazy instantiation to improve performance |
def _tcpdump_callback(self, line, kill_switch):
line = line.lower()
if ("listening" in line) or ("reading" in line):
self.started = True
if ("no suitable device" in line):
self.error = True
self.kill_switch()
if "by kernel" in line:
self.stopped = True | Callback function to handle tcpdump |
def meta_redirect(content):
decoded = content.decode("utf-8", errors="replace")
try:
soup = BeautifulSoup.BeautifulSoup(decoded)
except Exception as e:
return None
result = soup.find("meta", attrs={"http-equiv": re.compile("^refresh$", re.I)})
if result:
try:
... | Returns redirecting URL if there is a HTML refresh meta tag,
returns None otherwise
:param content: HTML content |
def _get_http_request(netloc, path="/", headers=None, ssl=False):
if ssl:
port = 443
else:
port = 80
host = netloc
if len(netloc.split(":")) == 2:
host, port = netloc.split(":")
request = {"host": host,
"port": port,
"path": path,
... | Actually gets the http. Moved this to it's own private method since
it is called several times for following redirects
:param host:
:param path:
:param headers:
:param ssl:
:return: |
def create_script_for_location(content, destination):
temp = tempfile.NamedTemporaryFile(mode='w', delete=False)
temp.write(content)
temp.close()
shutil.move(temp.name, destination)
cur_perms = os.stat(destination).st_mode
set_perms = cur_perms | stat.S_IXOTH | stat.S_IXGRP | stat.S_IXUSR
... | Create a script with the given content, mv it to the
destination, and make it executable
Parameters:
content- the content to put in the script
destination- the directory to copy to
Note: due to constraints on os.rename, destination must be an
absolute path to a file, not just a directory |
def daemonize(package, bin_loc, user):
path = "/etc/cron.hourly/centinel-" + user
if user != "root":
# create a script to run centinel every hour as the current user
hourly = "".join(["#!/bin/bash\n",
"# cron job for centinel\n",
"su ", ... | Create crontab entries to run centinel every hour and
autoupdate every day
Parameters:
package- name of the currently installed package (will be used for
autoupdate). If this parameter is None, the autoupdater will
not be used
bin_loc- location of the centinel binary/script.
Note... |
def create_config_files(directory):
# get the config file template
template_url = ("https://securenetconnection.com/vpnconfig/"
"openvpn-template.ovpn")
resp = requests.get(template_url)
resp.raise_for_status()
template = resp.content
# get the available servers and cre... | Create all available VPN configuration files in the given directory
Note: I am basically just following along with what their script
client does |
def informed_consent(self):
if self.typeable_handle is None:
consent_url = [self.config['server']['server_url'],
"/get_initial_consent?username="]
consent_url.append(urlsafe_b64encode(self.username))
consent_url.append("&password=")
... | Create a URL for the user to give their consent through |
def create_config_files(directory):
# Some constant strings
vpn_gate_url = "http://www.vpngate.net/api/iphone/"
if not os.path.exists(directory):
os.makedirs(directory)
# get csv into memory
csv_str = ""
logging.info("Downloading info from VPN Gate API...")
r = requests.get(vp... | Initialize directory ready for vpn walker
:param directory: the path where you want this to happen
:return: |
def return_abs_path(directory, path):
if directory is None or path is None:
return
directory = os.path.expanduser(directory)
return os.path.abspath(os.path.join(directory, path)) | Unfortunately, Python is not smart enough to return an absolute
path with tilde expansion, so I writing functionality to do this
:param directory:
:param path:
:return: |
def parse_config(self, config_file):
with open(config_file, 'r') as f:
config = json.load(f)
self.params = config
if self.params['proxy']['proxy_type']:
self.params['proxy'] = {self.params['proxy']['proxy_type']:
self.params['... | Given a configuration file, read in and interpret the results
:param config_file:
:return: |
def update(self, old, backup_path=None):
for category in old.params.keys():
for parameter in old.params[category].keys():
if (category in self.params and parameter in self.params[category] and
(old.params[category][parameter] != self.params[category][... | Update the old configuration file with new values.
:param old: old configuration to update.
:param backup_path: path to write a backup of the old config file.
:return: |
def write_out_config(self, config_file):
with open(config_file, 'w') as f:
json.dump(self.params, f, indent=2,
separators=(',', ': ')) | Write out the configuration file
:param config_file:
:return:
Note: this will erase all comments from the config file |
def setup_profile(self, firebug=True, netexport=True):
profile = webdriver.FirefoxProfile()
profile.set_preference("app.update.enabled", False)
if firebug:
profile.add_extension(os.path.join(self.cur_path, 'extensions/firebug-2.0.8.xpi'))
profile.set_preference("... | Setup the profile for firefox
:param firebug: whether add firebug extension
:param netexport: whether add netexport extension
:return: a firefox profile object |
def divide_url(self, url):
if 'https://' in url:
host = url[8:].split('/')[0]
path = url[8 + len(host):]
elif 'http://' in url:
host = url[7:].split('/')[0]
path = url[7 + len(host):]
else:
host = url.split('/')[0]
... | divide url into host and path two parts |
def get(self, host, files_count, path="/", ssl=False, external=None):
theme = "https" if ssl else "http"
url = host + path
http_url = theme + "://" + url
result = {}
try:
capture_path = os.getcwd() + '/'
har_file_path = capture_path + "har/"
... | Send get request to a url and wrap the results
:param host (str): the host name of the url
:param path (str): the path of the url (start with "/")
:return (dict): the result of the test url |
def run(self, input_files, url=None, verbose=0):
if not url and not input_files:
logging.warning("No input file")
return {"error": "no inputs"}
results = {}
self.open_virtual_display()
if verbose > 0:
log_file = sys.stdout
else:
... | run the headless browser with given input
if url given, the proc will only run hlb with given url and ignore input_list.
:param url:
:param input_files: the name of the file in "index url" format. i.e.
1, www.facebook.com
1, www.google.com
...
... |
def hash_folder(folder, regex='[!_]*'):
file_hashes = {}
for path in glob.glob(os.path.join(folder, regex)):
# exclude folders
if not os.path.isfile(path):
continue
with open(path, 'r') as fileP:
md5_hash = hashlib.md5(fileP.read()).digest()
file_na... | Get the md5 sum of each file in the folder and return to the user
:param folder: the folder to compute the sums over
:param regex: an expression to limit the files we match
:return:
Note: by default we will hash every file in the folder
Note: we will not match anything that starts with an undersc... |
def compute_files_to_download(client_hashes, server_hashes):
to_dload, to_delete = [], []
for filename in server_hashes:
if filename not in client_hashes:
to_dload.append(filename)
continue
if client_hashes[filename] != server_hashes[filename]:
to_dload.a... | Given a dictionary of file hashes from the client and the
server, specify which files should be downloaded from the server
:param client_hashes: a dictionary where the filenames are keys and the
values are md5 hashes as strings
:param server_hashes: a dictionary where the filename... |
def spinner(beep=False, disable=False, force=False):
return Spinner(beep, disable, force) | This function creates a context manager that is used to display a
spinner on stdout as long as the context has not exited.
The spinner is created only if stdout is not redirected, or if the spinner
is forced using the `force` parameter.
Parameters
----------
beep : bool
Beep when spinn... |
def verifier(self, url):
webbrowser.open(url)
print('A browser should have opened up with a link to allow us to access')
print('your account, follow the instructions on the link and paste the verifier')
print('Code into here to give us access, if the browser didn\'t open, the li... | Will ask user to click link to accept app and write code |
def write_config(self):
if not os.path.exists(os.path.dirname(self.config_file)):
os.makedirs(os.path.dirname(self.config_file))
with open(self.config_file, 'w') as f:
f.write(json.dumps(self.config))
f.close() | Write config to file |
def read_config(self):
try:
with open(self.config_file, 'r') as f:
self.config = json.loads(f.read())
f.close()
except IOError:
return False
return True | Read config from file |
def post_note(self):
if self.args.note_title:
note_title = self.args.note_title
else:
note_title = None
note_content = self.args.note_content
mynote = self.pump.Note(display_name=note_title, content=note_content)
mynote.to = self.pump.me.follower... | Post note and return the URL of the posted note |
def get_obj_id(self, item):
if item is not None:
if isinstance(item, six.string_types):
return item
elif hasattr(item, 'id'):
return item.id | Get the id of a PumpObject.
:param item: id string or PumpObject |
def get_page(self, url):
if url:
data = self.feed._request(url, offset=self._offset, since=self._since, before=self._before)
# set values to False to avoid using them for next request
self._before = False if self._before is not None else None
self._since... | Get a page of items from API |
def get_cached(self):
def id_in_list(list, id):
if id:
if [i for i in list if i.id == id]:
return True
else:
raise PyPumpException("id %r not in feed." % self._since)
tmp = []
if self._before is not Non... | Get items from feed cache while trying to emulate
how API handles offset/since/before parameters |
def done(self):
if self._done:
return self._done
if self._limit is None:
self._done = False
elif self.itemcount >= self._limit:
self._done = True
return self._done | Check if we should stop returning objects |
def _build_cache(self):
self.cache = []
if self.done:
return
for i in (self.get_cached() if self._cached else self.get_page(self.url)):
if not self._cached:
# some objects don't have objectType set (inbox activities)
if not i.get(... | Build a list of objects from feed's cached items or API page |
def items(self, offset=None, limit=20, since=None, before=None, *args, **kwargs):
return ItemList(self, offset=offset, limit=limit, since=since, before=before, cached=self.is_cached) | Get a feed's items.
:param offset: Amount of items to skip before returning data
:param since: Return items added after this id (ordered old -> new)
:param before: Return items added before this id (ordered new -> old)
:param limit: Amount of items to return |
def _subfeed(self, feedname):
url = self.url
if not url.endswith("/"):
url += "/"
return url + feedname | Used for Inbox/Outbox major/minor/direct subfeeds |
def direct(self):
url = self._subfeed("direct")
if "direct" in self.url or "major" in self.url or "minor" in self.url:
return self
if self._direct is None:
self._direct = self.__class__(url, pypump=self._pump)
return self._direct | Direct inbox feed,
contains activities addressed directly to the owner of the inbox. |
def major(self):
url = self._subfeed("major")
if "major" in self.url or "minor" in self.url:
return self
if self._major is None:
self._major = self.__class__(url, pypump=self._pump)
return self._major | Major inbox feed, contains major activities such as notes and images. |
def minor(self):
url = self._subfeed("minor")
if "minor" in self.url or "major" in self.url:
return self
if self._minor is None:
self._minor = self.__class__(url, pypump=self._pump)
return self._minor | Minor inbox feed, contains minor activities such as likes, shares and follows. |
def create(self, display_name, content=None):
activity = {
"verb": "create",
"object": {
"objectType": "collection",
"objectTypes": [self.membertype],
"displayName": display_name,
"content": content
}
... | Create a new user list :class:`collection <pypump.models.collection.Collection>`.
:param display_name: List title.
:param content: (optional) List description.
Example:
>>> pump.me.lists.create(display_name='Friends', content='List of friends')
>>> myfriends = pump.me.l... |
def serialize(self):
data = super(Note, self).serialize()
data.update({
"verb": "post",
"object": {
"objectType": self.object_type,
"content": self.content,
}
})
if self.display_name:
data["object"][... | Converts the post to something compatible with `json.dumps` |
def context(self):
type = "client_associate" if self.key is None else "client_update"
data = {
"type": type,
"application_type": self.type,
}
# is this an update?
if self.key:
data["client_id"] = self.key
data["client_secr... | Provides request context |
def request(self, server=None):
request = {
"headers": {"Content-Type": "application/json"},
"timeout": self._pump.timeout,
"data": self.context,
}
url = "{proto}://{server}/{endpoint}".format(
proto=self._pump.protocol,
serve... | Sends the request |
def register(self, server=None):
if (self.key or self.secret):
return self.update()
server_data = self.request(server)
self.key = server_data["client_id"]
self.secret = server_data["client_secret"]
self.expirey = server_data["expires_at"] | Registers the client with the Pump API retrieving the id and secret |
def update(self):
error = ""
if self.key is None:
error = "To update a client you need to provide a key"
if self.secret is None:
error = "To update a client you need to provide the secret"
if error:
raise ClientException(error)
self... | Updates the information the Pump server has about the client |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.