text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Shows members banned from the bot. <END_TASK> <USER_TASK:> Description: async def plonks(self, ctx): """Shows members banned from the bot."""
plonks = self.config.get('plonks', {}) guild = ctx.message.server db = plonks.get(guild.id, []) members = '\n'.join(map(str, filter(None, map(guild.get_member, db)))) if members: await self.bot.responses.basic(title="Plonked Users:", message=members) else: await self.bot.responses.failure(message='No members are banned in this server.')
<SYSTEM_TASK:> Unbans a user from using the bot. <END_TASK> <USER_TASK:> Description: async def unplonk(self, ctx, *, member: discord.Member): """Unbans a user from using the bot. To use this command you must have the Manage Server permission or have a Bot Admin role. """
plonks = self.config.get('plonks', {}) guild_id = ctx.message.server.id db = plonks.get(guild_id, []) try: db.remove(member.id) except ValueError: await self.bot.responses.failure(message='%s is not banned from using the bot in this server.' % member) else: plonks[guild_id] = db await self.config.put('plonks', plonks) await self.bot.responses.success(message='%s has been unbanned from using the bot in this server.' % member)
<SYSTEM_TASK:> Sends you the bot invite link. <END_TASK> <USER_TASK:> Description: async def join(self, ctx): """Sends you the bot invite link."""
perms = discord.Permissions.none() perms.read_messages = True perms.send_messages = True perms.manage_messages = True perms.embed_links = True perms.read_message_history = True perms.attach_files = True perms.add_reactions = True await self.bot.send_message(ctx.message.author, discord.utils.oauth_url(self.bot.client_id, perms))
<SYSTEM_TASK:> Shows info about a member. <END_TASK> <USER_TASK:> Description: async def info(self, ctx, *, member : discord.Member = None): """Shows info about a member. This cannot be used in private messages. If you don't specify a member then the info returned will be yours. """
channel = ctx.message.channel if member is None: member = ctx.message.author e = discord.Embed() roles = [role.name.replace('@', '@\u200b') for role in member.roles] shared = sum(1 for m in self.bot.get_all_members() if m.id == member.id) voice = member.voice_channel if voice is not None: other_people = len(voice.voice_members) - 1 voice_fmt = '{} with {} others' if other_people else '{} by themselves' voice = voice_fmt.format(voice.name, other_people) else: voice = 'Not connected.' e.set_author(name=str(member), icon_url=member.avatar_url or member.default_avatar_url) e.set_footer(text='Member since').timestamp = member.joined_at e.add_field(name='ID', value=member.id) e.add_field(name='Servers', value='%s shared' % shared) e.add_field(name='Voice', value=voice) e.add_field(name='Created', value=member.created_at) e.add_field(name='Roles', value=', '.join(roles)) e.colour = member.colour if member.avatar: e.set_image(url=member.avatar_url) await self.bot.say(embed=e)
<SYSTEM_TASK:> Interactively adds a custom reaction <END_TASK> <USER_TASK:> Description: async def addreaction(self, ctx, *, reactor=""): """Interactively adds a custom reaction"""
if not reactor: await self.bot.say("What should I react to?") response = await self.bot.wait_for_message(author=ctx.message.author) reactor = response.content data = self.config.get(ctx.message.server.id, {}) keyword = data.get(reactor, {}) if keyword: await self.bot.responses.failure(message="Reaction '{}' already exists.".format(reactor)) return await self.bot.say("Okay, I'll react to '{}'. What do you want me to say? (Type $none for no response)".format(reactor)) response = await self.bot.wait_for_message(author=ctx.message.author) reactions = [] def check(reaction, user): if str(reaction.emoji) != "\U000023f9": reactions.append(reaction.emoji) return False else: return user == ctx.message.author msg = await self.bot.say("Awesome! Now react to this message any reactions I should have to '{}'. (React \U000023f9 to stop)".format(reactor)) await self.bot.wait_for_reaction(message=msg, check=check) for i, reaction in enumerate(reactions): reaction = reaction if isinstance(reaction, str) else reaction.name + ":" + str(reaction.id) await self.bot.add_reaction(ctx.message, reaction) reactions[i] = reaction if response: keyword["response"] = response.content if response.content.lower() != "$none" else "" keyword["reaction"] = reactions data[reactor] = keyword await self.config.put(ctx.message.server.id, data) await self.bot.responses.success(message="Reaction '{}' has been added.".format(reactor))
<SYSTEM_TASK:> Lists all the reactions for the server <END_TASK> <USER_TASK:> Description: async def listreactions(self, ctx): """Lists all the reactions for the server"""
data = self.config.get(ctx.message.server.id, {}) if not data: await self.bot.responses.failure(message="There are no reactions on this server.") return try: pager = Pages(self.bot, message=ctx.message, entries=list(data.keys())) pager.embed.colour = 0x738bd7 # blurple pager.embed.set_author(name=ctx.message.server.name + " Reactions", icon_url=ctx.message.server.icon_url) await pager.paginate() except Exception as e: await self.bot.say(e)
<SYSTEM_TASK:> Views a specific reaction <END_TASK> <USER_TASK:> Description: async def viewreaction(self, ctx, *, reactor : str): """Views a specific reaction"""
data = self.config.get(ctx.message.server.id, {}) keyword = data.get(reactor, {}) if not keyword: await self.bot.responses.failure(message="Reaction '{}' was not found.".format(reactor)) return response = data.get(reactor, {}).get("response", "") reacts = data.get(reactor, {}).get("reaction", []) for i, r in enumerate(reacts): if ":" in r: reacts[i] = "<:" + r + ">" reacts = " ".join(reacts) if reacts else "-" response = response if response else "-" string = "Here's what I say to '{reactor}': {response}\n"\ "I'll react to this message how I react to '{reactor}'.".format(reactor=reactor,response=response) await self.bot.responses.full(sections=[{"name": "Response", "value": response}, {"name": "Reactions", "value": reacts, "inline": False}])
<SYSTEM_TASK:> Shows this message. <END_TASK> <USER_TASK:> Description: async def _default_help_command(ctx, *commands : str): """Shows this message."""
bot = ctx.bot destination = ctx.message.author if bot.pm_help else ctx.message.channel def repl(obj): return _mentions_transforms.get(obj.group(0), '') # help by itself just lists our own commands. if len(commands) == 0: pages = bot.formatter.format_help_for(ctx, bot) elif len(commands) == 1: # try to see if it is a cog name name = _mention_pattern.sub(repl, commands[0]) command = None if name in [x.lower() for x in bot.cogs]: command = bot.cogs[[x for x in bot.cogs if x.lower() == name][0]] else: command = bot.commands.get(name) if command is None: await bot.responses.failure(destination=destination, message=bot.command_not_found.format(name)) return pages = bot.formatter.format_help_for(ctx, command) else: name = _mention_pattern.sub(repl, commands[0]) command = bot.commands.get(name) if command is None: await bot.responses.failure(destination=destination, message=bot.command_not_found.format(name)) return for key in commands[1:]: try: key = _mention_pattern.sub(repl, key) command = command.commands.get(key) if command is None: await bot.responses.failure(destination=destination, message=bot.command_not_found.format(name)) return except AttributeError: await bot.responses.failure(destination=destination, message=bot.command_has_no_subcommands.format(command, key)) return pages = bot.formatter.format_help_for(ctx, command) if bot.pm_help is None: characters = sum(map(lambda l: len(l), pages.values())) if characters > 1000: destination = ctx.message.author await bot.responses.full(destination=destination, **pages)
<SYSTEM_TASK:> Check if the attribute header and payload can be accessed safely. <END_TASK> <USER_TASK:> Description: def nla_ok(nla, remaining): """Check if the attribute header and payload can be accessed safely. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L148 Verifies that the header and payload do not exceed the number of bytes left in the attribute stream. This function must be called before access the attribute header or payload when iterating over the attribute stream using nla_next(). Positional arguments: nla -- attribute of any kind (nlattr class instance). remaining -- number of bytes remaining in attribute stream (c_int). Returns: True if the attribute can be accessed safely, False otherwise. """
return remaining.value >= nla.SIZEOF and nla.SIZEOF <= nla.nla_len <= remaining.value
<SYSTEM_TASK:> Return next attribute in a stream of attributes. <END_TASK> <USER_TASK:> Description: def nla_next(nla, remaining): """Return next attribute in a stream of attributes. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L171 Calculates the offset to the next attribute based on the attribute given. The attribute provided is assumed to be accessible, the caller is responsible to use nla_ok() beforehand. The offset (length of specified attribute including padding) is then subtracted from the remaining bytes variable and a pointer to the next attribute is returned. nla_next() can be called as long as remaining is >0. Positional arguments: nla -- attribute of any kind (nlattr class instance). remaining -- number of bytes remaining in attribute stream (c_int). Returns: Next nlattr class instance. """
totlen = int(NLA_ALIGN(nla.nla_len)) remaining.value -= totlen return nlattr(bytearray_ptr(nla.bytearray, totlen))
<SYSTEM_TASK:> Create attribute index based on a stream of attributes. <END_TASK> <USER_TASK:> Description: def nla_parse(tb, maxtype, head, len_, policy): """Create attribute index based on a stream of attributes. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L242 Iterates over the stream of attributes and stores a pointer to each attribute in the index array using the attribute type as index to the array. Attribute with a type greater than the maximum type specified will be silently ignored in order to maintain backwards compatibility. If `policy` is not None, the attribute will be validated using the specified policy. Positional arguments: tb -- dictionary to be filled (maxtype+1 elements). maxtype -- maximum attribute type expected and accepted (integer). head -- first nlattr with more in its bytearray payload (nlattr class instance). len_ -- length of attribute stream (integer). policy -- dictionary of nla_policy class instances as values, with nla types as keys. Returns: 0 on success or a negative error code. """
rem = c_int() for nla in nla_for_each_attr(head, len_, rem): type_ = nla_type(nla) if type_ > maxtype: continue if policy: err = validate_nla(nla, maxtype, policy) if err < 0: return err if type_ in tb and tb[type_]: _LOGGER.debug('Attribute of type %d found multiple times in message, previous attribute is being ignored.', type_) tb[type_] = nla if rem.value > 0: _LOGGER.debug('netlink: %d bytes leftover after parsing attributes.', rem.value) return 0
<SYSTEM_TASK:> Iterate over a stream of attributes. <END_TASK> <USER_TASK:> Description: def nla_for_each_attr(head, len_, rem): """Iterate over a stream of attributes. https://github.com/thom311/libnl/blob/libnl3_2_25/include/netlink/attr.h#L262 Positional arguments: head -- first nlattr with more in its bytearray payload (nlattr class instance). len_ -- length of attribute stream (integer). rem -- initialized to len, holds bytes currently remaining in stream (c_int). Returns: Generator yielding nlattr instances. """
pos = head rem.value = len_ while nla_ok(pos, rem): yield pos pos = nla_next(pos, rem)
<SYSTEM_TASK:> Iterate over a stream of nested attributes. <END_TASK> <USER_TASK:> Description: def nla_for_each_nested(nla, rem): """Iterate over a stream of nested attributes. https://github.com/thom311/libnl/blob/libnl3_2_25/include/netlink/attr.h#L274 Positional arguments: nla -- attribute containing the nested attributes (nlattr class instance). rem -- initialized to len, holds bytes currently remaining in stream (c_int). Returns: Generator yielding nlattr instances. """
pos = nlattr(nla_data(nla)) rem.value = nla_len(nla) while nla_ok(pos, rem): yield pos pos = nla_next(pos, rem)
<SYSTEM_TASK:> Find a single attribute in a stream of attributes. <END_TASK> <USER_TASK:> Description: def nla_find(head, len_, attrtype): """Find a single attribute in a stream of attributes. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L323 Iterates over the stream of attributes and compares each type with the type specified. Returns the first attribute which matches the type. Positional arguments: head -- first nlattr with more in its bytearray payload (nlattr class instance). len_ -- length of attributes stream (integer). attrtype -- attribute type to look for (integer). Returns: Attribute found (nlattr class instance) or None. """
rem = c_int() for nla in nla_for_each_attr(head, len_, rem): if nla_type(nla) == attrtype: return nla return None
<SYSTEM_TASK:> Reserve space for an attribute. <END_TASK> <USER_TASK:> Description: def nla_reserve(msg, attrtype, attrlen): """Reserve space for an attribute. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L456 Reserves room for an attribute in the specified Netlink message and fills in the attribute header (type, length). Returns None if there is insufficient space for the attribute. Any padding between payload and the start of the next attribute is zeroed out. Positional arguments: msg -- Netlink message (nl_msg class instance). attrtype -- attribute type (integer). attrlen -- length of payload (integer). Returns: nlattr class instance allocated to the new space or None on failure. """
tlen = NLMSG_ALIGN(msg.nm_nlh.nlmsg_len) + nla_total_size(attrlen) if tlen > msg.nm_size: return None nla = nlattr(nlmsg_tail(msg.nm_nlh)) nla.nla_type = attrtype nla.nla_len = nla_attr_size(attrlen) if attrlen: padlen = nla_padlen(attrlen) nla.bytearray[nla.nla_len:nla.nla_len + padlen] = bytearray(b'\0') * padlen msg.nm_nlh.nlmsg_len = tlen _LOGGER.debug('msg 0x%x: attr <0x%x> %d: Reserved %d (%d) bytes at offset +%d nlmsg_len=%d', id(msg), id(nla), nla.nla_type, nla_total_size(attrlen), attrlen, nla.bytearray.slice.start - nlmsg_data(msg.nm_nlh).slice.start, msg.nm_nlh.nlmsg_len) return nla
<SYSTEM_TASK:> Add a unspecific attribute to Netlink message. <END_TASK> <USER_TASK:> Description: def nla_put(msg, attrtype, datalen, data): """Add a unspecific attribute to Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L497 Reserves room for an unspecific attribute and copies the provided data into the message as payload of the attribute. Returns an error if there is insufficient space for the attribute. Positional arguments: msg -- Netlink message (nl_msg class instance). attrtype -- attribute type (integer). datalen -- length of data to be used as payload (integer). data -- data to be used as attribute payload (bytearray). Returns: 0 on success or a negative error code. """
nla = nla_reserve(msg, attrtype, datalen) if not nla: return -NLE_NOMEM if datalen <= 0: return 0 nla_data(nla)[:datalen] = data[:datalen] _LOGGER.debug('msg 0x%x: attr <0x%x> %d: Wrote %d bytes at offset +%d', id(msg), id(nla), nla.nla_type, datalen, nla.bytearray.slice.start - nlmsg_data(msg.nm_nlh).slice.start) return 0
<SYSTEM_TASK:> Add abstract data as unspecific attribute to Netlink message. <END_TASK> <USER_TASK:> Description: def nla_put_data(msg, attrtype, data): """Add abstract data as unspecific attribute to Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L527 Equivalent to nla_put() except that the length of the payload is derived from the bytearray data object. Positional arguments: msg -- Netlink message (nl_msg class instance). attrtype -- attribute type (integer). data -- data to be used as attribute payload (bytearray). Returns: 0 on success or a negative error code. """
return nla_put(msg, attrtype, len(data), data)
<SYSTEM_TASK:> Add 8 bit integer attribute to Netlink message. <END_TASK> <USER_TASK:> Description: def nla_put_u8(msg, attrtype, value): """Add 8 bit integer attribute to Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L563 Positional arguments: msg -- Netlink message (nl_msg class instance). attrtype -- attribute type (integer). value -- numeric value to store as payload (int() or c_uint8()). Returns: 0 on success or a negative error code. """
data = bytearray(value if isinstance(value, c_uint8) else c_uint8(value)) return nla_put(msg, attrtype, SIZEOF_U8, data)
<SYSTEM_TASK:> Add 16 bit integer attribute to Netlink message. <END_TASK> <USER_TASK:> Description: def nla_put_u16(msg, attrtype, value): """Add 16 bit integer attribute to Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L588 Positional arguments: msg -- Netlink message (nl_msg class instance). attrtype -- attribute type (integer). value -- numeric value to store as payload (int() or c_uint16()). Returns: 0 on success or a negative error code. """
data = bytearray(value if isinstance(value, c_uint16) else c_uint16(value)) return nla_put(msg, attrtype, SIZEOF_U16, data)
<SYSTEM_TASK:> Add 32 bit integer attribute to Netlink message. <END_TASK> <USER_TASK:> Description: def nla_put_u32(msg, attrtype, value): """Add 32 bit integer attribute to Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L613 Positional arguments: msg -- Netlink message (nl_msg class instance). attrtype -- attribute type (integer). value -- numeric value to store as payload (int() or c_uint32()). Returns: 0 on success or a negative error code. """
data = bytearray(value if isinstance(value, c_uint32) else c_uint32(value)) return nla_put(msg, attrtype, SIZEOF_U32, data)
<SYSTEM_TASK:> Add 64 bit integer attribute to Netlink message. <END_TASK> <USER_TASK:> Description: def nla_put_u64(msg, attrtype, value): """Add 64 bit integer attribute to Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L638 Positional arguments: msg -- Netlink message (nl_msg class instance). attrtype -- attribute type (integer). value -- numeric value to store as payload (int() or c_uint64()). Returns: 0 on success or a negative error code. """
data = bytearray(value if isinstance(value, c_uint64) else c_uint64(value)) return nla_put(msg, attrtype, SIZEOF_U64, data)
<SYSTEM_TASK:> Add string attribute to Netlink message. <END_TASK> <USER_TASK:> Description: def nla_put_string(msg, attrtype, value): """Add string attribute to Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L674 Positional arguments: msg -- Netlink message (nl_msg class instance). attrtype -- attribute type (integer). value -- bytes() or bytearray() value (e.g. 'Test'.encode('ascii')). Returns: 0 on success or a negative error code. """
data = bytearray(value) + bytearray(b'\0') return nla_put(msg, attrtype, len(data), data)
<SYSTEM_TASK:> Add msecs Netlink attribute to Netlink message. <END_TASK> <USER_TASK:> Description: def nla_put_msecs(msg, attrtype, msecs): """Add msecs Netlink attribute to Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L737 Positional arguments: msg -- Netlink message (nl_msg class instance). attrtype -- attribute type (integer). msecs -- number of msecs (int(), c_uint64(), or c_ulong()). Returns: 0 on success or a negative error code. """
if isinstance(msecs, c_uint64): pass elif isinstance(msecs, c_ulong): msecs = c_uint64(msecs.value) else: msecs = c_uint64(msecs) return nla_put_u64(msg, attrtype, msecs)
<SYSTEM_TASK:> Add nested attributes to Netlink message. <END_TASK> <USER_TASK:> Description: def nla_put_nested(msg, attrtype, nested): """Add nested attributes to Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L772 Takes the attributes found in the `nested` message and appends them to the message `msg` nested in a container of the type `attrtype`. The `nested` message may not have a family specific header. Positional arguments: msg -- Netlink message (nl_msg class instance). attrtype -- attribute type (integer). nested -- message containing attributes to be nested (nl_msg class instance). Returns: 0 on success or a negative error code. """
_LOGGER.debug('msg 0x%x: attr <> %d: adding msg 0x%x as nested attribute', id(msg), attrtype, id(nested)) return nla_put(msg, attrtype, nlmsg_datalen(nested.nm_nlh), nlmsg_data(nested.nm_nlh))
<SYSTEM_TASK:> Create attribute index based on nested attribute. <END_TASK> <USER_TASK:> Description: def nla_parse_nested(tb, maxtype, nla, policy): """Create attribute index based on nested attribute. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L885 Feeds the stream of attributes nested into the specified attribute to nla_parse(). Positional arguments: tb -- dictionary to be filled (maxtype+1 elements). maxtype -- maximum attribute type expected and accepted (integer). nla -- nested attribute (nlattr class instance). policy -- attribute validation policy. Returns: 0 on success or a negative error code. """
return nla_parse(tb, maxtype, nlattr(nla_data(nla)), nla_len(nla), policy)
<SYSTEM_TASK:> Send a Generic Netlink message consisting only of a header. <END_TASK> <USER_TASK:> Description: def genl_send_simple(sk, family, cmd, version, flags): """Send a Generic Netlink message consisting only of a header. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/genl.c#L84 This function is a shortcut for sending a Generic Netlink message without any message payload. The message will only consist of the Netlink and Generic Netlink headers. The header is constructed based on the specified parameters and passed on to nl_send_simple() to send it on the specified socket. Positional arguments: sk -- Generic Netlink socket (nl_sock class instance). family -- numeric family identifier (integer). cmd -- numeric command identifier (integer). version -- interface version (integer). flags -- additional Netlink message flags (integer). Returns: 0 on success or a negative error code. """
hdr = genlmsghdr(cmd=cmd, version=version) return int(nl_send_simple(sk, family, flags, hdr, hdr.SIZEOF))
<SYSTEM_TASK:> Validate Generic Netlink message headers. <END_TASK> <USER_TASK:> Description: def genlmsg_valid_hdr(nlh, hdrlen): """Validate Generic Netlink message headers. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/genl.c#L117 Verifies the integrity of the Netlink and Generic Netlink headers by enforcing the following requirements: - Valid Netlink message header (`nlmsg_valid_hdr()`) - Presence of a complete Generic Netlink header - At least `hdrlen` bytes of payload included after the generic Netlink header. Positional arguments: nlh -- Netlink message header (nlmsghdr class instance). hdrlen -- length of user header (integer). Returns: True if the headers are valid or False if not. """
if not nlmsg_valid_hdr(nlh, GENL_HDRLEN): return False ghdr = genlmsghdr(nlmsg_data(nlh)) if genlmsg_len(ghdr) < NLMSG_ALIGN(hdrlen): return False return True
<SYSTEM_TASK:> Parse Generic Netlink message including attributes. <END_TASK> <USER_TASK:> Description: def genlmsg_parse(nlh, hdrlen, tb, maxtype, policy): """Parse Generic Netlink message including attributes. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/genl.c#L191 Verifies the validity of the Netlink and Generic Netlink headers using genlmsg_valid_hdr() and calls nla_parse() on the message payload to parse eventual attributes. Positional arguments: nlh -- Netlink message header (nlmsghdr class instance). hdrlen -- length of user header (integer). tb -- empty dict, to be updated with nlattr class instances to store parsed attributes. maxtype -- maximum attribute id expected (integer). policy -- dictionary of nla_policy class instances as values, with nla types as keys. Returns: 0 on success or a negative error code. """
if not genlmsg_valid_hdr(nlh, hdrlen): return -NLE_MSG_TOOSHORT ghdr = genlmsghdr(nlmsg_data(nlh)) return int(nla_parse(tb, maxtype, genlmsg_attrdata(ghdr, hdrlen), genlmsg_attrlen(ghdr, hdrlen), policy))
<SYSTEM_TASK:> Return length of message payload including user header. <END_TASK> <USER_TASK:> Description: def genlmsg_len(gnlh): """Return length of message payload including user header. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/genl.c#L224 Positional arguments: gnlh -- Generic Netlink message header (genlmsghdr class instance). Returns: Length of user payload including an eventual user header in number of bytes. """
nlh = nlmsghdr(bytearray_ptr(gnlh.bytearray, -NLMSG_HDRLEN, oob=True)) return nlh.nlmsg_len - GENL_HDRLEN - NLMSG_HDRLEN
<SYSTEM_TASK:> Add Generic Netlink headers to Netlink message. <END_TASK> <USER_TASK:> Description: def genlmsg_put(msg, port, seq, family, hdrlen, flags, cmd, version): """Add Generic Netlink headers to Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/genl.c#L348 Calls nlmsg_put() on the specified message object to reserve space for the Netlink header, the Generic Netlink header, and a user header of specified length. Fills out the header fields with the specified parameters. Positional arguments: msg -- Netlink message object (nl_msg class instance). port -- Netlink port or NL_AUTO_PORT (c_uint32). seq -- sequence number of message or NL_AUTO_SEQ (c_uint32). family -- numeric family identifier (integer). hdrlen -- length of user header (integer). flags -- additional Netlink message flags (integer). cmd -- numeric command identifier (c_uint8). version -- interface version (c_uint8). Returns: bytearray starting at user header or None if an error occurred. """
hdr = genlmsghdr(cmd=cmd, version=version) nlh = nlmsg_put(msg, port, seq, family, GENL_HDRLEN + hdrlen, flags) if nlh is None: return None nlmsg_data(nlh)[:hdr.SIZEOF] = hdr.bytearray[:hdr.SIZEOF] _LOGGER.debug('msg 0x%x: Added generic netlink header cmd=%d version=%d', id(msg), cmd, version) return bytearray_ptr(nlmsg_data(nlh), GENL_HDRLEN)
<SYSTEM_TASK:> Allocate new Netlink socket. Does not yet actually open a socket. <END_TASK> <USER_TASK:> Description: def nl_socket_alloc(cb=None): """Allocate new Netlink socket. Does not yet actually open a socket. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L206 Also has code for generating local port once. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L123 Keyword arguments: cb -- custom callback handler. Returns: Newly allocated Netlink socket (nl_sock class instance) or None. """
# Allocate the callback. cb = cb or nl_cb_alloc(default_cb) if not cb: return None # Allocate the socket. sk = nl_sock() sk.s_cb = cb sk.s_local.nl_family = getattr(socket, 'AF_NETLINK', -1) sk.s_peer.nl_family = getattr(socket, 'AF_NETLINK', -1) sk.s_seq_expect = sk.s_seq_next = int(time.time()) sk.s_flags = NL_OWN_PORT # The port is 0 (unspecified), meaning NL_OWN_PORT. # Generate local port. nl_socket_get_local_port(sk) # I didn't find this in the C source, but during testing I saw this behavior. return sk
<SYSTEM_TASK:> Join groups. <END_TASK> <USER_TASK:> Description: def nl_socket_add_memberships(sk, *group): """Join groups. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L417 Joins the specified groups using the modern socket option. The list of groups has to be terminated by 0. Make sure to use the correct group definitions as the older bitmask definitions for nl_join_groups() are likely to still be present for backward compatibility reasons. Positional arguments: sk -- Netlink socket (nl_sock class instance). group -- group identifier (integer). Returns: 0 on success or a negative error code. """
if sk.s_fd == -1: return -NLE_BAD_SOCK for grp in group: if not grp: break if grp < 0: return -NLE_INVAL try: sk.socket_instance.setsockopt(SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, grp) except OSError as exc: return -nl_syserr2nlerr(exc.errno) return 0
<SYSTEM_TASK:> Leave groups. <END_TASK> <USER_TASK:> Description: def nl_socket_drop_memberships(sk, *group): """Leave groups. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L465 Leaves the specified groups using the modern socket option. The list of groups has to terminated by 0. Positional arguments: sk -- Netlink socket (nl_sock class instance). group -- group identifier (integer). Returns: 0 on success or a negative error code. """
if sk.s_fd == -1: return -NLE_BAD_SOCK for grp in group: if not grp: break if grp < 0: return -NLE_INVAL try: sk.socket_instance.setsockopt(SOL_NETLINK, NETLINK_DROP_MEMBERSHIP, grp) except OSError as exc: return -nl_syserr2nlerr(exc.errno) return 0
<SYSTEM_TASK:> Modify the callback handler associated with the socket. <END_TASK> <USER_TASK:> Description: def nl_socket_modify_cb(sk, type_, kind, func, arg): """Modify the callback handler associated with the socket. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L633 Sets specific callback functions in the existing nl_cb class instance stored in the nl_sock socket. Positional arguments: sk -- Netlink socket (nl_sock class instance). type_ -- which type callback to set (integer). 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. """
return int(nl_cb_set(sk.s_cb, type_, kind, func, arg))
<SYSTEM_TASK:> Modify the error callback handler associated with the socket. <END_TASK> <USER_TASK:> Description: def nl_socket_modify_err_cb(sk, kind, func, arg): """Modify the error callback handler associated with the socket. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L649 Positional arguments: sk -- Netlink socket (nl_sock 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. """
return int(nl_cb_err(sk.s_cb, kind, func, arg))
<SYSTEM_TASK:> Set socket buffer size of Netlink socket. <END_TASK> <USER_TASK:> Description: def nl_socket_set_buffer_size(sk, rxbuf, txbuf): """Set socket buffer size of Netlink socket. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L675 Sets the socket buffer size of a Netlink socket to the specified values `rxbuf` and `txbuf`. Providing a value of 0 assumes a good default value. Positional arguments: sk -- Netlink socket (nl_sock class instance). rxbuf -- new receive socket buffer size in bytes (integer). txbuf -- new transmit socket buffer size in bytes (integer). Returns: 0 on success or a negative error code. """
rxbuf = 32768 if rxbuf <= 0 else rxbuf txbuf = 32768 if txbuf <= 0 else txbuf if sk.s_fd == -1: return -NLE_BAD_SOCK try: sk.socket_instance.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, txbuf) except OSError as exc: return -nl_syserr2nlerr(exc.errno) try: sk.socket_instance.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, rxbuf) except OSError as exc: return -nl_syserr2nlerr(exc.errno) sk.s_flags |= NL_SOCK_BUFSIZE_SET return 0
<SYSTEM_TASK:> Handle calling the parser function to convert bytearray data into Python data types. <END_TASK> <USER_TASK:> Description: def _get(out_parsed, in_bss, key, parser_func): """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. """
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
<SYSTEM_TASK:> Retrieve nested dict data from either information elements or beacon IES dicts. <END_TASK> <USER_TASK:> Description: def _fetch(in_parsed, *keys): """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. """
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
<SYSTEM_TASK:> Allocate a new callback handle. <END_TASK> <USER_TASK:> Description: def nl_cb_alloc(kind): """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. """
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
<SYSTEM_TASK:> Set up a callback. Updates `cb` in place. <END_TASK> <USER_TASK:> Description: def nl_cb_set(cb, type_, kind, func, arg): """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. """
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
<SYSTEM_TASK:> Set up an error callback. Updates `cb` in place. <END_TASK> <USER_TASK:> Description: def nl_cb_err(cb, kind, func, arg): """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. """
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
<SYSTEM_TASK:> Create subclasses of ctypes. <END_TASK> <USER_TASK:> Description: def _class_factory(base): """Create subclasses of ctypes. Positional arguments: base -- base class to subclass. Returns: New class definition. """
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
<SYSTEM_TASK:> Look up generic Netlink family by family name querying the kernel directly. <END_TASK> <USER_TASK:> Description: def genl_ctrl_probe_by_name(sk, name): """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. """
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
<SYSTEM_TASK:> Resolve Generic Netlink family name to numeric identifier. <END_TASK> <USER_TASK:> Description: def genl_ctrl_resolve(sk, name): """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. """
family = genl_ctrl_probe_by_name(sk, name) if family is None: return -NLE_OBJ_NOTFOUND return int(genl_family_get_id(family))
<SYSTEM_TASK:> Resolve Generic Netlink family group name. <END_TASK> <USER_TASK:> Description: def genl_ctrl_resolve_grp(sk, family_name, 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. """
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)
<SYSTEM_TASK:> Update the mutable integer `arg` with the error code. <END_TASK> <USER_TASK:> Description: def error_handler(_, err, arg): """Update the mutable integer `arg` with the error code."""
arg.value = err.error return libnl.handlers.NL_STOP
<SYSTEM_TASK:> Called when the kernel is done scanning. Only signals if it was successful or if it failed. No other data. <END_TASK> <USER_TASK:> Description: def callback_trigger(msg, arg): """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. """
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
<SYSTEM_TASK:> Here is where SSIDs and their data is decoded from the binary data sent by the kernel. <END_TASK> <USER_TASK:> Description: def callback_dump(msg, results): """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. """
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
<SYSTEM_TASK:> Issue a scan request to the kernel and wait for it to reply with a signal. <END_TASK> <USER_TASK:> Description: def do_scan_trigger(sk, if_index, driver_id, mcid): """Issue a scan request to the kernel and wait for it to reply with a signal. This function issues NL80211_CMD_TRIGGER_SCAN which requires root privileges. The way NL80211 works is first you issue NL80211_CMD_TRIGGER_SCAN and wait for the kernel to signal that the scan is done. When that signal occurs, data is not yet available. The signal tells us if the scan was aborted or if it was successful (if new scan results are waiting). This function handles that simple signal. 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). mcid -- nl80211 scanning group ID from genl_ctrl_resolve_grp() (integer). Returns: 0 on success or a negative error code. """
# First get the "scan" membership group ID and join the socket to the group. _LOGGER.debug('Joining group %d.', mcid) ret = nl_socket_add_membership(sk, mcid) # Listen for results of scan requests (aborted or new results). if ret < 0: return ret # Build the message to be sent to the kernel. msg = nlmsg_alloc() genlmsg_put(msg, 0, 0, driver_id, 0, 0, nl80211.NL80211_CMD_TRIGGER_SCAN, 0) # Setup which command to run. nla_put_u32(msg, nl80211.NL80211_ATTR_IFINDEX, if_index) # Setup which interface to use. ssids_to_scan = nlmsg_alloc() nla_put(ssids_to_scan, 1, 0, b'') # Scan all SSIDs. nla_put_nested(msg, nl80211.NL80211_ATTR_SCAN_SSIDS, ssids_to_scan) # Setup what kind of scan to perform. # Setup the callbacks to be used for triggering the scan only. err = ctypes.c_int(1) # Used as a mutable integer to be updated by the callback function. Signals end of messages. results = ctypes.c_int(-1) # Signals if the scan was successful (new results) or aborted, or not started. 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_trigger, results) libnl.handlers.nl_cb_err(cb, libnl.handlers.NL_CB_CUSTOM, error_handler, err) libnl.handlers.nl_cb_set(cb, libnl.handlers.NL_CB_ACK, libnl.handlers.NL_CB_CUSTOM, ack_handler, err) libnl.handlers.nl_cb_set(cb, libnl.handlers.NL_CB_SEQ_CHECK, libnl.handlers.NL_CB_CUSTOM, lambda *_: libnl.handlers.NL_OK, None) # Ignore sequence checking. # Now we send the message to the kernel, and retrieve the acknowledgement. The kernel takes a few seconds to finish # scanning for access points. _LOGGER.debug('Sending NL80211_CMD_TRIGGER_SCAN...') ret = nl_send_auto(sk, msg) if ret < 0: return ret while err.value > 0: _LOGGER.debug('Retrieving NL80211_CMD_TRIGGER_SCAN acknowledgement...') ret = nl_recvmsgs(sk, cb) if ret < 0: return ret if err.value < 0: error('Unknown error {0} ({1})'.format(err.value, errmsg[abs(err.value)])) # Block until the kernel is done scanning or aborted the scan. while results.value < 0: _LOGGER.debug('Retrieving NL80211_CMD_TRIGGER_SCAN final response...') ret = nl_recvmsgs(sk, cb) if ret < 0: return ret if results.value > 0: error('The kernel aborted the scan.') # Done, cleaning up. _LOGGER.debug('Leaving group %d.', mcid) return nl_socket_drop_membership(sk, mcid)
<SYSTEM_TASK:> Convert seconds remaining into human readable strings. <END_TASK> <USER_TASK:> Description: def eta_letters(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. """
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)
<SYSTEM_TASK:> Print the table of detected SSIDs and their data to screen. <END_TASK> <USER_TASK:> Description: def print_table(data): """Print the table of detected SSIDs and their data to screen. Positional arguments: data -- list of dictionaries. """
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)
<SYSTEM_TASK:> Lookup message type cache association. <END_TASK> <USER_TASK:> Description: def nl_msgtype_lookup(ops, msgtype): """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. """
for i in ops.co_msgtypes: if i.mt_id == msgtype: return i return None
<SYSTEM_TASK:> Register a set of cache operations. <END_TASK> <USER_TASK:> Description: def nl_cache_mngt_register(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 negative error code. """
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
<SYSTEM_TASK:> Create file descriptor and bind socket. <END_TASK> <USER_TASK:> Description: def nl_connect(sk, protocol): """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. """
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
<SYSTEM_TASK:> Finalize Netlink message. <END_TASK> <USER_TASK:> Description: def nl_complete_msg(sk, msg): """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). """
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
<SYSTEM_TASK:> Construct and transmit a Netlink message. <END_TASK> <USER_TASK:> Description: def nl_send_simple(sk, type_, flags, buf=None, size=0): """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. """
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)
<SYSTEM_TASK:> Receive data from Netlink socket. <END_TASK> <USER_TASK:> Description: def nl_recv(sk, nla, buf, creds=None): """Receive data from Netlink socket. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L625 Receives data from a connected netlink socket using recvmsg() and returns the number of bytes read. The read data is stored in a newly allocated buffer that is assigned to `buf`. The peer's netlink address will be stored in `nla`. This function blocks until data is available to be read unless the socket has been put into non-blocking mode using nl_socket_set_nonblocking() in which case this function will return immediately with a return value of 0. The buffer size used when reading from the netlink socket and thus limiting the maximum size of a netlink message that can be read defaults to the size of a memory page (getpagesize()). The buffer size can be modified on a per socket level using the function `nl_socket_set_msg_buf_size()`. If message peeking is enabled using nl_socket_enable_msg_peek() the size of the message to be read will be determined using the MSG_PEEK flag prior to performing the actual read. This leads to an additional recvmsg() call for every read operation which has performance implications and is not recommended for high throughput protocols. An eventual interruption of the recvmsg() system call is automatically handled by retrying the operation. If receiving of credentials has been enabled using the function `nl_socket_set_passcred()`, this function will allocate a new struct `ucred` filled with the received credentials and assign it to `creds`. Positional arguments: sk -- Netlink socket (nl_sock class instance) (input). nla -- Netlink socket structure to hold address of peer (sockaddr_nl class instance) (output). buf -- destination bytearray() for message content (output). creds -- destination class instance for credentials (ucred class instance) (output). Returns: Two-item tuple. First item is number of bytes read, 0 on EOF, 0 on no data event (non-blocking mode), or a negative error code. Second item is the message content from the socket or None. """
flags = 0 page_size = resource.getpagesize() * 4 if sk.s_flags & NL_MSG_PEEK: flags |= socket.MSG_PEEK | socket.MSG_TRUNC iov_len = sk.s_bufsize or page_size if creds and sk.s_flags & NL_SOCK_PASSCRED: raise NotImplementedError # TODO https://github.com/Robpol86/libnl/issues/2 while True: # This is the `goto retry` implementation. try: if hasattr(sk.socket_instance, 'recvmsg'): iov, _, msg_flags, address = sk.socket_instance.recvmsg(iov_len, 0, flags) else: iov, address = sk.socket_instance.recvfrom(iov_len, flags) msg_flags = 0 except OSError as exc: if exc.errno == errno.EINTR: continue # recvmsg() returned EINTR, retrying. return -nl_syserr2nlerr(exc.errno) nla.nl_family = sk.socket_instance.family # recvmsg() in C does this, but not Python's. if not iov: return 0 if msg_flags & socket.MSG_CTRUNC: raise NotImplementedError # TODO https://github.com/Robpol86/libnl/issues/2 if iov_len < len(iov) or msg_flags & socket.MSG_TRUNC: # Provided buffer is not long enough. # Enlarge it to size of n (which should be total length of the message) and try again. iov_len = len(iov) continue if flags: # Buffer is big enough, do the actual reading. flags = 0 continue nla.nl_pid = address[0] nla.nl_groups = address[1] if creds and sk.s_flags * NL_SOCK_PASSCRED: raise NotImplementedError # TODO https://github.com/Robpol86/libnl/issues/2 if iov: buf += iov return len(buf)
<SYSTEM_TASK:> Receive a set of messages from a Netlink socket and report parsed messages. <END_TASK> <USER_TASK:> Description: def nl_recvmsgs_report(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(). """
if cb.cb_recvmsgs_ow: return int(cb.cb_recvmsgs_ow(sk, cb)) return int(recvmsgs(sk, cb))
<SYSTEM_TASK:> Receive a set of messages from a Netlink socket. <END_TASK> <USER_TASK:> Description: def nl_recvmsgs(sk, cb): """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(). """
err = nl_recvmsgs_report(sk, cb) if err > 0: return 0 return int(err)
<SYSTEM_TASK:> Wait for ACK. <END_TASK> <USER_TASK:> Description: def nl_wait_for_ack(sk): """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(). """
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))
<SYSTEM_TASK:> Iterate over a stream of attributes in a message. <END_TASK> <USER_TASK:> Description: def nlmsg_for_each_attr(nlh, hdrlen, rem): """Iterate over a stream of attributes in a message. https://github.com/thom311/libnl/blob/libnl3_2_25/include/netlink/msg.h#L123 Positional arguments: nlh -- Netlink message header (nlmsghdr class instance). hdrlen -- length of family header (integer). rem -- initialized to len, holds bytes currently remaining in stream (c_int). Returns: Generator yielding nl_attr instances. """
return nla_for_each_attr(nlmsg_attrdata(nlh, hdrlen), nlmsg_attrlen(nlh, hdrlen), rem)
<SYSTEM_TASK:> Head of attributes data. <END_TASK> <USER_TASK:> Description: def nlmsg_attrdata(nlh, hdrlen): """Head of attributes data. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L143 Positional arguments: nlh -- Netlink message header (nlmsghdr class instance). hdrlen -- length of family specific header (integer). Returns: First attribute (nlattr class instance with others in its payload). """
data = nlmsg_data(nlh) return libnl.linux_private.netlink.nlattr(bytearray_ptr(data, libnl.linux_private.netlink.NLMSG_ALIGN(hdrlen)))
<SYSTEM_TASK:> Length of attributes data. <END_TASK> <USER_TASK:> Description: def nlmsg_attrlen(nlh, hdrlen): """Length of attributes data. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L154 nlh -- Netlink message header (nlmsghdr class instance). hdrlen -- length of family specific header (integer). Returns: Integer. """
return max(nlmsg_len(nlh) - libnl.linux_private.netlink.NLMSG_ALIGN(hdrlen), 0)
<SYSTEM_TASK:> Check if the Netlink message fits into the remaining bytes. <END_TASK> <USER_TASK:> Description: def nlmsg_ok(nlh, remaining): """Check if the Netlink message fits into the remaining bytes. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L179 Positional arguments: nlh -- Netlink message header (nlmsghdr class instance). remaining -- number of bytes remaining in message stream (c_int). Returns: Boolean. """
sizeof = libnl.linux_private.netlink.nlmsghdr.SIZEOF return remaining.value >= sizeof and sizeof <= nlh.nlmsg_len <= remaining.value
<SYSTEM_TASK:> Next Netlink message in message stream. <END_TASK> <USER_TASK:> Description: def nlmsg_next(nlh, remaining): """Next Netlink message in message stream. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L194 Positional arguments: nlh -- Netlink message header (nlmsghdr class instance). remaining -- number of bytes remaining in message stream (c_int). Returns: The next Netlink message in the message stream and decrements remaining by the size of the current message. """
totlen = libnl.linux_private.netlink.NLMSG_ALIGN(nlh.nlmsg_len) remaining.value -= totlen return libnl.linux_private.netlink.nlmsghdr(bytearray_ptr(nlh.bytearray, totlen))
<SYSTEM_TASK:> Parse attributes of a Netlink message. <END_TASK> <USER_TASK:> Description: def nlmsg_parse(nlh, hdrlen, tb, maxtype, policy): """Parse attributes of a Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L213 Positional arguments: nlh -- Netlink message header (nlmsghdr class instance). hdrlen -- length of family specific header (integer). tb -- dictionary of nlattr instances (length of maxtype+1). maxtype -- maximum attribute type to be expected (integer). policy -- validation policy (nla_policy class instance). Returns: 0 on success or a negative error code. """
if not nlmsg_valid_hdr(nlh, hdrlen): return -NLE_MSG_TOOSHORT return nla_parse(tb, maxtype, nlmsg_attrdata(nlh, hdrlen), nlmsg_attrlen(nlh, hdrlen), policy)
<SYSTEM_TASK:> Find a specific attribute in a Netlink message. <END_TASK> <USER_TASK:> Description: def nlmsg_find_attr(nlh, hdrlen, attrtype): """Find a specific attribute in a Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L231 Positional arguments: nlh -- Netlink message header (nlmsghdr class instance). hdrlen -- length of family specific header (integer). attrtype -- type of attribute to look for (integer). Returns: The first attribute which matches the specified type (nlattr class instance). """
return nla_find(nlmsg_attrdata(nlh, hdrlen), nlmsg_attrlen(nlh, hdrlen), attrtype)
<SYSTEM_TASK:> Allocate a new Netlink message with maximum payload size specified. <END_TASK> <USER_TASK:> Description: def nlmsg_alloc(len_=default_msg_size): """Allocate a new Netlink message with maximum payload size specified. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L299 Allocates a new Netlink message without any further payload. The maximum payload size defaults to resource.getpagesize() or as otherwise specified with nlmsg_set_default_size(). Returns: Newly allocated Netlink message (nl_msg class instance). """
len_ = max(libnl.linux_private.netlink.nlmsghdr.SIZEOF, len_) nm = nl_msg() nm.nm_refcnt = 1 nm.nm_nlh = libnl.linux_private.netlink.nlmsghdr(bytearray(b'\0') * len_) nm.nm_protocol = -1 nm.nm_size = len_ nm.nm_nlh.nlmsg_len = nlmsg_total_size(0) _LOGGER.debug('msg 0x%x: Allocated new message, maxlen=%d', id(nm), len_) return nm
<SYSTEM_TASK:> Allocate a new Netlink message and inherit Netlink message header. <END_TASK> <USER_TASK:> Description: def nlmsg_inherit(hdr=None): """Allocate a new Netlink message and inherit Netlink message header. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L322 Allocates a new Netlink message and inherits the original message header. If `hdr` is not None it will be used as a template for the Netlink message header, otherwise the header is left blank. Keyword arguments: hdr -- Netlink message header template (nlmsghdr class instance). Returns: Newly allocated Netlink message (nl_msg class instance). """
nm = nlmsg_alloc() if hdr: new = nm.nm_nlh new.nlmsg_type = hdr.nlmsg_type new.nlmsg_flags = hdr.nlmsg_flags new.nlmsg_seq = hdr.nlmsg_seq new.nlmsg_pid = hdr.nlmsg_pid return nm
<SYSTEM_TASK:> Allocate a new Netlink message. <END_TASK> <USER_TASK:> Description: def nlmsg_alloc_simple(nlmsgtype, flags): """Allocate a new Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L346 Positional arguments: nlmsgtype -- Netlink message type (integer). flags -- message flags (integer). Returns: Newly allocated Netlink message (nl_msg class instance) or None. """
nlh = libnl.linux_private.netlink.nlmsghdr(nlmsg_type=nlmsgtype, nlmsg_flags=flags) msg = nlmsg_inherit(nlh) _LOGGER.debug('msg 0x%x: Allocated new simple message', id(msg)) return msg
<SYSTEM_TASK:> Convert a Netlink message received from a Netlink socket to an nl_msg. <END_TASK> <USER_TASK:> Description: def nlmsg_convert(hdr): """Convert a Netlink message received from a Netlink socket to an nl_msg. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L382 Allocates a new Netlink message and copies all of the data in `hdr` into the new message object. Positional arguments: hdr -- Netlink message received from netlink socket (nlmsghdr class instance). Returns: Newly allocated Netlink message (nl_msg class instance) or None. """
nm = nlmsg_alloc(hdr.nlmsg_len) if not nm: return None nm.nm_nlh.bytearray = hdr.bytearray.copy()[:hdr.nlmsg_len] return nm
<SYSTEM_TASK:> Reserve room for additional data in a Netlink message. <END_TASK> <USER_TASK:> Description: def nlmsg_reserve(n, len_, pad): """Reserve room for additional data in a Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L407 Reserves room for additional data at the tail of the an existing netlink message. Eventual padding required will be zeroed out. bytearray_ptr() at the start of additional data or None. """
nlmsg_len_ = n.nm_nlh.nlmsg_len tlen = len_ if not pad else ((len_ + (pad - 1)) & ~(pad - 1)) if tlen + nlmsg_len_ > n.nm_size: return None buf = bytearray_ptr(n.nm_nlh.bytearray, nlmsg_len_) n.nm_nlh.nlmsg_len += tlen if tlen > len_: bytearray_ptr(buf, len_, tlen)[:] = bytearray(b'\0') * (tlen - len_) _LOGGER.debug('msg 0x%x: Reserved %d (%d) bytes, pad=%d, nlmsg_len=%d', id(n), tlen, len_, pad, n.nm_nlh.nlmsg_len) return buf
<SYSTEM_TASK:> Append data to tail of a Netlink message. <END_TASK> <USER_TASK:> Description: def nlmsg_append(n, data, len_, pad): """Append data to tail of a Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L442 Extends the Netlink message as needed and appends the data of given length to the message. Positional arguments: n -- Netlink message (nl_msg class instance). data -- data to add. len_ -- length of data (integer). pad -- number of bytes to align data to (integer). Returns: 0 on success or a negative error code. """
tmp = nlmsg_reserve(n, len_, pad) if tmp is None: return -NLE_NOMEM tmp[:len_] = data.bytearray[:len_] _LOGGER.debug('msg 0x%x: Appended %d bytes with padding %d', id(n), len_, pad) return 0
<SYSTEM_TASK:> Add a Netlink message header to a Netlink message. <END_TASK> <USER_TASK:> Description: def nlmsg_put(n, pid, seq, type_, payload, flags): """Add a Netlink message header to a Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L503 Adds or overwrites the Netlink message header in an existing message object. Positional arguments: n -- Netlink message (nl_msg class instance). pid -- Netlink process id or NL_AUTO_PID (c_uint32). seq -- sequence number of message or NL_AUTO_SEQ (c_uint32). type_ -- message type (integer). payload -- length of message payload (integer). flags -- message flags (integer). Returns: nlmsghdr class instance or None. """
if n.nm_nlh.nlmsg_len < libnl.linux_private.netlink.NLMSG_HDRLEN: raise BUG nlh = n.nm_nlh nlh.nlmsg_type = type_ nlh.nlmsg_flags = flags nlh.nlmsg_pid = pid nlh.nlmsg_seq = seq _LOGGER.debug('msg 0x%x: Added netlink header type=%d, flags=%d, pid=%d, seq=%d', id(n), type_, flags, pid, seq) if payload > 0 and nlmsg_reserve(n, payload, libnl.linux_private.netlink.NLMSG_ALIGNTO) is None: return None return nlh
<SYSTEM_TASK:> Convert `start` to hex and logs it, 16 bytes per log statement. <END_TASK> <USER_TASK:> Description: def dump_hex(ofd, start, len_, prefix=0): """Convert `start` to hex and logs it, 16 bytes per log statement. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L760 Positional arguments: ofd -- function to call with arguments similar to `logging.debug`. start -- bytearray() or bytearray_ptr() instance. len_ -- size of `start` (integer). Keyword arguments: prefix -- additional number of whitespace pairs to prefix each log statement with. """
prefix_whitespaces = ' ' * prefix limit = 16 - (prefix * 2) start_ = start[:len_] for line in (start_[i:i + limit] for i in range(0, len(start_), limit)): # stackoverflow.com/a/9475354/1198943 hex_lines, ascii_lines = list(), list() for c in line: hex_lines.append('{0:02x}'.format(c if hasattr(c, 'real') else ord(c))) c2 = chr(c) if hasattr(c, 'real') else c ascii_lines.append(c2 if c2 in string.printable[:95] else '.') hex_line = ' '.join(hex_lines).ljust(limit * 3) ascii_line = ''.join(ascii_lines) ofd(' %s%s%s', prefix_whitespaces, hex_line, ascii_line)
<SYSTEM_TASK:> Dump message in human readable format to callable. <END_TASK> <USER_TASK:> Description: def nl_msg_dump(msg, ofd=_LOGGER.debug): """Dump message in human readable format to callable. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L970 Positional arguments: msg -- message to print (nl_msg class instance). Keyword arguments: ofd -- function to call with arguments similar to `logging.debug`. """
hdr = nlmsg_hdr(msg) ofd('-------------------------- BEGIN NETLINK MESSAGE ---------------------------') ofd(' [NETLINK HEADER] %d octets', hdr.SIZEOF) print_hdr(ofd, msg) if hdr.nlmsg_type == libnl.linux_private.netlink.NLMSG_ERROR: dump_error_msg(msg, ofd) elif nlmsg_len(hdr) > 0: print_msg(msg, ofd, hdr) ofd('--------------------------- END NETLINK MESSAGE ---------------------------')
<SYSTEM_TASK:> Allocate a new object of kind specified by the operations handle. <END_TASK> <USER_TASK:> Description: def nl_object_alloc(ops): """Allocate a new object of kind specified by the operations handle. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/object.c#L54 Positional arguments: ops -- cache operations handle (nl_object_ops class instance). Returns: New nl_object class instance or None. """
new = nl_object() nl_init_list_head(new.ce_list) new.ce_ops = ops if ops.oo_constructor: ops.oo_constructor(new) _LOGGER.debug('Allocated new object 0x%x', id(new)) return new
<SYSTEM_TASK:> Register Generic Netlink family and associated commands. <END_TASK> <USER_TASK:> Description: def genl_register_family(ops): """Register Generic Netlink family and associated commands. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/mngt.c#L164 Registers the specified Generic Netlink family definition together with all associated commands. After registration, received Generic Netlink messages can be passed to genl_handle_msg() which will validate the messages, look for a matching command and call the respective callback function automatically. Positional arguments: ops -- Generic Netlink family definition (genl_ops class instance). Returns: 0 on success or a negative error code. """
if not ops.o_name or (ops.o_cmds and ops.o_ncmds <= 0): return -NLE_INVAL if ops.o_id and lookup_family(ops.o_id): return -NLE_EXIST if lookup_family_by_name(ops.o_name): return -NLE_EXIST nl_list_add_tail(ops.o_list, genl_ops_list) return 0
<SYSTEM_TASK:> Register Generic Netlink family backed cache. <END_TASK> <USER_TASK:> Description: def genl_register(ops): """Register Generic Netlink family backed cache. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/genl/mngt.c#L241 Same as genl_register_family() but additionally registers the specified cache operations using nl_cache_mngt_register() and associates it with the Generic Netlink family. Positional arguments: ops -- cache operations definition (nl_cache_ops class instance). Returns: 0 on success or a negative error code. """
if ops.co_protocol != NETLINK_GENERIC: return -NLE_PROTO_MISMATCH if ops.co_hdrsize < GENL_HDRSIZE(0): return -NLE_INVAL if ops.co_genl is None: return -NLE_INVAL ops.co_genl.o_cache_ops = ops ops.co_genl.o_hdrsize = ops.co_hdrsize - GENL_HDRLEN ops.co_genl.o_name = ops.co_msgtypes[0].mt_name ops.co_genl.o_id = ops.co_msgtypes[0].mt_id ops.co_msg_parser = genl_msg_parser err = genl_register_family(ops.co_genl) if err < 0: return err return nl_cache_mngt_register(ops)
<SYSTEM_TASK:> each operation requested represents a session <END_TASK> <USER_TASK:> Description: def __setup_connection(self): """ each operation requested represents a session the session holds information about the plugin running it and establishes a project object """
if self.payload != None and type(self.payload) is dict and 'settings' in self.payload: config.plugin_client_settings = self.payload['settings'] config.offline = self.args.offline config.connection = PluginConnection( client=self.args.client or 'SUBLIME_TEXT_3', ui=self.args.ui_switch, args=self.args, params=self.payload, operation=self.operation, verbose=self.args.verbose) config.project = MavensMateProject(params=self.payload,ui=self.args.ui_switch) config.sfdc_client = config.project.sfdc_client
<SYSTEM_TASK:> Executes requested command <END_TASK> <USER_TASK:> Description: def execute(self): """ Executes requested command """
try: self.__setup_connection() #if the arg switch argument is included, the request is to launch the out of box #MavensMate UI, so we generate the HTML for the UI and launch the process #example: mm -o new_project --ui if self.args.ui_switch == True: config.logger.debug('UI operation requested, attempting to launch MavensMate UI') tmp_html_file = util.generate_ui(self.operation,self.payload,self.args) if config.connection.plugin_client == 'ATOM': #returning location of html file here so we can open the page inside an atom panel self.__printr(util.generate_success_response(tmp_html_file)) else: util.launch_ui(tmp_html_file) self.__printr(util.generate_success_response('UI Generated Successfully')) #non-ui command else: commands = get_available_commands() #debug(commands) try: command_clazz = commands[self.operation](params=self.payload,args=self.args) except KeyError: raise MMUnsupportedOperationException('Could not find the operation you requested. Be sure the command is located in mm.commands, inherits from Command (found in basecommand.py) and includes an execute method.') except NotImplementedError: raise MMException("This command is not properly implemented. Be sure it contains an 'execute' method.") self.__printr(command_clazz.execute()) except Exception, e: self.__printr(e, is_exception=True)
<SYSTEM_TASK:> Recieves a day as an argument and returns the prediction for that alert <END_TASK> <USER_TASK:> Description: def get_alert(self, alert): """ Recieves a day as an argument and returns the prediction for that alert if is available. If not, function will return None. """
if alert > self.alerts_count() or self.alerts_count() is None: return None else: return self.get()[alert-1]
<SYSTEM_TASK:> Gets the weather data from darksky api and stores it in <END_TASK> <USER_TASK:> Description: def get_forecast(self, latitude, longitude): """ Gets the weather data from darksky api and stores it in the respective dictionaries if available. This function should be used to fetch weather information. """
reply = self.http_get(self.url_builder(latitude, longitude)) self.forecast = json.loads(reply) for item in self.forecast.keys(): setattr(self, item, self.forecast[item])
<SYSTEM_TASK:> Gets the weather data from a darksky api response string <END_TASK> <USER_TASK:> Description: def get_forecast_fromstr(self, reply): """ Gets the weather data from a darksky api response string and stores it in the respective dictionaries if available. This function should be used to fetch weather information. """
self.forecast = json.loads(reply) for item in self.forecast.keys(): setattr(self, item, self.forecast[item])
<SYSTEM_TASK:> This function is used to build the correct url to make the request <END_TASK> <USER_TASK:> Description: def url_builder(self, latitude, longitude): """ This function is used to build the correct url to make the request to the forecast.io api. Recieves the latitude and the longitude. Return a string with the url. """
try: float(latitude) float(longitude) except TypeError: raise TypeError('Latitude (%s) and Longitude (%s) must be a float number' % (latitude, longitude)) url = self._darksky_url + self.forecast_io_api_key + '/' url += str(latitude).strip() + ',' + str(longitude).strip() if self.time_url and not self.time_url.isspace(): url += ',' + self.time_url.strip() url += '?units=' + self.units_url.strip() url += '&lang=' + self.lang_url.strip() if self.exclude_url is not None: excludes = '' if self.exclude_url in self._allowed_excludes_extends: excludes += self.exclude_url + ',' else: for item in self.exclude_url: if item in self._allowed_excludes_extends: excludes += item + ',' if len(excludes) > 0: url += '&exclude=' + excludes.rstrip(',') if self.extend_url is not None: extends = '' if self.extend_url in self._allowed_excludes_extends: extends += self.extend_url + ',' else: for item in self.extend_url: if item in self._allowed_excludes_extends: extends += item + ',' if len(extends) > 0: url += '&extend=' + extends.rstrip(',') return url
<SYSTEM_TASK:> This function recieves the request url and it is used internally to get <END_TASK> <USER_TASK:> Description: def http_get(self, request_url): """ This function recieves the request url and it is used internally to get the information via http. Returns the response content. Raises Timeout, TooManyRedirects, RequestException. Raises KeyError if headers are not present. Raises HTTPError if responde code is not 200. """
try: headers = {'Accept-Encoding': 'gzip, deflate'} response = requests.get(request_url, headers=headers) except requests.exceptions.Timeout as ext: log.error('Error: Timeout', ext) except requests.exceptions.TooManyRedirects as extmr: log.error('Error: TooManyRedirects', extmr) except requests.exceptions.RequestException as ex: log.error('Error: RequestException', ex) sys.exit(1) try: self.cache_control = response.headers['Cache-Control'] except KeyError as kerr: log.warning('Warning: Could not get headers. %s' % kerr) self.cache_control = None try: self.expires = response.headers['Expires'] except KeyError as kerr: log.warning('Warning: Could not get headers. %s' % kerr) self.extend_url = None try: self.x_forecast_api_calls = response.headers['X-Forecast-API-Calls'] except KeyError as kerr: log.warning('Warning: Could not get headers. %s' % kerr) self.x_forecast_api_calls = None try: self.x_responde_time = response.headers['X-Response-Time'] except KeyError as kerr: log.warning('Warning: Could not get headers. %s' % kerr) self.x_responde_time = None if response.status_code is not 200: raise requests.exceptions.HTTPError('Bad response, status code: %x' % (response.status_code)) self.raw_response = response.text return self.raw_response
<SYSTEM_TASK:> Shared function between parmap.map and parmap.starmap. <END_TASK> <USER_TASK:> Description: def _map_or_starmap(function, iterable, args, kwargs, map_or_starmap): """ Shared function between parmap.map and parmap.starmap. Refer to those functions for details. """
arg_newarg = (("parallel", "pm_parallel"), ("chunksize", "pm_chunksize"), ("pool", "pm_pool"), ("processes", "pm_processes"), ("parmap_progress", "pm_pbar")) kwargs = _deprecated_kwargs(kwargs, arg_newarg) chunksize = kwargs.pop("pm_chunksize", None) progress = kwargs.pop("pm_pbar", False) progress = progress and HAVE_TQDM parallel, pool, close_pool = _create_pool(kwargs) # Map: if parallel: func_star = _get_helper_func(map_or_starmap) try: if progress and close_pool: try: num_tasks = len(iterable) # get a chunksize (as multiprocessing does): chunksize = _get_default_chunksize(chunksize, pool, num_tasks) # use map_async to get progress information result = pool.map_async(func_star, izip(repeat(function), iterable, repeat(list(args)), repeat(kwargs)), chunksize) finally: pool.close() # Progress bar: try: _do_pbar(result, num_tasks, chunksize) finally: output = result.get() else: result = pool.map_async(func_star, izip(repeat(function), iterable, repeat(list(args)), repeat(kwargs)), chunksize) output = result.get() finally: if close_pool: if not progress: pool.close() pool.join() else: output = _serial_map_or_starmap(function, iterable, args, kwargs, progress, map_or_starmap) return output
<SYSTEM_TASK:> Shared function between parmap.map_async and parmap.starmap_async. <END_TASK> <USER_TASK:> Description: def _map_or_starmap_async(function, iterable, args, kwargs, map_or_starmap): """ Shared function between parmap.map_async and parmap.starmap_async. Refer to those functions for details. """
arg_newarg = (("parallel", "pm_parallel"), ("chunksize", "pm_chunksize"), ("pool", "pm_pool"), ("processes", "pm_processes"), ("callback", "pm_callback"), ("error_callback", "pm_error_callback")) kwargs = _deprecated_kwargs(kwargs, arg_newarg) chunksize = kwargs.pop("pm_chunksize", None) callback = kwargs.pop("pm_callback", None) error_callback = kwargs.pop("pm_error_callback", None) parallel, pool, close_pool = _create_pool(kwargs) # Map: if parallel: func_star = _get_helper_func(map_or_starmap) try: if sys.version_info[0] == 2: # does not support error_callback result = pool.map_async(func_star, izip(repeat(function), iterable, repeat(list(args)), repeat(kwargs)), chunksize, callback) else: result = pool.map_async(func_star, izip(repeat(function), iterable, repeat(list(args)), repeat(kwargs)), chunksize, callback, error_callback) finally: if close_pool: pool.close() result = _ParallelAsyncResult(result, pool) else: result = _ParallelAsyncResult(result) else: values = _serial_map_or_starmap(function, iterable, args, kwargs, False, map_or_starmap) result = _DummyAsyncResult(values) return result
<SYSTEM_TASK:> This function is the multiprocessing.Pool.map_async version that <END_TASK> <USER_TASK:> Description: def map_async(function, iterable, *args, **kwargs): """This function is the multiprocessing.Pool.map_async version that supports multiple arguments. >>> [function(x, args[0], args[1],...) for x in iterable] :param pm_parallel: Force parallelization on/off. If False, the function won't be asynchronous. :type pm_parallel: bool :param pm_chunksize: see :py:class:`multiprocessing.pool.Pool` :type pm_chunksize: int :param pm_callback: see :py:class:`multiprocessing.pool.Pool` :type pm_callback: function :param pm_error_callback: (not on python 2) see :py:class:`multiprocessing.pool.Pool` :type pm_error_callback: function :param pm_pool: Pass an existing pool. :type pm_pool: multiprocessing.pool.Pool :param pm_processes: Number of processes to use in the pool. See :py:class:`multiprocessing.pool.Pool` :type pm_processes: int """
return _map_or_starmap_async(function, iterable, args, kwargs, "map")
<SYSTEM_TASK:> This function is the multiprocessing.Pool.starmap_async version that <END_TASK> <USER_TASK:> Description: def starmap_async(function, iterables, *args, **kwargs): """This function is the multiprocessing.Pool.starmap_async version that supports multiple arguments. >>> return ([function(x1,x2,x3,..., args[0], args[1],...) for >>> (x1,x2,x3...) in iterable]) :param pm_parallel: Force parallelization on/off. If False, the function won't be asynchronous. :type pm_parallel: bool :param pm_chunksize: see :py:class:`multiprocessing.pool.Pool` :type pm_chunksize: int :param pm_callback: see :py:class:`multiprocessing.pool.Pool` :type pm_callback: function :param pm_error_callback: see :py:class:`multiprocessing.pool.Pool` :type pm_error_callback: function :param pm_pool: Pass an existing pool. :type pm_pool: multiprocessing.pool.Pool :param pm_processes: Number of processes to use in the pool. See :py:class:`multiprocessing.pool.Pool` :type pm_processes: int """
return _map_or_starmap_async(function, iterables, args, kwargs, "starmap")
<SYSTEM_TASK:> Wrapper for DNSQuery method <END_TASK> <USER_TASK:> Description: def lookup_domain(domain, nameservers=[], rtype="A", exclude_nameservers=[], timeout=2): """Wrapper for DNSQuery method"""
dns_exp = DNSQuery(domains=[domain], nameservers=nameservers, rtype=rtype, exclude_nameservers=exclude_nameservers, timeout=timeout) return dns_exp.lookup_domain(domain)
<SYSTEM_TASK:> Given a message, parse out the ips in the answer <END_TASK> <USER_TASK:> Description: def parse_out_ips(message): """Given a message, parse out the ips in the answer"""
ips = [] for entry in message.answer: for rdata in entry.items: ips.append(rdata.to_text()) return ips
<SYSTEM_TASK:> Send chaos queries to identify the DNS server and its manufacturer <END_TASK> <USER_TASK:> Description: def send_chaos_queries(self): """Send chaos queries to identify the DNS server and its manufacturer Note: we send 2 queries for BIND stuff per RFC 4892 and 1 query per RFC 6304 Note: we are not waiting on a second response because we shouldn't be getting injected packets here """
names = ["HOSTNAME.BIND", "VERSION.BIND", "ID.SERVER"] self.results = {'exp-name': "chaos-queries"} for name in names: self.results[name] = {} for nameserver in self.nameservers: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.settimeout(self.timeout) query = dns.message.make_query(name, dns.rdatatype.from_text("TXT"), dns.rdataclass.from_text("CH")) sock.sendto(query.to_wire(), (nameserver, 53)) reads, _, _ = select.select([sock], [], [], self.timeout) if len(reads) == 0: self.results[name][nameserver] = None else: response = reads[0].recvfrom(4096)[0] self.results[name][nameserver] = b64encode(response) return self.results
<SYSTEM_TASK:> More complex DNS primitive that looks up domains concurrently <END_TASK> <USER_TASK:> Description: def lookup_domains(self): """More complex DNS primitive that looks up domains concurrently Note: if you want to lookup multiple domains, you should use this function """
thread_error = False thread_wait_timeout = 200 ind = 1 total_item_count = len(self.domains) for domain in self.domains: for nameserver in self.nameservers: wait_time = 0 while threading.active_count() > self.max_threads: time.sleep(1) wait_time += 1 if wait_time > thread_wait_timeout: thread_error = True break if thread_error: self.results["error"] = "Threads took too long to finish." break log_prefix = "%d/%d: " % (ind, total_item_count) thread = threading.Thread(target=self.lookup_domain, args=(domain, nameserver, log_prefix)) thread.setDaemon(1) thread_open_success = False retries = 0 while not thread_open_success and retries < MAX_THREAD_START_RETRY: try: thread.start() self.threads.append(thread) thread_open_success = True except: retries += 1 time.sleep(THREAD_START_DELAY) logging.error("%sThread start failed for %s, retrying... (%d/%d)" % (log_prefix, domain, retries, MAX_THREAD_START_RETRY)) if retries == MAX_THREAD_START_RETRY: logging.error("%sCan't start a new thread for %s after %d retries." % (log_prefix, domain, retries)) if thread_error: break ind += 1 for thread in self.threads: thread.join(self.timeout * 3) return self.results
<SYSTEM_TASK:> Start running the command <END_TASK> <USER_TASK:> Description: def start(self, timeout=None): """Start running the command"""
self.thread.start() start_time = time.time() if not timeout: timeout = self.timeout # every second, check the condition of the thread and return # control to the user if appropriate while start_time + timeout > time.time(): self.thread.join(1) if self.started: return True if self.error: return False return False
<SYSTEM_TASK:> Stop the given command <END_TASK> <USER_TASK:> Description: def stop(self, timeout=None): """Stop the given command"""
if not timeout: timeout = self.timeout self.kill_switch() # Send the signal to all the process groups self.process.kill() self.thread.join(timeout) try: os.killpg(os.getpgid(self.process.pid), signal.SIGTERM) except: pass if self.stopped: return True else: return False
<SYSTEM_TASK:> This is a parallel version of the traceroute primitive. <END_TASK> <USER_TASK:> Description: def traceroute_batch(input_list, results={}, method="udp", cmd_arguments=None, delay_time=0.1, max_threads=100): """ This is a parallel version of the traceroute primitive. :param input_list: the input is a list of domain names :param method: the packet type used for traceroute, UDP by default :param cmd_arguments: the list of arguments that need to be passed to traceroute. :param delay_time: delay before starting each thread :param max_threads: maximum number of concurrent threads :return: """
threads = [] thread_error = False thread_wait_timeout = 200 ind = 1 total_item_count = len(input_list) for domain in input_list: wait_time = 0 while threading.active_count() > max_threads: time.sleep(1) wait_time += 1 if wait_time > thread_wait_timeout: thread_error = True break if thread_error: results["error"] = "Threads took too long to finish." break # add just a little bit of delay before starting the thread # to avoid overwhelming the connection. time.sleep(delay_time) log_prefix = "%d/%d: " % (ind, total_item_count) thread = threading.Thread(target=traceroute, args=(domain, method, cmd_arguments, results, log_prefix)) ind += 1 thread.setDaemon(1) thread_open_success = False retries = 0 while not thread_open_success and retries < MAX_THREAD_START_RETRY: try: thread.start() threads.append(thread) thread_open_success = True except: retries += 1 time.sleep(THREAD_START_DELAY) logging.error("%sThread start failed for %s, retrying... (%d/%d)" % (log_prefix, domain, retries, MAX_THREAD_START_RETRY)) if retries == MAX_THREAD_START_RETRY: logging.error("%sCan't start a new thread for %s after %d retries." % (log_prefix, domain, retries)) for thread in threads: thread.join(thread_wait_timeout) return results
<SYSTEM_TASK:> Callback function to handle traceroute. <END_TASK> <USER_TASK:> Description: def _traceroute_callback(self, line, kill_switch): """ Callback function to handle traceroute. :param self: :param line: :param kill_switch: :return: """
line = line.lower() if "traceroute to" in line: self.started = True # need to run as root but not running as root. # usually happens when doing TCP and ICMP traceroute. if "enough privileges" in line: self.error = True self.kill_switch() self.stopped = True # name resolution failed if "service not known" in line: self.error = True self.kill_switch() self.stopped = True
<SYSTEM_TASK:> Set status of openvpn according to what we process <END_TASK> <USER_TASK:> Description: def output_callback(self, line, kill_switch): """Set status of openvpn according to what we process"""
self.notifications += line + "\n" if "Initialization Sequence Completed" in line: self.started = True if "ERROR:" in line or "Cannot resolve host address:" in line: self.error = True if "process exiting" in line: self.stopped = True
<SYSTEM_TASK:> This function will return the list of experiments. <END_TASK> <USER_TASK:> Description: def load_experiments(self): """This function will return the list of experiments. """
logging.debug("Loading experiments.") # look for experiments in experiments directory exp_dir = self.config['dirs']['experiments_dir'] for path in glob.glob(os.path.join(exp_dir, '[!_]*.py')): # get name of file and path name, ext = os.path.splitext(os.path.basename(path)) # load the experiment try: # do not load modules that have already been loaded if name in loaded_modules: continue imp.load_source(name, path) loaded_modules.add(name) logging.debug("Loaded experiment \"%s(%s)\"." % (name, path)) except Exception as exception: logging.exception("Failed to load experiment %s: %s" % (name, exception)) logging.debug("Finished loading experiments.") # return dict of experiment names and classes return ExperimentList.experiments