code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
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
def nlmsg_append(n, data, len_, pad)
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_ -...
6.61039
7.567386
0.873537
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 type=%d, flags=%d, pid=%d, seq=%d', id(n), type_, fla...
def nlmsg_put(n, pid, seq, type_, payload, flags)
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...
5.082391
4.943311
1.028135
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), ('ROOT', libnl.linux_private.netlink...
def nl_nlmsg_flags2str(flags, buf, _=None)
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`.
1.944761
1.968036
0.988174
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 in line: hex_lines.append('{0:...
def dump_hex(ofd, start, len_, prefix=0)
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...
3.254252
3.281356
0.99174
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('{0}::{1}'.format(ops.co_...
def print_hdr(ofd, msg)
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).
4.510665
4.286226
1.052363
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)
def print_genl_hdr(ofd, start)
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.
7.648335
7.582736
1.008651
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 if hdrsize > 0: if payloadlen.value < ...
def print_genl_msg(_, ofd, hdr, ops, payloadlen)
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...
4.534066
4.042669
1.121552
dump_hex(ofd, nla_data(attr), nla_len(attr), prefix)
def dump_attr(ofd, attr, prefix=0)
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.
11.280748
21.212223
0.531804
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: is_nested = ' NESTED' if nla_is_nested(nla) e...
def dump_attrs(ofd, attrs, attrlen, prefix=0)
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 ...
2.948778
3.040663
0.969781
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 MESSAGE] %d octets', hdr.SIZEOF) err...
def dump_error_msg(msg, ofd=_LOGGER.debug)
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`.
9.334065
10.524982
0.886849
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.linux_private.netlink.NETLINK...
def print_msg(msg, ofd, hdr)
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).
5.589067
5.256348
1.063298
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_error_msg(msg, ofd) elif nlmsg_len(hdr...
def nl_msg_dump(msg, ofd=_LOGGER.debug)
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`.
7.106976
8.159803
0.870974
#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): for litem in src: if isinstance(...
def setChecked(src, ids=[], dpth = 0, key = '')
Recursively find checked item.
3.956407
3.805016
1.039787
#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(src['children']) is list and len(src['children']) > 0: ...
def setThirdStateChecked(src, ids=[], dpth = 0, key = '')
Recursively find checked item.
3.547436
3.447704
1.028927
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
def nl_object_alloc(ops)
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.
8.652455
9.718167
0.890338
for i in range(ops.o_ncmds): cmd = ops.o_cmds[i] if cmd.c_id == cmd_id: return cmd return None
def lookup_cmd(ops, cmd_id)
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.
3.08546
3.400519
0.90735
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(who=who, nlh=nlh, genlhdr=ghdr, userhdr=genlmsg_user_...
def cmd_msg_parser(who, nlh, ops, cache_ops, arg)
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: ...
6.995409
6.876133
1.017346
if ops.co_genl is None: raise BUG return int(cmd_msg_parser(who, nlh, ops.co_genl, ops, pp))
def genl_msg_parser(ops, who, nlh, 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.
11.142261
8.724489
1.277125
for ops in nl_list_for_each_entry(genl_ops(), genl_ops_list, 'o_list'): if ops.o_id == family: return ops return None
def lookup_family(family)
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.
20.835629
13.054704
1.596025
for ops in nl_list_for_each_entry(genl_ops(), genl_ops_list, 'o_list'): if ops.o_name == name: return ops return None
def lookup_family_by_name(name)
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.
19.657026
11.977437
1.641171
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) return 0
def genl_register_family(ops)
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...
6.078488
5.58601
1.088163
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 ops.co_genl.o_name =...
def genl_register(ops)
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...
5.17076
4.115153
1.256517
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.args.client or 'SUBLIME_TEXT_3...
def __setup_connection(self)
each operation requested represents a session the session holds information about the plugin running it and establishes a project object
6.29795
5.666198
1.111495
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 self.args.ui_switch ...
def execute(self)
Executes requested command
9.553879
9.398968
1.016482
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_NOTFOUND, errno.ENOENT: lib...
def nl_syserr2nlerr(error_)
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/error.c#L84.
2.058733
2.000608
1.029053
if alert > self.alerts_count() or self.alerts_count() is None: return None else: return self.get()[alert-1]
def get_alert(self, alert)
Recieves a day as an argument and returns the prediction for that alert if is available. If not, function will return None.
6.181813
5.222853
1.183609
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])
def get_forecast(self, latitude, longitude)
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.
4.164036
4.146783
1.004161
self.forecast = json.loads(reply) for item in self.forecast.keys(): setattr(self, item, self.forecast[item])
def get_forecast_fromstr(self, reply)
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.
3.492635
3.365443
1.037793
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 + '/' url += str(latitude).strip() + ...
def url_builder(self, latitude, longitude)
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.
2.08424
2.077045
1.003464
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.TooManyRedirects as extmr: log...
def http_get(self, request_url)
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.
2.131071
2.099081
1.01524
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: warnings.warn("Argument '{}' is deprecated. Use ...
def _deprecated_kwargs(kwargs, arg_newarg)
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.
2.16651
2.229408
0.971787
arg_newarg = (("parallel", "pm_parallel"), ("chunksize", "pm_chunksize"), ("pool", "pm_pool"), ("processes", "pm_processes"), ("parmap_progress", "pm_pbar")) kwargs = _deprecated_kwargs(kwargs, arg_newarg) chunksize = kwargs.pop("pm_chunksize", None) progress = k...
def _map_or_starmap(function, iterable, args, kwargs, map_or_starmap)
Shared function between parmap.map and parmap.starmap. Refer to those functions for details.
3.345402
3.323886
1.006473
return _map_or_starmap(function, iterable, args, kwargs, "map")
def map(function, iterable, *args, **kwargs)
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...
6.658763
15.03139
0.44299
return _map_or_starmap(function, iterables, args, kwargs, "starmap")
def starmap(function, iterables, *args, **kwargs)
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...
5.000772
11.287512
0.443036
arg_newarg = (("parallel", "pm_parallel"), ("chunksize", "pm_chunksize"), ("pool", "pm_pool"), ("processes", "pm_processes"), ("callback", "pm_callback"), ("error_callback", "pm_error_callback")) kwargs = _deprecated_kwargs(kwargs, arg_newarg) chunk...
def _map_or_starmap_async(function, iterable, args, kwargs, map_or_starmap)
Shared function between parmap.map_async and parmap.starmap_async. Refer to those functions for details.
2.92316
2.924683
0.999479
return _map_or_starmap_async(function, iterable, args, kwargs, "map")
def map_async(function, iterable, *args, **kwargs)
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...
6.58019
15.409089
0.427033
return _map_or_starmap_async(function, iterables, args, kwargs, "starmap")
def starmap_async(function, iterables, *args, **kwargs)
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 ...
4.911889
10.846948
0.452836
dns_exp = DNSQuery(domains=[domain], nameservers=nameservers, rtype=rtype, exclude_nameservers=exclude_nameservers, timeout=timeout) return dns_exp.lookup_domain(domain)
def lookup_domain(domain, nameservers=[], rtype="A", exclude_nameservers=[], timeout=2)
Wrapper for DNSQuery method
3.249442
2.948898
1.101917
ips = [] for entry in message.answer: for rdata in entry.items: ips.append(rdata.to_text()) return ips
def parse_out_ips(message)
Given a message, parse out the ips in the answer
4.504314
3.427374
1.314217
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, socket.SOCK_DGRAM) ...
def send_chaos_queries(self)
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
2.780813
2.660129
1.045368
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() > self.max_threads: ...
def lookup_domains(self)
More complex DNS primitive that looks up domains concurrently Note: if you want to lookup multiple domains, you should use this function
2.59188
2.58006
1.004581
if domain not in self.results: self.results[domain] = [] # get the resolver to use if nameserver is None: logging.debug("Nameserver not specified, using %s" % self.nameservers[0]) nameserver = self.nameservers[0] results = {'domain': domain, '...
def lookup_domain(self, domain, nameserver=None, log_prefix='')
Most basic DNS primitive that looks up a domain, waits for a second response, then returns all of the results :param domain: the domain to lookup :param nameserver: the nameserver to use :param log_prefix: :return: Note: if you want to lookup multiple domains you *shoul...
2.459161
2.438236
1.008582
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.time(): self.thread.jo...
def start(self, timeout=None)
Start running the command
4.564991
4.609407
0.990364
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) except: p...
def stop(self, timeout=None)
Stop the given command
3.408933
3.367594
1.012276
# the method specified by the function parameter here will # over-ride the ones given in cmd_arguments because # traceroute will use the last one in the argument list. _cmd_arguments = [] logging.debug("%sRunning traceroute for " "%s using %s probes." % (log_prefix, domain, ...
def traceroute(domain, method="udp", cmd_arguments=None, external=None, log_prefix='')
This function uses centinel.command to issue a traceroute command, wait for it to finish execution and parse the results out to a dictionary. :param domain: the domain to be queried :param method: the packet type used for traceroute, UDP by default :param cmd_arguments: the list of arguments that n...
2.851404
2.881041
0.989713
threads = [] thread_error = False thread_wait_timeout = 200 ind = 1 total_item_count = len(input_list) for domain in input_list: wait_time = 0 while threading.active_count() > max_threads: time.sleep(1) wait_time += 1 if wait_time > thread...
def traceroute_batch(input_list, results={}, method="udp", cmd_arguments=None, delay_time=0.1, max_threads=100)
This is a parallel version of the traceroute primitive. :param input_list: the input is a list of domain names :param method: the packet type used for traceroute, UDP by default :param cmd_arguments: the list of arguments that need to be passed to traceroute. :param delay_time: ...
2.563625
2.562061
1.000611
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 self.kill_switch() self.stopped = True ...
def _traceroute_callback(self, line, kill_switch)
Callback function to handle traceroute. :param self: :param line: :param kill_switch: :return:
6.577969
6.581069
0.999529
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 line: self.stopped = True
def output_callback(self, line, kill_switch)
Set status of openvpn according to what we process
6.853468
6.014335
1.139522
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 self.started: logging...
def start(self, timeout=None)
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:
4.080056
3.753031
1.087136
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: OpenVPN.connected...
def stop(self, timeout=None)
Stop OpenVPN process group :param timeout: time in seconds to wait for process to stop :return:
4.005162
3.703014
1.081595
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, ext = os.path.splitext(os.pa...
def load_experiments(self)
This function will return the list of experiments.
3.266923
3.265852
1.000328
# 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 public IP") ...
def get_meta(self)
we only want to get the meta information (our normalized IP) once, so we are going to do lazy instantiation to improve performance
3.598671
2.861331
1.257691
# XXX: android build needs this. refactor if data_dir: centinel_home = data_dir self.config['dirs']['results_dir'] = os.path.join(centinel_home, 'results') logging.info('Centinel started.') ...
def run(self, data_dir=None)
Note: this function will check the experiments directory for a special file, scheduler.info, that details how often each experiment should be run and the last time the experiment was run. If the time since the experiment was run is shorter than the scheduled interval in seconds, then the...
3.114572
2.983062
1.044085
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
def _tcpdump_callback(self, line, kill_switch)
Callback function to handle tcpdump
6.925782
6.947704
0.996845
args = parse_args() # parse custom parameters custom_meta = None if args.custom_meta: print "Adding custom parameters:" custom_meta = {} try: for item in args.custom_meta.split(','): key, value = item.split(':') custom_meta[key] ...
def _run()
Entry point for package and cli uses
3.293198
3.265236
1.008564
threads = [] thread_error = False thread_wait_timeout = 200 ind = 1 total_item_count = len(input_list) for row in input_list: if len(row.split(":")) == 2: host, port = row.split(":") elif len(row.split(":")) == 1: host = row port = default...
def get_fingerprint_batch(input_list, results={}, default_port=443, delay_time=0.5, max_threads=100)
This is a parallel version of the TLS fingerprint primitive. :param input_list: the input is a list of host:ports. :param default_port: default port to use when no port specified :param delay_time: delay before starting each thread :param max_threads: maximum number of concurrent threads :return:
2.433571
2.432416
1.000475
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: wait, text = result["cont...
def meta_redirect(content)
Returns redirecting URL if there is a HTML refresh meta tag, returns None otherwise :param content: HTML content
3.887768
3.91012
0.994283
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, "ssl": ssl, "method": "GET"} if headers...
def _get_http_request(netloc, path="/", headers=None, ssl=False)
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:
2.844975
2.975199
0.95623
threads = [] thread_error = False thread_wait_timeout = 200 ind = 1 total_item_count = len(input_list) # randomly select one user agent for one input list user_agent = random.choice(user_agent_pool) for row in input_list: headers = {} path = "/" ssl = False ...
def get_requests_batch(input_list, results={}, delay_time=0.5, max_threads=100)
This is a parallel version of the HTTP GET primitive. :param input_list: the input is a list of either dictionaries containing query information, or just domain names (and NOT URLs). :param delay_time: delay before starting each thread :param max_threads: maximum number of concurrent...
2.535616
2.37337
1.068361
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 os.chmod(destination, set_perms)
def create_script_for_location(content, destination)
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
2.206381
2.297133
0.960493
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 ", user, " -c '", bin_loc, " --sync'\n", ...
def daemonize(package, bin_loc, user)
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...
3.140825
2.84595
1.103612
# 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 create a config file for each server ...
def create_config_files(directory)
Create all available VPN configuration files in the given directory Note: I am basically just following along with what their script client does
2.905301
2.868848
1.012706
# get the server scheduler.info file url = "%s/%s/%s" % (self.config['server']['server_url'], "experiments", "scheduler.info") try: req = requests.get(url, proxies=self.config['proxy']['proxy'], auth=self.auth, ...
def sync_scheduler(self)
Download the scheduler.info file and perform a smart comparison with what we currently have so that we don't overwrite the last_run timestamp To do a smart comparison, we go over each entry in the server's scheduler file. If a scheduler entry is not present in the server copy, w...
2.521074
2.348391
1.073533
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=") consent_url.append(urls...
def informed_consent(self)
Create a URL for the user to give their consent through
3.521538
3.147586
1.118806
# 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(vpn_gate_url) for line in r.text.s...
def create_config_files(directory)
Initialize directory ready for vpn walker :param directory: the path where you want this to happen :return:
2.724714
2.71872
1.002205
# Some constant strings config_zip_url = "http://www.ipvanish.com/software/configs/configs.zip" if not os.path.exists(directory): os.makedirs(directory) logging.info("Starting to download IPVanish config file zip") url_opener = urllib.URLopener() zip_path = os.path.join(directory,...
def create_config_files(directory)
Initialize directory ready for vpn walker :param directory: the path where you want this to happen :return:
2.658133
2.671873
0.994857
if directory is None or path is None: return directory = os.path.expanduser(directory) return os.path.abspath(os.path.join(directory, path))
def return_abs_path(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:
2.225363
2.907948
0.765269
logging.info("Starting to create config files from openvpn files") vpn_dir = return_abs_path(directory, "vpns") conf_dir = return_abs_path(directory, "configs") os.mkdir(conf_dir) home_dirs = return_abs_path(directory, "home") os.mkdir(home_dirs) for filename in os.listdir(vpn_dir): ...
def create_config_files(directory)
For each VPN file in directory/vpns, create a new configuration file and all the associated directories Note: the expected directory structure is args.directory -----vpns (contains the OpenVPN config files -----configs (contains the Centinel config files) -----exps (contains the experiments dir...
2.487821
2.336148
1.064925
args = parse_args() # register signal handler signal.signal(signal.SIGTERM, signal_handler) signal.signal(signal.SIGINT, signal_handler) # set up logging log_formatter = logging.Formatter("%(asctime)s %(filename)s(line %(lineno)d) " "%(levelname)s: %(...
def _run()
Entry point for all uses of centinel
2.301171
2.286325
1.006494
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['proxy']['proxy_url']}
def parse_config(self, config_file)
Given a configuration file, read in and interpret the results :param config_file: :return:
2.97889
3.173131
0.938786
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][parameter]) and (...
def update(self, old, backup_path=None)
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:
2.817841
2.872221
0.981067
with open(config_file, 'w') as f: json.dump(self.params, f, indent=2, separators=(',', ': '))
def write_out_config(self, config_file)
Write out the configuration file :param config_file: :return: Note: this will erase all comments from the config file
2.726895
3.322802
0.820661
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("extensions.firebug.currentVersion", "2.0.8") ...
def setup_profile(self, firebug=True, netexport=True)
Setup the profile for firefox :param firebug: whether add firebug extension :param netexport: whether add netexport extension :return: a firefox profile object
2.216922
2.212011
1.00222
if 'fd' not in kwargs \ or 'url' not in kwargs \ or 'files_count' not in kwargs: logging.error("Missing arguments in wrap_results function") return {} external = kwargs['external'] if 'external' in kwargs else None fd = kwargs['f...
def wrap_results(self, **kwargs)
Wrap returned http response into a well formatted dict :param kwargs: this dict param should contains following keys: fd: file directory to url: the test url fo the result files_count: the number of files under har/ directory ...
2.652393
2.446143
1.084316
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] path = url[len(host):] ...
def divide_url(self, url)
divide url into host and path two parts
1.715683
1.550367
1.10663
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/" # fc.load_page(self.driver, http_url) fc.switch_...
def get(self, host, files_count, path="/", ssl=False, external=None)
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
3.578471
3.551516
1.00759
capture_path = self.cur_path display_mode = 0 # 0 is virtural display(Xvfb mode) site_list = [] file_name, file_contents = input_file result = {"file_name": file_name} file_metadata = {} file_comments = [] run_start_time = time.time() ...
def run_file(self, input_file, results)
use foctor_core library do get requests :param input_file: the file name of the list of test urls format: 1, www.facebook.com 2, www.google.com ... :param results: the object to save the response...
4.923791
4.922781
1.000205
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: log_file = None # set up firefox...
def run(self, input_files, url=None, verbose=0)
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 ... ...
4.017754
4.046207
0.992968
# Some constant strings config_zip_url = "https://s3-us-west-1.amazonaws.com/heartbleed/linux/linux-files.zip" if not os.path.exists(directory): os.makedirs(directory) logging.info("Starting to download PureVPN config file zip") url_opener = urllib.URLopener() zip_path = os.path.j...
def create_config_files(directory)
Initialize directory ready for vpn walker :param directory: the path where you want this to happen :return:
2.86628
2.854598
1.004092
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_name = os.path.basename(path) file...
def hash_folder(folder, regex='[!_]*')
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...
2.541368
2.675421
0.949895
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.append(filename) for filename in client_hashes: i...
def compute_files_to_download(client_hashes, server_hashes)
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...
1.964562
1.710766
1.148352
return Spinner(beep, disable, force)
def spinner(beep=False, disable=False, force=False)
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...
6.096221
23.179192
0.263004
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 link is:') print(ur...
def verifier(self, url)
Will ask user to click link to accept app and write code
10.984691
9.687598
1.133892
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()
def write_config(self)
Write config to file
1.733493
1.637676
1.058508
try: with open(self.config_file, 'r') as f: self.config = json.loads(f.read()) f.close() except IOError: return False return True
def read_config(self)
Read config from file
2.463575
2.274332
1.083208
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.followers mynote.cc =...
def post_note(self)
Post note and return the URL of the posted note
4.670893
4.371893
1.068391
if item is not None: if isinstance(item, six.string_types): return item elif hasattr(item, 'id'): return item.id
def get_obj_id(self, item)
Get the id of a PumpObject. :param item: id string or PumpObject
2.85876
3.895874
0.733792
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 = False if self._since i...
def get_page(self, url)
Get a page of items from API
5.648541
5.407418
1.044591
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 None: # retur...
def get_cached(self)
Get items from feed cache while trying to emulate how API handles offset/since/before parameters
3.130256
2.880295
1.086783
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
def done(self)
Check if we should stop returning objects
3.709307
3.342756
1.109655
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("objectType"): ...
def _build_cache(self)
Build a list of objects from feed's cached items or API page
4.938962
4.455835
1.108426
return ItemList(self, offset=offset, limit=limit, since=since, before=before, cached=self.is_cached)
def items(self, offset=None, limit=20, since=None, before=None, *args, **kwargs)
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
4.868427
7.27166
0.669507
url = self.url if not url.endswith("/"): url += "/" return url + feedname
def _subfeed(self, feedname)
Used for Inbox/Outbox major/minor/direct subfeeds
4.387498
3.887816
1.128525
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
def direct(self)
Direct inbox feed, contains activities addressed directly to the owner of the inbox.
7.322869
7.490718
0.977592
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
def major(self)
Major inbox feed, contains major activities such as notes and images.
7.777628
7.176063
1.083829
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
def minor(self)
Minor inbox feed, contains minor activities such as likes, shares and follows.
8.014178
8.016472
0.999714
activity = { "verb": "create", "object": { "objectType": "collection", "objectTypes": [self.membertype], "displayName": display_name, "content": content } } if self._post_activity(activi...
def create(self, display_name, content=None)
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...
5.140728
6.216192
0.82699
data = super(Note, self).serialize() data.update({ "verb": "post", "object": { "objectType": self.object_type, "content": self.content, } }) if self.display_name: data["object"]["displayName"] = self...
def serialize(self)
Converts the post to something compatible with `json.dumps`
3.302811
2.871302
1.150283
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_secret"] = self.secret ...
def context(self)
Provides request context
3.648883
3.592593
1.015668
request = { "headers": {"Content-Type": "application/json"}, "timeout": self._pump.timeout, "data": self.context, } url = "{proto}://{server}/{endpoint}".format( proto=self._pump.protocol, server=server or self.server, ...
def request(self, server=None)
Sends the request
3.312899
3.332396
0.994149