Search is not available for this dataset
text
stringlengths 75
104k
|
---|
def strip_db_antsignal(self, idx):
"""strip(1 byte) radiotap.db_antsignal
:return: int
idx
:return: int
"""
db_antsignal, = struct.unpack_from('<B', self._rtap, idx)
return idx + 1, db_antsignal |
def strip_db_antnoise(self, idx):
"""strip(1 byte) radiotap.db_antnoise
:return: int
idx
:return: int
"""
db_antnoise, = struct.unpack_from('<B', self._rtap, idx)
return idx + 1, db_antnoise |
def strip_rx_flags(self, idx):
"""strip(2 byte) radiotap.rxflags
:idx: int
:return: int
idx
:return: collections.namedtuple
"""
rx_flags = collections.namedtuple('rx_flags', ['reserved', 'badplcp'])
idx = Radiotap.align(idx, 2)
flags, = struct.unpack_from('<H', self._rtap, idx)
flag_bits = format(flags, '08b')[::-1]
rx_flags.reserved = int(flag_bits[0])
rx_flags.badplcp = int(flag_bits[1])
return idx + 2, rx_flags |
def strip_tx_flags(self, idx):
"""strip(1 byte) tx_flags
:idx: int
:return: int
idx
:return: int
"""
idx = Radiotap.align(idx, 2)
tx_flags, = struct.unpack_from('<B', self._rtap, idx)
return idx + 1, tx_flags |
def strip_rts_retries(self, idx):
"""strip(1 byte) rts_retries
:idx: int
:return: int
idx
:return: int
"""
rts_retries, = struct.unpack_from('<B', self._rtap, idx)
return idx + 1, rts_retries |
def strip_data_retries(self, idx):
"""strip(1 byte) data_retries
:idx: int
:return: int
idx
:return: int
"""
data_retries, = struct.unpack_from('<B', self._rtap, idx)
return idx + 1, data_retries |
def strip_xchannel(self, idx):
"""strip(7 bytes) radiotap.xchannel.channel(1 byte),
radiotap.xchannel.freq(2 bytes) and radiotap.xchannel.flags(4 bytes)
:idx: int
:return: int
idx
:return: collections.namedtuple
"""
xchannel = collections.namedtuple(
'xchannel', ['flags', 'freq', 'channel', 'max_power'])
flags = collections.namedtuple(
'flags', ['turbo', 'cck', 'ofdm', 'two_g', 'five_g', 'passive',
'dynamic', 'gfsk', 'gsm', 'sturbo', 'hafl', 'quarter',
'ht_20', 'ht_40u', 'ht_40d'])
idx = Radiotap.align(idx, 2)
flag_val, freq, channel, max_power = struct.unpack_from('<lHBB', self._rtap, idx)
xchannel.freq = freq
xchannel.channel = channel
xchannel.max_power = max_power
bits = format(flag_val, '032b')[::-1]
flags.turbo = int(bits[4])
flags.cck = int(bits[5])
flags.ofdm = int(bits[6])
flags.two_g = int(bits[7])
flags.five_g = int(bits[8])
flags.passive = int(bits[9])
flags.dynamic = int(bits[10])
flags.gfsk = int(bits[11])
flags.gsm = int(bits[12])
flags.sturbo = int(bits[13])
flags.half = int(bits[14])
flags.quarter = int(bits[15])
flags.ht_20 = int(bits[16])
flags.ht_40u = int(bits[17])
flags.ht_40d = int(bits[18])
xchannel.flags = flags
return idx + 8, xchannel |
def strip_mcs(self, idx):
"""strip(3 byte) radiotap.mcs which contains 802.11n bandwidth,
mcs(modulation and coding scheme) and stbc(space time block coding)
information.
:idx: int
:return: int
idx
:return: collections.namedtuple
"""
mcs = collections.namedtuple(
'mcs', ['known', 'index', 'have_bw', 'have_mcs', 'have_gi',
'have_format', 'have_fec', 'have_stbc', 'have_ness',
'ness_bit1'])
idx = Radiotap.align(idx, 1)
known, flags, index = struct.unpack_from('<BBB', self._rtap, idx)
bits = format(flags, '032b')[::-1]
mcs.known = known # Known MCS information
mcs.index = index # MCS index
mcs.have_bw = int(bits[0]) # Bandwidth
mcs.have_mcs = int(bits[1]) # MCS
mcs.have_gi = int(bits[2]) # Guard Interval
mcs.have_format = int(bits[3]) # Format
mcs.have_fec = int(bits[4]) # FEC(Forward Error Correction) type
mcs.have_stbc = int(bits[5]) # Space Time Block Coding
mcs.have_ness = int(bits[6]) # Number of Extension Spatial Streams
mcs.ness_bit1 = int(bits[7]) # Number of Extension Spatial Streams bit 1
return idx + 3, mcs |
def strip_ampdu(self, idx):
"""strip(8 byte) radiotap.ampdu
:idx: int
:return: int
idx
:return: collections.namedtuple
"""
ampdu = collections.namedtuple(
'ampdu', ['reference', 'crc_val', 'reservered', 'flags'])
flags = collections.namedtuple(
'flags', ['report_zerolen', 'is_zerolen', 'lastknown', 'last',
'delim_crc_error'])
idx = Radiotap.align(idx, 4)
refnum, flag_vals, crc_val, reserved = struct.unpack_from('<LHBB', self._rtap, idx)
ampdu.flags = flags
ampdu.reference = refnum
ampdu.crc_val = crc_val
ampdu.reserved = reserved
bits = format(flag_vals, '032b')[::-1]
ampdu.flags.report_zerolen = int(bits[0])
ampdu.flags.is_zerolen = int(bits[1])
ampdu.flags.lastknown = int(bits[2])
ampdu.flags.last = int(bits[3])
ampdu.flags.delim_crc_error = int(bits[4])
return idx + 8, ampdu |
def strip_vht(self, idx):
"""strip(12 byte) radiotap.vht
:idx: int
:return: int
idx
:return: collections.namedtuple
"""
vht = collections.namedtuple(
'vht', ['known_bits', 'have_stbc', 'have_txop_ps', 'have_gi',
'have_sgi_nsym_da', 'have_ldpc_extra', 'have_beamformed',
'have_bw', 'have_gid', 'have_paid', 'stbc', 'txop_ps', 'gi',
'sgi_nysm_da', 'ldpc_extra', 'group_id', 'partial_id',
'beamformed', 'user_0', 'user_1', 'user_2', 'user_3'])
user = collections.namedtuple('user', ['nss', 'mcs', 'coding'])
idx = Radiotap.align(idx, 2)
known, flags, bw = struct.unpack_from('<HBB', self._rtap, idx)
mcs_nss_0, mcs_nss_1, mcs_nss_2, mcs_nss_3 = struct.unpack_from('<BBBB', self._rtap, idx + 4)
coding, group_id, partial_id = struct.unpack_from('<BBH', self._rtap, idx + 8)
known_bits = format(known, '032b')[::-1]
vht.known_bits = known_bits
vht.have_stbc = int(known_bits[0]) # Space Time Block Coding
vht.have_txop_ps = int(known_bits[1]) # TXOP_PS_NOT_ALLOWD
vht.have_gi = int(known_bits[2]) # Short/Long Guard Interval
vht.have_sgi_nsym_da = int(known_bits[3]) # Short Guard Interval Nsym Disambiguation
vht.have_ldpc_extra = int(known_bits[4]) # LDPC(Low Density Parity Check)
vht.have_beamformed = int(known_bits[5]) # Beamformed
vht.have_bw = int(known_bits[6]) # Bandwidth
vht.have_gid = int(known_bits[7]) # Group ID
vht.have_paid = int(known_bits[8]) # Partial AID
flag_bits = format(flags, '032b')[::-1]
vht.flag_bits = flag_bits
vht.stbc = int(flag_bits[0])
vht.txop_ps = int(flag_bits[1])
vht.gi = int(flag_bits[2])
vht.sgi_nysm_da = int(flag_bits[3])
vht.ldpc_extra = int(flag_bits[4])
vht.beamformed = int(flag_bits[5])
vht.group_id = group_id
vht.partial_id = partial_id
vht.bw = bw
vht.user_0 = user(None, None, None)
vht.user_1 = user(None, None, None)
vht.user_2 = user(None, None, None)
vht.user_3 = user(None, None, None)
for (i, mcs_nss) in enumerate([mcs_nss_0, mcs_nss_1, mcs_nss_2, mcs_nss_3]):
if mcs_nss:
nss = mcs_nss & 0xf0 >> 4
mcs = (mcs_nss & 0xf0) >> 4
coding = (coding & 2**i) >> i
if i == 0:
vht.user_0 = user(nss, mcs, coding)
elif i == 1:
vht.user_1 = user(nss, mcs, coding)
elif i == 2:
vht.user_2 = user(nss, mcs, coding)
elif i == 3:
vht.user_3 = user(nss, mcs, coding)
return idx + 12, vht |
def extract_protocol(self):
"""extract 802.11 protocol from radiotap.channel.flags
:return: str
protocol name
one of below in success
[.11a, .11b, .11g, .11n, .11ac]
None in fail
"""
if self.present.mcs:
return '.11n'
if self.present.vht:
return '.11ac'
if self.present.channel and hasattr(self, 'chan'):
if self.chan.five_g:
if self.chan.ofdm:
return '.11a'
elif self.chan.two_g:
if self.chan.cck:
return '.11b'
elif self.chan.ofdm or self.chan.dynamic:
return '.11g'
return 'None' |
def get_shark_field(self, fields):
"""get parameters via wireshark syntax.
out = x.get_shark_field('wlan.fc.type')
out = x.get_shark_field(['wlan.fc.type', 'wlan.seq'])
:fields: str or str[]
:return: dict
out[fields[0]] = val[0] or None
out[fields[1]] = val[1] or None ...
"""
keys, exist, out = None, {}, None
if isinstance(fields, str):
fields = [fields]
elif not isinstance(fields, list):
logging.error('invalid input type')
return None
out = dict.fromkeys(fields)
if hasattr(self, '_shark_'):
exist.update(self._shark_)
if hasattr(self, '_s_shark_'):
exist.update(self._s_shark_)
if hasattr(self.radiotap, '_r_shark_'):
exist.update(self.radiotap._r_shark_)
keys = exist.keys()
for elem in fields:
if elem in keys:
obj_field, tmp = exist[elem], None
try:
tmp = operator.attrgetter(obj_field)(self)
except AttributeError:
tmp = None
if not tmp:
try:
tmp = operator.attrgetter(obj_field)(self.radiotap)
except AttributeError:
tmp = None
out[elem] = tmp
return out |
def get_mac_addr(mac_addr):
"""converts bytes to mac addr format
:mac_addr: ctypes.structure
:return: str
mac addr in format
11:22:33:aa:bb:cc
"""
mac_addr = bytearray(mac_addr)
mac = b':'.join([('%02x' % o).encode('ascii') for o in mac_addr])
return mac |
def strip_mac_addrs(self):
"""strip mac address(each 6 byte) information.
(wlan.ta, wlan.ra, wlan.sa, wlan.da)
(transmitter, receiver, source, destination)
:return: int
index of sequence control
:return: int
index after mac addresses
:return: str
source address (sa)
:return: str
transmitter address (ta)
:return: str
receiver address (ra)
:return: str
destination address (da)
:return: str
basic service sed identifier (bssid)
"""
qos_idx, seq_idx = 0, 0
sa, ta, ra, da, bssid = None, None, None, None, None
if self.to_ds == 1 and self.from_ds == 1:
(ra, ta, da) = struct.unpack('!6s6s6s', self._packet[4:22])
sa = struct.unpack('!6s', self._packet[24:30])[0]
qos_idx = 30
seq_idx = 22
elif self.to_ds == 0 and self.from_ds == 1:
(ra, ta, sa) = struct.unpack('!6s6s6s', self._packet[4:22])
qos_idx = 24
seq_idx = 22
elif self.to_ds == 1 and self.from_ds == 0:
(ra, ta, da) = struct.unpack('!6s6s6s', self._packet[4:22])
qos_idx = 24
seq_idx = 22
elif self.to_ds == 0 and self.from_ds == 0:
(ra, ta, bssid) = struct.unpack('!6s6s6s', self._packet[4:22])
qos_idx = 24
seq_idx = 22
if ta is not None:
ta = Wifi.get_mac_addr(ta)
if ra is not None:
ra = Wifi.get_mac_addr(ra)
if sa is not None:
sa = Wifi.get_mac_addr(sa)
if da is not None:
da = Wifi.get_mac_addr(da)
if bssid is not None:
bssid = Wifi.get_mac_addr(bssid)
return seq_idx, qos_idx, sa, ta, ra, da, bssid |
def strip_seq_cntrl(self, idx):
"""strip(2 byte) wlan.seq(12 bit) and wlan.fram(4 bit)
number information.
:seq_cntrl: ctypes.Structure
:return: int
sequence number
:return: int
fragment number
"""
seq_cntrl = struct.unpack('H', self._packet[idx:idx + 2])[0]
seq_num = seq_cntrl >> 4
frag_num = seq_cntrl & 0x000f
return seq_num, frag_num |
def strip_qos_cntrl(self, idx, prot_type):
"""strip(2 byte) wlan.qos
:idx: int
:prot_type: string
802.11 protocol type(.11ac, .11a, .11n, etc)
:return: int
number of processed bytes
:return: int
qos priority
:return: int
qos bit
:return: int
qos acknowledgement
:return: int
amsdupresent(aggregated mac service data unit)
"""
qos_cntrl, = struct.unpack('H', self._packet[idx:idx + 2])
qos_cntrl_bits = format(qos_cntrl, '016b')[::-1]
qos_pri = qos_cntrl & 0x000f
qos_bit = int(qos_cntrl_bits[5])
qos_ack = int(qos_cntrl_bits[6:8], 2)
amsdupresent = 0
if prot_type == '.11ac':
amsdupresent = int(qos_cntrl_bits[7])
return 2, qos_pri, qos_bit, qos_ack, amsdupresent |
def strip_ccmp(self, idx):
"""strip(8 byte) wlan.ccmp.extiv
CCMP Extended Initialization Vector
:return: int
number of processed bytes
:return: ctypes.raw
ccmp vector
"""
ccmp_extiv = None
if len(self._packet[idx:]) >= 8:
raw_bytes = self._packet[idx:idx + 8]
ccmp_extiv, = struct.unpack_from('Q', raw_bytes, 0)
return 8, ccmp_extiv |
def strip_msdu(self, idx):
"""strip single mac servis data unit(msdu)
see -> https://mrncciew.com/2014/11/01/cwap-802-11-data-frame-aggregation/
:idx: int
:return: dict
msdu
:return: int
number of processed bytes
"""
# length of msdu payload has to be multiple of 4,
# this guaranteed with padding
padding = 0
len_payload = 0
msdu = {
'llc': {},
'wlan.da': None,
'wlan.sa': None,
'payload': None,
'length': 0
}
(da_mac, sa_mac) = struct.unpack('!6s6s', self._packet[idx:idx + 12])
msdu['wlan.da'] = Wifi.get_mac_addr(da_mac)
msdu['wlan.sa'] = Wifi.get_mac_addr(sa_mac)
idx += 12
msdu['length'] = struct.unpack('!H', self._packet[idx:idx + 2])[0]
idx += 2
offset, msdu['llc'] = self.strip_llc(idx)
idx += offset
len_payload = msdu['length'] - offset
msdu['payload'] = self._packet[idx:idx + len_payload]
padding = 4 - (len_payload % 4)
return msdu, msdu['length'] + padding + 12 |
def strip_llc(self, idx):
"""strip(4 or 8 byte) logical link control headers
:return: int
number of processed bytes
:return: dict
llc information
see -> http://www.wildpackets.com/resources/compendium/ethernet/frame_snap_iee8023
ABBRVS.
ssap: source service access point
dsap: destination service access point
SNAP(Subnetwork Acess Protocol)
"""
llc = {}
snap = 170
llc_dsap = struct.unpack('B', self._packet[idx:idx + 1])[0]
llc['dsap.dsap'] = llc_dsap >> 1
llc['dsap.ig'] = llc_dsap & 0b01
idx += 1
llc_ssap = struct.unpack('B', self._packet[idx:idx + 1])[0]
llc['ssap.sap'] = llc_ssap >> 1
llc['ssap.cr'] = llc_ssap & 0b01
idx += 1
if llc_dsap == snap and llc_ssap == snap:
llc_control = struct.unpack('B', self._packet[idx:idx + 1])[0]
llc['control.u_modifier_cmd'] = llc_control >> 2
llc['control.ftype'] = llc_control & 0x03
idx += 1
llc['organization_code'] = self._packet[idx:idx + 3]
idx += 3
llc['type'] = self._packet[idx:idx + 2]
return 8, llc
else:
return 4, llc |
def parse_tagged_params(raw_tagged_params):
"""strip tagged information elements wlan_mgt.tag
which has generic type-length-value structure
[type, length, value]
type(1 byte), length(1 byte), value(varies)
[wlan_mgt.tag.number, wlan_mgt.tag.length, payload]
structured fields.
:return: dict[]
list of tagged params
:return: int
0 in succ, 1 for
"""
fcs_len = 4 # wlan.fcs (4 bytes)
idx = 0
tagged_params = []
while idx < len(raw_tagged_params) - fcs_len:
tag_num, tag_len = struct.unpack('BB', raw_tagged_params[idx:idx + 2])
idx += 2
if len(raw_tagged_params) >= idx + tag_len:
param = {}
param['number'], param['length'] = tag_num, tag_len
payload = raw_tagged_params[idx:idx + tag_len]
if tag_num in MNGMT_TAGS:
param['name'] = MNGMT_TAGS[tag_num]
if MNGMT_TAGS[tag_num] == 'TAG_VENDOR_SPECIFIC_IE':
param['payload'] = Management.parse_vendor_ie(payload)
else:
param['payload'] = payload
else:
param['name'] = None
tagged_params.append(param)
idx += tag_len
else:
logging.warning('out tag length header points out of boundary')
log_msg = 'index: {p_idx}, pack_len: {p_len}'
log_msg = log_msg.format(p_idx=idx + tag_len,
p_len=len(raw_tagged_params))
logging.warning(log_msg)
return 1, tagged_params
return 0, tagged_params |
def get_fixed_capabils(payload):
"""strip(2 byte) wlan_mgt.fixed.capabilities
:payload: ctypes.structure
2 byte
:return: dict
None in error
"""
if len(payload) != 2:
return None
capabils = {}
fix_cap = struct.unpack('H', payload)[0]
cap_bits = format(fix_cap, '016b')[::-1]
capabils['ess'] = int(cap_bits[0]) # Extended Service Set
capabils['ibss'] = int(cap_bits[1]) # Independent Basic Service Set
capabils['priv'] = int(cap_bits[4]) # Privacy
capabils['short_preamble'] = int(cap_bits[5]) # Short Preamble
capabils['pbcc'] = int(cap_bits[6]) # Packet Binary Convolutional Code
capabils['chan_agility'] = int(cap_bits[7]) # Channel Agility
capabils['spec_man'] = int(cap_bits[8]) # Spectrum Management
capabils['short_slot'] = int(cap_bits[10]) # Short Slot Time
capabils['apsd'] = int(cap_bits[11]) # Automatic Power Save Delivery
capabils['radio_meas'] = int(cap_bits[12]) # Radio Measurement
capabils['dss_ofdm'] = int(cap_bits[13]) # Direct Spread Spectrum
capabils['del_back'] = int(cap_bits[14]) # Delayed Block Acknowledgement
capabils['imm_back'] = int(cap_bits[15]) # Immediate Block Acknowledgement
return capabils |
def parse_vendor_ie(payload):
"""parse vendor specific information element
oui -> organizationally unique identifier
first 3 bytes of mac addresses
see:https://www.wireshark.org/tools/oui-lookup.html
strip wlan_mgt.tag.oui(3 bytes),
wlan_mgt.tag.vendor.oui.type(1 byte)
wlan_mgt.tag.vendor.data (varies)
:payload: ctypes.structure
:return: dict
{'oui':00-11-22, 'oui_type':1, 'oui_data':ctypes.structure}
"""
output = {}
oui = struct.unpack('BBB', payload[0:3])
oui = b'-'.join([('%02x' % o).encode('ascii') for o in oui])
oui_type = struct.unpack('B', payload[3:4])[0]
oui_data = payload[4:]
output['oui'] = oui.upper()
output['oui_type'] = oui_type
output['oui_data'] = oui_data
return output |
def strip_fixed_params(payload):
"""strip(12 byte) wlan_mgt.fixed.all
:payload: ctypes.structure
:return: int
timestamp
:return: int
beacon interval
:return: dict
capabilities
"""
if len(payload) != 12:
return None, None, None
idx = 0
timestamp = Management.get_timestamp(payload[idx:idx + 8])
idx += 8
interval = Management.get_interval(payload[idx:idx + 2])
idx += 2
capabils = Management.get_fixed_capabils(payload[idx:idx + 2])
return timestamp, interval, capabils |
def is_valid_mac_oui(mac_block):
"""checks whether mac block is in format of
00-11-22 or 00:11:22.
:return: int
"""
if len(mac_block) != 8:
return 0
if ':' in mac_block:
if len(mac_block.split(':')) != 3:
return 0
elif '-' in mac_block:
if len(mac_block.split('-')) != 3:
return 0
return 1 |
def set_fixed_capabils(self, capabils):
"""set keys of capabils into fields of object
:capabils: dict
"""
self.ess = capabils['ess']
self.ibss = capabils['ibss']
self.priv = capabils['priv']
self.short_preamble = capabils['short_preamble']
self.pbcc = capabils['pbcc']
self.chan_agility = capabils['chan_agility']
self.spec_man = capabils['spec_man']
self.short_slot = capabils['short_slot']
self.apsd = capabils['apsd']
self.radio_meas = capabils['radio_meas']
self.dss_ofdm = capabils['dss_ofdm']
self.del_back = capabils['del_back']
self.imm_back = capabils['imm_back'] |
def get_vendor_ies(self, mac_block=None, oui_type=None):
"""vendor information element querying
:mac_block: str
first 3 bytes of mac addresses in format of
00-11-22 or 00:11:22 or 001122
:oui_type: int
vendors ie type
:return: int
is valid mac_block format
-1 is unknown
:return: dict[]
list of oui information elements
-1 on error (invalid v
"""
vendor_ies = []
if mac_block is not None:
if Management.is_valid_mac_oui(mac_block):
mac_block = mac_block.upper()
if ':' in mac_block:
mac_block.replace(':', '-')
else:
logging.warning("invalid oui macblock")
return None
for elem in self.tagged_params:
tag_num = elem['number']
if MNGMT_TAGS[tag_num] == 'TAG_VENDOR_SPECIFIC_IE':
if mac_block is None:
vendor_ies.append(elem)
elif elem['payload']['oui'] == mac_block.encode('ascii'):
if oui_type is None:
vendor_ies.append(elem)
elif elem['payload']['oui_type'] == oui_type:
vendor_ies.append(elem)
return vendor_ies |
def get_shark_field(self, fields):
"""
:fields: str[]
"""
out = super(BACK, self).get_shark_field(fields)
out.update({'acked_seqs': self.acked_seqs,
'bitmap_str': self.bitmap_str})
return out |
def strip_cntrl(payload):
"""strip(2 byte) wlan.ba.control
:payload: ctypes.structure
:return: int
multitid (tid: traffic indicator)
:return: int
ackpolicy
"""
cntrl = struct.unpack('H', payload)[0]
cntrl_bits = format(cntrl, '016b')[::-1]
ackpolicy = int(cntrl_bits[0])
multitid = int(cntrl_bits[1])
return ackpolicy, multitid |
def strip_ssc(payload):
"""strip(2 byte) wlan_mgt.fixed.ssc
:payload: ctypes.structure
:return: int
ssc_seq (starting sequence control sequence)
:return: int
ssc_frag (starting sequence control fragment number)
"""
ssc = struct.unpack('H', payload)[0]
ssc_seq = ssc >> 4
ssc_frag = ssc & 0x000f
return ssc_seq, ssc_frag |
def strip_bitmap_str(payload):
"""strip(8 byte) wlan.ba.bm
:payload: ctypes.structure
:return: str
bitmap
"""
bitmap = struct.unpack('BBBBBBBB', payload)
bitmap_str = ''
for elem in bitmap:
bitmap_str += format(elem, '08b')[::-1]
return bitmap_str |
def extract_acked_seqs(bitmap, ssc_seq):
"""extracts acknowledged sequences from bitmap and
starting sequence number.
:bitmap: str
:ssc_seq: int
:return: int[]
acknowledged sequence numbers
"""
acked_seqs = []
for idx, val in enumerate(bitmap):
if int(val) == 1:
seq = (ssc_seq + idx) % 4096
acked_seqs.append(seq)
return acked_seqs |
def heartbeat():
"""Call Heartbeat URL"""
print "We got a call heartbeat notification\n"
if request.method == 'POST':
print request.form
else:
print request.args
return "OK" |
def request(self, path, method=None, data={}):
"""sends a request and gets a response from the Plivo REST API
path: the URL (relative to the endpoint URL, after the /v1
method: the HTTP method to use, defaults to POST
data: for POST or PUT, a dict of data to send
returns Plivo response in XML or raises an exception on error
"""
if not path:
raise ValueError('Invalid path parameter')
if method and method not in ['GET', 'POST', 'DELETE', 'PUT']:
raise NotImplementedError(
'HTTP %s method not implemented' % method)
if path[0] == '/':
uri = self.url + path
else:
uri = self.url + '/' + path
if APPENGINE:
return json.loads(self._appengine_fetch(uri, data, method))
return json.loads(self._urllib2_fetch(uri, data, method)) |
def reload_config(self, call_params):
"""REST Reload Plivo Config helper
"""
path = '/' + self.api_version + '/ReloadConfig/'
method = 'POST'
return self.request(path, method, call_params) |
def reload_cache_config(self, call_params):
"""REST Reload Plivo Cache Config helper
"""
path = '/' + self.api_version + '/ReloadCacheConfig/'
method = 'POST'
return self.request(path, method, call_params) |
def call(self, call_params):
"""REST Call Helper
"""
path = '/' + self.api_version + '/Call/'
method = 'POST'
return self.request(path, method, call_params) |
def bulk_call(self, call_params):
"""REST BulkCalls Helper
"""
path = '/' + self.api_version + '/BulkCall/'
method = 'POST'
return self.request(path, method, call_params) |
def group_call(self, call_params):
"""REST GroupCalls Helper
"""
path = '/' + self.api_version + '/GroupCall/'
method = 'POST'
return self.request(path, method, call_params) |
def transfer_call(self, call_params):
"""REST Transfer Live Call Helper
"""
path = '/' + self.api_version + '/TransferCall/'
method = 'POST'
return self.request(path, method, call_params) |
def hangup_all_calls(self):
"""REST Hangup All Live Calls Helper
"""
path = '/' + self.api_version + '/HangupAllCalls/'
method = 'POST'
return self.request(path, method) |
def hangup_call(self, call_params):
"""REST Hangup Live Call Helper
"""
path = '/' + self.api_version + '/HangupCall/'
method = 'POST'
return self.request(path, method, call_params) |
def schedule_hangup(self, call_params):
"""REST Schedule Hangup Helper
"""
path = '/' + self.api_version + '/ScheduleHangup/'
method = 'POST'
return self.request(path, method, call_params) |
def cancel_scheduled_hangup(self, call_params):
"""REST Cancel a Scheduled Hangup Helper
"""
path = '/' + self.api_version + '/CancelScheduledHangup/'
method = 'POST'
return self.request(path, method, call_params) |
def record_start(self, call_params):
"""REST RecordStart helper
"""
path = '/' + self.api_version + '/RecordStart/'
method = 'POST'
return self.request(path, method, call_params) |
def record_stop(self, call_params):
"""REST RecordStop
"""
path = '/' + self.api_version + '/RecordStop/'
method = 'POST'
return self.request(path, method, call_params) |
def conference_mute(self, call_params):
"""REST Conference Mute helper
"""
path = '/' + self.api_version + '/ConferenceMute/'
method = 'POST'
return self.request(path, method, call_params) |
def play(self, call_params):
"""REST Play something on a Call Helper
"""
path = '/' + self.api_version + '/Play/'
method = 'POST'
return self.request(path, method, call_params) |
def play_stop(self, call_params):
"""REST PlayStop on a Call Helper
"""
path = '/' + self.api_version + '/PlayStop/'
method = 'POST'
return self.request(path, method, call_params) |
def schedule_play(self, call_params):
"""REST Schedule playing something on a call Helper
"""
path = '/' + self.api_version + '/SchedulePlay/'
method = 'POST'
return self.request(path, method, call_params) |
def cancel_scheduled_play(self, call_params):
"""REST Cancel a Scheduled Play Helper
"""
path = '/' + self.api_version + '/CancelScheduledPlay/'
method = 'POST'
return self.request(path, method, call_params) |
def sound_touch(self, call_params):
"""REST Add soundtouch audio effects to a Call
"""
path = '/' + self.api_version + '/SoundTouch/'
method = 'POST'
return self.request(path, method, call_params) |
def sound_touch_stop(self, call_params):
"""REST Remove soundtouch audio effects on a Call
"""
path = '/' + self.api_version + '/SoundTouchStop/'
method = 'POST'
return self.request(path, method, call_params) |
def send_digits(self, call_params):
"""REST Send digits to a Call
"""
path = '/' + self.api_version + '/SendDigits/'
method = 'POST'
return self.request(path, method, call_params) |
def conference_unmute(self, call_params):
"""REST Conference Unmute helper
"""
path = '/' + self.api_version + '/ConferenceUnmute/'
method = 'POST'
return self.request(path, method, call_params) |
def conference_kick(self, call_params):
"""REST Conference Kick helper
"""
path = '/' + self.api_version + '/ConferenceKick/'
method = 'POST'
return self.request(path, method, call_params) |
def conference_hangup(self, call_params):
"""REST Conference Hangup helper
"""
path = '/' + self.api_version + '/ConferenceHangup/'
method = 'POST'
return self.request(path, method, call_params) |
def conference_deaf(self, call_params):
"""REST Conference Deaf helper
"""
path = '/' + self.api_version + '/ConferenceDeaf/'
method = 'POST'
return self.request(path, method, call_params) |
def conference_undeaf(self, call_params):
"""REST Conference Undeaf helper
"""
path = '/' + self.api_version + '/ConferenceUndeaf/'
method = 'POST'
return self.request(path, method, call_params) |
def conference_record_start(self, call_params):
"""REST Conference RecordStart helper
"""
path = '/' + self.api_version + '/ConferenceRecordStart/'
method = 'POST'
return self.request(path, method, call_params) |
def conference_record_stop(self, call_params):
"""REST Conference RecordStop
"""
path = '/' + self.api_version + '/ConferenceRecordStop/'
method = 'POST'
return self.request(path, method, call_params) |
def conference_play(self, call_params):
"""REST Conference Play helper
"""
path = '/' + self.api_version + '/ConferencePlay/'
method = 'POST'
return self.request(path, method, call_params) |
def conference_speak(self, call_params):
"""REST Conference Speak helper
"""
path = '/' + self.api_version + '/ConferenceSpeak/'
method = 'POST'
return self.request(path, method, call_params) |
def conference_list(self, call_params):
"""REST Conference List Helper
"""
path = '/' + self.api_version + '/ConferenceList/'
method = 'POST'
return self.request(path, method, call_params) |
def conference_list_members(self, call_params):
"""REST Conference List Members Helper
"""
path = '/' + self.api_version + '/ConferenceListMembers/'
method = 'POST'
return self.request(path, method, call_params) |
def _xml(self, root):
"""
Return an XML element representing this element
"""
element = root.createElement(self.name)
# Add attributes
keys = self.attrs.keys()
keys.sort()
for a in keys:
element.setAttribute(a, self.attrs[a])
if self.body:
text = root.createTextNode(self.body)
element.appendChild(text)
for c in self.elements:
element.appendChild(c._xml(root))
return element |
def validateRequest(self, uri, postVars, expectedSignature):
"""validate a request from plivo
uri: the full URI that Plivo requested on your server
postVars: post vars that Plivo sent with the request
expectedSignature: signature in HTTP X-Plivo-Signature header
returns true if the request passes validation, false if not
"""
# append the POST variables sorted by key to the uri
s = uri
for k, v in sorted(postVars.items()):
s += k + v
# compute signature and compare signatures
return (base64.encodestring(hmac.new(self.auth_token, s, sha1).digest()).\
strip() == expectedSignature) |
def DFS_prefix(self, root=None):
"""
Depth-first search.
.. seealso::
`Wikipedia DFS descritpion <http://en.wikipedia.org/wiki/Depth-first_search>`_
:param root: first to start the search
:return: list of nodes
"""
if not root:
root = self._root
return self._DFS_prefix(root) |
def BFS(self, root=None):
"""
Breadth-first search.
.. seealso::
`Wikipedia BFS descritpion <http://en.wikipedia.org/wiki/Breadth-first_search>`_
:param root: first to start the search
:return: list of nodes
"""
if not root:
root = self.root()
queue = deque()
queue.append(root)
nodes = []
while len(queue) > 0:
x = queue.popleft()
nodes.append(x)
for child in x.children():
queue.append(child)
return nodes |
def add_node(self,label):
'''Return a node with label. Create node if label is new'''
try:
n = self._nodes[label]
except KeyError:
n = Node()
n['label'] = label
self._nodes[label]=n
return n |
def add_edge(self, n1_label, n2_label,directed=False):
"""
Get or create edges using get_or_create_node
"""
n1 = self.add_node(n1_label)
n2 = self.add_node(n2_label)
e = Edge(n1, n2, directed)
self._edges.append(e)
return e |
def parse_dom(dom):
"""Parse dom into a Graph.
:param dom: dom as returned by minidom.parse or minidom.parseString
:return: A Graph representation
"""
root = dom.getElementsByTagName("graphml")[0]
graph = root.getElementsByTagName("graph")[0]
name = graph.getAttribute('id')
g = Graph(name)
# # Get attributes
# attributes = []
# for attr in root.getElementsByTagName("key"):
# attributes.append(attr)
# Get nodes
for node in graph.getElementsByTagName("node"):
n = g.add_node(id=node.getAttribute('id'))
for attr in node.getElementsByTagName("data"):
if attr.firstChild:
n[attr.getAttribute("key")] = attr.firstChild.data
else:
n[attr.getAttribute("key")] = ""
# Get edges
for edge in graph.getElementsByTagName("edge"):
source = edge.getAttribute('source')
dest = edge.getAttribute('target')
# source/target attributes refer to IDs: http://graphml.graphdrawing.org/xmlns/1.1/graphml-structure.xsd
e = g.add_edge_by_id(source, dest)
for attr in edge.getElementsByTagName("data"):
if attr.firstChild:
e[attr.getAttribute("key")] = attr.firstChild.data
else:
e[attr.getAttribute("key")] = ""
return g |
def parse_string(self, string):
"""Parse a string into a Graph.
:param string: String that is to be passed into Grapg
:return: Graph
"""
dom = minidom.parseString(string)
return self.parse_dom(dom) |
def node(self, node):
"""
Return the other node
"""
if node == self.node1:
return self.node2
elif node == self.node2:
return self.node1
else:
return None |
def consume(self, **kwargs):
"""Return a generator that yields whenever a message is waiting in the
queue. Will block otherwise. Example:
>>> for msg in queue.consume(timeout=1):
... print msg
my message
another message
:param kwargs: any arguments that :meth:`~hotqueue.HotQueue.get` can
accept (:attr:`block` will default to ``True`` if not given)
"""
kwargs.setdefault('block', True)
try:
while True:
msg = self.get(**kwargs)
if msg is None:
break
yield msg
except KeyboardInterrupt:
print; return |
def get(self, block=False, timeout=None):
"""Return a message from the queue. Example:
>>> queue.get()
'my message'
>>> queue.get()
'another message'
:param block: whether or not to wait until a msg is available in
the queue before returning; ``False`` by default
:param timeout: when using :attr:`block`, if no msg is available
for :attr:`timeout` in seconds, give up and return ``None``
"""
if block:
if timeout is None:
timeout = 0
msg = self.__redis.blpop(self.key, timeout=timeout)
if msg is not None:
msg = msg[1]
else:
msg = self.__redis.lpop(self.key)
if msg is not None and self.serializer is not None:
msg = self.serializer.loads(msg)
return msg |
def put(self, *msgs):
"""Put one or more messages onto the queue. Example:
>>> queue.put("my message")
>>> queue.put("another message")
To put messages onto the queue in bulk, which can be significantly
faster if you have a large number of messages:
>>> queue.put("my message", "another message", "third message")
"""
if self.serializer is not None:
msgs = map(self.serializer.dumps, msgs)
self.__redis.rpush(self.key, *msgs) |
def worker(self, *args, **kwargs):
"""Decorator for using a function as a queue worker. Example:
>>> @queue.worker(timeout=1)
... def printer(msg):
... print msg
>>> printer()
my message
another message
You can also use it without passing any keyword arguments:
>>> @queue.worker
... def printer(msg):
... print msg
>>> printer()
my message
another message
:param kwargs: any arguments that :meth:`~hotqueue.HotQueue.get` can
accept (:attr:`block` will default to ``True`` if not given)
"""
def decorator(worker):
@wraps(worker)
def wrapper(*args):
for msg in self.consume(**kwargs):
worker(*args + (msg,))
return wrapper
if args:
return decorator(*args)
return decorator |
def _arg_parser():
"""Factory for creating the argument parser"""
description = "Converts a completezip to a litezip"
parser = argparse.ArgumentParser(description=description)
verbose_group = parser.add_mutually_exclusive_group()
verbose_group.add_argument(
'-v', '--verbose', action='store_true',
dest='verbose', default=None,
help="increase verbosity")
verbose_group.add_argument(
'-q', '--quiet', action='store_false',
dest='verbose', default=None,
help="print nothing to stdout or stderr")
parser.add_argument(
'location',
help="Location of the unpacked litezip")
return parser |
def to_bytes(self, previous: bytes):
"""
Complex code ahead. Comments have been added in as needed.
"""
# First, validate the lengths.
if len(self.conditions) != len(self.body):
raise exc.CompileError("Conditions and body length mismatch!")
bc = b""
prev_len = len(previous)
# Loop over the conditions and bodies
for condition, body in zip(self.conditions, self.body):
# Generate the conditional data.
cond_bytecode = condition.to_bytecode(previous)
bc += cond_bytecode
# Complex calculation. First, generate the bytecode for all tokens in the body. Then
# we calculate the len() of that. We create a POP_JUMP_IF_FALSE operation that jumps
# to the instructions after the body code + 3 for the pop call. This is done for all
# chained IF calls, as if it was an elif call. Else calls are not possible to be
# auto-generated, but it is possible to emulate them using an elif call that checks
# for the opposite of the above IF.
# Call the _compile_func method from compiler to compile the body.
body_bc = compiler.compile_bytecode(body)
bdyl = len(body_bc)
# Add together the lengths.
gen_len = prev_len + len(cond_bytecode) + bdyl + 1
# Generate the POP_JUMP_IF_FALSE instruction
bc += generate_simple_call(tokens.POP_JUMP_IF_FALSE, gen_len)
# Add the body_bc
bc += body_bc
# Update previous_len
prev_len = len(previous) + len(bc)
return bc |
def to_bytes_35(self, previous: bytes):
"""
A to-bytes specific to Python 3.5 and below.
"""
# Calculations ahead.
bc = b""
# Calculate the length of the iterator.
it_bc = util.generate_bytecode_from_obb(self.iterator, previous)
bc += it_bc
# Push a get_iter on.
bc += util.generate_bytecode_from_obb(tokens.GET_ITER, b"")
prev_len = len(previous) + len(bc)
# Calculate the bytecode for the body.
body_bc = b""
for op in self._body:
# Add padding bytes to the bytecode to allow if blocks to work.
padded_bc = previous
# Add padding for SETUP_LOOP
padded_bc += b"\x00\x00\x00"
padded_bc += bc
# Add padding for FOR_ITER
padded_bc += b"\x00\x00\x00"
# Add previous body
padded_bc += body_bc
body_bc += util.generate_bytecode_from_obb(op, padded_bc)
# Add a JUMP_ABSOLUTE
body_bc += util.generate_simple_call(tokens.JUMP_ABSOLUTE, prev_len + 3)
# Add a POP_TOP
body_bc += util.generate_bytecode_from_obb(tokens.POP_BLOCK, b"")
# Calculate the right lengths.
# Add a FOR_ITER, using len(body_bc)
body_bc = util.generate_simple_call(tokens.FOR_ITER, len(body_bc) - 1) + body_bc
# Add the SETUP_LOOP call
bc = util.generate_simple_call(tokens.SETUP_LOOP, prev_len + len(body_bc) - 6) + bc + body_bc
return bc |
def to_bytes_36(self, previous: bytes):
"""
A to-bytes specific to Python 3.6 and above.
"""
# Calculations ahead.
bc = b""
# Calculate the length of the iterator.
it_bc = util.generate_bytecode_from_obb(self.iterator, previous)
bc += it_bc
bc += util.ensure_instruction(tokens.GET_ITER) |
def validate_content(*objs):
"""Runs the correct validator for given `obj`ects. Assumes all same type"""
from .main import Collection, Module
validator = {
Collection: cnxml.validate_collxml,
Module: cnxml.validate_cnxml,
}[type(objs[0])]
return validator(*[obj.file for obj in objs]) |
def validate_litezip(struct):
"""Validate the given litezip as `struct`.
Returns a list of validation messages.
"""
msgs = []
def _fmt_err(err):
return (Path(err.filename), "{}:{} -- {}: {}".format(*(err[1:])))
obj_by_type = {}
for obj in struct:
if not is_valid_identifier(obj.id):
msg = (obj.file.parent,
"{} is not a valid identifier".format(obj.id),)
logger.info("{}: {}".format(*msg))
msgs.append(msg)
obj_by_type.setdefault(type(obj), []).append(obj)
for obtype in obj_by_type:
content_msgs = list([_fmt_err(err) for err in
validate_content(*obj_by_type[obtype])])
for msg in content_msgs:
logger.info("{}: {}".format(*msg))
msgs.extend(content_msgs)
return msgs |
def ensure_instruction(instruction: int) -> bytes:
"""
Wraps an instruction to be Python 3.6+ compatible. This does nothing on Python 3.5 and below.
This is most useful for operating on bare, single-width instructions such as
``RETURN_FUNCTION`` in a version portable way.
:param instruction: The instruction integer to use.
:return: A safe bytes object, if applicable.
"""
if PY36:
return instruction.to_bytes(2, byteorder="little")
else:
return instruction.to_bytes(1, byteorder="little") |
def pack_value(index: int) -> bytes:
"""
Small helper value to pack an index value into bytecode.
This is used for version compat between 3.5- and 3.6+
:param index: The item to pack.
:return: The packed item.
"""
if PY36:
return index.to_bytes(1, byteorder="little")
else:
return index.to_bytes(2, byteorder="little") |
def generate_simple_call(opcode: int, index: int):
"""
Generates a simple call, with an index for something.
:param opcode: The opcode to generate.
:param index: The index to use as an argument.
:return:
"""
bs = b""
# add the opcode
bs += opcode.to_bytes(1, byteorder="little")
# Add the index
if isinstance(index, int):
if PY36:
bs += index.to_bytes(1, byteorder="little")
else:
bs += index.to_bytes(2, byteorder="little")
else:
bs += index
return bs |
def generate_bytecode_from_obb(obb: object, previous: bytes) -> bytes:
"""
Generates a bytecode from an object.
:param obb: The object to generate.
:param previous: The previous bytecode to use when generating subobjects.
:return: The generated bytecode.
"""
# Generates bytecode from a specified object, be it a validator or an int or bytes even.
if isinstance(obb, pyte.superclasses._PyteOp):
return obb.to_bytes(previous)
elif isinstance(obb, (pyte.superclasses._PyteAugmentedComparator,
pyte.superclasses._PyteAugmentedValidator._FakeMathematicalOP)):
return obb.to_bytes(previous)
elif isinstance(obb, pyte.superclasses._PyteAugmentedValidator):
obb.validate()
return obb.to_load()
elif isinstance(obb, int):
return obb.to_bytes((obb.bit_length() + 7) // 8, byteorder="little") or b''
elif isinstance(obb, bytes):
return obb
else:
raise TypeError("`{}` was not a valid bytecode-encodable item".format(obb)) |
def _get_const_info(const_index, const_list):
"""
Helper to get optional details about const references
Returns the dereferenced constant and its repr if the constant
list is defined.
Otherwise returns the constant index and its repr().
"""
argval = const_index
if const_list is not None:
try:
argval = const_list[const_index]
except IndexError:
raise ValidationError("Consts value out of range: {}".format(const_index)) from None
return argval, repr(argval) |
def _get_name_info(name_index, name_list):
"""Helper to get optional details about named references
Returns the dereferenced name as both value and repr if the name
list is defined.
Otherwise returns the name index and its repr().
"""
argval = name_index
if name_list is not None:
try:
argval = name_list[name_index]
except IndexError:
raise ValidationError("Names value out of range: {}".format(name_index)) from None
argrepr = argval
else:
argrepr = repr(argval)
return argval, argrepr |
def add_to_parser(parser, usage, ignore_existing=False):
"""
Add arguments described in the usage string to the
parser. View more details at the <create_parser> docs
Args:
parser (ArgumentParser): parser to add arguments to
usage (str): Usage string in the format described above
ignore_existing (bool): Ignore any arguments that have already been defined
"""
usage = '\n' + usage
first_line = [i for i in usage.split('\n') if i][0]
indent = ' ' * (len(first_line) - len(first_line.lstrip(' ')))
usage = usage.replace('\n' + indent, '\n')
usage = usage.replace('\n...', '')
defaults = {}
description, *descriptors = usage.split('\n:')
description = description.replace('\n', ' ').strip()
if description and (not parser.description or not ignore_existing):
parser.description = description
for descriptor in descriptors:
try:
options, *info = descriptor.split('\n')
info = ' '.join(i for i in info if i).replace(' ', '')
if options.count(' ') == 1:
if options[0] == '-':
short, long = options.split(' ')
var_name = long.strip('-').replace('-', '_')
parser.add_argument(short, long, dest=var_name, action='store_true', help=info)
defaults[var_name] = False
else:
short, typ = options.split(' ')
parser.add_argument(short, type=types[typ], help=info)
else:
short, long, typ, default = options.split(' ')
info = info.rstrip() + '. Default: ' + default
default = '' if default == '-' else default
parser.add_argument(short, long, type=types[typ], default=default, help=info)
except ArgumentError:
if not ignore_existing:
raise
except Exception as e:
print(e.__class__.__name__ + ': ' + str(e))
print('While parsing:')
print(descriptor)
raise ValueError('Failed to create parser from usage string') |
def compile_bytecode(code: list) -> bytes:
"""
Compiles Pyte objects into a bytecode list.
:param code: A list of objects to compile.
:return: The computed bytecode.
"""
bc = b""
for i, op in enumerate(code):
try:
# Get the bytecode.
if isinstance(op, _PyteOp) or isinstance(op, _PyteAugmentedComparator):
bc_op = op.to_bytes(bc)
elif isinstance(op, int):
bc_op = op.to_bytes(1, byteorder="little")
elif isinstance(op, bytes):
bc_op = op
else:
raise CompileError("Could not compile code of type {}".format(type(op)))
bc += bc_op
except Exception as e:
print("Fatal compiliation error on operator {i} ({op}).".format(i=i, op=op))
raise e
return bc |
def _simulate_stack(code: list) -> int:
"""
Simulates the actions of the stack, to check safety.
This returns the maximum needed stack.
"""
max_stack = 0
curr_stack = 0
def _check_stack(ins):
if curr_stack < 0:
raise CompileError("Stack turned negative on instruction: {}".format(ins))
if curr_stack > max_stack:
return curr_stack
# Iterate over the bytecode.
for instruction in code:
assert isinstance(instruction, dis.Instruction)
if instruction.arg is not None:
try:
effect = dis.stack_effect(instruction.opcode, instruction.arg)
except ValueError as e:
raise CompileError("Invalid opcode `{}` when compiling"
.format(instruction.opcode)) from e
else:
try:
effect = dis.stack_effect(instruction.opcode)
except ValueError as e:
raise CompileError("Invalid opcode `{}` when compiling"
.format(instruction.opcode)) from e
curr_stack += effect
# Re-check the stack.
_should_new_stack = _check_stack(instruction)
if _should_new_stack:
max_stack = _should_new_stack
return max_stack |
def compile(code: list, consts: list, names: list, varnames: list,
func_name: str = "<unknown, compiled>",
arg_count: int = 0, kwarg_defaults: Tuple[Any] = (), use_safety_wrapper: bool = True):
"""
Compiles a set of bytecode instructions into a working function, using Python's bytecode
compiler.
:param code: A list of bytecode instructions.
:param consts: A list of constants to compile into the function.
:param names: A list of names to compile into the function.
:param varnames: A list of ``varnames`` to compile into the function.
:param func_name: The name of the function to use.
:param arg_count: The number of arguments this function takes. Must be ``<= len(varnames)``.
:param kwarg_defaults: A tuple of defaults for kwargs.
:param use_safety_wrapper: Use the safety wrapper? This hijacks SystemError to print better \
stack traces.
"""
varnames = tuple(varnames)
consts = tuple(consts)
names = tuple(names)
# Flatten the code list.
code = util.flatten(code)
if arg_count > len(varnames):
raise CompileError("arg_count > len(varnames)")
if len(kwarg_defaults) > len(varnames):
raise CompileError("len(kwarg_defaults) > len(varnames)")
# Compile it.
bc = compile_bytecode(code)
dis.dis(bc)
# Check for a final RETURN_VALUE.
if PY36:
# TODO: Add Python 3.6 check
pass
else:
if bc[-1] != tokens.RETURN_VALUE:
raise CompileError(
"No default RETURN_VALUE. Add a `pyte.tokens.RETURN_VALUE` to the end of your "
"bytecode if you don't need one.")
# Set default flags
flags = 1 | 2 | 64
frame_data = inspect.stack()[1]
if sys.version_info[0:2] > (3, 3):
# Validate the stack.
stack_size = _simulate_stack(dis._get_instructions_bytes(
bc, constants=consts, names=names, varnames=varnames)
)
else:
warnings.warn("Cannot check stack for safety.")
stack_size = 99
# Generate optimization warnings.
_optimize_warn_pass(dis._get_instructions_bytes(bc, constants=consts, names=names, varnames=varnames))
obb = types.CodeType(
arg_count, # Varnames - used for arguments.
0, # Kwargs are not supported yet
len(varnames), # co_nlocals -> Non-argument local variables
stack_size, # Auto-calculated
flags, # 67 is default for a normal function.
bc, # co_code - use the bytecode we generated.
consts, # co_consts
names, # co_names, used for global calls.
varnames, # arguments
frame_data[1], # use <unknown, compiled>
func_name, # co_name
frame_data[2], # co_firstlineno, ignore this.
b'', # https://svn.python.org/projects/python/trunk/Objects/lnotab_notes.txt
(), # freevars - no idea what this does
() # cellvars - used for nested functions - we don't use these.
)
# Update globals
f_globals = frame_data[0].f_globals
# Create a function type.
f = types.FunctionType(obb, f_globals)
f.__name__ = func_name
f.__defaults__ = kwarg_defaults
if use_safety_wrapper:
def __safety_wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
except SystemError as e:
if 'opcode' not in ' '.join(e.args):
# Re-raise any non opcode related errors.
raise
msg = "Bytecode exception!" \
"\nFunction {} returned an invalid opcode." \
"\nFunction dissection:\n\n".format(f.__name__)
# dis sucks and always prints to stdout
# so we capture it
file = io.StringIO()
with contextlib.redirect_stdout(file):
dis.dis(f)
msg += file.getvalue()
raise SystemError(msg) from e
returned_func = __safety_wrapper
returned_func.wrapped = f
else:
returned_func = f
# return the func
return returned_func |
def _parse_document_id(elm_tree):
"""Given the parsed xml to an `ElementTree`,
parse the id from the content.
"""
xpath = '//md:content-id/text()'
return [x for x in elm_tree.xpath(xpath, namespaces=COLLECTION_NSMAP)][0] |
def _find_resources(directory, excludes=[]):
"""Return a list of resource paths from the directory.
Ignore records via the list of `excludes`,
which are callables that take a file parameter (as a `Path` instance).
"""
return sorted([r for r in directory.glob('*')
if True not in [e(r) for e in excludes]]) |
def parse_module(path, excludes=None):
"""Parse the file structure to a data structure given the path to
a module directory.
"""
file = path / MODULE_FILENAME
if not file.exists():
raise MissingFile(file)
id = _parse_document_id(etree.parse(file.open()))
excludes = excludes or []
excludes.extend([
lambda filepath: filepath.name == MODULE_FILENAME,
])
resources_paths = _find_resources(path, excludes=excludes)
resources = tuple(_resource_from_path(res) for res in resources_paths)
return Module(id, file, resources) |
def parse_collection(path, excludes=None):
"""Parse a file structure to a data structure given the path to
a collection directory.
"""
file = path / COLLECTION_FILENAME
if not file.exists():
raise MissingFile(file)
id = _parse_document_id(etree.parse(file.open()))
excludes = excludes or []
excludes.extend([
lambda filepath: filepath.name == COLLECTION_FILENAME,
lambda filepath: filepath.is_dir(),
])
resources_paths = _find_resources(path, excludes=excludes)
resources = tuple(_resource_from_path(res) for res in resources_paths)
return Collection(id, file, resources) |
def parse_litezip(path):
"""Parse a litezip file structure to a data structure given the path
to the litezip directory.
"""
struct = [parse_collection(path)]
struct.extend([parse_module(x) for x in path.iterdir()
if x.is_dir() and x.name.startswith('m')])
return tuple(sorted(struct)) |
def convert_completezip(path):
"""Converts a completezip file structure to a litezip file structure.
Returns a litezip data structure.
"""
for filepath in path.glob('**/index_auto_generated.cnxml'):
filepath.rename(filepath.parent / 'index.cnxml')
logger.debug('removed {}'.format(filepath))
for filepath in path.glob('**/index.cnxml.html'):
filepath.unlink()
return parse_litezip(path) |
def _get_instructions_bytes(code, varnames=None, names=None, constants=None,
cells=None, linestarts=None, line_offset=0):
"""Iterate over the instructions in a bytecode string.
Generates a sequence of Instruction namedtuples giving the details of each
opcode. Additional information about the code's runtime environment
(e.g. variable names, constants) can be specified using optional
arguments.
"""
labels = dis.findlabels(code)
extended_arg = 0
starts_line = None
free = None
# enumerate() is not an option, since we sometimes process
# multiple elements on a single pass through the loop
n = len(code)
i = 0
while i < n:
op = code[i]
offset = i
if linestarts is not None:
starts_line = linestarts.get(i, None)
if starts_line is not None:
starts_line += line_offset
is_jump_target = i in labels
i = i + 1
arg = None
argval = None
argrepr = ''
if op >= dis.HAVE_ARGUMENT:
arg = code[i] + code[i + 1] * 256 + extended_arg
extended_arg = 0
i = i + 2
if op == dis.EXTENDED_ARG:
extended_arg = arg * 65536
# Set argval to the dereferenced value of the argument when
# availabe, and argrepr to the string representation of argval.
# _disassemble_bytes needs the string repr of the
# raw name index for LOAD_GLOBAL, LOAD_CONST, etc.
argval = arg
if op in dis.hasconst:
argval, argrepr = dis._get_const_info(arg, constants)
elif op in dis.hasname:
argval, argrepr = dis._get_name_info(arg, names)
elif op in dis.hasjrel:
argval = i + arg
argrepr = "to " + repr(argval)
elif op in dis.haslocal:
argval, argrepr = dis._get_name_info(arg, varnames)
elif op in dis.hascompare:
argval = dis.cmp_op[arg]
argrepr = argval
elif op in dis.hasfree:
argval, argrepr = dis._get_name_info(arg, cells)
elif op in dis.hasnargs:
argrepr = "%d positional, %d keyword pair" % (code[i - 2], code[i - 1])
yield dis.Instruction(dis.opname[op], op,
arg, argval, argrepr,
offset, starts_line, is_jump_target) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.