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: answers.append('Dynamic SM Power Save') if (cap >> 2) & 0x3 == 3: answers.append('SM Power Save disabled') if cap & 16: answers.append('RX Greenfield') if cap & 32: answers.append('RX HT20 SGI') if cap & 64: answers.append('RX HT40 SGI') if cap & 128: answers.append('TX STBC') if (cap >> 8) & 0x3 == 0: answers.append('No RX STBC') if (cap >> 8) & 0x3 == 1: answers.append('RX STBC 1-stream') if (cap >> 8) & 0x3 == 2: answers.append('RX STBC 2-streams') if (cap >> 8) & 0x3 == 3: answers.append('RX STBC 3-streams') if cap & 1024: answers.append('HT Delayed Block Ack') if not cap & 2048: answers.append('Max AMSDU length: 3839 bytes') if cap & 2048: answers.append('Max AMSDU length: 7935 bytes') if cap & 4096: answers.append('DSSS/CCK HT40') if not cap & 4096: answers.append('No DSSS/CCK HT40') if cap & 16384: answers.append('40 MHz Intolerant') if cap & 32768: answers.append('L-SIG TXOP protection') return answers
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 << 4)) if max_rx_supp_data_rate: answers['HT Max RX data rate (Mbps)'] = max_rx_supp_data_rate if tx_mcs_set_defined and tx_mcs_set_equal: answers['HT TX/RX MCS rate indexes supported'] = get_mcs_index(mcs) elif tx_mcs_set_defined: answers['HT RX MCS rate indexes supported'] = get_mcs_index(mcs) answers['TX unequal modulation supported'] = bool(tx_unequal_modulation) answers['HT TX Max spatial streams'] = tx_max_num_spatial_streams else: answers['HT RX MCS rate indexes supported'] = get_mcs_index(mcs) return answers
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_bss[key_integer])] out_parsed[short_key] = data
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.nl80211.nl80211). parser_func -- function to call, with the bytearray data as the only argument.
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, nlh.nlmsg_pid, ) return answer
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_args[type_] = arg return 0
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 -- argument passed to callback. Returns: 0 on success or a negative error code.
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. Returns: 0 on success or a negative error code.
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_stderr)
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.error: len_ = len(ba) size = struct.calcsize(getattr(cls, '_type_')) if len_ < size: raise ValueError('Buffer size too small ({0} instead of at least {1} bytes)'.format(len_, size)) raise return cls(integer) class ClsPy26(base): def __repr__(self): return repr(base(super(ClsPy26, self).value)) def __iter__(self): return iter(struct.pack(getattr(super(ClsPy26, self), '_type_'), super(ClsPy26, self).value)) try: base.from_buffer(bytearray(base())) except TypeError: # Python2.6, ctypes cannot be converted to bytearrays. return ClsPy26 except AttributeError: # PyPy on my Raspberry Pi, ctypes don't have from_buffer attribute. return ClsPyPy except ValueError: # PyPy on Travis CI, from_buffer cannot handle non-buffer() bytearrays. return ClsPyPy return base
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 the first null byte.
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.SIGNATURE[index] return slice(pad_start, pad_stop)
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_list_head(family.gf_mc_grps)
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 = genl_family_grp() if family is None: return for ops in nl_list_for_each_entry_safe(ops, tmp, family.gf_ops, 'o_list'): nl_list_del(ops.o_list) for grp in nl_list_for_each_entry_safe(grp, t_grp, family.gf_mc_grps, 'list_'): nl_list_del(grp.list_)
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 = comment_re.search(content) while match: # single line comment content = content[:match.start()] + content[match.end():] match = comment_re.search(content) # Return json file return json.loads(content)
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 itertools.izip_longest(fillvalue=fillvalue, *args)
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 if not tb[CTRL_ATTR_MCAST_GRP_ID] or not tb[CTRL_ATTR_MCAST_GRP_NAME]: return -NLE_MISSING_ATTR id_ = nla_get_u32(tb[CTRL_ATTR_MCAST_GRP_ID]) name = nla_get_string(tb[CTRL_ATTR_MCAST_GRP_NAME]) err = genl_family_add_grp(family, id_, name) if err < 0: return err return 0
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])) if tb[CTRL_ATTR_MCAST_GROUPS] and parse_mcast_grps(ret, tb[CTRL_ATTR_MCAST_GROUPS]) < 0: return NL_SKIP return NL_STOP
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 instance). arg -- genl_family class instance to fill out. Returns: Indicator to keep processing frames or not (NL_SKIP or NL_STOP).
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) nla_put_string(msg, CTRL_ATTR_FAMILY_NAME, name) nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, probe_response, ret) if nl_send_auto(sk, msg) < 0: return None if nl_recvmsgs(sk, cb) < 0: return None if wait_for_ack(sk) < 0: # If search was successful, request may be ACKed after data. return None if genl_family_get_id(ret) != 0: return ret
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, allowing for module autoload to take place to resolve the family request. Using an nl_cache prevents that operation. Positional arguments: sk -- Generic Netlink socket (nl_sock class instance). name -- family name (bytes). Returns: Generic Netlink family `genl_family` class instance or None if no match was found.
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 to resolve multiple names. Positional arguments: sk -- Generic Netlink socket (nl_sock class instance). name -- name of Generic Netlink family (bytes). Returns: The numeric family identifier or a negative error code.
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 -- name of Generic Netlink family (bytes). grp_name -- name of group to resolve (bytes). Returns: The numeric group identifier or a negative error code.
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: value = '{0}.{1}'.format(int(r / 2), int(5 * (r & 1))) answer.append('{0}{1}'.format(value, '*' if data[i] & 0x80 else '')) return answer
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_extension_id answers['Regulatory Class'] = triplet.ext.reg_class answers['Coverage class'] = triplet.ext.coverage_class answers['up to dm'] = triplet.ext.coverage_class * 450 data = data[3:] continue if triplet.chans.first_channel <= 14: # 2 GHz. end_channel = triplet.chans.first_channel + (triplet.chans.num_channels - 1) else: end_channel = triplet.chans.first_channel + (4 * (triplet.chans.num_channels - 1)) answers['Channels dBm'] = triplet.chans.max_power answers['Channels'] = (triplet.chans.first_channel, end_channel) data = data[3:] return answers
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, '{0:02x}-{1:02x}-{2:02x}:{3}'.format(data[0], data[1], data[2], data[3]))
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, 0), } answers.update(get_ht_mcs(data[3:])) return answers
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'] = True answers['proto_id'] = {0: 'ANQP', 1: 'MIH Information Service', 3: 'Emergency Alert System (EAS)', 2: 'MIH Command and Event Services Capability Discovery', 221: 'Vendor Specific'}.get(proto_id, 'Reserved: {0}'.format(proto_id)) idx += 2 return answers
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], 'RIFS': (data[1] & 0x8) >> 3, 'HT protection': protection[data[2] & 0x3], 'non-GF present': (data[2] & 0x4) >> 2, 'OBSS non-GF present': (data[2] & 0x10) >> 4, 'dual beacon': (data[4] & 0x40) >> 6, 'dual CTS protection': (data[4] & 0x80) >> 7, 'STBC beacon': data[5] & 0x1, 'L-SIG TXOP Prot': (data[5] & 0x2) >> 1, 'PCO active': (data[5] & 0x4) >> 2, 'PCO phase': (data[5] & 0x8) >> 3, } return answers
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 total per channel': (data[9] << 8) | data[8], 'BSS width channel transition delay factor': (data[11] << 8) | data[10], 'OBSS Scan Activity Threshold': ((data[13] << 8) | data[12]) / 100.0 } return answers
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} return {instance.name: instance.print_(key, 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 keys.
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 value['CW'] = ((1 << (data[1] & 0xf)) - 1, (1 << (data[1] >> 4)) - 1) value['AIFSN'] = data[0] & 0xf if data[2] | data[3]: value['TXOP'] = (data[2] + (data[3] << 8)) * 32 answers[key] = value data = data[4:] return {'Parameter version 1': answers}
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] == 0x00: key = 'information' else: key = 'type {0}'.format(data[0]) answers[key] = ' '.join(format(x, '02x') for x in data) return answers
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, data[4:]) return dict(('MS/WiFi {0:02x}, data'.format(key), ' '.join(format(x, '02x'))) for x in data[4:]) if bytes(data[:3]) == wfa_oui: if key in wfa_printers and wfa_printers[key].flags & 1: return get_ie(wfa_printers[key], key, data[4:]) return dict(('WFA {0:02x}, data'.format(key), ' '.join(format(x, '02x'))) for x in data[4:]) unknown_key = 'Vendor specific: OUI {0:02x}:{1:02x}:{2:02x}, data'.format(data[0], data[1], data[2]) unknown_value = ' '.join(format(x, '02x') for x in data[3:]) return {unknown_key: unknown_value}
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[key].flags & 1: answers.update(get_ie(ieprinters[key], key, data)) elif key == 221: answers.update(get_vendor(data)) else: answers['Unknown IE ({0})'.format(key)] = ' '.join(format(x, '02x') for x in data) ie = ie[len_ + 2:] return answers
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" of data printed by iw), and data values (integers/strings/etc).
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. `callback_dump` will collect the results later. return libnl.handlers.NL_SKIP
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_SKIP. It tells libnl to stop calling other callbacks for this message and proceed with processing the next kernel message.
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, nl80211.NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0), genlmsg_attrlen(gnlh, 0), None) if not tb[nl80211.NL80211_ATTR_BSS]: print('WARNING: BSS info missing for an access point.') return libnl.handlers.NL_SKIP if nla_parse_nested(bss, nl80211.NL80211_BSS_MAX, tb[nl80211.NL80211_ATTR_BSS], bss_policy): print('WARNING: Failed to parse nested attributes for an access point!') return libnl.handlers.NL_SKIP if not bss[nl80211.NL80211_BSS_BSSID]: print('WARNING: No BSSID detected for an access point!') return libnl.handlers.NL_SKIP if not bss[nl80211.NL80211_BSS_INFORMATION_ELEMENTS]: print('WARNING: No additional information available for an access point!') return libnl.handlers.NL_SKIP # Further parse and then store. Overwrite existing data for BSSID if scan is run multiple times. bss_parsed = parse_bss(bss) results[bss_parsed['bssid']] = bss_parsed return libnl.handlers.NL_SKIP
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 parsed data.
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_cb_set(cb, libnl.handlers.NL_CB_VALID, libnl.handlers.NL_CB_CUSTOM, callback_dump, results) _LOGGER.debug('Sending NL80211_CMD_GET_SCAN...') ret = nl_send_auto(sk, msg) if ret >= 0: _LOGGER.debug('Retrieving NL80211_CMD_GET_SCAN response...') ret = nl_recvmsgs(sk, cb) return ret
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 arguments: sk -- nl_sock class instance (from nl_socket_alloc()). if_index -- interface index (integer). driver_id -- nl80211 driver ID from genl_ctrl_resolve() (integer). results -- dictionary to populate with results. Keys are BSSIDs (MAC addresses) and values are dicts of data. Returns: 0 on success or a negative error code.
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) final_seconds -= final_hours * 3600 if final_seconds >= 60: final_minutes = int(final_seconds / 60.0) final_seconds -= final_minutes * 60 final_seconds = int(math.ceil(final_seconds)) if final_days: template = '{1:d}d {2:d}h {3:02d}m {4:02d}s' elif final_hours: template = '{2:d}h {3:02d}m {4:02d}s' elif final_minutes: template = '{3:02d}m {4:02d}s' else: template = '{4:02d}s' return template.format(final_days, final_hours, final_minutes, final_seconds)
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', ''), str(row_in.get('security', '')), str(row_in.get('channel', '')), str(row_in.get('frequency', '')), str(row_in.get('signal', '')), str(row_in.get('bssid', '')), ] if row_out[3]: row_out[3] += ' MHz' if row_out[4]: row_out[4] += ' dBm' table_data.append(row_out) sort_by_column = [c.lower() for c in COLUMNS].index(OPTIONS['--key'].lower()) table_data.sort(key=lambda c: c[sort_by_column], reverse=OPTIONS['--reverse']) table.table_data.extend(table_data) print(table.table)
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 = logging.getLogger() root_logger.setLevel(logging.DEBUG) root_logger.addHandler(handler_stderr)
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 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' % sObjectType
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 ''' obj = self._sforce.factory.create('ens:sObject') obj.type = sObjectType return obj
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() process() retrieve() undelete() update() upsert() describeSObjects() sendEmail() ''' if self._strictResultTyping == False and len(result) == 1: return result[0] else: return resulf _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() process() retrieve() undelete() update() upsert() describeSObjects() sendEmail() ''' if self._strictResultTyping == False and len(result) == 1: return result[0] else: return 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() process() retrieve() undelete() update() upsert() describeSObjects() sendEmail()
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 = location) except: self._sforce.wsdl.service.setlocation(location) self._location = locatiof _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 = location) except: self._sforce.wsdl.service.setlocation(location) self._location = location
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, endDatef 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, endDate)
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 SESSION return invalidateSessionsResult ''' self._setHeaders('invalidateSessions') return self._handleResultTyping(self._sforce.service.invalidateSessions(sessionIds)f 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 SESSION return invalidateSessionsResult ''' self._setHeaders('invalidateSessions') return self._handleResultTyping(self._sforce.service.invalidateSessions(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 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 and returns data that matches the specified criteria. ''' self._setHeaders('query') return self._sforce.service.query(queryString)
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 have been deleted. ''' self._setHeaders('queryAll') return self._sforce.service.queryAll(queryString)
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('queryMore') return self._sforce.service.queryMore(queryLocator)
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 (field list and object properties) for the specified object. ''' self._setHeaders('describeSObject') return self._sforce.service.describeSObject(sObjectsType)
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.describeSObjects(sObjectTypes)f 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.describeSObjects(sObjectTypes))
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._setHeaders('resetPassword') return self._sforce.service.resetPassword(userId)
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 value. ''' self._setHeaders('setPassword') return self._sforce.service.setPassword(userId, password)
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 None
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 message type (integer). Returns: A message type association or None.
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 _LOGGER.debug('Registered cache operations {0}'.format(ops.co_name)) return 0
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 negative error code.
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 = config.sfdc_client.create_apex_checkpoint(self.params) if type(create_result) is list: create_result = create_result[0] IndexApexOverlaysCommand(params=self.params).execute() if type(create_result) is not str and type(create_result) is not unicode: return json.dumps(create_result) else: return create_result
self.params = { "ActionScriptType" : "None", "ExecutableEntityId" : "01pd0000001yXtYAAU", "IsDumpingHeap" : True, "Iteration" : 1, "Line" : 3, "ScopeId" : "005d0000000xxzsAAA" }
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.errno) if not sk.s_flags & NL_SOCK_BUFSIZE_SET: err = nl_socket_set_buffer_size(sk, 0, 0) if err < 0: sk.socket_instance.close() return err try: sk.socket_instance.bind((sk.s_local.nl_pid, sk.s_local.nl_groups)) except OSError as exc: sk.socket_instance.close() return -nl_syserr2nlerr(exc.errno) sk.s_local.nl_pid = sk.socket_instance.getsockname()[0] if sk.s_local.nl_family != socket.AF_NETLINK: sk.socket_instance.close() return -NLE_AF_NOSUPPORT sk.s_proto = protocol return 0
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. Positional arguments: sk -- Netlink socket (nl_sock class instance). protocol -- Netlink protocol to use (integer). Returns: 0 on success or a negative error code.
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 credentials if present. creds = nlmsg_get_creds(msg) if creds: raise NotImplementedError # TODO https://github.com/Robpol86/libnl/issues/2 return nl_sendmsg(sk, msg, hdr)
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 instance). iov -- data payload to be sent (bytearray). Returns: Number of bytes sent on success or a negative error code.
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 the nl_socket_set_peer_port() or nl_socket_set_peer_groups() function. The peer address can be overwritten by specifying an address in the `msg` object using nlmsg_set_dst(). If present in the `msg`, credentials set by the nlmsg_set_creds() function are added to the control buffer of the message. Calls to this function can be overwritten by providing an alternative using the nl_cb_overwrite_send() function. This function triggers the `NL_CB_MSG_OUT` callback. ATTENTION: Unlike `nl_send_auto()`, this function does *not* finalize the message in terms of automatically adding needed flags or filling out port numbers. Positional arguments: sk -- Netlink socket (nl_sock class instance). msg -- Netlink message (nl_msg class instance). Returns: Number of bytes sent on success or a negative error code.
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 nlh.nlmsg_flags |= NLM_F_REQUEST if not sk.s_flags & NL_NO_AUTO_ACK: nlh.nlmsg_flags |= NLM_F_ACK
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`) will be set to the local port number of the socket. - If not yet specified, the next available sequence number is assigned to the message (`nlmsg_seq`). - If not yet specified, the protocol field of the message will be set to the protocol field of the socket. - The `NLM_F_REQUEST` Netlink message flag will be set. - The `NLM_F_ACK` flag will be set if Auto-ACK mode is enabled on the socket. Positional arguments: sk -- Netlink socket (nl_sock class instance). msg -- Netlink message (nl_msg class instance).
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()`. Positional arguments: sk -- Netlink socket (nl_sock class instance). type_ -- Netlink message type (integer). flags -- Netlink message flags (integer). Keyword arguments: buf -- payload data. size -- size of `data` (integer). Returns: Number of characters sent on success or a negative error code.
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(). Positional arguments: sk -- Netlink socket (nl_sock class instance). cb -- set of callbacks to control behaviour (nl_cb class instance). Returns: Number of received messages or a negative error code from nl_recv().
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 the callbacks returns NL_STOP or nl_recv returns either 0 or a negative error code. A non-blocking sockets causes the function to return immediately if no data is available. See nl_recvmsgs_report(). Positional arguments: sk -- Netlink socket (nl_sock class instance). cb -- set of callbacks to control behaviour (nl_cb class instance). Returns: 0 on success or a negative error code from nl_recv().
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 code from nl_recvmsgs().
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(n), member) continue break
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: Generator yielding a class instances.
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_OK(hdr, remaining): # Each rtattr (which is what hdr is) instance is only one type. Looping through all of them until we run into # the ones we care about. if hdr.rta_type == IFLA_IFNAME: print('Found network interface {0}: {1}'.format(iface.ifi_index, get_string(RTA_DATA(hdr)).decode('ascii'))) hdr = RTA_NEXT(hdr, remaining) return NL_OK
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_connect() returned {0} ({1})'.format(ret, reason)) # Next we send the request to the kernel. rt_hdr = rtgenmsg(rtgen_family=socket.AF_PACKET) ret = nl_send_simple(sk, RTM_GETLINK, NLM_F_REQUEST | NLM_F_DUMP, rt_hdr, rt_hdr.SIZEOF) if ret < 0: reason = errmsg[abs(ret)] return error('nl_send_simple() returned {0} ({1})'.format(ret, reason)) print('Sent {0} bytes to the kernel.'.format(ret)) # Finally we'll retrieve the kernel's answer, process it, and call any callbacks attached to the `nl_sock` instance. nl_socket_modify_cb(sk, NL_CB_VALID, NL_CB_CUSTOM, callback, None) # Add callback to the `nl_sock` instance. ret = nl_recvmsgs_default(sk) # Get kernel's answer, and call attached callbacks. if ret < 0: reason = errmsg[abs(ret)] return error('nl_recvmsgs_default() returned {0} ({1})'.format(ret, reason))
Main function called upon script execution.