code
stringlengths 52
7.75k
| docs
stringlengths 1
5.85k
|
---|---|
def init_defaults(self):
super(ModelTable, self).init_defaults()
self.model = self.table
self.name = self.model._meta.db_table | Sets a model instance variable to the table value and sets the name to the
table name as determined from the model class |
def before_add_field(self, field):
if self.extract_fields and field.name == '*':
field.ignore = True
fields = [model_field.column for model_field in self.model._meta.fields]
self.add_fields(fields) | If extract_fields is set to True, then '*' fields will be removed and each
individual field will read from the model meta data and added. |
def init_defaults(self):
super(QueryTable, self).init_defaults()
self.query = self.table
self.query.is_inner = True | Sets a query instance variable to the table value |
def run_command(cmd_to_run):
with tempfile.TemporaryFile() as stdout_file, tempfile.TemporaryFile() as stderr_file:
# Run the command
popen = subprocess.Popen(cmd_to_run, stdout=stdout_file, stderr=stderr_file)
popen.wait()
stderr_file.seek(0)
stdout_file.seek(0)
stderr = stderr_file.read()
stdout = stdout_file.read()
if six.PY3:
stderr = stderr.decode()
stdout = stdout.decode()
return stderr, stdout | Wrapper around subprocess that pipes the stderr and stdout from `cmd_to_run`
to temporary files. Using the temporary files gets around subprocess.PIPE's
issues with handling large buffers.
Note: this command will block the python process until `cmd_to_run` has completed.
Returns a tuple, containing the stderr and stdout as strings. |
def log(self, level, prefix = ''):
logging.log(level, "%sname: %s", prefix, self.__name)
logging.log(level, "%soptions: %s", prefix, self.__options) | Writes the contents of the Extension to the logging system. |
def specbits(self):
bits = []
for opt in sorted(self.__options):
# handle the case where this is a negated option
m = re.match(r'^! (.*)', opt)
if m:
bits.extend(['!', "--%s" % m.group(1)])
else:
bits.append("--%s" % opt)
optval = self.__options[opt]
if isinstance(optval, list):
bits.extend(optval)
else:
bits.append(optval)
return bits | Returns the array of arguments that would be given to
iptables for the current Extension. |
def log(self, level, prefix = ''):
logging.log(level, "%sin interface: %s", prefix, self.in_interface)
logging.log(level, "%sout interface: %s", prefix, self.out_interface)
logging.log(level, "%ssource: %s", prefix, self.source)
logging.log(level, "%sdestination: %s", prefix, self.destination)
logging.log(level, "%smatches:", prefix)
for match in self.matches:
match.log(level, prefix + ' ')
if self.jump:
logging.log(level, "%sjump:", prefix)
self.jump.log(level, prefix + ' ') | Writes the contents of the Rule to the logging system. |
def specbits(self):
def host_bits(opt, optval):
# handle the case where this is a negated value
m = re.match(r'^!\s*(.*)', optval)
if m:
return ['!', opt, m.group(1)]
else:
return [opt, optval]
bits = []
if self.protocol:
bits.extend(host_bits('-p', self.protocol))
if self.in_interface:
bits.extend(host_bits('-i', self.in_interface))
if self.out_interface:
bits.extend(host_bits('-o', self.out_interface))
if self.source:
bits.extend(host_bits('-s', self.source))
if self.destination:
bits.extend(host_bits('-d', self.destination))
for mod in self.matches:
bits.extend(['-m', mod.name()])
bits.extend(mod.specbits())
if self.goto:
bits.extend(['-g', self.goto.name()])
bits.extend(self.goto.specbits())
elif self.jump:
bits.extend(['-j', self.jump.name()])
bits.extend(self.jump.specbits())
return bits | Returns the array of arguments that would be given to
iptables for the current Rule. |
def parse_chains(data):
chains = odict()
for line in data.splitlines(True):
m = re_chain.match(line)
if m:
policy = None
if m.group(2) != '-':
policy = m.group(2)
chains[m.group(1)] = {
'policy': policy,
'packets': int(m.group(3)),
'bytes': int(m.group(4)),
}
return chains | Parse the chain definitions. |
def parse_rules(data, chain):
rules = []
for line in data.splitlines(True):
m = re_rule.match(line)
if m and m.group(3) == chain:
rule = parse_rule(m.group(4))
rule.packets = int(m.group(1))
rule.bytes = int(m.group(2))
rules.append(rule)
return rules | Parse the rules for the specified chain. |
def _get_new_connection(self, conn_params):
self.__connection_string = conn_params.get('connection_string', '')
conn = self.Database.connect(**conn_params)
return conn | Opens a connection to the database. |
def get_connection_params(self):
from django.conf import settings
settings_dict = self.settings_dict
options = settings_dict.get('OPTIONS', {})
autocommit = options.get('autocommit', False)
conn_params = {
'server': settings_dict['HOST'],
'database': settings_dict['NAME'],
'user': settings_dict['USER'],
'port': settings_dict.get('PORT', '1433'),
'password': settings_dict['PASSWORD'],
'timeout': self.command_timeout,
'autocommit': autocommit,
'use_mars': options.get('use_mars', False),
'load_balancer': options.get('load_balancer', None),
'failover_partner': options.get('failover_partner', None),
'use_tz': utc if getattr(settings, 'USE_TZ', False) else None,
}
for opt in _SUPPORTED_OPTIONS:
if opt in options:
conn_params[opt] = options[opt]
self.tzinfo_factory = utc_tzinfo_factory if settings.USE_TZ else None
return conn_params | Returns a dict of parameters suitable for get_new_connection. |
def create_cursor(self, name=None):
cursor = self.connection.cursor()
cursor.tzinfo_factory = self.tzinfo_factory
return cursor | Creates a cursor. Assumes that a connection is established. |
def __get_dbms_version(self, make_connection=True):
major, minor, _, _ = self.get_server_version(make_connection=make_connection)
return '{}.{}'.format(major, minor) | Returns the 'DBMS Version' string |
def get_buffer(self):
buffer = []
for table in self.__tables:
buffer.extend(table.get_buffer())
return buffer | Get the change buffers. |
def run(self, args):
prog = args[0]
if len(args) < 2:
self.usage(prog)
return 1
command = args[1]
if command == "start":
self.start()
elif command == "stop":
self.stop()
elif command == "restart":
self.stop()
self.start()
else:
self.usage(prog)
return 1
return 0 | Process command line arguments and run the given command command
(start, stop, restart). |
def start(self):
self.clear()
self.setDefaultPolicy()
self.acceptIcmp()
self.acceptInput('lo') | Start the firewall. |
def delete_chain(self, chainname=None):
args = ['-X']
if chainname: args.append(chainname)
self.__run_iptables(args) | Attempts to delete the specified user-defined chain (all the
chains in the table if none is given). |
def flush_chain(self, chainname=None):
args = ['-F']
if chainname: args.append(chainname)
self.__run_iptables(args) | Flushes the specified chain (all the chains in the table if
none is given). This is equivalent to deleting all the rules
one by one. |
def list_rules(self, chainname):
data = self.__run([self.__iptables_save, '-t', self.__name, '-c'])
return netfilter.parser.parse_rules(data, chainname) | Returns a list of Rules in the specified chain. |
def commit(self):
while len(self.__buffer) > 0:
self.__run(self.__buffer.pop(0)) | Commits any buffered commands. This is only useful if
auto_commit is False. |
async def numbered_page(self):
to_delete = []
to_delete.append(await self.bot.send_message(self.message.channel, 'What page do you want to go to?'))
msg = await self.bot.wait_for_message(author=self.author, channel=self.message.channel,
check=lambda m: m.content.isdigit(), timeout=30.0)
if msg is not None:
page = int(msg.content)
to_delete.append(msg)
if page != 0 and page <= self.maximum_pages:
await self.show_page(page)
else:
to_delete.append(await self.bot.say('Invalid page given. (%s/%s)' % (page, self.maximum_pages)))
await asyncio.sleep(5)
else:
to_delete.append(await self.bot.send_message(self.message.channel, 'Took too long.'))
await asyncio.sleep(5)
try:
await self.bot.delete_messages(to_delete)
except Exception:
pass | lets you type a page number to go to |
async def show_help(self):
e = discord.Embed()
messages = ['Welcome to the interactive paginator!\n']
messages.append('This interactively allows you to see pages of text by navigating with ' \
'reactions. They are as follows:\n')
for (emoji, func) in self.reaction_emojis:
messages.append('%s %s' % (emoji, func.__doc__))
e.description = '\n'.join(messages)
e.colour = 0x738bd7 # blurple
e.set_footer(text='We were on page %s before this message.' % self.current_page)
await self.bot.edit_message(self.message, embed=e)
async def go_back_to_current_page():
await asyncio.sleep(60.0)
await self.show_current_page()
self.bot.loop.create_task(go_back_to_current_page()) | shows this message |
async def stop_pages(self):
await self.bot.delete_message(self.message)
self.paginating = False | stops the interactive pagination session |
async def paginate(self):
await self.show_page(1, first=True)
while self.paginating:
react = await self.bot.wait_for_reaction(message=self.message, check=self.react_check, timeout=120.0)
if react is None:
self.paginating = False
try:
await self.bot.clear_reactions(self.message)
except:
pass
finally:
break
try:
await self.bot.remove_reaction(self.message, react.reaction.emoji, react.user)
except:
pass # can't remove it so don't bother doing so
await self.match() | Actually paginate the entries and run the interactive loop if necessary. |
async def _senddms(self):
data = self.bot.config.get("meta", {})
tosend = data.get('send_dms', True)
data['send_dms'] = not tosend
await self.bot.config.put('meta', data)
await self.bot.responses.toggle(message="Forwarding of DMs to owner has been {status}.", success=data['send_dms']) | Toggles sending DMs to owner. |
async def _quit(self):
await self.bot.responses.failure(message="Bot shutting down")
await self.bot.logout() | Quits the bot. |
async def _setcolor(self, *, color : discord.Colour):
data = self.bot.config.get("meta", {})
data['default_color'] = str(color)
await self.bot.config.put('meta', data)
await self.bot.responses.basic(message="The default color has been updated.") | Sets the default color of embeds. |
async def _do(self, ctx, times: int, *, command):
msg = copy.copy(ctx.message)
msg.content = command
for i in range(times):
await self.bot.process_commands(msg) | Repeats a command a specified number of times. |
async def disable(self, ctx, *, command: str):
command = command.lower()
if command in ('enable', 'disable'):
return await self.bot.responses.failure(message='Cannot disable that command.')
if command not in self.bot.commands:
return await self.bot.responses.failure(message='Command "{}" was not found.'.format(command))
guild_id = ctx.message.server.id
cmds = self.config.get('commands', {})
entries = cmds.get(guild_id, [])
entries.append(command)
cmds[guild_id] = entries
await self.config.put('commands', cmds)
await self.bot.responses.success(message='"%s" command disabled in this server.' % command) | Disables a command for this server.
You must have Manage Server permissions or the
Bot Admin role to use this command. |
async def enable(self, ctx, *, command: str):
command = command.lower()
guild_id = ctx.message.server.id
cmds = self.config.get('commands', {})
entries = cmds.get(guild_id, [])
try:
entries.remove(command)
except KeyError:
await self.bot.responses.failure(message='The command does not exist or is not disabled.')
else:
cmds[guild_id] = entries
await self.config.put('commands', cmds)
await self.bot.responses.success(message='"%s" command enabled in this server.' % command) | Enables a command for this server.
You must have Manage Server permissions or the
Bot Admin role to use this command. |
async def ignore(self, ctx):
if ctx.invoked_subcommand is None:
await self.bot.say('Invalid subcommand passed: {0.subcommand_passed}'.format(ctx)) | Handles the bot's ignore lists.
To use these commands, you must have the Bot Admin role or have
Manage Channels permissions. These commands are not allowed to be used
in a private message context.
Users with Manage Roles or Bot Admin role can still invoke the bot
in ignored channels. |
async def ignore_list(self, ctx):
ignored = self.config.get('ignored', [])
channel_ids = set(c.id for c in ctx.message.server.channels)
result = []
for channel in ignored:
if channel in channel_ids:
result.append('<#{}>'.format(channel))
if result:
await self.bot.responses.basic(title="Ignored Channels:", message='\n\n{}'.format(', '.join(result)))
else:
await self.bot.responses.failure(message='I am not ignoring any channels here.') | Tells you what channels are currently ignored in this server. |
async def channel_cmd(self, ctx, *, channel : discord.Channel = None):
if channel is None:
channel = ctx.message.channel
ignored = self.config.get('ignored', [])
if channel.id in ignored:
await self.bot.responses.failure(message='That channel is already ignored.')
return
ignored.append(channel.id)
await self.config.put('ignored', ignored)
await self.bot.responses.success(message='Channel <#{}> will be ignored.'.format(channel.id)) | Ignores a specific channel from being processed.
If no channel is specified, the current channel is ignored.
If a channel is ignored then the bot does not process commands in that
channel until it is unignored. |
async def _all(self, ctx):
ignored = self.config.get('ignored', [])
channels = ctx.message.server.channels
ignored.extend(c.id for c in channels if c.type == discord.ChannelType.text)
await self.config.put('ignored', list(set(ignored))) # make unique
await self.bot.responses.success(message='All channels ignored.') | Ignores every channel in the server from being processed.
This works by adding every channel that the server currently has into
the ignore list. If more channels are added then they will have to be
ignored by using the ignore command.
To use this command you must have Manage Server permissions along with
Manage Channels permissions. You could also have the Bot Admin role. |
async def unignore(self, ctx, *channels: discord.Channel):
if len(channels) == 0:
channels = (ctx.message.channel,)
# a set is the proper data type for the ignore list
# however, JSON only supports arrays and objects not sets.
ignored = self.config.get('ignored', [])
result = []
for channel in channels:
try:
ignored.remove(channel.id)
except ValueError:
pass
else:
result.append('<#{}>'.format(channel.id))
await self.config.put('ignored', ignored)
await self.bot.responses.success(message='Channel(s) {} will no longer be ignored.'.format(', '.join(result))) | Unignores channels from being processed.
If no channels are specified, it unignores the current channel.
To use this command you must have the Manage Channels permission or have the
Bot Admin role. |
async def unignore_all(self, ctx):
channels = [c for c in ctx.message.server.channels if c.type is discord.ChannelType.text]
await ctx.invoke(self.unignore, *channels) | Unignores all channels in this server from being processed.
To use this command you must have the Manage Channels permission or have the
Bot Admin role. |
async def plonk(self, ctx, *, member: discord.Member):
plonks = self.config.get('plonks', {})
guild_id = ctx.message.server.id
db = plonks.get(guild_id, [])
if member.id in db:
await self.bot.responses.failure(message='That user is already bot banned in this server.')
return
db.append(member.id)
plonks[guild_id] = db
await self.config.put('plonks', plonks)
await self.bot.responses.success(message='%s has been banned from using the bot in this server.' % member) | Bans a user from using the bot.
This bans a person from using the bot in the current server.
There is no concept of a global ban. This ban can be bypassed
by having the Manage Server permission.
To use this command you must have the Manage Server permission
or have a Bot Admin role. |
async def plonks(self, ctx):
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.') | Shows members banned from the bot. |
async def unplonk(self, ctx, *, member: discord.Member):
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) | Unbans a user from using the bot.
To use this command you must have the Manage Server permission
or have a Bot Admin role. |
async def join(self, ctx):
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)) | Sends you the bot invite link. |
async def info(self, ctx, *, member : discord.Member = None):
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) | 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. |
async def put(self, key, value, *args):
self._db[key] = value
await self.save() | Edits a data entry. |
def format(self):
values = {}
title = "Description"
description = self.command.description + "\n\n" + self.get_ending_note() if not self.is_cog() else inspect.getdoc(self.command)
sections = []
if isinstance(self.command, Command):
description = self.command.short_doc
sections = [{"name": "Usage", "value": self.get_command_signature()},
{"name": "More Info", "value": self.command.help.replace(self.command.short_doc, "").format(prefix=self.clean_prefix),
"inline": False}]
def category(tup):
cog = tup[1].cog_name
return cog + ':' if cog is not None else '\u200bNo Category:'
if self.is_bot():
title = self.bot.user.display_name + " Help"
data = sorted(self.filter_command_list(), key=category)
for category, commands in itertools.groupby(data, key=category):
section = {}
commands = list(commands)
if len(commands) > 0:
section['name'] = category
section['value'] = self.add_commands(commands)
section['inline'] = False
sections.append(section)
elif not sections or self.has_subcommands():
section = {"name": "Commands:", "inline": False, "value": self.add_commands(self.filter_command_list())}
sections.append(section)
values['title'] = title
values['description'] = description
values['sections'] = sections
return values | Handles the actual behaviour involved with formatting.
To change the behaviour, this method should be overridden.
Returns
--------
list
A paginated output of the help command. |
async def addreaction(self, ctx, *, reactor=""):
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)) | Interactively adds a custom reaction |
async def listreactions(self, ctx):
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) | Lists all the reactions for the server |
async def viewreaction(self, ctx, *, reactor : str):
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}]) | Views a specific reaction |
async def deletereaction(self, ctx, *, reactor : str):
data = self.config.get(ctx.message.server.id, {})
keyword = data.get(reactor, {})
if keyword:
data.pop(reactor)
await self.config.put(ctx.message.server.id, data)
await self.bot.responses.success(message="Reaction '{}' has been deleted.".format(reactor))
else:
await self.bot.responses.failure(message="Reaction '{}' was not found.".format(reactor)) | Removes a reaction |
async def deleteallreactions(self, ctx):
data = self.config.get(ctx.message.server.id, {})
if data:
await self.config.put(ctx.message.server.id, {})
await self.bot.responses.success(message="All reactions have been deleted.")
else:
await self.bot.responses.failure(message="This server has no reactions.") | Removes a reaction |
async def _default_help_command(ctx, *commands : str):
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) | Shows this message. |
def nla_ok(nla, remaining):
return remaining.value >= nla.SIZEOF and nla.SIZEOF <= nla.nla_len <= remaining.value | 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. |
def nla_next(nla, remaining):
totlen = int(NLA_ALIGN(nla.nla_len))
remaining.value -= totlen
return nlattr(bytearray_ptr(nla.bytearray, totlen)) | 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. |
def validate_nla(nla, maxtype, policy):
minlen = 0
type_ = nla_type(nla)
if type_ < 0 or type_ > maxtype:
return 0
pt = policy[type_]
if pt.type_ > NLA_TYPE_MAX:
raise BUG
if pt.minlen:
minlen = pt.minlen
elif pt.type_ != NLA_UNSPEC:
minlen = nla_attr_minlen[pt.type_]
if nla_len(nla) < minlen:
return -NLE_RANGE
if pt.maxlen and nla_len(nla) > pt.maxlen:
return -NLE_RANGE
if pt.type_ == NLA_STRING:
data = nla_data(nla)
if data[nla_len(nla) - 1] != 0:
return -NLE_INVAL
return 0 | https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L188.
Positional arguments:
nla -- nlattr class instance.
maxtype -- integer.
policy -- dictionary of nla_policy class instances as values, with nla types as keys.
Returns:
0 on success or a negative error code. |
def nla_parse(tb, maxtype, head, len_, policy):
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 | 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. |
def nla_for_each_attr(head, len_, rem):
pos = head
rem.value = len_
while nla_ok(pos, rem):
yield pos
pos = nla_next(pos, 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. |
def nla_for_each_nested(nla, rem):
pos = nlattr(nla_data(nla))
rem.value = nla_len(nla)
while nla_ok(pos, rem):
yield pos
pos = nla_next(pos, 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. |
def nla_find(head, len_, attrtype):
rem = c_int()
for nla in nla_for_each_attr(head, len_, rem):
if nla_type(nla) == attrtype:
return nla
return None | 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. |
def nla_reserve(msg, attrtype, attrlen):
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 | 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. |
def nla_put(msg, attrtype, datalen, data):
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 | 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. |
def nla_put_data(msg, attrtype, data):
return nla_put(msg, attrtype, len(data), 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. |
def nla_put_u8(msg, attrtype, value):
data = bytearray(value if isinstance(value, c_uint8) else c_uint8(value))
return nla_put(msg, attrtype, SIZEOF_U8, data) | 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. |
def nla_put_u16(msg, attrtype, value):
data = bytearray(value if isinstance(value, c_uint16) else c_uint16(value))
return nla_put(msg, attrtype, SIZEOF_U16, data) | 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. |
def nla_put_u32(msg, attrtype, value):
data = bytearray(value if isinstance(value, c_uint32) else c_uint32(value))
return nla_put(msg, attrtype, SIZEOF_U32, data) | 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. |
def nla_put_u64(msg, attrtype, value):
data = bytearray(value if isinstance(value, c_uint64) else c_uint64(value))
return nla_put(msg, attrtype, SIZEOF_U64, data) | 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. |
def nla_get_u64(nla):
tmp = c_uint64(0)
if nla and nla_len(nla) >= sizeof(tmp):
tmp = c_uint64.from_buffer(nla_data(nla)[:SIZEOF_U64])
return int(tmp.value) | Return value of 64 bit integer attribute as an int().
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/attr.c#L649
Positional arguments:
nla -- 64 bit integer attribute (nlattr class instance).
Returns:
Payload as an int(). |
def nla_put_string(msg, attrtype, value):
data = bytearray(value) + bytearray(b'\0')
return nla_put(msg, attrtype, len(data), data) | 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. |
def nla_put_msecs(msg, attrtype, msecs):
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) | 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. |
def nla_put_nested(msg, attrtype, nested):
_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)) | 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. |
def nla_parse_nested(tb, maxtype, nla, policy):
return nla_parse(tb, maxtype, nlattr(nla_data(nla)), nla_len(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. |
def genl_send_simple(sk, family, cmd, version, flags):
hdr = genlmsghdr(cmd=cmd, version=version)
return int(nl_send_simple(sk, family, flags, hdr, hdr.SIZEOF)) | 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. |
def genlmsg_valid_hdr(nlh, hdrlen):
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 | 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. |
def genlmsg_parse(nlh, hdrlen, tb, maxtype, policy):
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)) | 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. |
def genlmsg_len(gnlh):
nlh = nlmsghdr(bytearray_ptr(gnlh.bytearray, -NLMSG_HDRLEN, oob=True))
return nlh.nlmsg_len - GENL_HDRLEN - NLMSG_HDRLEN | 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. |
def genlmsg_put(msg, port, seq, family, hdrlen, flags, cmd, version):
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) | 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. |
def nl_cb_call(cb, type_, msg):
cb.cb_active = type_
ret = cb.cb_set[type_](msg, cb.cb_args[type_])
cb.cb_active = 10 + 1 # NL_CB_TYPE_MAX + 1
return int(ret) | Call a callback function.
https://github.com/thom311/libnl/blob/libnl3_2_25/include/netlink-private/netlink.h#L136
Positional arguments:
cb -- nl_cb class instance.
type_ -- callback type integer (e.g. NL_CB_MSG_OUT).
msg -- Netlink message (nl_msg class instance).
Returns:
Integer from the callback function (like NL_OK, NL_SKIP, etc). |
def nl_family(self, value):
self.bytearray[self._get_slicers(0)] = bytearray(c_uint(value or 0)) | Family setter. |
def nl_pad(self, value):
self.bytearray[self._get_slicers(1)] = bytearray(c_ushort(value or 0)) | Pad setter. |
def nl_pid(self, value):
self.bytearray[self._get_slicers(2)] = bytearray(c_uint32(value or 0)) | Port ID setter. |
def nl_groups(self, value):
self.bytearray[self._get_slicers(3)] = bytearray(c_uint32(value or 0)) | Group setter. |
def nlmsg_len(self, value):
self.bytearray[self._get_slicers(0)] = bytearray(c_uint32(value or 0)) | Length setter. |
def nlmsg_type(self, value):
self.bytearray[self._get_slicers(1)] = bytearray(c_uint16(value or 0)) | Message content setter. |
def nlmsg_flags(self, value):
self.bytearray[self._get_slicers(2)] = bytearray(c_uint16(value or 0)) | Message flags setter. |
def nlmsg_seq(self, value):
self.bytearray[self._get_slicers(3)] = bytearray(c_uint32(value or 0)) | Sequence setter. |
def nlmsg_pid(self, value):
self.bytearray[self._get_slicers(4)] = bytearray(c_uint32(value or 0)) | Port ID setter. |
def nla_len(self, value):
self.bytearray[self._get_slicers(0)] = bytearray(c_uint16(value or 0)) | Length setter. |
def nla_type(self, value):
self.bytearray[self._get_slicers(1)] = bytearray(c_uint16(value or 0)) | Type setter. |
def init_default_cb():
global default_cb
nlcb = os.environ.get('NLCB', '').lower()
if not nlcb:
return
if nlcb == 'default':
default_cb = NL_CB_DEFAULT
elif nlcb == 'verbose':
default_cb = NL_CB_VERBOSE
elif nlcb == 'debug':
default_cb = NL_CB_DEBUG
else:
_LOGGER.warning('Unknown value for NLCB, valid values: {default | verbose | debug}') | https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L42. |
def generate_local_port():
global _PREVIOUS_LOCAL_PORT
if _PREVIOUS_LOCAL_PORT is None:
try:
with contextlib.closing(socket.socket(getattr(socket, 'AF_NETLINK', -1), socket.SOCK_RAW)) as s:
s.bind((0, 0))
_PREVIOUS_LOCAL_PORT = int(s.getsockname()[0])
except OSError:
_PREVIOUS_LOCAL_PORT = 4294967295 # UINT32_MAX
return int(_PREVIOUS_LOCAL_PORT) | https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L63. |
def nl_socket_alloc(cb=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 | 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. |
def nl_socket_get_local_port(sk):
if not sk.s_local.nl_pid:
port = generate_local_port()
sk.s_flags &= ~NL_OWN_PORT
sk.s_local.nl_pid = port
return port
return sk.s_local.nl_pid | https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L357.
Also https://github.com/thom311/libnl/blob/libnl3_2_25/lib/socket.c#L338 |
def nl_socket_add_memberships(sk, *group):
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 | 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. |
def nl_socket_drop_memberships(sk, *group):
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 | 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. |
def nl_socket_modify_cb(sk, type_, kind, func, arg):
return int(nl_cb_set(sk.s_cb, 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. |
def nl_socket_modify_err_cb(sk, kind, func, arg):
return int(nl_cb_err(sk.s_cb, 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. |
def nl_socket_set_buffer_size(sk, rxbuf, txbuf):
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 | 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. |
def cmd(self, value):
self.bytearray[self._get_slicers(0)] = bytearray(c_uint8(value or 0)) | Command setter. |
def version(self, value):
self.bytearray[self._get_slicers(1)] = bytearray(c_uint8(value or 0)) | Version setter. |
def reserved(self, value):
self.bytearray[self._get_slicers(2)] = bytearray(c_uint16(value or 0)) | Reserved setter. |
def get_ssid(_, data):
converted = list()
for i in range(len(data)):
try:
c = unichr(data[i])
except NameError:
c = chr(data[i])
if unicodedata.category(c) != 'Cc' and c not in (' ', '\\'):
converted.append(c)
elif c == '\0':
converted.append(c)
elif c == ' ' and i not in (0, len(data)):
converted.append(' ')
else:
converted.append('\\{0:02x}'.format(data[i]))
return ''.join(converted) | http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/util.c?id=v3.17#n313.
Positional arguments:
data -- bytearray data to read.
Returns:
String. |
def get_mcs_index(mcs):
answers = list()
for mcs_bit in range(77):
mcs_octet = int(mcs_bit / 8)
mcs_rate_bit = 1 << mcs_bit % 8
mcs_rate_idx_set = not not (mcs[mcs_octet] & mcs_rate_bit)
if not mcs_rate_idx_set:
continue
answers.append(mcs_bit)
return answers | http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/util.c?id=v3.17#n453.
Positional arguments:
mcs -- bytearray
Returns:
List. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.