Skip to content

Commit 869c336

Browse files
authored
Merge pull request #1240 from karpierz/little_but_obvious_code_improvements_2
Scapy 2.4.0rc5-40: Little but obvious code improvements. [PR is ready for merge to the master]
2 parents 8dbc779 + dc595c3 commit 869c336

14 files changed

Lines changed: 86 additions & 153 deletions

File tree

scapy/arch/__init__.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -78,11 +78,8 @@ def get_if_addr6(iff):
7878
interface, in human readable form. If no global address is found,
7979
None is returned.
8080
"""
81-
for x in in6_getifaddr():
82-
if x[2] == iff and x[1] == IPV6_ADDR_GLOBAL:
83-
return x[0]
84-
85-
return None
81+
return next((x[0] for x in in6_getifaddr()
82+
if x[2] == iff and x[1] == IPV6_ADDR_GLOBAL), None)
8683

8784
def get_if_raw_addr6(iff):
8885
"""

scapy/arch/windows/__init__.py

Lines changed: 28 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -371,11 +371,13 @@ def _where(filename, dirs=None, env="PATH"):
371371
if glob(filename):
372372
return filename
373373
paths = [os.curdir] + os.environ[env].split(os.path.pathsep) + dirs
374-
for path in paths:
375-
for match in glob(os.path.join(path, filename)):
376-
if match:
377-
return os.path.normpath(match)
378-
raise IOError("File not found: %s" % filename)
374+
try:
375+
return next(os.path.normpath(match)
376+
for path in paths
377+
for match in glob(os.path.join(path, filename))
378+
if match)
379+
except StopIteration:
380+
raise IOError("File not found: %s" % filename)
379381

380382
def win_find_exe(filename, installsubdir=None, env="ProgramFiles"):
381383
"""Find executable in current dir, system path or given ProgramFiles subdir"""
@@ -810,28 +812,31 @@ def dev_from_name(self, name):
810812
"""Return the first pcap device name for a given Windows
811813
device name.
812814
"""
813-
for iface in six.itervalues(self):
814-
if iface.name == name:
815-
return iface
816-
raise ValueError("Unknown network interface %r" % name)
815+
try:
816+
return next(iface for iface in six.itervalues(self)
817+
if iface.name == name)
818+
except StopIteration:
819+
raise ValueError("Unknown network interface %r" % name)
817820

818821
def dev_from_pcapname(self, pcap_name):
819822
"""Return Windows device name for given pcap device name."""
820-
for iface in six.itervalues(self):
821-
if iface.pcap_name == pcap_name:
822-
return iface
823-
raise ValueError("Unknown pypcap network interface %r" % pcap_name)
823+
try:
824+
return next(iface for iface in six.itervalues(self)
825+
if iface.pcap_name == pcap_name)
826+
except StopIteration:
827+
raise ValueError("Unknown pypcap network interface %r" % pcap_name)
824828

825829
def dev_from_index(self, if_index):
826830
"""Return interface name from interface index"""
827-
for devname, iface in six.iteritems(self):
828-
if iface.win_index == str(if_index):
829-
return iface
830-
if str(if_index) == "1":
831-
# Test if the loopback interface is set up
832-
if isinstance(scapy.consts.LOOPBACK_INTERFACE, NetworkInterface):
833-
return scapy.consts.LOOPBACK_INTERFACE
834-
raise ValueError("Unknown network interface index %r" % if_index)
831+
try:
832+
return next(iface for iface in six.itervalues(self)
833+
if iface.win_index == str(if_index))
834+
except StopIteration:
835+
if str(if_index) == "1":
836+
# Test if the loopback interface is set up
837+
if isinstance(scapy.consts.LOOPBACK_INTERFACE, NetworkInterface):
838+
return scapy.consts.LOOPBACK_INTERFACE
839+
raise ValueError("Unknown network interface index %r" % if_index)
835840

836841
def remove_invalid_ifaces(self):
837842
"""Remove all invalid interfaces"""
@@ -1150,9 +1155,8 @@ def _get_valid_guid():
11501155
if scapy.consts.LOOPBACK_INTERFACE:
11511156
return scapy.consts.LOOPBACK_INTERFACE.guid
11521157
else:
1153-
for i in six.itervalues(IFACES):
1154-
if not i.is_invalid():
1155-
return i.guid
1158+
return next((i.guid for i in six.itervalues(IFACES)
1159+
if not i.is_invalid()), None)
11561160

11571161
def route_add_loopback(routes=None, ipv6=False, iflist=None):
11581162
"""Add a route to 127.0.0.1 and ::1 to simplify unit tests on Windows"""

scapy/asn1fields.py

Lines changed: 6 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -279,10 +279,7 @@ def __init__(self, *seq, **kwargs):
279279
default = [field.default for field in seq]
280280
for kwarg in ["context", "implicit_tag",
281281
"explicit_tag", "flexible_tag"]:
282-
if kwarg in kwargs:
283-
setattr(self, kwarg, kwargs[kwarg])
284-
else:
285-
setattr(self, kwarg, None)
282+
setattr(self, kwarg, kwargs.get(kwarg))
286283
ASN1F_field.__init__(self, name, default, context=self.context,
287284
implicit_tag=self.implicit_tag,
288285
explicit_tag=self.explicit_tag,
@@ -292,10 +289,7 @@ def __init__(self, *seq, **kwargs):
292289
def __repr__(self):
293290
return "<%s%r>" % (self.__class__.__name__, self.seq)
294291
def is_empty(self, pkt):
295-
for f in self.seq:
296-
if not f.is_empty(pkt):
297-
return False
298-
return True
292+
return all(f.is_empty(pkt) for f in self.seq)
299293
def get_fields_list(self):
300294
return reduce(lambda x,y: x+y.get_fields_list(), self.seq, [])
301295
def m2i(self, pkt, s):
@@ -441,10 +435,7 @@ def __init__(self, name, default, *args, **kwargs):
441435
raise ASN1_Error(err_msg)
442436
self.implicit_tag = None
443437
for kwarg in ["context", "explicit_tag"]:
444-
if kwarg in kwargs:
445-
setattr(self, kwarg, kwargs[kwarg])
446-
else:
447-
setattr(self, kwarg, None)
438+
setattr(self, kwarg, kwargs.get(kwarg))
448439
ASN1F_field.__init__(self, name, None, context=self.context,
449440
explicit_tag=self.explicit_tag)
450441
self.default = default
@@ -569,10 +560,7 @@ def m2i(self, pkt, s):
569560
raise BER_Decoding_Error("unexpected remainder", remaining=s)
570561
return p, remain
571562
def i2m(self, pkt, x):
572-
if x is None:
573-
s = b""
574-
else:
575-
s = raw(x)
563+
s = b"" if x is None else raw(x)
576564
s = b"".join(binrepr(orb(x)).zfill(8).encode("utf8") for x in s)
577565
return ASN1F_BIT_STRING.i2m(self, pkt, s)
578566

@@ -587,11 +575,8 @@ def __init__(self, name, default, mapping, context=None,
587575
explicit_tag=explicit_tag)
588576
def get_flags(self, pkt):
589577
fbytes = getattr(pkt, self.name).val
590-
flags = []
591-
for i, positional in enumerate(fbytes):
592-
if positional == '1' and i < len(self.mapping):
593-
flags.append(self.mapping[i])
594-
return flags
578+
return [self.mapping[i] for i, positional in enumerate(fbytes)
579+
if positional == '1' and i < len(self.mapping)]
595580
def i2repr(self, pkt, x):
596581
if x is not None:
597582
pretty_s = ", ".join(self.get_flags(pkt))

scapy/base_classes.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
Generators and packet meta classes.
88
"""
99

10-
###############
10+
################
1111
## Generators ##
1212
################
1313

@@ -24,7 +24,7 @@ def __iter__(self):
2424

2525
def _get_values(value):
2626
"""Generate a range object from (start, stop[, step]) tuples, or
27-
return value.
27+
return value.
2828
2929
"""
3030
if (isinstance(value, tuple) and (2 <= len(value) <= 3) and \
@@ -197,10 +197,7 @@ def __new__(cls, name, bases, dct):
197197
for attr in cls.__slots__
198198
)
199199

200-
if hasattr(newcls, "aliastypes"):
201-
newcls.aliastypes = [newcls] + newcls.aliastypes
202-
else:
203-
newcls.aliastypes = [newcls]
200+
newcls.aliastypes = [newcls] + getattr(newcls, "aliastypes", [])
204201

205202
if hasattr(newcls,"register_variant"):
206203
newcls.register_variant()

scapy/config.py

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -124,10 +124,9 @@ def __contains__(self, item):
124124
if isinstance(item, base_classes.Packet_metaclass):
125125
return item in self.layer2num
126126
return item in self.num2layer
127+
127128
def get(self, item, default=None):
128-
if item in self:
129-
return self[item]
130-
return default
129+
return self[item] if item in self else default
131130

132131
def __repr__(self):
133132
lst = []
@@ -147,22 +146,18 @@ def __repr__(self):
147146

148147

149148
class LayersList(list):
149+
150150
def __repr__(self):
151-
s=[]
152-
for l in self:
153-
s.append("%-20s: %s" % (l.__name__,l.name))
154-
return "\n".join(s)
151+
return "\n".join("%-20s: %s" % (l.__name__, l.name) for l in self)
152+
155153
def register(self, layer):
156154
self.append(layer)
157155

158156
class CommandsList(list):
159157
def __repr__(self):
160158
s=[]
161159
for l in sorted(self,key=lambda x:x.__name__):
162-
if l.__doc__:
163-
doc = l.__doc__.split("\n")[0]
164-
else:
165-
doc = "--"
160+
doc = l.__doc__.split("\n")[0] if l.__doc__ else "--"
166161
s.append("%-20s: %s" % (l.__name__,doc))
167162
return "\n".join(s)
168163
def register(self, cmd):

scapy/contrib/diameter.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -353,7 +353,7 @@ def GuessAvpType(p, **kargs):
353353
vndCode = vnd and struct.unpack("!I", p[8:12])[0] or 0
354354
# Check if vendor and code defined and fetch the corresponding AVP
355355
# definition
356-
if vndCode in AvpDefDict.keys():
356+
if vndCode in AvpDefDict:
357357
AvpVndDict = AvpDefDict[vndCode]
358358
if avpCode in AvpVndDict:
359359
# Unpack only the first 4 tupple items at this point
@@ -392,8 +392,8 @@ def AVP(avpId, **fields):
392392
classType = AVP_Unknown
393393
if isinstance(avpId, str):
394394
try:
395-
for vnd in AvpDefDict.keys():
396-
for code in AvpDefDict[vnd].keys():
395+
for vnd in AvpDefDict:
396+
for code in AvpDefDict[vnd]:
397397
val = AvpDefDict[vnd][code]
398398
if val[0][:len(
399399
avpId)] == avpId: # A prefix of the full name is considered valid
@@ -421,10 +421,10 @@ def AVP(avpId, **fields):
421421
# Set/override AVP code
422422
fields['avpCode'] = code
423423
# Set vendor if not already defined and relevant
424-
if 'avpVnd' not in fields.keys() and vnd:
424+
if 'avpVnd' not in fields and vnd:
425425
fields['avpVnd'] = vnd
426426
# Set flags if not already defined and possible ...
427-
if 'avpFlags' not in fields.keys():
427+
if 'avpFlags' not in fields:
428428
if val:
429429
fields['avpFlags'] = val[2]
430430
else:
@@ -4748,7 +4748,7 @@ def getCmdParams(cmd, request, **fields):
47484748
# Fetch the parameters if cmd is found in dict
47494749
if isinstance(cmd, int):
47504750
drCode = cmd # Enable to craft commands with non standard code
4751-
if cmd in DR_cmd_def.keys():
4751+
if cmd in DR_cmd_def:
47524752
params = DR_cmd_def[drCode]
47534753
else:
47544754
params = ('Unknown', 'UK', {0: (128, 0)})
@@ -4775,7 +4775,7 @@ def getCmdParams(cmd, request, **fields):
47754775
# The drCode is set/overriden in any case
47764776
fields['drCode'] = drCode
47774777
# Processing of drAppId
4778-
if 'drAppId' in fields.keys():
4778+
if 'drAppId' in fields:
47794779
val = fields['drAppId']
47804780
if isinstance(val, str): # Translate into application Id code
47814781
found = False
@@ -4799,7 +4799,7 @@ def getCmdParams(cmd, request, **fields):
47994799
# Set the command name
48004800
name = request and params[0] + '-Request' or params[0] + '-Answer'
48014801
# Processing of flags (only if not provided manually)
4802-
if 'drFlags' not in fields.keys():
4802+
if 'drFlags' not in fields:
48034803
if drAppId in params[2].keys():
48044804
flags = params[2][drAppId]
48054805
fields['drFlags'] = request and flags[0] or flags[1]

scapy/contrib/openflow3.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -600,7 +600,7 @@ def getfield(self, pkt, s):
600600
l = OXMPacketListField._get_oxm_length(remain) + 4
601601
# this could also be done by parsing oxm_fields (fixed lengths)
602602
if l <= 4 or len(remain) < l:
603-
# no incoherent length
603+
# no incoherent length
604604
break
605605
current = remain[:l]
606606
remain = remain[l:]
@@ -997,9 +997,9 @@ def getfield(self, pkt, s):
997997
while remain and len(remain)>=4:
998998
l = ActionPacketListField._get_action_length(remain)
999999
if l < 8 or len(remain) < l:
1000-
# length should be at least 8 (non-zero, 64-bit aligned),
1001-
# and no incoherent length
1002-
break
1000+
# length should be at least 8 (non-zero, 64-bit aligned),
1001+
# and no incoherent length
1002+
break
10031003
current = remain[:l]
10041004
remain = remain[l:]
10051005
p = self.m2i(pkt, current)
@@ -1214,8 +1214,8 @@ def getfield(self, pkt, s):
12141214
while remain and len(remain) >= 4:
12151215
l = ActionIDPacketListField._get_action_id_length(remain)
12161216
if l < 4 or len(remain) < l:
1217-
# length is 4 (may be more for experimenter messages),
1218-
# and no incoherent length
1217+
# length is 4 (may be more for experimenter messages),
1218+
# and no incoherent length
12191219
break
12201220
current = remain[:l]
12211221
remain = remain[l:]
@@ -1317,8 +1317,8 @@ def getfield(self, pkt, s):
13171317
while remain and len(remain) > 4:
13181318
l = InstructionPacketListField._get_instruction_length(remain)
13191319
if l < 8 or len(remain) < l:
1320-
# length should be at least 8 (non-zero, 64-bit aligned),
1321-
# and no incoherent length
1320+
# length should be at least 8 (non-zero, 64-bit aligned),
1321+
# and no incoherent length
13221322
break
13231323
current = remain[:l]
13241324
remain = remain[l:]
@@ -1392,8 +1392,8 @@ def getfield(self, pkt, s):
13921392
while remain and len(remain) >= 4:
13931393
l = InstructionIDPacketListField._get_instruction_id_length(remain)
13941394
if l < 4 or len(remain) < l:
1395-
# length is 4 (may be more for experimenter messages),
1396-
# and no incoherent length
1395+
# length is 4 (may be more for experimenter messages),
1396+
# and no incoherent length
13971397
break
13981398
current = remain[:l]
13991399
remain = remain[l:]
@@ -3019,7 +3019,7 @@ def getfield(self, pkt, s):
30193019
# add padding !
30203020
lpad = l + (8 - l%8)%8
30213021
if l < 4 or len(remain) < lpad:
3022-
# no zero length nor incoherent length
3022+
# no zero length nor incoherent length
30233023
break
30243024
current = remain[:lpad]
30253025
remain = remain[lpad:]

scapy/error.py

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -45,16 +45,8 @@ def filter(self, record):
4545
self.warning_table[caller] = (tm,nb)
4646
return 1
4747

48-
try:
49-
from logging import NullHandler
50-
except ImportError:
51-
# compat for python 2.6
52-
from logging import Handler
53-
class NullHandler(Handler):
54-
def emit(self, record):
55-
pass
5648
log_scapy = logging.getLogger("scapy")
57-
log_scapy.addHandler(NullHandler())
49+
log_scapy.addHandler(logging.NullHandler())
5850
log_runtime = logging.getLogger("scapy.runtime") # logs at runtime
5951
log_runtime.addFilter(ScapyFreqFilter())
6052
log_interactive = logging.getLogger("scapy.interactive") # logs in interactive functions

0 commit comments

Comments
 (0)