code stringlengths 52 7.75k | docs stringlengths 1 5.85k |
|---|---|
def filenames(self, sources):
filename = []
for src in sources:
filename.append(src.split("/")[-1])
return filename | Return filenames from sources links |
def not_downgrade(self, prgnam):
name = "-".join(prgnam.split("-")[:-1])
sbo_ver = prgnam.split("-")[-1]
ins_ver = GetFromInstalled(name).version()[1:]
if not ins_ver:
ins_ver = "0"
if LooseVersion(sbo_ver) < LooseVersion(ins_ver):
self.msg.templa... | Don't downgrade packages if sbo version is lower than
installed |
def sbosrcarsh(self, prgnam, sbo_link, src_link):
sources = []
name = "-".join(prgnam.split("-")[:-1])
category = "{0}/{1}/".format(sbo_link.split("/")[-2], name)
for link in src_link:
source = link.split("/")[-1]
sources.append("{0}{1}{2}".format(self.me... | Alternative repository for sbo sources |
def prog_version():
print("Version : {0}\n"
"Licence : {1}\n"
"Email : {2}\n"
"Maintainer: {3}".format(_meta_.__version__,
_meta_.__license__,
_meta_.__email__,
_meta_.... | Print version, license and email |
def binary(self, name, flag):
if self.meta.rsl_deps in ["on", "ON"] and "--resolve-off" not in flag:
sys.setrecursionlimit(10000)
dependencies = []
requires = Requires(name, self.repo).get_deps()
if requires:
for req in requires:
... | Build all dependencies of a package |
def pkg_not_found(self, bol, pkg, message, eol):
print("{0}No such package {1}: {2}{3}".format(bol, pkg, message, eol)) | Print message when package not found |
def build_FAILED(self, prgnam):
self.template(78)
print("| Some error on the package {0} [ {1}FAILED{2} ]".format(
prgnam, self.meta.color["RED"], self.meta.color["ENDC"]))
self.template(78)
print("| See the log file in '{0}/var/log/slpkg/sbo/build_logs{1}' "
... | Print error message if build failed |
def reading(self):
sys.stdout.write("{0}Reading package lists...{1} ".format(
self.meta.color["GREY"], self.meta.color["ENDC"]))
sys.stdout.flush() | Message reading |
def done(self):
sys.stdout.write("\b{0}Done{1}\n".format(self.meta.color["GREY"],
self.meta.color["ENDC"])) | Message done |
def answer(self):
if self.meta.default_answer in ["y", "Y"]:
answer = self.meta.default_answer
else:
try:
answer = raw_input("Would you like to continue [y/N]? ")
except EOFError:
print("")
raise SystemExit()
... | Message answer |
def security_pkg(self, pkg):
print("")
self.template(78)
print("| {0}{1}*** WARNING ***{2}").format(
" " * 27, self.meta.color["RED"], self.meta.color["ENDC"])
self.template(78)
print("| Before proceed with the package '{0}' will you must read\n"
... | Warning message for some special reasons |
def reference(self, install, upgrade):
self.template(78)
print("| Total {0} {1} installed and {2} {3} upgraded".format(
len(install), self.pkg(len(install)),
len(upgrade), self.pkg(len(upgrade))))
self.template(78)
for installed, upgraded in itertools.izi... | Reference list with packages installed
and upgraded |
def matching(self, packages):
print("\nNot found package with the name [ {0}{1}{2} ]. "
"Matching packages:\nNOTE: Not dependenc"
"ies are resolved\n".format(self.meta.color["CYAN"],
"".join(packages),
... | Message for matching packages |
def mirrors(name, location):
rel = _meta_.slack_rel
ver = slack_ver()
repo = Repo().slack()
if _meta_.arch == "x86_64":
if rel == "stable":
http = repo + "slackware64-{0}/{1}{2}".format(ver, location, name)
else:
http = repo + "slackware64-{0}/{1}{2}".format(... | Select Slackware official mirror packages
based architecture and version. |
def select(self):
print("\nDetected Slackware binary package for installation:\n")
for pkg in self.packages:
print(" " + pkg.split("/")[-1])
print("")
self.msg.template(78)
print("| Choose a Slackware command:")
self.msg.template(78)
for com i... | Select Slackware command |
def execute(self):
if self.choice in self.commands.keys():
if self.choice == "i":
PackageManager(self.packages).install("")
elif self.choice in ["u", "r"]:
PackageManager(self.packages).upgrade(
self.commands[self.choice][11:]) | Execute Slackware command |
def choose(self):
keys = """
Choose repositories at the right side for enable or to the
left side for disable.
Keys: SPACE select or deselect the highlighted repositories,
move it between the left and right lists
^ move the focus to the left list
$ move t... | Choose repositories |
def read_enabled(self):
for line in self.conf.splitlines():
line = line.lstrip()
if self.tag in line:
self.tag_line = True
if (line and self.tag_line and not line.startswith("#") and
self.tag not in line):
self.enab... | Read enable repositories |
def read_disabled(self):
for line in self.conf.splitlines():
line = line.lstrip()
if self.tag in line:
self.tag_line = True
if self.tag_line and line.startswith("#"):
line = "".join(line.split("#")).strip()
self.disable... | Read disable repositories |
def update_repos(self):
with open("{0}{1}".format(self.meta.conf_path,
self.repositories_conf), "w") as new_conf:
for line in self.conf.splitlines():
line = line.lstrip()
if self.tag in line:
self.tag_line... | Update repositories.conf file with enabled or disabled
repositories |
def reference(self):
total_enabled = ", ".join(self.selected)
if len(total_enabled) < 1:
total_enabled = ("{0}Are you crazy? This is a package "
"manager for packages :p{1}".format(
self.meta.color["RED"],
... | Reference enable repositories |
def sbo_search_pkg(name):
repo = Repo().default_repository()["sbo"]
sbo_url = "{0}{1}/".format(repo, slack_ver())
SLACKBUILDS_TXT = Utils().read_file(
_meta_.lib_path + "sbo_repo/SLACKBUILDS.TXT")
for line in SLACKBUILDS_TXT.splitlines():
if line.startswith("SLACKBUILD LOCATION"):
... | Search for package path from SLACKBUILDS.TXT file and
return url |
def router_main(self):
'''
Main method for router; we stay in a loop in this method, receiving
packets until the end of time.
'''
while True:
gotpkt = True
try:
timestamp,dev,pkt = self.net.recv_packet(timeout=1.0)
except No... | Main method for router; we stay in a loop in this method, receiving
packets until the end of time. |
def find_source_files(input_path, excludes):
java_files = []
input_path = os.path.normpath(os.path.abspath(input_path))
for dirpath, dirnames, filenames in os.walk(input_path):
if is_excluded(dirpath, excludes):
del dirnames[:]
continue
for filename in filena... | Get a list of filenames for all Java source files within the given
directory. |
def from_bytes(rawbytes):
'''
Takes a byte string as a parameter and returns a list of
IPOption objects.
'''
ipopts = IPOptionList()
i = 0
while i < len(rawbytes):
opttype = rawbytes[i]
optcopied = opttype >> 7 # high order 1 bit
... | Takes a byte string as a parameter and returns a list of
IPOption objects. |
def to_bytes(self):
'''
Takes a list of IPOption objects and returns a packed byte string
of options, appropriately padded if necessary.
'''
raw = b''
if not self._options:
return raw
for ipopt in self._options:
raw += ipopt.to_bytes()
... | Takes a list of IPOption objects and returns a packed byte string
of options, appropriately padded if necessary. |
def intf_down(self, interface):
'''
Can be called when an interface goes down.
FIXME: doesn't really do anything at this point.
'''
intf = self._devinfo.get(interface, None)
if intf and self._devupdown_callback:
self._devupdown_callback(intf, 'down'f intf_down... | Can be called when an interface goes down.
FIXME: doesn't really do anything at this point. |
def intf_up(self, interface):
'''
Can be called when an interface is put in service.
FIXME: not currently used; more needs to be done to
correctly put a new intf into service.
'''
if interface.name not in self._devinfo:
self._devinfo[interface.name] = interfac... | Can be called when an interface is put in service.
FIXME: not currently used; more needs to be done to
correctly put a new intf into service. |
def interface_by_name(self, name):
'''
Given a device name, return the corresponding interface object
'''
if name in self._devinfo:
return self._devinfo[name]
raise KeyError("No device named {}".format(name)f interface_by_name(self, name):
'''
Given a ... | Given a device name, return the corresponding interface object |
def interface_by_ipaddr(self, ipaddr):
'''
Given an IP address, return the interface that 'owns' this address
'''
ipaddr = IPAddr(ipaddr)
for devname,iface in self._devinfo.items():
if iface.ipaddr == ipaddr:
return iface
raise KeyError("No dev... | Given an IP address, return the interface that 'owns' this address |
def interface_by_macaddr(self, macaddr):
'''
Given a MAC address, return the interface that 'owns' this address
'''
macaddr = EthAddr(macaddr)
for devname,iface in self._devinfo.items():
if iface.ethaddr == macaddr:
return iface
raise KeyError(... | Given a MAC address, return the interface that 'owns' this address |
def from_bytes(rawbytes):
'''
Takes a byte string as a parameter and returns a list of
ICMPv6Option objects.
'''
icmpv6popts = ICMPv6OptionList()
i = 0
while i < len(rawbytes):
opttype = rawbytes[i]
optnum = ICMPv6OptionNumber(opttype)
... | Takes a byte string as a parameter and returns a list of
ICMPv6Option objects. |
def to_bytes(self):
'''
Takes a list of ICMPv6Option objects and returns a packed byte string
of options, appropriately padded if necessary.
'''
raw = b''
if not self._options:
return raw
for icmpv6popt in self._options:
raw += icmpv6popt.t... | Takes a list of ICMPv6Option objects and returns a packed byte string
of options, appropriately padded if necessary. |
def _unpack_bitmap(bitmap, xenum):
'''
Given an integer bitmap and an enumerated type, build
a set that includes zero or more enumerated type values
corresponding to the bitmap.
'''
unpacked = set()
for enval in xenum:
if enval.value & bitmap == enval.value:
unpacked.add(... | Given an integer bitmap and an enumerated type, build
a set that includes zero or more enumerated type values
corresponding to the bitmap. |
def _make_wildcard_attr_map():
'''
Create a dictionary that maps an attribute name
in OpenflowMatch with a non-prefix-related wildcard
bit from the above OpenflowWildcard enumeration.
'''
_xmap = {}
for wc in OpenflowWildcard:
if not wc.name.endswith('All') and \
not wc.n... | Create a dictionary that maps an attribute name
in OpenflowMatch with a non-prefix-related wildcard
bit from the above OpenflowWildcard enumeration. |
def _unpack_actions(raw):
'''
deserialize 1 or more actions; return a list of
Action* objects
'''
actions = []
while len(raw) > 0:
atype, alen = struct.unpack('!HH', raw[:4])
atype = OpenflowActionType(atype)
action = _ActionClassMap.get(atype)()
action.from_byte... | deserialize 1 or more actions; return a list of
Action* objects |
def overlaps_with(self, othermatch, strict=False):
'''
Two match objects overlap if the same packet can be matched
by both *and* they have the same priority.
'''
one = self.matches_entry(othermatch, strict)
if strict:
return one
return one and otherma... | Two match objects overlap if the same packet can be matched
by both *and* they have the same priority. |
def build_from_packet(pkt):
'''
Build and return a new OpenflowMatch object based on the
packet object passed as a parameter.
'''
m = OpenflowMatch()
for mf,pkttuple in OpenflowMatch._match_field_to_packet.items():
for pktcls,field in pkttuple:
... | Build and return a new OpenflowMatch object based on the
packet object passed as a parameter. |
def pre_serialize(self, raw, pkt, i):
'''
Set length of the header based on
'''
self.length = len(raw) + OpenflowHeader._MINLEf pre_serialize(self, raw, pkt, i):
'''
Set length of the header based on
'''
self.length = len(raw) + OpenflowHeader._MINLEN | Set length of the header based on |
def set_bpf_filter_on_all_devices(filterstr):
'''
Long method name, but self-explanatory. Set the bpf
filter on all devices that have been opened.
'''
with PcapLiveDevice._lock:
for dev in PcapLiveDevice._OpenDevices.values():
_PcapFfi.instance()._set... | Long method name, but self-explanatory. Set the bpf
filter on all devices that have been opened. |
def create_ip_arp_reply(srchw, dsthw, srcip, targetip):
'''
Create an ARP reply (just change what needs to be changed
from a request)
'''
pkt = create_ip_arp_request(srchw, srcip, targetip)
pkt[0].dst = dsthw
pkt[1].operation = ArpOperation.Reply
pkt[1].targethwaddr = dsthw
return pk... | Create an ARP reply (just change what needs to be changed
from a request) |
def create_ip_arp_request(srchw, srcip, targetip):
'''
Create and return a packet containing an Ethernet header
and ARP header.
'''
ether = Ethernet()
ether.src = srchw
ether.dst = SpecialEthAddr.ETHER_BROADCAST.value
ether.ethertype = EtherType.ARP
arp = Arp()
arp.operation = Ar... | Create and return a packet containing an Ethernet header
and ARP header. |
def setup_logging(debug, logfile=None):
'''
Setup logging format and log level.
'''
if debug:
level = logging.DEBUG
else:
level = logging.INFO
if logfile is not None:
logging.basicConfig(format="%(asctime)s %(levelname)8s %(message)s", datefmt="%H:%M:%S %Y/%m/%d", level=l... | Setup logging format and log level. |
def shutdown(self):
'''
Should be called by Switchyard user code when a network object is
being shut down. (This method cleans up internal threads and network
interaction objects.)
'''
if not LLNetReal.running:
return
LLNetReal.running = False
... | Should be called by Switchyard user code when a network object is
being shut down. (This method cleans up internal threads and network
interaction objects.) |
def _spawn_threads(self):
'''
Internal method. Creates threads to handle low-level
network receive.
'''
for devname,pdev in self._pcaps.items():
t = threading.Thread(target=LLNetReal._low_level_dispatch, args=(pdev, devname, self._pktqueue))
t.start()
... | Internal method. Creates threads to handle low-level
network receive. |
def _make_pcaps(self):
'''
Internal method. Create libpcap devices
for every network interface we care about and
set them in non-blocking mode.
'''
self._pcaps = {}
for devname,intf in self._devinfo.items():
if intf.iftype == InterfaceType.Loopback:
... | Internal method. Create libpcap devices
for every network interface we care about and
set them in non-blocking mode. |
def _sig_handler(self, signum, stack):
'''
Handle process INT signal.
'''
log_debug("Got SIGINT.")
if signum == signal.SIGINT:
LLNetReal.running = False
if self._pktqueue.qsize() == 0:
# put dummy pkt in queue to unblock a
... | Handle process INT signal. |
def _low_level_dispatch(pcapdev, devname, pktqueue):
'''
Thread entrypoint for doing low-level receive and dispatch
for a single pcap device.
'''
while LLNetReal.running:
# a non-zero timeout value is ok here; this is an
# independent thread that handles i... | Thread entrypoint for doing low-level receive and dispatch
for a single pcap device. |
def __default_filter(self, node):
if not isinstance(node, javalang.tree.Declaration):
return False
if 'private' in node.modifiers:
return False
if isinstance(node, javalang.tree.Documented) and node.documentation:
doc = javalang.javadoc.parse(node.... | Excludes private members and those tagged "@hide" / "@exclude" in their
docblocks. |
def __output_see(self, see):
if see.startswith('<a href'):
# HTML link -- <a href="...">...</a>
return self.__html_to_rst(see)
elif '"' in see:
# Plain text
return see
else:
# Type reference (default)
return ':java... | Convert the argument to a @see tag to rest |
def compile(self, ast):
documents = {}
imports = util.StringBuilder()
for imp in ast.imports:
if imp.static or imp.wildcard:
continue
package_parts = []
cls_parts = []
for part in imp.path.split('.'):
if... | Compile autodocs for the given Java syntax tree. Documents will be
returned documenting each separate type. |
def to_bytes(self):
'''
Return packed byte representation of the UDP header.
'''
hdr = struct.pack(RIPv2._PACKFMT, self.command.value, 2)
routes = b''.join([r.to_bytes() for r in self._routes])
return hdr + routef to_bytes(self):
'''
Return packed byte rep... | Return packed byte representation of the UDP header. |
def checksum (data, start = 0, skip_word = None):
if len(data) % 2 != 0:
arr = array.array('H', data[:-1])
else:
arr = array.array('H', data)
if skip_word is not None:
for i in range(0, len(arr)):
if i == skip_word:
continue
start += arr[i]
else:
for i in range(0, len(ar... | Calculate standard internet checksum over data starting at start'th byte
skip_word: If specified, it's the word offset of a word in data to "skip"
(as if it were zero). The purpose is when data is received
data which contains a computed checksum that you are trying to
verify -... |
def javadoc_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
has_explicit_title, title, target = split_explicit_title(text)
title = utils.unescape(title)
target = utils.unescape(target)
if not has_explicit_title:
target = target.lstrip('~')
if title[0] == '~':
... | Role for linking to external Javadoc |
def add(self, port, pkt):
'''
Add new input port + packet to buffer.
'''
id = len(self._buffer) + 1
if id > self._buffsize:
raise FullBuffer()
self._buffer[id] = (port, deepcopy(pkt))
return if add(self, port, pkt):
'''
Add new input p... | Add new input port + packet to buffer. |
def _process_actions(self, actions, inport, packet):
'''
Process actions in order, in two stages. Each action implements a __call__, which
applies any packet-level changes or other non-output changes. The functors
can optionally return another function to be applied at the second stage... | Process actions in order, in two stages. Each action implements a __call__, which
applies any packet-level changes or other non-output changes. The functors
can optionally return another function to be applied at the second stage. |
def _handle_datapath(self, inport, packet):
'''
Handle single packet on the data plane.
'''
inport = self._switchyard_net.port_by_name(inport)
portnum = inport.ifnum
log_info("Processing packet: {}->{}".format(portnum, packet))
actions = None
for tnum,t i... | Handle single packet on the data plane. |
def to_bytes(self):
'''
Return packed byte representation of the UDP header.
'''
return struct.pack(UDP._PACKFMT, self._src, self._dst,
self._len, self._checksumf to_bytes(self):
'''
Return packed byte representation of the UDP header.
'''
retu... | Return packed byte representation of the UDP header. |
def from_bytes(self, raw):
'''Return an Ethernet object reconstructed from raw bytes, or an
Exception if we can't resurrect the packet.'''
if len(raw) < UDP._MINLEN:
raise NotEnoughDataError("Not enough bytes ({}) to reconstruct an UDP object".format(len(raw)))
fields = st... | Return an Ethernet object reconstructed from raw bytes, or an
Exception if we can't resurrect the packet. |
def to_bytes(self):
'''
Return packed byte representation of the TCP header.
'''
header = self._make_header(self._checksum)
return header + self._options.to_bytes(f to_bytes(self):
'''
Return packed byte representation of the TCP header.
'''
header... | Return packed byte representation of the TCP header. |
def from_bytes(self, raw):
'''Return an Ethernet object reconstructed from raw bytes, or an
Exception if we can't resurrect the packet.'''
if len(raw) < TCP._MINLEN:
raise NotEnoughDataError("Not enough bytes ({}) to reconstruct an TCP object".format(len(raw)))
fields = st... | Return an Ethernet object reconstructed from raw bytes, or an
Exception if we can't resurrect the packet. |
def to_bytes(self, dochecksum=True):
'''
Return packed byte representation of the UDP header.
'''
csum = 0
if dochecksum:
csum = self.checksum()
return b''.join((struct.pack(ICMP._PACKFMT, self._type.value, self._code.value, csum), self._icmpdata.to_bytes())f ... | Return packed byte representation of the UDP header. |
def _parse_codeargs(argstr):
'''
Parse and clean up argument to user code; separate *args from
**kwargs.
'''
args = []
kwargs = {}
if isinstance(argstr, str):
for a in argstr.split():
if '=' in a:
k,attr = a.split('=')
kwargs[k] = attr
... | Parse and clean up argument to user code; separate *args from
**kwargs. |
def netmask_to_cidr (dq):
if isinstance(dq, str):
dq = IPv4Address(dq)
v = int(dq)
c = 0
while v & 0x80000000:
c += 1
v <<= 1
v = v & 0xffFFffFF
if v != 0:
raise RuntimeError("Netmask %s is not CIDR-compatible" % (dq,))
return c | Takes a netmask as either an IPAddr or a string, and returns the number
of network bits. e.g., 255.255.255.0 -> 24
Raise exception if subnet mask is not CIDR-compatible. |
def parse_cidr (addr, infer=True, allow_host=False):
def check (r0, r1):
a = int(r0)
b = r1
if (not allow_host) and (a & ((1<<b)-1)):
raise RuntimeError("Host part of CIDR address is not zero (%s)"
% (addr,))
return (r0,32-r1)
addr = addr.split('/', 2)
if len(add... | Takes a CIDR address or plain dotted-quad, and returns a tuple of address
and count-of-network-bits.
Can infer the network bits based on network classes if infer=True.
Can also take a string in the form 'address/netmask', as long as the
netmask is representable in CIDR.
FIXME: This function is badly named. |
def infer_netmask (addr):
addr = int(addr)
if addr == 0:
# Special case -- default network
return 32-32 # all bits wildcarded
if (addr & (1 << 31)) == 0:
# Class A
return 32-24
if (addr & (3 << 30)) == 2 << 30:
# Class B
return 32-16
if (addr & (7 << 29)) == 6 << 29:
# Class C
... | Uses network classes to guess the number of network bits |
def isBridgeFiltered (self):
return ((self.__value[0] == 0x01)
and (self.__value[1] == 0x80)
and (self.__value[2] == 0xC2)
and (self.__value[3] == 0x00)
and (self.__value[4] == 0x00)
and (self.__value[5] <= 0x0F)) | Checks if address is an IEEE 802.1D MAC Bridge Filtered MAC Group Address
This range is 01-80-C2-00-00-00 to 01-80-C2-00-00-0F. MAC frames that
have a destination MAC address within this range are not relayed by
bridges conforming to IEEE 802.1D |
def toStr (self, separator = ':'):
return separator.join(('{:02x}'.format(x) for x in self.__value)) | Returns the address as string consisting of 12 hex chars separated
by separator. |
def to_bytes(self):
'''
Return packed byte representation of the Ethernet header.
'''
return struct.pack(Ethernet._PACKFMT, self._dst.packed,
self._src.packed, self._ethertype.valuef to_bytes(self):
'''
Return packed byte representation of the Ethernet header... | Return packed byte representation of the Ethernet header. |
def from_bytes(self, raw):
'''Return an Ethernet object reconstructed from raw bytes, or an
Exception if we can't resurrect the packet.'''
if len(raw) < Ethernet._MINLEN:
raise NotEnoughDataError("Not enough bytes ({}) to reconstruct an "
"Ethernet object".format(len(... | Return an Ethernet object reconstructed from raw bytes, or an
Exception if we can't resurrect the packet. |
def run_simulation(topo, **kwargs):
'''
Get the simulation substrate started. The key things are to set up
a series of queues that connect nodes together and get the link emulation
objects started (all inside the NodeExecutor class). The NodePlumbing
named tuples hold together threads for each nod... | Get the simulation substrate started. The key things are to set up
a series of queues that connect nodes together and get the link emulation
objects started (all inside the NodeExecutor class). The NodePlumbing
named tuples hold together threads for each node, the emulation
substrate (NodeExecutors), ... |
def _init():
'''
Internal switchyard static initialization method.
'''
if ApplicationLayer._isinit:
return
ApplicationLayer._isinit = True
ApplicationLayer._to_app = {}
ApplicationLayer._from_app = Queue(f _init():
'''
Internal switch... | Internal switchyard static initialization method. |
def recv_from_app(timeout=_default_timeout):
'''
Called by a network stack implementer to receive application-layer
data for sending on to a remote location.
Can optionally take a timeout value. If no data are available,
raises NoPackets exception.
Returns a 2-tuple:... | Called by a network stack implementer to receive application-layer
data for sending on to a remote location.
Can optionally take a timeout value. If no data are available,
raises NoPackets exception.
Returns a 2-tuple: flowaddr and data.
The flowaddr consists of 5 items: pro... |
def _register_socket(s):
'''
Internal method used by socket emulation layer to create a new "upward"
queue for an app-layer socket and to register the socket object.
Returns two queues: "downward" (fromapp) and "upward" (toapp).
'''
queue_to_app = Queue()
with _lo... | Internal method used by socket emulation layer to create a new "upward"
queue for an app-layer socket and to register the socket object.
Returns two queues: "downward" (fromapp) and "upward" (toapp). |
def _registry_update(s, oldid):
'''
Internal method used to update an existing socket registry when the socket
is re-bound to a different local port number. Requires the socket object
and old sockid. Returns None.
'''
with _lock:
sock_queue = ApplicationLaye... | Internal method used to update an existing socket registry when the socket
is re-bound to a different local port number. Requires the socket object
and old sockid. Returns None. |
def _unregister_socket(s):
'''
Internal method used to remove the socket from AppLayer registry.
Warns if the "upward" socket queue has any left-over data.
'''
with _lock:
sock_queue = ApplicationLayer._to_app.pop(s._sockid())
if not sock_queue.empty():
... | Internal method used to remove the socket from AppLayer registry.
Warns if the "upward" socket queue has any left-over data. |
def bind(self, address):
'''
Alter the local address with which this socket is associated.
The address parameter is a 2-tuple consisting of an IP address
and port number.
NB: this method fails and returns -1 if the requested port
to bind to is already in use but does *n... | Alter the local address with which this socket is associated.
The address parameter is a 2-tuple consisting of an IP address
and port number.
NB: this method fails and returns -1 if the requested port
to bind to is already in use but does *not* check that the
address is valid. |
def recv(self, buffersize, flags=0):
'''
Receive data on the socket. The buffersize and flags
arguments are currently ignored. Only returns the data.
'''
_,_,data = self._recv(buffersize)
return datf recv(self, buffersize, flags=0):
'''
Receive data on t... | Receive data on the socket. The buffersize and flags
arguments are currently ignored. Only returns the data. |
def recvfrom(self, buffersize, flags=0):
'''
Receive data on the socket. The buffersize and flags
arguments are currently ignored. Returns the data and
an address tuple (IP address and port) of the remote host.
'''
_,remoteaddr,data = self._recv(buffersize)
retu... | Receive data on the socket. The buffersize and flags
arguments are currently ignored. Returns the data and
an address tuple (IP address and port) of the remote host. |
def send(self, data, flags=0):
'''
Send data on the socket. A call to connect() must have
been previously made for this call to succeed.
Flags is currently ignored.
'''
if self._remote_addr == (None,None):
raise sockerr("ENOTCONN: socket not connected")
... | Send data on the socket. A call to connect() must have
been previously made for this call to succeed.
Flags is currently ignored. |
def sendto(self, data, *args):
'''
Send data on the socket. Accepts the same parameters as the
built-in socket sendto: data[, flags], address
where address is a 2-tuple of IP address and port.
Any flags are currently ignored.
'''
remoteaddr = args[-1]
rem... | Send data on the socket. Accepts the same parameters as the
built-in socket sendto: data[, flags], address
where address is a 2-tuple of IP address and port.
Any flags are currently ignored. |
def settimeout(self, timeout):
'''
Set the timeout value for this socket.
'''
if timeout is None:
self._block = True
elif float(timeout) == 0.0:
self._block = False
else:
self._timeout = float(timeout)
self._block = Truf set... | Set the timeout value for this socket. |
def to_bytes(self):
'''
Return packed byte representation of the ARP header.
'''
return struct.pack(Arp._PACKFMT, self._hwtype.value, self._prototype.value, self._hwaddrlen, self._protoaddrlen, self._operation.value, self._senderhwaddr.packed, self._senderprotoaddr.packed, self._targethw... | Return packed byte representation of the ARP header. |
def _process_table_cells(self, table):
rows = []
for i, tr in enumerate(table.find_all('tr')):
row = []
for c in tr.contents:
cell_type = getattr(c, 'name', None)
if cell_type not in ('td', 'th'):
continue
... | Compile all the table cells.
Returns a list of rows. The rows may have different lengths because of
column spans. |
def block(self):
'''
pfctl -a switchyard -f- < rules.txt
pfctl -a switchyard -F rules
pfctl -t switchyard -F r
'''
st,output = _runcmd("/sbin/pfctl -aswitchyard -f -", self._rules)
log_debug("Installing rules: {}".format(output)f block(self):
'''
p... | pfctl -a switchyard -f- < rules.txt
pfctl -a switchyard -F rules
pfctl -t switchyard -F r |
def show_graph(cn_topo, showintfs=False, showaddrs=False):
'''
Display the topology
'''
__do_draw(cn_topo, showintfs=showintfs, showaddrs=showaddrs)
pyp.show(f show_graph(cn_topo, showintfs=False, showaddrs=False):
'''
Display the topology
'''
__do_draw(cn_topo, showintfs=showintfs... | Display the topology |
def save_graph(cn_topo, filename, showintfs=False, showaddrs=False):
'''
Save the topology to an image file
'''
__do_draw(cn_topo, showintfs=showintfs, showaddrs=showaddrs)
pyp.savefig(filenamef save_graph(cn_topo, filename, showintfs=False, showaddrs=False):
'''
Save the topology to an ima... | Save the topology to an image file |
def load_from_file(filename):
'''
Load a topology from filename and return it.
'''
t = None
with open(filename, 'rU') as infile:
tdata = infile.read()
t = Topology.unserialize(tdata)
return f load_from_file(filename):
'''
Load a topology from filename and return it.
'... | Load a topology from filename and return it. |
def save_to_file(cn_topo, filename):
'''
Save a topology to a file.
'''
jstr = cn_topo.serialize()
with open(filename, 'w') as outfile:
outfile.write(jstrf save_to_file(cn_topo, filename):
'''
Save a topology to a file.
'''
jstr = cn_topo.serialize()
with open(filename, '... | Save a topology to a file. |
def __addNode(self, name, cls):
'''
Add a node to the topology
'''
if name in self.nodes:
raise Exception("A node by the name {} already exists. Can't add a duplicate.".format(name))
self.__nxgraph.add_node(name)
self.__nxgraph.node[name]['label'] = name
... | Add a node to the topology |
def addHost(self, name=None):
'''
Add a new host node to the topology.
'''
if name is None:
while True:
name = 'h' + str(self.__hnum)
self.__hnum += 1
if name not in self.__nxgraph:
break
self.__addNo... | Add a new host node to the topology. |
def addSwitch(self, name=None):
'''
Add a new switch to the topology.
'''
if name is None:
while True:
name = 's' + str(self.__snum)
self.__snum += 1
if name not in self.__nxgraph:
break
self.__addNod... | Add a new switch to the topology. |
def addRouter(self, name=None):
'''
Add a new switch to the topology.
'''
if name is None:
while True:
name = 'r' + str(self.__rnum)
self.__rnum += 1
if name not in self.__nxgraph:
break
self.__addNod... | Add a new switch to the topology. |
def serialize(self):
'''
Return a JSON string of the serialized topology
'''
return json.dumps(json_graph.node_link_data(self.__nxgraph), cls=Encoderf serialize(self):
'''
Return a JSON string of the serialized topology
'''
return json.dumps(json_graph.nod... | Return a JSON string of the serialized topology |
def unserialize(jsonstr):
'''
Unserialize a JSON string representation of a topology
'''
topod = json.loads(jsonstr)
G = json_graph.node_link_graph(topod)
for n,ndict in G.nodes(data=True):
if 'nodeobj' not in ndict or 'type' not in ndict:
rais... | Unserialize a JSON string representation of a topology |
def getLinkInterfaces(self, node1, node2):
'''
Given two node names that identify a link, return the pair of
interface names assigned at each endpoint (as a tuple in the
same order as the nodes given).
'''
linkdata = self.getLink(node1,node2)
return linkdata[node... | Given two node names that identify a link, return the pair of
interface names assigned at each endpoint (as a tuple in the
same order as the nodes given). |
def setInterfaceAddresses(self, node, interface, mac=None, ip=None, netmask=None):
'''
Set any one of Ethernet (MAC) address, IP address or IP netmask for
a given interface on a node.
'''
if not self.hasNode(node):
raise Exception("No such node {}".format(node))
... | Set any one of Ethernet (MAC) address, IP address or IP netmask for
a given interface on a node. |
def getInterfaceAddresses(self, node, interface):
'''
Return the Ethernet and IP+mask addresses assigned to a
given interface on a node.
'''
intf = self.getNode(node)['nodeobj'].getInterface(interface)
return intf.ethaddr,intf.ipaddr,intf.netmasf getInterfaceAddresses(sel... | Return the Ethernet and IP+mask addresses assigned to a
given interface on a node. |
def addNodeLabelPrefix(self, prefix=None, copy=False):
'''
Rename all nodes in the network from x to prefix_x. If no prefix
is given, use the name of the graph as the prefix.
The purpose of this method is to make node names unique so that
composing two graphs is well-de... | Rename all nodes in the network from x to prefix_x. If no prefix
is given, use the name of the graph as the prefix.
The purpose of this method is to make node names unique so that
composing two graphs is well-defined. |
def from_bytes(self, raw):
'''Return a Null header object reconstructed from raw bytes, or an
Exception if we can't resurrect the packet.'''
if len(raw) < 4:
raise NotEnoughDataError("Not enough bytes ({}) to reconstruct a Null object".format(len(raw)))
fields = struct.unpack... | Return a Null header object reconstructed from raw bytes, or an
Exception if we can't resurrect the packet. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.