code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def get_ht_capability(cap): answers = list() if cap & 1: answers.append('RX LDPC') if cap & 2: answers.append('HT20/HT40') if not cap & 2: answers.append('HT20') if (cap >> 2) & 0x3 == 0: answers.append('Static SM Power Save') if (cap >> 2) & 0x3 == 1: ...
http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/util.c?id=v3.17#n541. Positional arguments: cap -- c_uint16 Returns: List.
def get_ht_mcs(mcs): answers = dict() max_rx_supp_data_rate = (mcs[10] & ((mcs[11] & 0x3) << 8)) tx_mcs_set_defined = not not (mcs[12] & (1 << 0)) tx_mcs_set_equal = not (mcs[12] & (1 << 1)) tx_max_num_spatial_streams = ((mcs[12] >> 2) & 3) + 1 tx_unequal_modulation = not not (mcs[12] & (1 ...
http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/util.c?id=v3.17#n591. Positional arguments: mcs -- bytearray. Returns: Dict.
def _get(out_parsed, in_bss, key, parser_func): short_key = key[12:].lower() key_integer = getattr(nl80211, key) if in_bss.get(key_integer) is None: return dict() data = parser_func(in_bss[key_integer]) if parser_func == libnl.attr.nla_data: data = data[:libnl.attr.nla_len(in_bs...
Handle calling the parser function to convert bytearray data into Python data types. Positional arguments: out_parsed -- dictionary to update with parsed data and string keys. in_bss -- dictionary of integer keys and bytearray values. key -- key string to lookup (must be a variable name in libnl.nl8021...
def _fetch(in_parsed, *keys): for ie in ('information_elements', 'beacon_ies'): target = in_parsed.get(ie, {}) for key in keys: target = target.get(key, {}) if target: return target return None
Retrieve nested dict data from either information elements or beacon IES dicts. Positional arguments: in_parsed -- dictionary to read from. keys -- one or more nested dict keys to lookup. Returns: Found value or None.
def print_header_content(nlh): answer = 'type={0} length={1} flags=<{2}> sequence-nr={3} pid={4}'.format( nl_nlmsgtype2str(nlh.nlmsg_type, bytearray(), 32).decode('ascii'), nlh.nlmsg_len, nl_nlmsg_flags2str(nlh.nlmsg_flags, bytearray(), 128).decode('ascii'), nlh.nlmsg_seq, ...
Return header content (doesn't actually print like the C library does). https://github.com/thom311/libnl/blob/libnl3_2_25/lib/handlers.c#L34 Positional arguments: nlh -- nlmsghdr class instance.
def nl_error_handler_verbose(_, err, arg): ofd = arg or _LOGGER.debug ofd('-- Error received: ' + strerror(-err.error)) ofd('-- Original message: ' + print_header_content(err.msg)) return -nl_syserr2nlerr(err.error)
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/handlers.c#L78.
def nl_valid_handler_debug(msg, arg): ofd = arg or _LOGGER.debug ofd('-- Debug: Unhandled Valid message: ' + print_header_content(nlmsg_hdr(msg))) return NL_OK
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/handlers.c#L92.
def nl_finish_handler_debug(msg, arg): ofd = arg or _LOGGER.debug ofd('-- Debug: End of multipart message block: ' + print_header_content(nlmsg_hdr(msg))) return NL_STOP
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/handlers.c#L103.
def nl_msg_in_handler_debug(msg, arg): ofd = arg or _LOGGER.debug ofd('-- Debug: Received Message:') nl_msg_dump(msg, ofd) return NL_OK
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/handlers.c#L114.
def nl_msg_out_handler_debug(msg, arg): ofd = arg or _LOGGER.debug ofd('-- Debug: Sent Message:') nl_msg_dump(msg, ofd) return NL_OK
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/handlers.c#L124.
def nl_skipped_handler_debug(msg, arg): ofd = arg or _LOGGER.debug ofd('-- Debug: Skipped message: ' + print_header_content(nlmsg_hdr(msg))) return NL_SKIP
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/handlers.c#L134.
def nl_cb_alloc(kind): if kind < 0 or kind > NL_CB_KIND_MAX: return None cb = nl_cb() cb.cb_active = NL_CB_TYPE_MAX + 1 for i in range(NL_CB_TYPE_MAX): nl_cb_set(cb, i, kind, None, None) nl_cb_err(cb, kind, None, None) return cb
Allocate a new callback handle. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/handlers.c#L201 Positional arguments: kind -- callback kind to be used for initialization. Returns: Newly allocated callback handle (nl_cb class instance) or None.
def nl_cb_set(cb, type_, kind, func, arg): if type_ < 0 or type_ > NL_CB_TYPE_MAX or kind < 0 or kind > NL_CB_KIND_MAX: return -NLE_RANGE if kind == NL_CB_CUSTOM: cb.cb_set[type_] = func cb.cb_args[type_] = arg else: cb.cb_set[type_] = cb_def[type_][kind] cb.cb_...
Set up a callback. Updates `cb` in place. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/handlers.c#L293 Positional arguments: cb -- nl_cb class instance. type_ -- callback to modify (integer). kind -- kind of implementation (integer). func -- callback function (NL_CB_CUSTOM). arg -...
def nl_cb_err(cb, kind, func, arg): if kind < 0 or kind > NL_CB_KIND_MAX: return -NLE_RANGE if kind == NL_CB_CUSTOM: cb.cb_err = func cb.cb_err_arg = arg else: cb.cb_err = cb_err_def[kind] cb.cb_err_arg = arg return 0
Set up an error callback. Updates `cb` in place. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/handlers.c#L343 Positional arguments: cb -- nl_cb class instance. kind -- kind of callback (integer). func -- callback function. arg -- argument to be passed to callback function. Return...
def setup_logging(): fmt = 'DBG<0>%(pathname)s:%(lineno)d %(funcName)s: %(message)s' handler_stderr = logging.StreamHandler(sys.stderr) handler_stderr.setFormatter(logging.Formatter(fmt)) root_logger = logging.getLogger() root_logger.setLevel(logging.DEBUG) root_logger.addHandler(handler...
Called when __name__ == '__main__' below. Sets up logging library. All logging messages go to stderr, from DEBUG to CRITICAL. This script uses print() for regular messages.
def rta_len(self, value): self.bytearray[self._get_slicers(0)] = bytearray(c_ushort(value or 0))
Length setter.
def rta_type(self, value): self.bytearray[self._get_slicers(1)] = bytearray(c_ushort(value or 0))
Type setter.
def rtgen_family(self, value): self.bytearray[self._get_slicers(0)] = bytearray(c_ubyte(value or 0))
Family setter.
def ifi_family(self, value): self.bytearray[self._get_slicers(0)] = bytearray(c_ubyte(value or 0))
Family setter.
def ifi_type(self, value): self.bytearray[self._get_slicers(2)] = bytearray(c_ushort(value or 0))
Type setter.
def ifi_index(self, value): self.bytearray[self._get_slicers(3)] = bytearray(c_int(value or 0))
Index setter.
def ifi_flags(self, value): self.bytearray[self._get_slicers(4)] = bytearray(c_uint(value or 0))
Message flags setter.
def ifi_change(self, value): self.bytearray[self._get_slicers(5)] = bytearray(c_uint(value or 0))
Change setter.
def _class_factory(base): class ClsPyPy(base): def __repr__(self): return repr(base(super(ClsPyPy, self).value)) @classmethod def from_buffer(cls, ba): try: integer = struct.unpack_from(getattr(cls, '_type_'), ba)[0] except struct.err...
Create subclasses of ctypes. Positional arguments: base -- base class to subclass. Returns: New class definition.
def get_string(stream): r ba = bytearray() for c in stream: if not c: break ba.append(c) return bytes(ba)
r"""Use this to grab a "string" from a bytearray() stream. C's printf() prints until it encounters a null byte (b'\0'). This function behaves the same. Positional arguments: stream -- bytearray stream of data. Returns: bytes() instance of any characters from the start of the stream until before t...
def _get_slicers(self, index): if not index: # first item. return slice(0, self.SIGNATURE[0]) if index >= len(self.SIGNATURE): raise IndexError('index out of self.SIGNATURE range') pad_start = sum(self.SIGNATURE[:index]) pad_stop = pad_start + self.SIGNA...
Return a slice object to slice a list/bytearray by. Positional arguments: index -- index of self.SIGNATURE to target self.bytearray by. Returns: slice() object. E.g. `x = _get_slicers(0); ba_instance[x]`
def pid(self, value): self.bytearray[self._get_slicers(0)] = bytearray(c_int32(value or 0))
Process ID setter.
def uid(self, value): self.bytearray[self._get_slicers(1)] = bytearray(c_int32(value or 0))
User ID setter.
def gid(self, value): self.bytearray[self._get_slicers(2)] = bytearray(c_int32(value or 0))
Group ID setter.
def family_constructor(c): family = c if not hasattr(family, 'gf_ops'): setattr(family, 'gf_ops', nl_list_head(container_of=family)) if not hasattr(family, 'gf_mc_grps'): setattr(family, 'gf_mc_grps', nl_list_head(container_of=family)) nl_init_list_head(family.gf_ops) nl_init_li...
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/family.c#L37. Positional arguments: c -- nl_object-derived class instance.
def family_free_data(c): family = c if not hasattr(family, 'gf_ops'): setattr(family, 'gf_ops', nl_list_head(container_of=family)) if not hasattr(family, 'gf_mc_grps'): setattr(family, 'gf_mc_grps', nl_list_head(container_of=family)) ops = tmp = genl_family_op() grp = t_grp = ge...
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/family.c#L45. Positional arguments: c -- nl_object-derived class instance.
def genl_family_add_grp(family, id_, name): grp = genl_family_grp(id_=id_, name=name) nl_list_add_tail(grp.list_, family.gf_mc_grps) return 0
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/family.c#L366. Positional arguments: family -- Generic Netlink family object (genl_family class instance). id_ -- new numeric identifier (integer). name -- new human readable name (string). Returns: 0
def parse_json(filename): # Regular expression for comments comment_re = re.compile( '(^)?[^\S\n]*/(?:\*(.*?)\*/[^\S\n]*|/[^\n]*)($)?', re.DOTALL | re.MULTILINE ) with open(filename) as f: content = ''.join(f.readlines()) ## Looking for comments match = com...
Parse a JSON file First remove comments and then use the json module package Comments look like : // ... or /* ... */
def grouper(n, iterable, fillvalue=None): "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return itertools.izip_longest(fillvalue=fillvalue, *argsf grouper(n, iterable, fillvalue=None): "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return itert...
grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
def ctrl_request_update(_, nl_sock_h): return int(genl_send_simple(nl_sock_h, GENL_ID_CTRL, CTRL_CMD_GETFAMILY, CTRL_VERSION, NLM_F_DUMP))
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/ctrl.c#L37. Positional arguments: nl_sock_h -- nl_sock class instance. Returns: Integer, genl_send_simple() output.
def parse_mcast_grps(family, grp_attr): remaining = c_int() if not grp_attr: raise BUG for nla in nla_for_each_nested(grp_attr, remaining): tb = dict() err = nla_parse_nested(tb, CTRL_ATTR_MCAST_GRP_MAX, nla, family_grp_policy) if err < 0: return err ...
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/ctrl.c#L64. Positional arguments: family -- genl_family class instance. grp_attr -- nlattr class instance. Returns: 0 on success or a negative error code.
def probe_response(msg, arg): tb = dict((i, None) for i in range(CTRL_ATTR_MAX + 1)) nlh = nlmsg_hdr(msg) ret = arg if genlmsg_parse(nlh, 0, tb, CTRL_ATTR_MAX, ctrl_policy): return NL_SKIP if tb[CTRL_ATTR_FAMILY_ID]: genl_family_set_id(ret, nla_get_u16(tb[CTRL_ATTR_FAMILY_ID])) ...
Process responses from from the query sent by genl_ctrl_probe_by_name(). https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/ctrl.c#L203 Process returned messages, filling out the missing information in the genl_family structure. Positional arguments: msg -- returned message (nl_msg class inst...
def genl_ctrl_probe_by_name(sk, name): ret = genl_family_alloc() if not ret: return None genl_family_set_name(ret, name) msg = nlmsg_alloc() orig = nl_socket_get_cb(sk) cb = nl_cb_clone(orig) genlmsg_put(msg, NL_AUTO_PORT, NL_AUTO_SEQ, GENL_ID_CTRL, 0, 0, CTRL_CMD_GETFAMILY, 1)...
Look up generic Netlink family by family name querying the kernel directly. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/ctrl.c#L237 Directly query's the kernel for a given family name. Note: This API call differs from genl_ctrl_search_by_name in that it queries the kernel directly, allowin...
def genl_ctrl_resolve(sk, name): family = genl_ctrl_probe_by_name(sk, name) if family is None: return -NLE_OBJ_NOTFOUND return int(genl_family_get_id(family))
Resolve Generic Netlink family name to numeric identifier. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/ctrl.c#L429 Resolves the Generic Netlink family name to the corresponding numeric family identifier. This function queries the kernel directly, use genl_ctrl_search_by_name() if you need t...
def genl_ctrl_grp_by_name(family, grp_name): for grp in nl_list_for_each_entry(genl_family_grp(), family.gf_mc_grps, 'list_'): if grp.name == grp_name: return grp.id_ return -NLE_OBJ_NOTFOUND
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/ctrl.c#L446. Positional arguments: family -- genl_family class instance. grp_name -- bytes. Returns: group ID or negative error code.
def genl_ctrl_resolve_grp(sk, family_name, grp_name): family = genl_ctrl_probe_by_name(sk, family_name) if family is None: return -NLE_OBJ_NOTFOUND return genl_ctrl_grp_by_name(family, grp_name)
Resolve Generic Netlink family group name. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/ctrl.c#L471 Looks up the family object and resolves the group name to the numeric group identifier. Positional arguments: sk -- Generic Netlink socket (nl_sock class instance). family_name -- nam...
def get_supprates(_, data): answer = list() for i in range(len(data)): r = data[i] & 0x7f if r == BSS_MEMBERSHIP_SELECTOR_VHT_PHY and data[i] & 0x80: value = 'VHT' elif r == BSS_MEMBERSHIP_SELECTOR_HT_PHY and data[i] & 0x80: value = 'HT' else: ...
http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n227. Positional arguments: data -- bytearray data to read.
def get_country(_, data): answers = {'Environment': country_env_str(chr(data[2]))} data = data[3:] while len(data) >= 3: triplet = ieee80211_country_ie_triplet(data) if triplet.ext.reg_extension_id >= IEEE80211_COUNTRY_EXTENSION_ID: answers['Extension ID'] = triplet.ext.reg...
http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n267. Positional arguments: data -- bytearray data to read. Returns: Dict.
def get_cipher(data): legend = {0: 'Use group cipher suite', 1: 'WEP-40', 2: 'TKIP', 4: 'CCMP', 5: 'WEP-104', } key = data[3] if ieee80211_oui == bytes(data[:3]): legend.update({6: 'AES-128-CMAC', 8: 'GCMP', }) elif ms_oui != bytes(data[:3]): key = None return legend.get(key, '{...
http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n336. Positional arguments: data -- bytearray data to read. Returns: WiFi stream cipher used by the access point (string).
def get_ht_capa(_, data): answers = { 'Capabilities': get_ht_capability(data[0] | (data[1] << 8)), 'Minimum RX AMPDU time spacing': ampdu_space.get((data[2] >> 2) & 7, 'BUG (spacing more than 3 bits!)'), 'Maximum RX AMPDU length': {0: 8191, 1: 16383, 2: 32767, 3: 65535}.get(data[2] & 3,...
http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n602. Positional arguments: data -- bytearray data to read. Returns: Dict.
def get_11u_advert(_, data): answers = dict() idx = 0 while idx < len(data) - 1: qri = data[idx] proto_id = data[idx + 1] answers['Query Response Info'] = qri answers['Query Response Length Limit'] = qri & 0x7f if qri & (1 << 7): answers['PAME-BI'] = ...
http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n676. Positional arguments: data -- bytearray data to read. Returns: Dict.
def get_ht_op(_, data): protection = ('no', 'nonmember', 20, 'non-HT mixed') sta_chan_width = (20, 'any') answers = { 'primary channel': data[0], 'secondary channel offset': ht_secondary_offset[data[1] & 0x3], 'STA channel width': sta_chan_width[(data[1] & 0x4) >> 2], 'R...
http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n766. Positional arguments: data -- bytearray data to read. Returns: Dict.
def get_capabilities(_, data): answers = list() for i in range(len(data)): base = i * 8 for bit in range(8): if not data[i] & (1 << bit): continue answers.append(CAPA.get(bit + base, bit)) return answers
http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n796. Positional arguments: data -- bytearray data to read. Returns: List.
def get_tim(_, data): answers = { 'DTIM Count': data[0], 'DTIM Period': data[1], 'Bitmap Control': data[2], 'Bitmap[0]': data[3], } if len(data) - 4: answers['+ octets'] = len(data) - 4 return answers
http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n874. Positional arguments: data -- bytearray data to read. Returns: Dict.
def get_obss_scan_params(_, data): answers = { 'passive dwell': (data[1] << 8) | data[0], 'active dwell': (data[3] << 8) | data[2], 'channel width trigger scan interval': (data[5] << 8) | data[4], 'scan passive total per channel': (data[7] << 8) | data[6], 'scan active t...
http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n914. Positional arguments: data -- bytearray data to read. Returns: Dict.
def get_secchan_offs(type_, data): if data[0] < len(ht_secondary_offset): return "{0} ({1})".format(ht_secondary_offset[data[0]], data[0]) return "{0}".format(data[0])
http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n927. Positional arguments: type_ -- corresponding `ieprinters` dictionary key for the instance. data -- bytearray data to read.
def get_bss_load(_, data): answers = { 'station count': (data[1] << 8) | data[0], 'channel utilisation': data[2] / 255.0, 'available admission capacity': (data[4] << 8) | data[3], } return answers
http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n935. Positional arguments: data -- bytearray data to read. Returns: Dict.
def get_ie(instance, key, data): if not instance.print_: return dict() if len(data) < instance.minlen or len(data) > instance.maxlen: if data: return {'<invalid: {0} byte(s)>'.format(len(data)): ' '.join(format(x, '02x') for x in data)} return {'<invalid: no data>': data...
http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n981. Positional arguments: instance -- `ie_print` class instance. key -- corresponding `ieprinters` dictionary key for the instance. data -- bytearray data to read. Returns: Dictionary of parsed data with string key...
def get_wifi_wmm_param(data): answers = dict() aci_tbl = ('BE', 'BK', 'VI', 'VO') if data[0] & 0x80: answers['u-APSD'] = True data = data[2:] for i in range(4): key = aci_tbl[(data[0] >> 5) & 3] value = dict() if data[0] & 0x10: value['acm'] = True ...
http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n1046. Positional arguments: data -- bytearray data to read. Returns: Dict.
def get_wifi_wmm(_, data): answers = dict() if data[0] == 0x01: if len(data) < 20: key = 'invalid' elif data[1] != 1: key = 'Parameter: not version 1' else: answers.update(get_wifi_wmm_param(data[2:])) return answers elif data[0] =...
http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n1088. Positional arguments: data -- bytearray data to read. Returns: Dict.
def get_vendor(data): if len(data) < 3: return dict(('Vendor specific: <too short> data', ' '.join(format(x, '02x'))) for x in data) key = data[3] if bytes(data[:3]) == ms_oui: if key in wifiprinters and wifiprinters[key].flags & 1: return get_ie(wifiprinters[key], key, dat...
http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n1401. Positional arguments: data -- bytearray data to read. Returns: Dictionary of parsed data with string keys.
def get_ies(ie): answers = dict() while len(ie) >= 2 and len(ie) >= ie[1]: key = ie[0] # Should be key in `ieprinters` dict. len_ = ie[1] # Length of this information element. data = ie[2:len_ + 2] # Data for this information element. if key in ieprinters and ieprinters[k...
http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n1456. Positional arguments: ie -- bytearray data to read. Returns: Dictionary of all parsed data. In the iw tool it prints everything to terminal. This function returns a dictionary with string keys (being the "titles" ...
def _safe_read(path, length): if not os.path.exists(os.path.join(HERE, path)): return '' file_handle = codecs.open(os.path.join(HERE, path), encoding='utf-8') contents = file_handle.read(length) file_handle.close() return contents
Read file contents.
def ok(no_exit, func, *args, **kwargs): ret = func(*args, **kwargs) if no_exit or ret >= 0: return ret reason = errmsg[abs(ret)] error('{0}() returned {1} ({2})'.format(func.__name__, ret, reason))
Exit if `ret` is not OK (a negative number).
def error_handler(_, err, arg): arg.value = err.error return libnl.handlers.NL_STOP
Update the mutable integer `arg` with the error code.
def callback_trigger(msg, arg): gnlh = genlmsghdr(nlmsg_data(nlmsg_hdr(msg))) if gnlh.cmd == nl80211.NL80211_CMD_SCAN_ABORTED: arg.value = 1 # The scan was aborted for some reason. elif gnlh.cmd == nl80211.NL80211_CMD_NEW_SCAN_RESULTS: arg.value = 0 # The scan completed successfully. ...
Called when the kernel is done scanning. Only signals if it was successful or if it failed. No other data. Positional arguments: msg -- nl_msg class instance containing the data sent by the kernel. arg -- mutable integer (ctypes.c_int()) to update with results. Returns: An integer, value of NL_SKI...
def callback_dump(msg, results): bss = dict() # To be filled by nla_parse_nested(). # First we must parse incoming data into manageable chunks and check for errors. gnlh = genlmsghdr(nlmsg_data(nlmsg_hdr(msg))) tb = dict((i, None) for i in range(nl80211.NL80211_ATTR_MAX + 1)) nla_parse(tb, nl...
Here is where SSIDs and their data is decoded from the binary data sent by the kernel. This function is called once per SSID. Everything in `msg` pertains to just one SSID. Positional arguments: msg -- nl_msg class instance containing the data sent by the kernel. results -- dictionary to populate with...
def do_scan_results(sk, if_index, driver_id, results): msg = nlmsg_alloc() genlmsg_put(msg, 0, 0, driver_id, 0, NLM_F_DUMP, nl80211.NL80211_CMD_GET_SCAN, 0) nla_put_u32(msg, nl80211.NL80211_ATTR_IFINDEX, if_index) cb = libnl.handlers.nl_cb_alloc(libnl.handlers.NL_CB_DEFAULT) libnl.handlers.nl_c...
Retrieve the results of a successful scan (SSIDs and data about them). This function does not require root privileges. It eventually calls a callback that actually decodes data about SSIDs but this function kicks that off. May exit the program (sys.exit()) if a fatal error occurs. Positional argument...
def eta_letters(seconds): final_days, final_hours, final_minutes, final_seconds = 0, 0, 0, seconds if final_seconds >= 86400: final_days = int(final_seconds / 86400.0) final_seconds -= final_days * 86400 if final_seconds >= 3600: final_hours = int(final_seconds / 3600.0) ...
Convert seconds remaining into human readable strings. From https://github.com/Robpol86/etaprogress/blob/ad934d4/etaprogress/components/eta_conversions.py. Positional arguments: seconds -- integer/float indicating seconds remaining.
def print_table(data): table = AsciiTable([COLUMNS]) table.justify_columns[2] = 'right' table.justify_columns[3] = 'right' table.justify_columns[4] = 'right' table_data = list() for row_in in data: row_out = [ str(row_in.get('ssid', '')).replace('\0', ''), st...
Print the table of detected SSIDs and their data to screen. Positional arguments: data -- list of dictionaries.
def setup_logging(): fmt = 'DBG<0>%(pathname)s:%(lineno)d %(funcName)s: %(message)s' handler_stderr = logging.StreamHandler(sys.stderr) handler_stderr.setFormatter(logging.Formatter(fmt)) if OPTIONS['--verbose'] == 1: handler_stderr.addFilter(logging.Filter(__name__)) root_logger = l...
Called when __name__ == '__main__' below. Sets up logging library. All logging messages go to stderr, from DEBUG to CRITICAL. This script uses print() for regular messages.
def generateHeader(self, sObjectType): ''' Generate a SOAP header as defined in: http://www.salesforce.com/us/developer/docs/api/Content/soap_headers.htm ''' try: return self._sforce.factory.create(sObjectType) except: print 'There is not a SOAP header of type %s' % sObjectTypf gener...
Generate a SOAP header as defined in: http://www.salesforce.com/us/developer/docs/api/Content/soap_headers.htm
def generateObject(self, sObjectType): ''' Generate a Salesforce object, such as a Lead or Contact ''' obj = self._sforce.factory.create('ens:sObject') obj.type = sObjectType return obf generateObject(self, sObjectType): ''' Generate a Salesforce object, such as a Lead or Contact '''...
Generate a Salesforce object, such as a Lead or Contact
def _handleResultTyping(self, result): ''' If any of the following calls return a single result, and self._strictResultTyping is true, return the single result, rather than [(SaveResult) {...}]: convertLead() create() delete() emptyRecycleBin() invalidateSessions() merge...
If any of the following calls return a single result, and self._strictResultTyping is true, return the single result, rather than [(SaveResult) {...}]: convertLead() create() delete() emptyRecycleBin() invalidateSessions() merge() process() retrieve() undelete(...
def _setEndpoint(self, location): ''' Set the endpoint after when Salesforce returns the URL after successful login() ''' # suds 0.3.7+ supports multiple wsdl services, but breaks setlocation :( # see https://fedorahosted.org/suds/ticket/261 try: self._sforce.set_options(location = locatio...
Set the endpoint after when Salesforce returns the URL after successful login()
def getUpdated(self, sObjectType, startDate, endDate): ''' Retrieves the list of individual objects that have been updated (added or changed) within the given timespan for the specified object. ''' self._setHeaders('getUpdated') return self._sforce.service.getUpdated(sObjectType, startDate, endD...
Retrieves the list of individual objects that have been updated (added or changed) within the given timespan for the specified object.
def invalidateSessions(self, sessionIds): ''' Invalidate a Salesforce session This should be used with extreme caution, for the following (undocumented) reason: All API connections for a given user share a single session ID This will call logout() WHICH LOGS OUT THAT USER FROM EVERY CONCURRENT SESS...
Invalidate a Salesforce session This should be used with extreme caution, for the following (undocumented) reason: All API connections for a given user share a single session ID This will call logout() WHICH LOGS OUT THAT USER FROM EVERY CONCURRENT SESSION return invalidateSessionsResult
def query(self, queryString): ''' Executes a query against the specified object and returns data that matches the specified criteria. ''' self._setHeaders('query') return self._sforce.service.query(queryStringf query(self, queryString): ''' Executes a query against the specified object a...
Executes a query against the specified object and returns data that matches the specified criteria.
def queryAll(self, queryString): ''' Retrieves data from specified objects, whether or not they have been deleted. ''' self._setHeaders('queryAll') return self._sforce.service.queryAll(queryStringf queryAll(self, queryString): ''' Retrieves data from specified objects, whether or not they ha...
Retrieves data from specified objects, whether or not they have been deleted.
def queryMore(self, queryLocator): ''' Retrieves the next batch of objects from a query. ''' self._setHeaders('queryMore') return self._sforce.service.queryMore(queryLocatorf queryMore(self, queryLocator): ''' Retrieves the next batch of objects from a query. ''' self._setHeaders('qu...
Retrieves the next batch of objects from a query.
def describeSObject(self, sObjectsType): ''' Describes metadata (field list and object properties) for the specified object. ''' self._setHeaders('describeSObject') return self._sforce.service.describeSObject(sObjectsTypef describeSObject(self, sObjectsType): ''' Describes metadata (fiel...
Describes metadata (field list and object properties) for the specified object.
def describeSObjects(self, sObjectTypes): ''' An array-based version of describeSObject; describes metadata (field list and object properties) for the specified object or array of objects. ''' self._setHeaders('describeSObjects') return self._handleResultTyping(self._sforce.service.describeSObje...
An array-based version of describeSObject; describes metadata (field list and object properties) for the specified object or array of objects.
def resetPassword(self, userId): ''' Changes a user's password to a system-generated value. ''' self._setHeaders('resetPassword') return self._sforce.service.resetPassword(userIdf resetPassword(self, userId): ''' Changes a user's password to a system-generated value. ''' self._setHea...
Changes a user's password to a system-generated value.
def setPassword(self, userId, password): ''' Sets the specified user's password to the specified value. ''' self._setHeaders('setPassword') return self._sforce.service.setPassword(userId, passwordf setPassword(self, userId, password): ''' Sets the specified user's password to the specified v...
Sets the specified user's password to the specified value.
def _nl_cache_ops_lookup(name): ops = cache_ops while ops: # Loop until `ops` is None. if ops.co_name == name: return ops ops = ops.co_next return None
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/cache_mngt.c#L41. Positional arguments: name -- string. Returns: nl_cache_ops instance or None.
def _cache_ops_associate(protocol, msgtype): ops = cache_ops while ops: # Loop until `ops` is None. if ops.co_protocol == protocol: for co_msgtype in ops.co_msgtypes: if co_msgtype.mt_id == msgtype: return ops ops = ops.co_next return Non...
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/cache_mngt.c#L111. Positional arguments: protocol -- Netlink protocol (integer). msgtype -- Netlink message type (integer). Returns: nl_cache_ops instance with matching protocol containing matching msgtype or None.
def nl_msgtype_lookup(ops, msgtype): for i in ops.co_msgtypes: if i.mt_id == msgtype: return i return None
Lookup message type cache association. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/cache_mngt.c#L189 Searches for a matching message type association ing the specified cache operations. Positional arguments: ops -- cache operations (nl_cache_ops class instance). msgtype -- Netlink messa...
def nl_cache_mngt_register(ops): global cache_ops if not ops.co_name or not ops.co_obj_ops: return -NLE_INVAL with cache_ops_lock: if _nl_cache_ops_lookup(ops.co_name): return -NLE_EXIST ops.co_refcnt = 0 ops.co_next = cache_ops cache_ops = ops ...
Register a set of cache operations. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/cache_mngt.c#L252 Called by users of caches to announce the availability of a certain cache type. Positional arguments: ops -- cache operations (nl_cache_ops class instance). Returns: 0 on success or a ...
def execute(self): config.logger.debug('logging self') config.logger.debug(self.params ) if 'project_name' in self.params: self.params.pop('project_name', None) if 'settings' in self.params: self.params.pop('settings', None) create_result = confi...
self.params = { "ActionScriptType" : "None", "ExecutableEntityId" : "01pd0000001yXtYAAU", "IsDumpingHeap" : True, "Iteration" : 1, "Line" : 3, "ScopeId" : "005d00000...
def nl_connect(sk, protocol): flags = getattr(socket, 'SOCK_CLOEXEC', 0) if sk.s_fd != -1: return -NLE_BAD_SOCK try: sk.socket_instance = socket.socket(getattr(socket, 'AF_NETLINK', -1), socket.SOCK_RAW | flags, protocol) except OSError as exc: return -nl_syserr2nlerr(exc.er...
Create file descriptor and bind socket. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L96 Creates a new Netlink socket using `socket.socket()` and binds the socket to the protocol and local port specified in the `sk` socket object (if any). Fails if the socket is already connected. Posit...
def nl_send_iovec(sk, msg, iov, _): hdr = msghdr(msg_name=sk.s_peer, msg_iov=iov) # Overwrite destination if specified in the message itself, defaults to the peer address of the socket. dst = nlmsg_get_dst(msg) if dst.nl_family == socket.AF_NETLINK: hdr.msg_name = dst # Add credential...
Transmit Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L342 This function is identical to nl_send(). This function triggers the `NL_CB_MSG_OUT` callback. Positional arguments: sk -- Netlink socket (nl_sock class instance). msg -- Netlink message (nl_msg class in...
def nl_send(sk, msg): cb = sk.s_cb if cb.cb_send_ow: return cb.cb_send_ow(sk, msg) hdr = nlmsg_hdr(msg) iov = hdr.bytearray[:hdr.nlmsg_len] return nl_send_iovec(sk, msg, iov, 1)
Transmit Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L416 Transmits the Netlink message `msg` over the Netlink socket using the `socket.sendmsg()`. This function is based on `nl_send_iovec()`. The message is addressed to the peer as specified in the socket by either th...
def nl_complete_msg(sk, msg): nlh = msg.nm_nlh if nlh.nlmsg_pid == NL_AUTO_PORT: nlh.nlmsg_pid = nl_socket_get_local_port(sk) if nlh.nlmsg_seq == NL_AUTO_SEQ: nlh.nlmsg_seq = sk.s_seq_next sk.s_seq_next += 1 if msg.nm_protocol == -1: msg.nm_protocol = sk.s_proto ...
Finalize Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L450 This function finalizes a Netlink message by completing the message with desirable flags and values depending on the socket configuration. - If not yet filled out, the source address of the message (`nlmsg_pid`)...
def nl_send_simple(sk, type_, flags, buf=None, size=0): msg = nlmsg_alloc_simple(type_, flags) if buf is not None and size: err = nlmsg_append(msg, buf, size, NLMSG_ALIGNTO) if err < 0: return err return nl_send_auto(sk, msg)
Construct and transmit a Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L549 Allocates a new Netlink message based on `type_` and `flags`. If `buf` points to payload of length `size` that payload will be appended to the message. Sends out the message using `nl_send_auto()...
def nl_recvmsgs_report(sk, cb): if cb.cb_recvmsgs_ow: return int(cb.cb_recvmsgs_ow(sk, cb)) return int(recvmsgs(sk, cb))
Receive a set of messages from a Netlink socket and report parsed messages. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L998 This function is identical to nl_recvmsgs() to the point that it will return the number of parsed messages instead of 0 on success. See nl_recvmsgs(). Posit...
def nl_recvmsgs(sk, cb): err = nl_recvmsgs_report(sk, cb) if err > 0: return 0 return int(err)
Receive a set of messages from a Netlink socket. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L1023 Repeatedly calls nl_recv() or the respective replacement if provided by the application (see nl_cb_overwrite_recv()) and parses the received data as Netlink messages. Stops reading if one of t...
def nl_wait_for_ack(sk): cb = nl_cb_clone(sk.s_cb) nl_cb_set(cb, NL_CB_ACK, NL_CB_CUSTOM, lambda *_: NL_STOP, None) return int(nl_recvmsgs(sk, cb))
Wait for ACK. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L1058 Waits until an ACK is received for the latest not yet acknowledged Netlink message. Positional arguments: sk -- Netlink socket (nl_sock class instance). Returns: Number of received messages or a negative error cod...
def _nl_list_add(obj, prev, next_): prev.next_ = obj obj.prev = prev next_.prev = obj obj.next_ = next_
https://github.com/thom311/libnl/blob/libnl3_2_25/include/netlink/list.h#L27. Positional arguments: obj -- nl_list_head class instance. prev -- nl_list_head class instance. next_ -- nl_list_head class instance.
def nl_list_del(obj): obj.next.prev = obj.prev obj.prev.next_ = obj.next_
https://github.com/thom311/libnl/blob/libnl3_2_25/include/netlink/list.h#L49. Positional arguments: obj -- nl_list_head class instance.
def nl_list_entry(ptr, type_, member): if ptr.container_of: return ptr.container_of null_data = type_() setattr(null_data, member, ptr) return null_data
https://github.com/thom311/libnl/blob/libnl3_2_25/include/netlink/list.h#L64.
def nl_list_for_each_entry(pos, head, member): pos = nl_list_entry(head.next_, type(pos), member) while True: yield pos if getattr(pos, member) != head: pos = nl_list_entry(getattr(pos, member).next_, type(pos), member) continue break
https://github.com/thom311/libnl/blob/libnl3_2_25/include/netlink/list.h#L79. Positional arguments: pos -- class instance holding an nl_list_head instance. head -- nl_list_head class instance. member -- attribute (string). Returns: Generator yielding a class instances.
def nl_list_for_each_entry_safe(pos, n, head, member): pos = nl_list_entry(head.next_, type(pos), member) n = nl_list_entry(pos.member.next_, type(pos), member) while True: yield pos if getattr(pos, member) != head: pos = n n = nl_list_entry(n.member.next_, type(...
https://github.com/thom311/libnl/blob/libnl3_2_25/include/netlink/list.h#L84. Positional arguments: pos -- class instance holding an nl_list_head instance. n -- class instance holding an nl_list_head instance. head -- nl_list_head class instance. member -- attribute (string). Returns: Gene...
def __type2str(type_, buf, _, tbl): del buf[:] if type_ in tbl: buf.extend(tbl[type_].encode('ascii')) else: buf.extend('0x{0:x}'.format(type_).encode('ascii')) return buf
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/utils.c#L968. Positional arguments: type_ -- integer, key to lookup in `tbl`. buf -- bytearray(). _ -- unused. tbl -- dict. Returns: Reference to `buf`.
def callback(msg, _): # First convert `msg` into something more manageable. nlh = nlmsg_hdr(msg) iface = ifinfomsg(nlmsg_data(nlh)) hdr = IFLA_RTA(iface) remaining = ctypes.c_int(nlh.nlmsg_len - NLMSG_LENGTH(iface.SIZEOF)) # Now iterate through each rtattr stored in `iface`. while RTA_...
Callback function called by libnl upon receiving messages from the kernel. Positional arguments: msg -- nl_msg class instance containing the data sent by the kernel. Returns: An integer, value of NL_OK. It tells libnl to proceed with processing the next kernel message.
def main(): # First open a socket to the kernel. Same one used for sending and receiving. sk = nl_socket_alloc() # Creates an `nl_sock` instance. ret = nl_connect(sk, NETLINK_ROUTE) # Create file descriptor and bind socket. if ret < 0: reason = errmsg[abs(ret)] return error('nl_co...
Main function called upon script execution.