diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2522474fbe26429a5c0735f60b522661b9051342..5e101fada831c63b4d0aabb1278779ef61883986 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -110,6 +110,13 @@ parsed from a string (during a network capture or a PCAP file read). Adding inefficient code here will have a disastrous effect on Scapy's performances. +### Python 2 and 3 compatibility + +The project aims to provide code that works both on Python 2 and Python 3. Therefore, some rules need to be apply to achieve compatibility: +- byte-string must be defined as `b"\x00\x01\x02"` +- exceptions must comply with the new Python 3 format: `except SomeError as e:` +- lambdas must be written using a single argument when using tuples: use `lambda x_y: x_y[0] + f(x_y[1])` instead of `lambda (x, y): x + f(y)`. + ### Code review Maintainers tend to be picky, and you might feel frustrated that your diff --git a/dev/scripts/autoFixer.py b/dev/scripts/autoFixer.py index efb54c7584c8dec22b5fe9192b72246642c04d62..ae8e8e10649a9d321fd57e2e446031c4a659a9d0 100644 --- a/dev/scripts/autoFixer.py +++ b/dev/scripts/autoFixer.py @@ -15,7 +15,7 @@ def main(): opts, args = getopt.getopt(sys.argv[1:], "t:") if not args: raise getopt.error, "At least one file argument required" - except getopt.error, msg: + except getopt.error as msg: print msg print "usage:", sys.argv[0], "files ..." return @@ -43,7 +43,7 @@ def process(filename, tabsize): f = open(filename) text = f.read() f.close() - except IOError, msg: + except IOError as msg: print "%r: I/O error: %s" % (filename, msg) return # Remove tabs diff --git a/scapy/arch/bpf/core.py b/scapy/arch/bpf/core.py index e862810cbeaf6a53463cdf575caf5124afc27a85..75a6035bc66a005bbbb5962c1f3ead479d72e2c1 100644 --- a/scapy/arch/bpf/core.py +++ b/scapy/arch/bpf/core.py @@ -51,7 +51,7 @@ def get_if_raw_addr(ifname): # Get ifconfig output try: fd = os.popen("%s %s" % (conf.prog.ifconfig, ifname)) - except OSError, msg: + except OSError as msg: warning("Failed to execute ifconfig: (%s)" % msg) return b"\0\0\0\0" @@ -78,7 +78,7 @@ def get_if_raw_hwaddr(ifname): # Get ifconfig output try: fd = os.popen("%s %s" % (conf.prog.ifconfig, ifname)) - except OSError, msg: + except OSError as msg: raise Scapy_Exception("Failed to execute ifconfig: (%s)" % msg) # Get MAC addresses @@ -104,7 +104,7 @@ def get_dev_bpf(): try: fd = os.open("/dev/bpf%i" % bpf, os.O_RDWR) return (fd, bpf) - except OSError, err: + except OSError as err: continue raise Scapy_Exception("No /dev/bpf handle is available !") @@ -117,7 +117,7 @@ def attach_filter(fd, iface, bpf_filter_string): command = "%s -i %s -ddd -s 1600 '%s'" % (conf.prog.tcpdump, iface, bpf_filter_string) try: f = os.popen(command) - except OSError, msg: + except OSError as msg: raise Scapy_Exception("Failed to execute tcpdump: (%s)" % msg) # Convert the byte code to a BPF program structure @@ -154,7 +154,7 @@ def get_if_list(): # Get ifconfig output try: fd = os.popen("%s -a" % conf.prog.ifconfig) - except OSError, msg: + except OSError as msg: raise Scapy_Exception("Failed to execute ifconfig: (%s)" % msg) # Get interfaces @@ -184,7 +184,7 @@ def get_working_ifaces(): # Get interface flags try: result = get_if(ifname, SIOCGIFFLAGS) - except IOError, msg: + except IOError as msg: warning("ioctl(SIOCGIFFLAGS) failed on %s !" % ifname) continue @@ -201,7 +201,7 @@ def get_working_ifaces(): try: fcntl.ioctl(fd, BIOCSETIF, struct.pack("16s16x", ifname)) interfaces.append((ifname, int(ifname[-1]))) - except IOError, err: + except IOError as err: pass # Close the file descriptor diff --git a/scapy/arch/bpf/supersocket.py b/scapy/arch/bpf/supersocket.py index 5d03c1bdd1259bddf418db5b2f90b642067406b9..41865be43a2dcc7da4d55e26c12cc239893e4e1e 100644 --- a/scapy/arch/bpf/supersocket.py +++ b/scapy/arch/bpf/supersocket.py @@ -56,14 +56,14 @@ class _L2bpfSocket(SuperSocket): # Set the BPF buffer length try: fcntl.ioctl(self.ins, BIOCSBLEN, struct.pack('I', BPF_BUFFER_LENGTH)) - except IOError, err: + except IOError as err: msg = "BIOCSBLEN failed on /dev/bpf%i" % self.dev_bpf raise Scapy_Exception(msg) # Assign the network interface to the BPF handle try: fcntl.ioctl(self.ins, BIOCSETIF, struct.pack("16s16x", self.iface)) - except IOError, err: + except IOError as err: msg = "BIOCSETIF failed on %s" % self.iface raise Scapy_Exception(msg) self.assigned_interface = self.iface @@ -75,7 +75,7 @@ class _L2bpfSocket(SuperSocket): # Don't block on read try: fcntl.ioctl(self.ins, BIOCIMMEDIATE, struct.pack('I', 1)) - except IOError, err: + except IOError as err: msg = "BIOCIMMEDIATE failed on /dev/bpf%i" % self.dev_bpf raise Scapy_Exception(msg) @@ -83,7 +83,7 @@ class _L2bpfSocket(SuperSocket): # Otherwise, it is written by the kernel try: fcntl.ioctl(self.ins, BIOCSHDRCMPLT, struct.pack('i', 1)) - except IOError, err: + except IOError as err: msg = "BIOCSHDRCMPLT failed on /dev/bpf%i" % self.dev_bpf raise Scapy_Exception(msg) @@ -105,7 +105,7 @@ class _L2bpfSocket(SuperSocket): try: fcntl.ioctl(self.ins, BIOCPROMISC, struct.pack('i', value)) - except IOError, err: + except IOError as err: msg = "Can't put your interface (%s) into promiscuous mode !" % self.iface raise Scapy_Exception(msg) @@ -120,7 +120,7 @@ class _L2bpfSocket(SuperSocket): try: ret = fcntl.ioctl(self.ins, BIOCGDLT, struct.pack('I', 0)) ret = struct.unpack('I', ret)[0] - except IOError, err: + except IOError as err: warning("BIOCGDLT failed: unable to guess type. Using Ethernet !") return Ether @@ -143,7 +143,7 @@ class _L2bpfSocket(SuperSocket): if self.fd_flags is None: try: self.fd_flags = fcntl.fcntl(self.ins, fcntl.F_GETFL) - except IOError, err: + except IOError as err: warning("Can't get flags on this file descriptor !") return @@ -165,7 +165,7 @@ class _L2bpfSocket(SuperSocket): try: ret = fcntl.ioctl(self.ins, BIOCGSTATS, struct.pack("2I", 0, 0)) return struct.unpack("2I", ret) - except IOError, err: + except IOError as err: warning("Unable to get stats from BPF !") return (None, None) @@ -175,7 +175,7 @@ class _L2bpfSocket(SuperSocket): try: ret = fcntl.ioctl(self.ins, BIOCGBLEN, struct.pack("I", 0)) return struct.unpack("I", ret)[0] - except IOError, err: + except IOError as err: warning("Unable to get the BPF buffer length") return @@ -282,7 +282,7 @@ class L2bpfListenSocket(_L2bpfSocket): # Get data from BPF try: bpf_buffer = os.read(self.ins, x) - except EnvironmentError, e: + except EnvironmentError as e: if e.errno == errno.EAGAIN: return else: @@ -333,7 +333,7 @@ class L3bpfSocket(L2bpfSocket): if self.assigned_interface != iff: try: fcntl.ioctl(self.outs, BIOCSETIF, struct.pack("16s16x", iff)) - except IOError, err: + except IOError as err: msg = "BIOCSETIF failed on %s" % iff raise Scapy_Exception(msg) self.assigned_interface = iff diff --git a/scapy/arch/linux.py b/scapy/arch/linux.py index f153caeeec67bfce759db656e62eff1ab1d241e0..8d4d7d662cf25cd1bf840bde9b3ecf5ed4e5818c 100644 --- a/scapy/arch/linux.py +++ b/scapy/arch/linux.py @@ -137,7 +137,7 @@ def attach_filter(s, bpf_filter, iface): conf.iface if iface is None else iface, bpf_filter, )) - except OSError,msg: + except OSError as msg: log_interactive.warning("Failed to execute tcpdump: (%s)") return lines = f.readlines() @@ -282,7 +282,7 @@ def in6_getifaddr(): ret = [] try: f = open("/proc/net/if_inet6","r") - except IOError, err: + except IOError as err: return ret l = f.readlines() for i in l: @@ -296,7 +296,7 @@ def in6_getifaddr(): def read_routes6(): try: f = open("/proc/net/ipv6_route","r") - except IOError, err: + except IOError as err: return [] # 1. destination network # 2. destination prefix length @@ -359,9 +359,9 @@ else: def _flush_fd(fd): - if type(fd) is not int: + if hasattr(fd, 'fileno'): fd = fd.fileno() - while 1: + while True: r,w,e = select([fd],[],[],0) if r: os.read(fd,MTU) @@ -457,7 +457,7 @@ class L3PacketSocket(SuperSocket): x.sent_time = time.time() try: self.outs.sendto(sx, sdto) - except socket.error, msg: + except socket.error as msg: if msg[0] == 22 and len(sx) < conf.min_pkt_size: self.outs.send(sx + b"\x00" * (conf.min_pkt_size - len(sx))) elif conf.auto_fragment and msg[0] == 90: @@ -522,7 +522,7 @@ class L2Socket(SuperSocket): def send(self, x): try: return SuperSocket.send(self, x) - except socket.error, msg: + except socket.error as msg: if msg[0] == 22 and len(x) < conf.min_pkt_size: padding = b"\x00" * (conf.min_pkt_size - len(x)) if isinstance(x, Packet): diff --git a/scapy/arch/pcapdnet.py b/scapy/arch/pcapdnet.py index 415cf86b2f381983ef3053115a7a1a67e6cd2340..b43b77c3ba27366ee7ac7f455e3605866bbd6df9 100644 --- a/scapy/arch/pcapdnet.py +++ b/scapy/arch/pcapdnet.py @@ -335,10 +335,10 @@ if conf.use_winpcapy: if conf.use_pcap: try: import pcap - except ImportError,e: + except ImportError as e: try: import pcapy as pcap - except ImportError,e2: + except ImportError as e2: if conf.interactive: log_loading.error("Unable to import pcap module: %s/%s" % (e,e2)) conf.use_pcap = False @@ -483,7 +483,7 @@ if conf.use_dnet: except ImportError: # Then, try to import dumbnet as dnet import dumbnet as dnet - except ImportError,e: + except ImportError as e: if conf.interactive: log_loading.error("Unable to import dnet module: %s" % e) conf.use_dnet = False diff --git a/scapy/arch/unix.py b/scapy/arch/unix.py index f85f4b6ef44e3e189d28ed0764edc1ce7ccbcd07..f73ee70c4a086240c71af732c2a89a77095e1cc6 100644 --- a/scapy/arch/unix.py +++ b/scapy/arch/unix.py @@ -148,7 +148,7 @@ def _in6_getifaddr(ifname): # Get the output of ifconfig try: f = os.popen("%s %s" % (conf.prog.ifconfig, ifname)) - except OSError,msg: + except OSError as msg: log_interactive.warning("Failed to execute ifconfig.") return [] @@ -188,7 +188,7 @@ def in6_getifaddr(): if OPENBSD: try: f = os.popen("%s" % conf.prog.ifconfig) - except OSError,msg: + except OSError as msg: log_interactive.warning("Failed to execute ifconfig.") return [] @@ -202,7 +202,7 @@ def in6_getifaddr(): else: # FreeBSD, NetBSD or Darwin try: f = os.popen("%s -l" % conf.prog.ifconfig) - except OSError,msg: + except OSError as msg: log_interactive.warning("Failed to execute ifconfig.") return [] diff --git a/scapy/arch/windows/__init__.py b/scapy/arch/windows/__init__.py index defeaef17caf66d41f073406fa3e721f864d222d..0bb5ed5cf6c6d7fd919f7fb1e09c22fb807538da 100755 --- a/scapy/arch/windows/__init__.py +++ b/scapy/arch/windows/__init__.py @@ -547,7 +547,7 @@ def pcapname(dev): device name. """ - if type(dev) is NetworkInterface: + if isinstance(dev, NetworkInterface): if dev.is_invalid(): return None return dev.pcap_name diff --git a/scapy/arch/windows/compatibility.py b/scapy/arch/windows/compatibility.py index 0f717c5cbf8daf4ae09d348aa8207254ffdf5cbb..a9f92a02ac0bcded8082289850262123c8203610 100644 --- a/scapy/arch/windows/compatibility.py +++ b/scapy/arch/windows/compatibility.py @@ -97,7 +97,7 @@ def sndrcv(pks, pkt, timeout = 2, inter = 0, verbose=None, chainCC=0, retry=0, m remaintime = None try: try: - while 1: + while True: if stoptime: remaintime = stoptime-time.time() if remaintime <= 0: @@ -206,7 +206,7 @@ stop_filter: python function applied to each packet to determine if timeout is not None: stoptime = time.time()+timeout remain = None - while 1: + while True: try: if timeout is not None: remain = stoptime-time.time() diff --git a/scapy/as_resolvers.py b/scapy/as_resolvers.py index 606d3c4d942cd0658251e5ba105c5496645533fe..d52b4000e4ac68c516d176c7d399dd2ca0d407d9 100644 --- a/scapy/as_resolvers.py +++ b/scapy/as_resolvers.py @@ -79,7 +79,7 @@ class AS_resolver_cymru(AS_resolver): s.connect((self.server,self.port)) s.send("begin\r\n"+"\r\n".join(ips)+"\r\nend\r\n") r = "" - while 1: + while True: l = s.recv(8192) if l == "": break diff --git a/scapy/asn1/asn1.py b/scapy/asn1/asn1.py index 973b24337cf7d5799b964acdf7f3dd6808ed1c21..f44dc7257cb0e1e507149ba4b2f4b9a4a9a3a54f 100644 --- a/scapy/asn1/asn1.py +++ b/scapy/asn1/asn1.py @@ -104,7 +104,7 @@ class ASN1Tag(EnumElement): def get_codec(self, codec): try: c = self._codec[codec] - except KeyError,msg: + except KeyError as msg: raise ASN1_Error("Codec %r not found for tag %r" % (codec, self)) return c @@ -118,7 +118,7 @@ class ASN1_Class_metaclass(Enum_metaclass): rdict = {} for k,v in dct.iteritems(): - if type(v) is int: + if isinstance(v, int): v = ASN1Tag(k,v) dct[k] = v rdict[v] = v diff --git a/scapy/asn1/ber.py b/scapy/asn1/ber.py index 42d61ccfeb645e4480e7ddeb13bb360ecc4a6556..e9b871aee789b7327eb3bc5dc29bfc14bd5a2646 100644 --- a/scapy/asn1/ber.py +++ b/scapy/asn1/ber.py @@ -241,12 +241,12 @@ class BERcodec_Object: return cls.do_dec(s, context, safe) try: return cls.do_dec(s, context, safe) - except BER_BadTag_Decoding_Error,e: + except BER_BadTag_Decoding_Error as e: o,remain = BERcodec_Object.dec(e.remaining, context, safe) return ASN1_BADTAG(o),remain - except BER_Decoding_Error, e: + except BER_Decoding_Error as e: return ASN1_DECODING_ERROR(s, exc=e),"" - except ASN1_Error, e: + except ASN1_Error as e: return ASN1_DECODING_ERROR(s, exc=e),"" @classmethod @@ -256,7 +256,7 @@ class BERcodec_Object: @classmethod def enc(cls, s): - if type(s) is str: + if isinstance(s, basestring): return BERcodec_STRING.enc(s) else: return BERcodec_INTEGER.enc(int(s)) @@ -273,7 +273,7 @@ class BERcodec_INTEGER(BERcodec_Object): @classmethod def enc(cls, i): s = [] - while 1: + while True: s.append(i&0xff) if -127 <= i < 0: break @@ -405,7 +405,7 @@ class BERcodec_SEQUENCE(BERcodec_Object): tag = ASN1_Class_UNIVERSAL.SEQUENCE @classmethod def enc(cls, l): - if type(l) is not str: + if not isinstance(l, str): l = "".join(x.enc(cls.codec) for x in l) return chr(cls.tag)+BER_len_enc(len(l))+l @classmethod @@ -418,7 +418,7 @@ class BERcodec_SEQUENCE(BERcodec_Object): while s: try: o,s = BERcodec_Object.dec(s, context, safe) - except BER_Decoding_Error, err: + except BER_Decoding_Error as err: err.remaining += t if err.decoded is not None: obj.append(err.decoded) diff --git a/scapy/asn1/mib.py b/scapy/asn1/mib.py index 59dc5b9617e728b881f39d9ddb25f00ad73c07ec..ed1d581db4d48c905cd2cccf25122747e1dc95a2 100644 --- a/scapy/asn1/mib.py +++ b/scapy/asn1/mib.py @@ -90,7 +90,7 @@ def mib_register(ident, value, the_mib, unresolved): v = the_mib[v] elif v in unresolved: v = unresolved[v] - if type(v) is list: + if isinstance(v, list): resval += v else: resval.append(v) @@ -119,7 +119,7 @@ def load_mib(filenames): for k in conf.mib.iterkeys(): mib_register(k, conf.mib[k].split("."), the_mib, unresolved) - if type(filenames) is str: + if isinstance(filenames, str): filenames = [filenames] for fnames in filenames: for fname in glob(fnames): diff --git a/scapy/asn1fields.py b/scapy/asn1fields.py index 7262736ff3e5ceace629bfaeb814d5b440d43a3a..5ed6ce673ddca2245f434305faf5f933aaf055e2 100644 --- a/scapy/asn1fields.py +++ b/scapy/asn1fields.py @@ -15,6 +15,7 @@ from scapy.volatile import * from scapy.base_classes import BasePacket from scapy.utils import binrepr from scapy import packet +from functools import reduce class ASN1F_badsequence(Exception): pass @@ -40,7 +41,7 @@ class ASN1F_field(ASN1F_element): self.name = name if default is None: self.default = None - elif type(default) is ASN1_NULL: + elif isinstance(default, ASN1_NULL): self.default = default else: self.default = self.ASN1_tag.asn1_object(default) @@ -127,7 +128,7 @@ class ASN1F_field(ASN1F_element): def do_copy(self, x): if hasattr(x, "copy"): return x.copy() - if type(x) is list: + if isinstance(x, list): x = x[:] for i in xrange(len(x)): if isinstance(x[i], BasePacket): @@ -170,7 +171,7 @@ class ASN1F_enum_INTEGER(ASN1F_INTEGER): explicit_tag=explicit_tag) i2s = self.i2s = {} s2i = self.s2i = {} - if type(enum) is list: + if isinstance(enum, list): keys = xrange(len(enum)) else: keys = enum.keys() @@ -310,7 +311,7 @@ class ASN1F_SEQUENCE(ASN1F_field): for obj in self.seq: try: s = obj.dissect(pkt, s) - except ASN1F_badsequence,e: + except ASN1F_badsequence as e: break if len(s) > 0: raise BER_Decoding_Error("unexpected remainder", remaining=s) @@ -444,7 +445,7 @@ class ASN1F_CHOICE(ASN1F_field): else: self.choices[p.ASN1_root.network_tag] = p elif hasattr(p, "ASN1_tag"): - if type(p) is type: # should be ASN1F_field class + if isinstance(p, type): # should be ASN1F_field class self.choices[p.ASN1_tag] = p else: # should be ASN1F_PACKET instance self.choices[p.network_tag] = p @@ -471,7 +472,7 @@ class ASN1F_CHOICE(ASN1F_field): if hasattr(choice, "ASN1_root"): # we don't want to import ASN1_Packet in this module... return self.extract_packet(choice, s) - elif type(choice) is type: + elif isinstance(choice, type): #XXX find a way not to instantiate the ASN1F_field return choice(self.name, "").m2i(pkt, s) else: @@ -493,7 +494,7 @@ class ASN1F_CHOICE(ASN1F_field): if hasattr(p, "ASN1_root"): # should be ASN1_Packet class randchoices.append(packet.fuzz(p())) elif hasattr(p, "ASN1_tag"): - if type(p) is type: # should be (basic) ASN1F_field class + if isinstance(p, type): # should be (basic) ASN1F_field class randchoices.append(p("dummy", None).randval()) else: # should be ASN1F_PACKET instance randchoices.append(p.randval()) diff --git a/scapy/automaton.py b/scapy/automaton.py index b39e08b3f111fe210ace5c7314dddd3b2912237c..a10f02292f7b7dbd8a083764be06a961d8fe27d7 100644 --- a/scapy/automaton.py +++ b/scapy/automaton.py @@ -48,21 +48,21 @@ class Message: class _instance_state: def __init__(self, instance): - self.im_self = instance.im_self - self.im_func = instance.im_func - self.im_class = instance.im_class + self.__self__ = instance.__self__ + self.__func__ = instance.__func__ + self.__self__.__class__ = instance.__self__.__class__ def __getattr__(self, attr): - return getattr(self.im_func, attr) + return getattr(self.__func__, attr) def __call__(self, *args, **kargs): - return self.im_func(self.im_self, *args, **kargs) + return self.__func__(self.__self__, *args, **kargs) def breaks(self): - return self.im_self.add_breakpoints(self.im_func) + return self.__self__.add_breakpoints(self.__func__) def intercepts(self): - return self.im_self.add_interception_points(self.im_func) + return self.__self__.add_interception_points(self.__func__) def unbreaks(self): - return self.im_self.remove_breakpoints(self.im_func) + return self.__self__.remove_breakpoints(self.__func__) def unintercepts(self): - return self.im_self.remove_interception_points(self.im_func) + return self.__self__.remove_interception_points(self.__func__) ############## @@ -102,16 +102,16 @@ class ATMT: def state(initial=0,final=0,error=0): def deco(f,initial=initial, final=final): f.atmt_type = ATMT.STATE - f.atmt_state = f.func_name + f.atmt_state = f.__name__ f.atmt_initial = initial f.atmt_final = final f.atmt_error = error def state_wrapper(self, *args, **kargs): return ATMT.NewStateRequested(f, self, *args, **kargs) - state_wrapper.func_name = "%s_wrapper" % f.func_name + state_wrapper.__name__ = "%s_wrapper" % f.__name__ state_wrapper.atmt_type = ATMT.STATE - state_wrapper.atmt_state = f.func_name + state_wrapper.atmt_state = f.__name__ state_wrapper.atmt_initial = initial state_wrapper.atmt_final = final state_wrapper.atmt_error = error @@ -132,7 +132,7 @@ class ATMT: def deco(f, state=state): f.atmt_type = ATMT.CONDITION f.atmt_state = state.atmt_state - f.atmt_condname = f.func_name + f.atmt_condname = f.__name__ f.atmt_prio = prio return f return deco @@ -141,7 +141,7 @@ class ATMT: def deco(f, state=state): f.atmt_type = ATMT.RECV f.atmt_state = state.atmt_state - f.atmt_condname = f.func_name + f.atmt_condname = f.__name__ f.atmt_prio = prio return f return deco @@ -150,7 +150,7 @@ class ATMT: def deco(f, state=state): f.atmt_type = ATMT.IOEVENT f.atmt_state = state.atmt_state - f.atmt_condname = f.func_name + f.atmt_condname = f.__name__ f.atmt_ioname = name f.atmt_prio = prio f.atmt_as_supersocket = as_supersocket @@ -162,7 +162,7 @@ class ATMT: f.atmt_type = ATMT.TIMEOUT f.atmt_state = state.atmt_state f.atmt_timeout = timeout - f.atmt_condname = f.func_name + f.atmt_condname = f.__name__ return f return deco @@ -192,7 +192,7 @@ class _ATMT_supersocket(SuperSocket): def fileno(self): return self.spa.fileno() def send(self, s): - if type(s) is not str: + if not isinstance(s, str): s = str(s) return self.spa.send(s) def recv(self, n=MTU): @@ -235,7 +235,7 @@ class Automaton_metaclass(type): members[k] = v decorated = [v for v in members.itervalues() - if type(v) is types.FunctionType and hasattr(v, "atmt_type")] + if isinstance(v, types.FunctionType) and hasattr(v, "atmt_type")] for m in decorated: if m.atmt_type == ATMT.STATE: @@ -296,7 +296,7 @@ class Automaton_metaclass(type): s += se for st in self.states.itervalues(): - for n in st.atmt_origfunc.func_code.co_names+st.atmt_origfunc.func_code.co_consts: + for n in st.atmt_origfunc.__code__.co_names+st.atmt_origfunc.__code__.co_consts: if n in self.states: s += '\t"%s" -> "%s" [ color=green ];\n' % (st.atmt_state,n) @@ -305,21 +305,21 @@ class Automaton_metaclass(type): [("red",k,v) for k,v in self.recv_conditions.items()]+ [("orange",k,v) for k,v in self.ioevents.items()]): for f in v: - for n in f.func_code.co_names+f.func_code.co_consts: + for n in f.__code__.co_names+f.__code__.co_consts: if n in self.states: l = f.atmt_condname for x in self.actions[f.atmt_condname]: - l += "\\l>[%s]" % x.func_name + l += "\\l>[%s]" % x.__name__ s += '\t"%s" -> "%s" [label="%s", color=%s];\n' % (k,n,l,c) for k,v in self.timeout.iteritems(): for t,f in v: if f is None: continue - for n in f.func_code.co_names+f.func_code.co_consts: + for n in f.__code__.co_names+f.__code__.co_consts: if n in self.states: l = "%s/%.1fs" % (f.atmt_condname,t) for x in self.actions[f.atmt_condname]: - l += "\\l>[%s]" % x.func_name + l += "\\l>[%s]" % x.__name__ s += '\t"%s" -> "%s" [label="%s",color=blue];\n' % (k,n,l) s += "}\n" return do_graph(s, **kargs) @@ -375,9 +375,9 @@ class Automaton: else: raise OSError("On windows, only instances of ObjectPipe are externally available") else: - if rd is not None and type(rd) is not int: + if rd is not None and not isinstance(rd, int): rd = rd.fileno() - if wr is not None and type(wr) is not int: + if wr is not None and not isinstance(wr, int): wr = wr.fileno() self.rd = rd self.wr = wr @@ -403,7 +403,7 @@ class Automaton: self.rd = rd self.wr = wr def fileno(self): - if type(self.rd) is int: + if isinstance(self.rd, int): return self.rd return self.rd.fileno() def recv(self, n=None): @@ -496,18 +496,18 @@ class Automaton: self.ioout = {} for n in self.ionames: extfd = external_fd.get(n) - if type(extfd) is not tuple: + if not isinstance(extfd, tuple): extfd = (extfd,extfd) elif WINDOWS: raise OSError("Tuples are not allowed as external_fd on windows") ioin,ioout = extfd if ioin is None: ioin = ObjectPipe() - elif type(ioin) is not types.InstanceType: + elif not isinstance(ioin, types.InstanceType): ioin = self._IO_fdwrapper(ioin,None) if ioout is None: ioout = ObjectPipe() - elif type(ioout) is not types.InstanceType: + elif not isinstance(ioout, types.InstanceType): ioout = self._IO_fdwrapper(None,ioout) self.ioin[n] = ioin @@ -535,16 +535,16 @@ class Automaton: try: self.debug(5, "Trying %s [%s]" % (cond.atmt_type, cond.atmt_condname)) cond(self,*args, **kargs) - except ATMT.NewStateRequested, state_req: + except ATMT.NewStateRequested as state_req: self.debug(2, "%s [%s] taken to state [%s]" % (cond.atmt_type, cond.atmt_condname, state_req.state)) if cond.atmt_type == ATMT.RECV: if self.store_packets: self.packets.append(args[0]) for action in self.actions[cond.atmt_condname]: - self.debug(2, " + Running action [%s]" % action.func_name) + self.debug(2, " + Running action [%s]" % action.__name__) action(self, *state_req.action_args, **state_req.action_kargs) raise - except Exception,e: + except Exception as e: self.debug(2, "%s [%s] raised exception [%s]" % (cond.atmt_type, cond.atmt_condname, e)) raise else: @@ -600,10 +600,10 @@ class Automaton: c = Message(type=_ATMT_Command.SINGLESTEP,state=state) self.cmdout.send(c) break - except StopIteration,e: + except StopIteration as e: c = Message(type=_ATMT_Command.END, result=e.args[0]) self.cmdout.send(c) - except Exception,e: + except Exception as e: exc_info = sys.exc_info() self.debug(3, "Transfering exception from tid=%i:\n%s"% (self.threadid, traceback.format_exc(exc_info))) m = Message(type=_ATMT_Command.EXCEPTION, exception=e, exc_info=exc_info) @@ -631,7 +631,7 @@ class Automaton: if state_output is None: state_output = () - elif type(state_output) is not list: + elif not isinstance(state_output, list): state_output = state_output, # Then check immediate conditions @@ -655,7 +655,7 @@ class Automaton: fds.append(self.listen_sock) for ioev in self.ioevents[self.state.state]: fds.append(self.ioin[ioev.atmt_ioname]) - while 1: + while True: t = time.time()-t0 if next_timeout is not None: if next_timeout <= t: @@ -688,7 +688,7 @@ class Automaton: if ioevt.atmt_ioname == fd.ioname: self._run_condition(ioevt, fd, *state_output) - except ATMT.NewStateRequested,state_req: + except ATMT.NewStateRequested as state_req: self.debug(2, "switching from [%s] to [%s]" % (self.state.state,state_req.state)) self.state = state_req yield state_req diff --git a/scapy/autorun.py b/scapy/autorun.py index b64a46a4c15fe6e21493925074e8eb0c38301375..eafe4dbb6caaec411602891e509aa6844c22dc3f 100644 --- a/scapy/autorun.py +++ b/scapy/autorun.py @@ -50,7 +50,7 @@ def autorun_commands(cmds,my_globals=None,verb=0): cmds.append("") # ensure we finish multi-line commands cmds.reverse() __builtin__.__dict__["_"] = None - while 1: + while True: if cmd: sys.stderr.write(sys.__dict__.get("ps2","... ")) else: @@ -87,7 +87,7 @@ def autorun_get_interactive_session(cmds, **kargs): try: sys.stdout = sys.stderr = sw res = autorun_commands(cmds, **kargs) - except StopAutorun,e: + except StopAutorun as e: e.code_run = sw.s raise finally: @@ -119,7 +119,7 @@ def autorun_get_html_interactive_session(cmds, **kargs): try: conf.color_theme = HTMLTheme2() s,res = autorun_get_interactive_session(cmds, **kargs) - except StopAutorun,e: + except StopAutorun as e: e.code_run = to_html(e.code_run) raise finally: @@ -134,7 +134,7 @@ def autorun_get_latex_interactive_session(cmds, **kargs): try: conf.color_theme = LatexTheme2() s,res = autorun_get_interactive_session(cmds, **kargs) - except StopAutorun,e: + except StopAutorun as e: e.code_run = to_latex(e.code_run) raise finally: diff --git a/scapy/base_classes.py b/scapy/base_classes.py index 8dfb967fff0a563d54b76c0aa6b5c4804a4e8f4c..eb9976da2a423825458b71bb159caffa6237c771 100644 --- a/scapy/base_classes.py +++ b/scapy/base_classes.py @@ -131,10 +131,10 @@ class OID(Gen): return "OID(%r)" % self.oid def __iter__(self): ii = [k[0] for k in self.cmpt] - while 1: + while True: yield self.fmt % tuple(ii) i = 0 - while 1: + while True: if i >= len(ii): raise StopIteration if ii[i] < self.cmpt[i][1]: diff --git a/scapy/config.py b/scapy/config.py index 4b93dc719fd317f6606bbbec1f30c7e183c1e5e1..6c9cf8c255b23721e4bbd8b4bdb48b23a3cda1c4 100755 --- a/scapy/config.py +++ b/scapy/config.py @@ -77,9 +77,9 @@ class ConfigFieldList: def _is_field(f): return hasattr(f, "owners") def _recalc_layer_list(self): - self.layers = set([owner for f in self.fields for owner in f.owners]) + self.layers = {owner for f in self.fields for owner in f.owners} def add(self, *flds): - self.fields |= set([f for f in flds if self._is_field(f)]) + self.fields |= {f for f in flds if self._is_field(f)} self._recalc_layer_list() def remove(self, *flds): self.fields -= set(flds) diff --git a/scapy/contrib/bgp.py b/scapy/contrib/bgp.py index c67a4db9d7dc3a8478f373142e34a49e19913091..2ac22cb7cdc0b63fc5805efcf803b00d2adc3184 100644 --- a/scapy/contrib/bgp.py +++ b/scapy/contrib/bgp.py @@ -2045,7 +2045,7 @@ class BGPPathAttr(Packet): # Set default flags value ? if self.type_flags is None: # Set the standard value, if it is exists in attributes_flags. - if attributes_flags.has_key(self.type_code): + if self.type_code in attributes_flags: flags_value = attributes_flags.get(self.type_code) # Otherwise, set to optional, non-transitive. diff --git a/scapy/contrib/dtp.py b/scapy/contrib/dtp.py index a3f7a54e9352c195d745c8a49b024a6f9dee57a5..208f6bacbccf58281e7b1de8c001901fa11fa2c6 100644 --- a/scapy/contrib/dtp.py +++ b/scapy/contrib/dtp.py @@ -34,6 +34,7 @@ from scapy.packet import * from scapy.fields import * from scapy.layers.l2 import SNAP,Dot3,LLC from scapy.sendrecv import sendp +from functools import reduce class DtpGenericTlv(Packet): name = "DTP Generic TLV" diff --git a/scapy/contrib/eigrp.py b/scapy/contrib/eigrp.py index 7a688d3fb043cb6eff2e0012a89591a82c225890..b931c9d0a6e52800a352d3ecd16d8863a70c8bc4 100644 --- a/scapy/contrib/eigrp.py +++ b/scapy/contrib/eigrp.py @@ -47,6 +47,7 @@ from scapy.packet import * from scapy.fields import * from scapy.layers.inet import IP from scapy.layers.inet6 import * +from functools import reduce class EigrpIPField(StrField, IPField): """ @@ -265,13 +266,13 @@ class ShortVersionField(ShortField): Valid numbers are between 0 and 255. """ - if type(x) is str and x.startswith("v") and len(x) <= 8: + if isinstance(x, str) and x.startswith("v") and len(x) <= 8: major = int(x.split(".")[0][1:]) minor = int(x.split(".")[1]) return (major << 8) | minor - elif type(x) is int and 0 <= x <= 65535: + elif isinstance(x, int) and 0 <= x <= 65535: return x else: if self.default != None: diff --git a/scapy/contrib/gsm_um.py b/scapy/contrib/gsm_um.py index 07403af0f847bbcc865f35a7f9d5a1657b515e75..7f370e17b58aede9025414c4572ba7cc4adceac9 100644 --- a/scapy/contrib/gsm_um.py +++ b/scapy/contrib/gsm_um.py @@ -49,7 +49,7 @@ from scapy.fields import * def sendum(x, typeSock=0): try: - if type(x) is not str: + if not isinstance(x, str): x = str(x) if typeSock is 0: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) diff --git a/scapy/contrib/http2.py b/scapy/contrib/http2.py index e760b997b84034bf0c911ec9f8cfb79126e5134b..7b37a95961e7691dba8ebf846b47f0e61a2e9000 100644 --- a/scapy/contrib/http2.py +++ b/scapy/contrib/http2.py @@ -193,7 +193,7 @@ class AbstractUVarIntField(fields.Field): @return None @raise AssertionError """ - assert(isinstance(default, types.NoneType) or (isinstance(default, (int, long)) and default >= 0)) + assert(default is None or (isinstance(default, (int, long)) and default >= 0)) assert(0 < size <= 8) super(AbstractUVarIntField, self).__init__(name, default) self.size = size @@ -335,7 +335,7 @@ class AbstractUVarIntField(fields.Field): @return int|None: the converted value. @raise AssertionError """ - if isinstance(x, types.NoneType): + if isinstance(x, type(None)): return x if isinstance(x, (int, long)): assert(x >= 0) @@ -503,7 +503,7 @@ class UVarIntField(AbstractUVarIntField): @raise AssertionError """ ret = super(UVarIntField, self).h2i(pkt, x) - assert(not isinstance(ret, types.NoneType) and ret >= 0) + assert(not isinstance(ret, type(None)) and ret >= 0) return ret def i2h(self, pkt, x): @@ -516,7 +516,7 @@ class UVarIntField(AbstractUVarIntField): @raise AssertionError """ ret = super(UVarIntField, self).i2h(pkt, x) - assert(not isinstance(ret, types.NoneType) and ret >= 0) + assert(not isinstance(ret, type(None)) and ret >= 0) return ret def any2i(self, pkt, x): @@ -529,7 +529,7 @@ class UVarIntField(AbstractUVarIntField): @raise AssertionError """ ret = super(UVarIntField, self).any2i(pkt, x) - assert(not isinstance(ret, types.NoneType) and ret >= 0) + assert(not isinstance(ret, type(None)) and ret >= 0) return ret def i2repr(self, pkt, x): @@ -1039,9 +1039,9 @@ class HPackZString(HPackStringsInterface): assert(i >= 0) assert(ibl >= 0) - if isinstance(cls.static_huffman_tree, types.NoneType): + if isinstance(cls.static_huffman_tree, type(None)): cls.huffman_compute_decode_tree() - assert(not isinstance(cls.static_huffman_tree, types.NoneType)) + assert(not isinstance(cls.static_huffman_tree, type(None))) s = [] j = 0 @@ -1058,7 +1058,7 @@ class HPackZString(HPackStringsInterface): if isinstance(elmt, HuffmanNode): interrupted = True cur = elmt - if isinstance(cur, types.NoneType): + if isinstance(cur, type(None)): raise AssertionError() elif isinstance(elmt, EOS): raise InvalidEncodingException('Huffman decoder met the full EOS symbol') @@ -2237,7 +2237,7 @@ class HPackHdrTable(Sized): @param int dynamic_table_cap_size: the maximum-maximum size of the dynamic entry table in bytes @raises AssertionError """ - if isinstance(type(self)._static_entries_last_idx, types.NoneType): + if isinstance(type(self)._static_entries_last_idx, type(None)): type(self).init_static_table() assert dynamic_table_max_size <= dynamic_table_cap_size, \ diff --git a/scapy/contrib/isis.py b/scapy/contrib/isis.py index 818acba883a72a4fe9b5e706e20dcb8a8995e2aa..cb709e1dec9d0f7eb73caba1c70986f715e068c9 100644 --- a/scapy/contrib/isis.py +++ b/scapy/contrib/isis.py @@ -136,7 +136,7 @@ class _ISIS_IdFieldBase(Field): return self.to_id(x) def any2i(self, pkt, x): - if type(x) is str and len(x) == self.length: + if isinstance(x, str) and len(x) == self.length: return self.m2i(pkt, x) return x diff --git a/scapy/contrib/ldp.py b/scapy/contrib/ldp.py index b27b39699166e681c418893d583e618a078d7b00..12019aaf6b63824ef6e07280c09df53566a47dbb 100644 --- a/scapy/contrib/ldp.py +++ b/scapy/contrib/ldp.py @@ -79,7 +79,7 @@ class FecTLVField(StrField): x=x[4+nbroctets:] return list def i2m(self, pkt, x): - if type(x) is str: + if isinstance(x, str): return x s = b"\x01\x00" l = 0 @@ -109,7 +109,7 @@ class LabelTLVField(StrField): def m2i(self, pkt, x): return struct.unpack("!I",x[4:8])[0] def i2m(self, pkt, x): - if type(x) is str: + if isinstance(x, str): return x s = b"\x02\x00\x00\x04" s += struct.pack("!I",x) @@ -137,7 +137,7 @@ class AddressTLVField(StrField): list.append(inet_ntoa(add)) return list def i2m(self, pkt, x): - if type(x) is str: + if isinstance(x, str): return x l=2+len(x)*4 s = b"\x01\x01"+struct.pack("!H",l)+b"\x00\x01" @@ -167,7 +167,7 @@ class StatusTLVField(StrField): l.append( struct.unpack("!H", x[12:14])[0] ) return l def i2m(self, pkt, x): - if type(x) is str: + if isinstance(x, str): return x s = b"\x03\x00" + struct.pack("!H",10) statuscode = 0 @@ -205,7 +205,7 @@ class CommonHelloTLVField(StrField): list.append(v) return list def i2m(self, pkt, x): - if type(x) is str: + if isinstance(x, str): return x s = b"\x04\x00\x00\x04" s += struct.pack("!H",x[0]) @@ -236,7 +236,7 @@ class CommonSessionTLVField(StrField): l.append( struct.unpack("!H",x[16:18])[0] ) return l def i2m(self, pkt, x): - if type(x) is str: + if isinstance(x, str): return x s = b"\x05\x00\x00\x0E\x00\x01" s += struct.pack("!H",x[0]) diff --git a/scapy/contrib/ppi_geotag.py b/scapy/contrib/ppi_geotag.py index a7f30c984f5cc8d3c8db1d0952dd24fde2c98341..47b3d83f35526248e7da04ca37ac7a1893a1cdfb 100644 --- a/scapy/contrib/ppi_geotag.py +++ b/scapy/contrib/ppi_geotag.py @@ -210,7 +210,7 @@ class VectorFlags_Field(XLEIntField): sout = "+".join(r) return sout def any2i(self, pkt, x): - if type(x) is str: + if isinstance(x, str): r = x.split("+") y = 0 for value in r: diff --git a/scapy/contrib/send.py b/scapy/contrib/send.py index c4fb0f2c8dd769c9ee663e796a7863efc5612e16..af9620b059f620207bee1cfb23af3648db102f4e 100644 --- a/scapy/contrib/send.py +++ b/scapy/contrib/send.py @@ -38,12 +38,12 @@ class HashField(Field): def __init__(self, name, default): Field.__init__(self, name, default, "16s") def h2i(self, pkt, x): - if type(x) is str: + if isinstance(x, str): try: x = in6_ptop(x) except socket.error: x = Net6(x) - elif type(x) is list: + elif isinstance(x, list): x = [Net6(e) for e in x] return x def i2m(self, pkt, x): diff --git a/scapy/contrib/skinny.py b/scapy/contrib/skinny.py index b4d7642e1481caa42acfcdaefbce70fe3679bad9..e21979e361ca33aa64d05e3a6bfc917428dc4256 100644 --- a/scapy/contrib/skinny.py +++ b/scapy/contrib/skinny.py @@ -208,13 +208,13 @@ class SkinnyDateTimeField(StrFixedLenField): return (year, month, day, hour, min, sec) def i2m(self, pkt, val): - if type(val) is str: + if isinstance(val, str): val = self.h2i(pkt, val) l= val[:2] + (0,) + val[2:7] + (0,) return struct.pack('<8I', *l) def i2h(self, pkt, x): - if type(x) is str: + if isinstance(x, str): return x else: return time.ctime(time.mktime(x+(0,0,0))) @@ -224,7 +224,7 @@ class SkinnyDateTimeField(StrFixedLenField): def h2i(self, pkt, s): t = () - if type(s) is str: + if isinstance(s, str): t = time.strptime(s) t = t[:2] + t[2:-3] else: diff --git a/scapy/dadict.py b/scapy/dadict.py index c6cf847794c5289f59ccd27693bae49421090ddf..67cb8515e7d782100aa6aba3fbaabace2c95b2b2 100644 --- a/scapy/dadict.py +++ b/scapy/dadict.py @@ -35,7 +35,7 @@ class DADict: def __setitem__(self, attr, val): return setattr(self, self.fixname(attr), val) def __iter__(self): - return iter(map(lambda (x,y):y,filter(lambda (x,y):x and x[0]!="_", self.__dict__.items()))) + return iter(map(lambda x_y1: x_y1[1],filter(lambda x_y: x_y[0] and x_y[0][0]!="_", self.__dict__.items()))) def _show(self): for k in self.__dict__.keys(): if k and k[0] != "_": diff --git a/scapy/data.py b/scapy/data.py index 6189b4671f4f48eeeea3f7077e63ba552280ae43..33224223078ac413755f272fab8c9e56e0f836a5 100644 --- a/scapy/data.py +++ b/scapy/data.py @@ -77,7 +77,7 @@ def load_protocols(filename): if len(lt) < 2 or not lt[0]: continue dct[lt[0]] = int(lt[1]) - except Exception,e: + except Exception as e: log_loading.info("Couldn't parse file [%s]: line [%r] (%s)" % (filename,l,e)) except IOError: log_loading.info("Can't open %s file" % filename) @@ -100,10 +100,10 @@ def load_ethertypes(filename): if len(lt) < 2 or not lt[0]: continue dct[lt[0]] = int(lt[1], 16) - except Exception,e: + except Exception as e: log_loading.info("Couldn't parse file [%s]: line [%r] (%s)" % (filename,l,e)) f.close() - except IOError,msg: + except IOError as msg: pass return dct @@ -128,7 +128,7 @@ def load_services(filename): tdct[lt[0]] = int(lt[1].split('/')[0]) elif lt[1].endswith("/udp"): udct[lt[0]] = int(lt[1].split('/')[0]) - except Exception,e: + except Exception as e: log_loading.warning("Couldn't file [%s]: line [%r] (%s)" % (filename,l,e)) f.close() except IOError: @@ -171,7 +171,7 @@ def load_manuf(filename): else: lng = l[i+2:] manufdb[oui] = shrt, lng - except Exception,e: + except Exception as e: log_loading.warning("Couldn't parse one line from [%s] [%r] (%s)" % (filename, l, e)) except IOError: log_loading.warning("Couldn't open [%s] file" % filename) diff --git a/scapy/fields.py b/scapy/fields.py index 140dc92a0136c63457febe4ec3ee8ffdc93d2e1e..da2e4c9867a023369eea87e85e949f713c1f5186 100644 --- a/scapy/fields.py +++ b/scapy/fields.py @@ -78,7 +78,7 @@ class Field(object): def do_copy(self, x): if hasattr(x, "copy"): return x.copy() - if type(x) is list: + if isinstance(x, list): x = x[:] for i in xrange(len(x)): if isinstance(x[i], BasePacket): @@ -208,7 +208,7 @@ class MACField(Field): def m2i(self, pkt, x): return str2mac(x) def any2i(self, pkt, x): - if type(x) is str and len(x) is 6: + if isinstance(x, str) and len(x) is 6: x = self.m2i(pkt, x) return x def i2repr(self, pkt, x): @@ -230,7 +230,7 @@ class IPField(Field): inet_aton(x) except socket.error: x = Net(x) - elif type(x) is list: + elif isinstance(x, list): x = [self.h2i(pkt, n) for n in x] return x def resolve(self, x): @@ -380,7 +380,7 @@ class StrField(Field): def i2m(self, pkt, x): if x is None: x = "" - elif type(x) is not str: + elif not isinstance(x, str): x=str(x) return x def addfield(self, pkt, s, val): @@ -440,12 +440,12 @@ class PacketListField(PacketField): def any2i(self, pkt, x): - if type(x) is not list: + if not isinstance(x, list): return [x] else: return x def i2count(self, pkt, val): - if type(val) is list: + if isinstance(val, list): return len(val) return 1 def i2len(self, pkt, val): @@ -500,7 +500,7 @@ class StrFixedLenField(StrField): if length is not None: self.length_from = lambda pkt,length=length: length def i2repr(self, pkt, v): - if type(v) is str: + if isinstance(v, str): v = v.rstrip(b"\0") return repr(v) def getfield(self, pkt, s): @@ -607,7 +607,7 @@ class FieldListField(Field): self.length_from = length_from def i2count(self, pkt, val): - if type(val) is list: + if isinstance(val, list): return len(val) return 1 def i2len(self, pkt, val): @@ -618,7 +618,7 @@ class FieldListField(Field): val = [] return val def any2i(self, pkt, x): - if type(x) is not list: + if not isinstance(x, list): return [self.field.any2i(pkt, x)] else: return [self.field.any2i(pkt, e) for e in x] @@ -730,7 +730,7 @@ class BitField(Field): def addfield(self, pkt, s, val): val = self.i2m(pkt, val) - if type(s) is tuple: + if isinstance(s, tuple): s,bitsdone,v = s else: bitsdone = 0 @@ -749,7 +749,7 @@ class BitField(Field): else: return s def getfield(self, pkt, s): - if type(s) is tuple: + if isinstance(s, tuple): s,bn = s else: bn = 0 @@ -795,7 +795,7 @@ class BitFieldLenField(BitField): self.count_of = count_of self.adjust = adjust def i2m(self, pkt, x): - return FieldLenField.i2m.im_func(self, pkt, x) + return FieldLenField.i2m.__func__(self, pkt, x) class XBitField(BitField): @@ -830,11 +830,11 @@ class _EnumField(Field): s2i = self.s2i = {} self.i2s_cb = None self.s2i_cb = None - if type(enum) is list: + if isinstance(enum, list): keys = range(len(enum)) else: keys = enum.keys() - if any(type(x) is str for x in keys): + if any(isinstance(x, str) for x in keys): i2s, s2i = s2i, i2s for k in keys: i2s[k] = enum[k] @@ -842,7 +842,7 @@ class _EnumField(Field): Field.__init__(self, name, default, fmt) def any2i_one(self, pkt, x): - if type(x) is str: + if isinstance(x, str): try: x = self.s2i[x] except TypeError: @@ -862,13 +862,13 @@ class _EnumField(Field): return repr(x) def any2i(self, pkt, x): - if type(x) is list: + if isinstance(x, list): return [self.any2i_one(pkt, z) for z in x] else: return self.any2i_one(pkt,x) def i2repr(self, pkt, x): - if type(x) is list: + if isinstance(x, list): return [self.i2repr_one(pkt, z) for z in x] else: return self.i2repr_one(pkt,x) @@ -957,7 +957,7 @@ class _MultiEnumField(_EnumField): self.s2i_all[v] = k Field.__init__(self, name, default, fmt) def any2i_one(self, pkt, x): - if type (x) is str: + if isinstance(x, str): v = self.depends_on(pkt) if v in self.s2i_multi: s2i = self.s2i_multi[v] @@ -1151,7 +1151,7 @@ class MultiFlagsField(BitField): else: v = self.depends_on(pkt) if v is not None: - assert self.names.has_key(v), 'invalid dependency' + assert v in self.names, 'invalid dependency' these_names = self.names[v] s = set() for i in x: @@ -1204,7 +1204,7 @@ class MultiFlagsField(BitField): def i2repr(self, pkt, x): v = self.depends_on(pkt) - if self.names.has_key(v): + if v in self.names: these_names = self.names[v] else: these_names = {} diff --git a/scapy/layers/all.py b/scapy/layers/all.py index f23fae1c3d0a0bcc286b438bf076ba8647e9d4c8..6624bec58dbbda63ac6e77d56af6c37ba828907c 100644 --- a/scapy/layers/all.py +++ b/scapy/layers/all.py @@ -33,6 +33,6 @@ for _l in conf.load_layers: try: if _l != "tls": _import_star(_l) - except Exception,e: + except Exception as e: log.warning("can't import layer %s: %s" % (_l,e)) diff --git a/scapy/layers/bluetooth.py b/scapy/layers/bluetooth.py index e17aac08352b4f8e4f72641705b9127aba3f5ca6..cb845062ceaeedcf4991de46c4b35b10cf60c38a 100644 --- a/scapy/layers/bluetooth.py +++ b/scapy/layers/bluetooth.py @@ -44,7 +44,7 @@ class LEMACField(Field): def m2i(self, pkt, x): return str2mac(x[::-1]) def any2i(self, pkt, x): - if type(x) is str and len(x) is 6: + if isinstance(x, str) and len(x) is 6: x = self.m2i(pkt, x) return x def i2repr(self, pkt, x): diff --git a/scapy/layers/dhcp.py b/scapy/layers/dhcp.py index 96094066867c80793e04bc946dfe7b0ea40f657e..f17191d616a5c94fd859f4f0a74e0ee15f9d58d6 100644 --- a/scapy/layers/dhcp.py +++ b/scapy/layers/dhcp.py @@ -145,7 +145,7 @@ DHCPOptions = { DHCPRevOptions = {} for k,v in DHCPOptions.iteritems(): - if type(v) is str: + if isinstance(v, str): n = v v = None else: @@ -173,7 +173,7 @@ class RandDHCPOptions(RandField): op = [] for k in xrange(self.size): o = random.choice(self._opts) - if type(o) is str: + if isinstance(o, str): op.append((o,self.rndstr*1)) else: op.append((o.name, o.randval()._fix())) @@ -185,8 +185,8 @@ class DHCPOptionsField(StrField): def i2repr(self,pkt,x): s = [] for v in x: - if type(v) is tuple and len(v) >= 2: - if DHCPRevOptions.has_key(v[0]) and isinstance(DHCPRevOptions[v[0]][1],Field): + if isinstance(v, tuple) and len(v) >= 2: + if v[0] in DHCPRevOptions and isinstance(DHCPRevOptions[v[0]][1],Field): f = DHCPRevOptions[v[0]][1] vv = ",".join(f.i2repr(pkt,val) for val in v[1:]) else: @@ -214,7 +214,7 @@ class DHCPOptionsField(StrField): if len(x) < 2 or len(x) < ord(x[1])+2: opt.append(x) break - elif DHCPOptions.has_key(o): + elif o in DHCPOptions: f = DHCPOptions[o] if isinstance(f, str): @@ -242,17 +242,17 @@ class DHCPOptionsField(StrField): x = x[olen+2:] return opt def i2m(self, pkt, x): - if type(x) is str: + if isinstance(x, str): return x s = "" for o in x: - if type(o) is tuple and len(o) >= 2: + if isinstance(o, tuple) and len(o) >= 2: name = o[0] lval = o[1:] if isinstance(name, int): onum, oval = name, "".join(lval) - elif DHCPRevOptions.has_key(name): + elif name in DHCPRevOptions: onum, f = DHCPRevOptions[name] if f is not None: lval = [f.addfield(pkt,"",f.any2i(pkt,val)) for val in lval] @@ -265,12 +265,12 @@ class DHCPOptionsField(StrField): s += chr(len(oval)) s += oval - elif (type(o) is str and DHCPRevOptions.has_key(o) and + elif (isinstance(o, str) and o in DHCPRevOptions and DHCPRevOptions[o][1] == None): s += chr(DHCPRevOptions[o][0]) - elif type(o) is int: + elif isinstance(o, int): s += chr(o)+b"\0" - elif type(o) is str: + elif isinstance(o, str): s += o else: warning("Malformed option %s" % o) @@ -336,8 +336,8 @@ class BOOTP_am(AnsweringMachine): def make_reply(self, req): mac = req.src - if type(self.pool) is list: - if not self.leases.has_key(mac): + if isinstance(self.pool, list): + if mac not in self.leases: self.leases[mac] = self.pool.pop() ip = self.leases[mac] else: @@ -361,7 +361,7 @@ class DHCP_am(BOOTP_am): if DHCP in req: dhcp_options = [(op[0],{1:2,3:5}.get(op[1],op[1])) for op in req[DHCP].options - if type(op) is tuple and op[0] == "message-type"] + if isinstance(op, tuple) and op[0] == "message-type"] dhcp_options += [("server_id",self.gw), ("domain", self.domain), ("router", self.gw), diff --git a/scapy/layers/dhcp6.py b/scapy/layers/dhcp6.py index 57deef952bcab9ef21ed2f15480cdaf5781cb004..7887a8d3c7de41d0b9270b288b45340b232a27ad 100644 --- a/scapy/layers/dhcp6.py +++ b/scapy/layers/dhcp6.py @@ -378,7 +378,7 @@ class _OptReqListField(StrLenField): def i2repr(self, pkt, x): s = [] for y in self.i2h(pkt, x): - if dhcp6opts.has_key(y): + if y in dhcp6opts: s.append(dhcp6opts[y]) else: s.append("%d" % y) @@ -1267,9 +1267,9 @@ dhcp6d( dns="2001:500::1035", domain="localdomain, local", duid=None) def norm_list(val, param_name): if val is None: return None - if type(val) is list: + if isinstance(val, list): return val - elif type(val) is str: + elif isinstance(val, str): l = val.split(',') return [x.strip() for x in l] else: @@ -1307,8 +1307,7 @@ dhcp6d( dns="2001:500::1035", domain="localdomain, local", duid=None) if self.debug: print "\n[+] List of active DHCPv6 options:" - opts = self.dhcpv6_options.keys() - opts.sort() + opts = sorted(self.dhcpv6_options.keys()) for i in opts: print " %d: %s" % (i, repr(self.dhcpv6_options[i])) @@ -1409,7 +1408,7 @@ dhcp6d( dns="2001:500::1035", domain="localdomain, local", duid=None) return False # provided server DUID must match ours duid = p[DHCP6OptServerId].duid - if (type(duid) != type(self.duid)): + if not isinstance(duid, type(self.duid)): return False if str(duid) != str(self.duid): return False @@ -1474,7 +1473,7 @@ dhcp6d( dns="2001:500::1035", domain="localdomain, local", duid=None) elif p.msgtype == 11: # Information-Request if DHCP6OptServerId in p: duid = p[DHCP6OptServerId].duid - if (type(duid) != type(self.duid)): + if not isinstance(duid, type(self.duid)): return False if str(duid) != str(self.duid): return False diff --git a/scapy/layers/dns.py b/scapy/layers/dns.py index 945b085ee85c5f20ab360580ae6d08cdce1d0c3b..2080e4adeda3242592ce25bab553bd8cf34eb53a 100644 --- a/scapy/layers/dns.py +++ b/scapy/layers/dns.py @@ -17,6 +17,7 @@ from scapy.sendrecv import sr1 from scapy.layers.inet import IP, DestIPField, UDP, TCP from scapy.layers.inet6 import DestIP6Field from scapy.error import warning +from functools import reduce class DNSStrField(StrField): @@ -42,7 +43,7 @@ class DNSStrField(StrField): if ord(s[0]) == 0: return s[1:], "." - while 1: + while True: l = ord(s[0]) s = s[1:] if not l: @@ -82,7 +83,7 @@ def DNSgetstr(s,p): name = "" q = 0 jpath = [p] - while 1: + while True: if p >= len(s): warning("DNS RR prematured end (ofs=%i, len=%i)"%(p,len(s))) break @@ -139,7 +140,7 @@ class DNSRRField(StrField): rr.rrname = name return rr,p def getfield(self, pkt, s): - if type(s) is tuple : + if isinstance(s, tuple) : s,p = s else: p = 0 @@ -365,7 +366,7 @@ dnssecdigesttypes = { 0:"Reserved", 1:"SHA-1", 2:"SHA-256", 3:"GOST R 34.11-94", class TimeField(IntField): def any2i(self, pkt, x): - if type(x) == str: + if isinstance(x, str): import time, calendar t = time.strptime(x, "%Y%m%d%H%M%S") return int(calendar.timegm(t)) @@ -428,8 +429,7 @@ def RRlist2bitmap(lst): import math bitmap = "" - lst = list(set(lst)) - lst.sort() + lst = sorted(set(lst)) lst = [abs(x) for x in lst if x <= 65535] @@ -442,8 +442,7 @@ def RRlist2bitmap(lst): for wb in xrange(min_window_blocks, max_window_blocks+1): # First, filter out RR not encoded in the current window block # i.e. keep everything between 256*wb <= 256*(wb+1) - rrlist = filter(lambda x: 256 * wb <= x < 256 * (wb + 1), lst) - rrlist.sort() + rrlist = sorted(filter(lambda x: 256 * wb <= x < 256 * (wb + 1), lst)) if rrlist == []: continue @@ -477,7 +476,7 @@ def RRlist2bitmap(lst): class RRlistField(StrField): def h2i(self, pkt, x): - if type(x) == list: + if isinstance(x, list): return RRlist2bitmap(x) return x diff --git a/scapy/layers/inet.py b/scapy/layers/inet.py index 26b476e0401ae7e2bbcade3166e5f0539f05b60d..f969dc5e9d5d0a8302e513b35a221d35f2399be7 100644 --- a/scapy/layers/inet.py +++ b/scapy/layers/inet.py @@ -44,8 +44,7 @@ class IPTools(object): else: os.system("whois %s" % self.src) def ottl(self): - t = [32,64,128,255]+[self.ttl] - t.sort() + t = sorted([32,64,128,255]+[self.ttl]) return t[t.index(self.ttl)+1] def hops(self): return self.ottl() - self.ttl @@ -269,7 +268,7 @@ class TCPOptionsField(StrField): warning("Malformed TCP option (announced length is %i)" % olen) olen = 2 oval = x[2:olen] - if TCPOptions[0].has_key(onum): + if onum in TCPOptions[0]: oname, ofmt = TCPOptions[0][onum] if onum == 5: #SAck ofmt += "%iI" % (len(oval)/4) @@ -286,20 +285,20 @@ class TCPOptionsField(StrField): def i2m(self, pkt, x): opt = "" for oname,oval in x: - if type(oname) is str: + if isinstance(oname, str): if oname == "NOP": opt += b"\x01" continue elif oname == "EOL": opt += b"\x00" continue - elif TCPOptions[1].has_key(oname): + elif oname in TCPOptions[1]: onum = TCPOptions[1][oname] ofmt = TCPOptions[0][onum][1] if onum == 5: #SAck ofmt += "%iI" % len(oval) - if ofmt is not None and (type(oval) is not str or "s" in ofmt): - if type(oval) is not tuple: + if ofmt is not None and (not isinstance(oval, str) or "s" in ofmt): + if not isinstance(oval, tuple): oval = (oval,) oval = struct.pack(ofmt, *oval) else: @@ -307,7 +306,7 @@ class TCPOptionsField(StrField): continue else: onum = oname - if type(oval) is not str: + if not isinstance(oval, str): warning("option [%i] is not string."%onum) continue opt += chr(onum)+chr(2+len(oval))+oval @@ -327,7 +326,7 @@ class ICMPTimeStampField(IntField): hour, min = divmod(min, 60) return "%d:%d:%d.%d" %(hour, min, sec, int(milli)) def any2i(self, pkt, val): - if type(val) is str: + if isinstance(val, str): hmsms = self.re_hmsm.match(val) if hmsms: h,_,m,_,s,_,ms = hmsms = hmsms.groups() @@ -1063,9 +1062,9 @@ class TracerouteResult(SndRcvList): self.nloc = None def show(self): - return self.make_table(lambda (s,r): (s.sprintf("%IP.dst%:{TCP:tcp%ir,TCP.dport%}{UDP:udp%ir,UDP.dport%}{ICMP:ICMP}"), - s.ttl, - r.sprintf("%-15s,IP.src% {TCP:%TCP.flags%}{ICMP:%ir,ICMP.type%}"))) + return self.make_table(lambda s_r: (s_r[0].sprintf("%IP.dst%:{TCP:tcp%ir,TCP.dport%}{UDP:udp%ir,UDP.dport%}{ICMP:ICMP}"), + s_r[0].ttl, + s_r[1].sprintf("%-15s,IP.src% {TCP:%TCP.flags%}{ICMP:%ir,ICMP.type%}"))) def get_trace(self): @@ -1159,7 +1158,7 @@ class TracerouteResult(SndRcvList): start = ip.pos movcenter=None - while 1: + while True: visual.rate(50) if visual.scene.kb.keys: k = visual.scene.kb.getkey() @@ -1235,7 +1234,7 @@ class TracerouteResult(SndRcvList): trace_id = (s.src,s.dst,s.proto,0) trace = rt.get(trace_id,{}) if not r.haslayer(ICMP) or r.type != 11: - if ports_done.has_key(trace_id): + if trace_id in ports_done: continue ports_done[trace_id] = None trace[s.ttl] = r.src @@ -1333,9 +1332,9 @@ class TracerouteResult(SndRcvList): trace = rt[rtk] max_trace = max(trace) for n in xrange(min(trace), max_trace): - if not trace.has_key(n): + if n not in trace: trace[n] = unknown_label.next() - if not ports_done.has_key(rtk): + if rtk not in ports_done: if rtk[2] == 1: #ICMP bh = "%s %i/icmp" % (rtk[1],rtk[3]) elif rtk[2] == 6: #TCP @@ -1421,7 +1420,7 @@ class TracerouteResult(SndRcvList): for rtk in rt: - s += "#---[%s\n" % `rtk` + s += "#---[%s\n" % repr(rtk) s += '\t\tedge [color="#%s%s%s"];\n' % forecolorlist.next() trace = rt[rtk] maxtrace = max(trace) @@ -1662,7 +1661,7 @@ def fragleak(target,sport=123, dport=123, timeout=0.2, onlyasc=0): intr=0 found={} try: - while 1: + while True: try: if not intr: s.send(pkt) @@ -1708,7 +1707,7 @@ def fragleak(target,sport=123, dport=123, timeout=0.2, onlyasc=0): def fragleak2(target, timeout=0.4, onlyasc=0): found={} try: - while 1: + while True: p = sr1(IP(dst=target, options=b"\x00"*40, proto=200)/"XXXXYYYYYYYYYYYY",timeout=timeout,verbose=0) if not p: continue diff --git a/scapy/layers/inet6.py b/scapy/layers/inet6.py index b628e389b864db8a3583d9e3fa7402fea25000e5..c35468f5815ba9ffd239491499cc59b750f6d069 100644 --- a/scapy/layers/inet6.py +++ b/scapy/layers/inet6.py @@ -208,12 +208,12 @@ class IP6Field(Field): def __init__(self, name, default): Field.__init__(self, name, default, "16s") def h2i(self, pkt, x): - if type(x) is str: + if isinstance(x, str): try: x = in6_ptop(x) except socket.error: x = Net6(x) - elif type(x) is list: + elif isinstance(x, list): x = [Net6(a) for a in x] return x def i2m(self, pkt, x): @@ -225,7 +225,7 @@ class IP6Field(Field): def i2repr(self, pkt, x): if x is None: return self.i2h(pkt,x) - elif not isinstance(x, Net6) and not type(x) is list: + elif not isinstance(x, Net6) and not isinstance(x, list): if in6_isaddrTeredo(x): # print Teredo info server, flag, maddr, mport = teredoAddrExtractInfo(x) return "%s [Teredo srv: %s cli: %s:%s]" % (self.i2h(pkt, x), server, maddr,mport) @@ -317,7 +317,7 @@ class IP6ListField(StrField): return 16*len(i) def i2count(self, pkt, i): - if type(i) is list: + if isinstance(i, list): return len(i) return 0 @@ -828,7 +828,7 @@ class _HopByHopOptionsField(PacketListField): return l def i2count(self, pkt, i): - if type(i) is list: + if isinstance(i, list): return len(i) return 0 @@ -851,7 +851,7 @@ class _HopByHopOptionsField(PacketListField): c -= 1 o = ord(x[0]) # Option type cls = self.cls - if _hbhoptcls.has_key(o): + if o in _hbhoptcls: cls = _hbhoptcls[o] try: op = cls(x) @@ -2149,7 +2149,7 @@ def names2dnsrepr(x): !!! At the moment, compression is not implemented !!! """ - if type(x) is str: + if isinstance(x, str): if x and x[-1] == b'\x00': # stupid heuristic return x x = [x] @@ -2206,7 +2206,7 @@ class NIQueryDataField(StrField): return val def h2i(self, pkt, x): - if x is tuple and type(x[0]) is int: + if x is tuple and isinstance(x[0], int): return x val = None @@ -2262,7 +2262,7 @@ class NIQueryDataField(StrField): return "", (1, s) def addfield(self, pkt, s, val): - if ((type(val) is tuple and val[1] is None) or + if ((isinstance(val, tuple) and val[1] is None) or val is None): val = (1, "") t = val[0] @@ -2360,7 +2360,7 @@ class NIReplyDataField(StrField): # overridden through 'qtype' in pkt # No user hint, let's use 'qtype' value for that purpose - if type(x) is not tuple: + if not isinstance(x, tuple): if pkt is not None: qtype = getattr(pkt, "qtype") else: @@ -2370,22 +2370,22 @@ class NIReplyDataField(StrField): # From that point on, x is the value (second element of the tuple) if qtype == 2: # DNS name - if type(x) is str: # listify the string + if isinstance(x, str): # listify the string x = [x] - if type(x) is list and x and type(x[0]) is not int: # ttl was omitted : use 0 + if isinstance(x, list) and x and not isinstance(x[0], int): # ttl was omitted : use 0 x = [0] + x ttl = x[0] names = x[1:] return (2, [ttl, names2dnsrepr(names)]) elif qtype in [3, 4]: # IPv4 or IPv6 addr - if type(x) is str: + if isinstance(x, str): x = [x] # User directly provided an IP, instead of list # List elements are not tuples, user probably # omitted ttl value : we will use 0 instead def addttl(x): - if type(x) is str: + if isinstance(x, str): return (0, x) return x @@ -2402,9 +2402,9 @@ class NIReplyDataField(StrField): ttl,dnsstr = tmp return s+ struct.pack("!I", ttl) + dnsstr elif t == 3: - return s + "".join(map(lambda (x,y): struct.pack("!I", x)+inet_pton(socket.AF_INET6, y), tmp)) + return s + "".join(map(lambda x_y1: struct.pack("!I", x_y1[0])+inet_pton(socket.AF_INET6, x_y1[1]), tmp)) elif t == 4: - return s + "".join(map(lambda (x,y): struct.pack("!I", x)+inet_pton(socket.AF_INET, y), tmp)) + return s + "".join(map(lambda x_y2: struct.pack("!I", x_y2[0])+inet_pton(socket.AF_INET, x_y2[1]), tmp)) else: return s + tmp @@ -2450,14 +2450,14 @@ class NIReplyDataField(StrField): if x is None: return "[]" - if type(x) is tuple and len(x) == 2: + if isinstance(x, tuple) and len(x) == 2: t, val = x if t == 2: # DNS names ttl,l = val l = dnsrepr2names(l) return "ttl:%d %s" % (ttl, ", ".join(l)) elif t == 3 or t == 4: - return "[ %s ]" % (", ".join(map(lambda (x,y): "(%d, %s)" % (x, y), val))) + return "[ %s ]" % (", ".join(map(lambda x_y: "(%d, %s)" % (x_y[0], x_y[1]), val))) return repr(val) return repr(x) # XXX should not happen @@ -2877,7 +2877,7 @@ class _MobilityOptionsField(PacketListField): while x: o = ord(x[0]) # Option type cls = self.cls - if moboptcls.has_key(o): + if o in moboptcls: cls = moboptcls[o] try: op = cls(x) @@ -3125,9 +3125,9 @@ class AS_resolver6(AS_resolver_riswhois): class TracerouteResult6(TracerouteResult): __slots__ = [] def show(self): - return self.make_table(lambda (s,r): (s.sprintf("%-42s,IPv6.dst%:{TCP:tcp%TCP.dport%}{UDP:udp%UDP.dport%}{ICMPv6EchoRequest:IER}"), # TODO: ICMPv6 ! - s.hlim, - r.sprintf("%-42s,IPv6.src% {TCP:%TCP.flags%}"+ + return self.make_table(lambda s_r: (s_r[0].sprintf("%-42s,IPv6.dst%:{TCP:tcp%TCP.dport%}{UDP:udp%UDP.dport%}{ICMPv6EchoRequest:IER}"), # TODO: ICMPv6 ! + s_r[0].hlim, + s_r[1].sprintf("%-42s,IPv6.src% {TCP:%TCP.flags%}"+ "{ICMPv6DestUnreach:%ir,type%}{ICMPv6PacketTooBig:%ir,type%}"+ "{ICMPv6TimeExceeded:%ir,type%}{ICMPv6ParamProblem:%ir,type%}"+ "{ICMPv6EchoReply:%ir,type%}"))) diff --git a/scapy/layers/isakmp.py b/scapy/layers/isakmp.py index cf8083fd4aeb01bee3c731b81df8297a62250f59..a18d5231f54c4239242b36759c22e568c5480f0d 100644 --- a/scapy/layers/isakmp.py +++ b/scapy/layers/isakmp.py @@ -15,6 +15,7 @@ from scapy.ansmachine import * from scapy.layers.inet import IP,UDP from scapy.sendrecv import sr from scapy.error import warning +from functools import reduce # see http://www.iana.org/assignments/ipsec-registry for details @@ -101,7 +102,8 @@ del(val) class ISAKMPTransformSetField(StrLenField): islist=1 - def type2num(self, (typ,val)): + def type2num(self, type_val_tuple): + typ, val = type_val_tuple type_val,enc_dict,tlv = ISAKMPTransformTypes.get(typ, (typ,{},0)) val = enc_dict.get(val, val) s = "" diff --git a/scapy/layers/l2.py b/scapy/layers/l2.py index ea9e6e07dd4d9678ed8cc58ab799104cfbf654d7..1e7aa7ed764ba99631183a173103f17197d45f8f 100644 --- a/scapy/layers/l2.py +++ b/scapy/layers/l2.py @@ -1169,7 +1169,7 @@ arpcachepoison(target, victim, [interval=60]) -> None tmac = getmacbyip(target) p = Ether(dst=tmac)/ARP(op="who-has", psrc=victim, pdst=target) try: - while 1: + while True: sendp(p, iface_hint=target) if conf.verb > 1: os.write(1,".") @@ -1262,7 +1262,7 @@ class ARP_am(AnsweringMachine): ether = req.getlayer(Ether) arp = req.getlayer(ARP) - if self.optsend.has_key('iface'): + if 'iface' in self.optsend: iff = self.optsend.get('iface') else: iff,a,gw = conf.route.route(arp.psrc) @@ -1284,7 +1284,7 @@ class ARP_am(AnsweringMachine): return resp def send_reply(self, reply): - if self.optsend.has_key('iface'): + if 'iface' in self.optsend: self.send_function(reply, **self.optsend) else: self.send_function(reply, iface=self.iff, **self.optsend) @@ -1297,7 +1297,7 @@ class ARP_am(AnsweringMachine): def etherleak(target, **kargs): """Exploit Etherleak flaw""" return srpflood(Ether()/ARP(pdst=target), - prn=lambda (s,r): conf.padding_layer in r and hexstr(r[conf.padding_layer].load), + prn=lambda s_r: conf.padding_layer in s_r[1] and hexstr(s_r[1][conf.padding_layer].load), filter="arp", **kargs) diff --git a/scapy/layers/sctp.py b/scapy/layers/sctp.py index 96ae3e261d5fe4e5ae9c6bfd5c519aa972453463..3799a1698e90e019854a5fb7c790f4065c5946de 100644 --- a/scapy/layers/sctp.py +++ b/scapy/layers/sctp.py @@ -476,7 +476,7 @@ class GapAckField(Field): def m2i(self, pkt, x): return "%d:%d"%(struct.unpack(">HH", x)) def any2i(self, pkt, x): - if type(x) is tuple and len(x) == 2: + if isinstance(x, tuple) and len(x) == 2: return "%d:%d"%(x) return x diff --git a/scapy/layers/snmp.py b/scapy/layers/snmp.py index e602e20bef2f55765acd4b605d2f3ceba73b01dc..cb2dc0b734de9462206b864fbabcf4ba203846a9 100644 --- a/scapy/layers/snmp.py +++ b/scapy/layers/snmp.py @@ -244,7 +244,7 @@ bind_layers( UDP, SNMP, dport=162) def snmpwalk(dst, oid="1", community="public"): try: - while 1: + while True: r = sr1(IP(dst=dst)/UDP(sport=RandShort())/SNMP(community=community, PDU=SNMPnext(varbindlist=[SNMPvarbind(oid=oid)])),timeout=2, chainCC=1, verbose=0, retry=2) if ICMP in r: print repr(r) diff --git a/scapy/layers/tls/cert.py b/scapy/layers/tls/cert.py index c5dcd54b03e460c94d69c9a6ed786746787e1ec4..47296a0a590d2c752b27695ea80256da898ede24 100644 --- a/scapy/layers/tls/cert.py +++ b/scapy/layers/tls/cert.py @@ -187,7 +187,7 @@ class _PubKeyFactory(_PKIObjMaker): return obj # This deals with the rare RSA 'kx export' call. - if type(key_path) is tuple: + if isinstance(key_path, tuple): obj = type.__call__(cls) obj.__class__ = PubKeyRSA obj.frmt = "tuple" @@ -671,7 +671,7 @@ class Cert(object): """ if now is None: now = time.localtime() - elif type(now) is str: + elif isinstance(now, str): try: if '/' in now: now = time.strptime(now, '%m/%d/%y') diff --git a/scapy/layers/tls/crypto/cipher_aead.py b/scapy/layers/tls/crypto/cipher_aead.py index dd759bb71f934ea2682c598ca5f8984ea9c7bf1f..b2e755976c996bbb3c4dd5309d71b914936dcc57 100644 --- a/scapy/layers/tls/crypto/cipher_aead.py +++ b/scapy/layers/tls/crypto/cipher_aead.py @@ -68,7 +68,7 @@ class _AEADCipher(object): self.ready["nonce_explicit"] = False nonce_explicit = 0 - if type(nonce_explicit) is str: + if isinstance(nonce_explicit, str): nonce_explicit = pkcs_os2ip(nonce_explicit) # we use super() in order to avoid any deadlock with __setattr__ @@ -92,7 +92,7 @@ class _AEADCipher(object): self._cipher.mode._initialization_vector = iv self.ready["salt"] = True elif name == "nonce_explicit": - if type(val) is str: + if isinstance(val, str): val = pkcs_os2ip(val) iv = self.salt + pkcs_i2osp(val, self.nonce_explicit_len) if self._cipher is not None: diff --git a/scapy/layers/tls/crypto/pkcs1.py b/scapy/layers/tls/crypto/pkcs1.py index d4172a8b241e53f862de37e3311f4122b761f5e7..81273877ee49d11e01bfd1280eb532e16c44de64 100644 --- a/scapy/layers/tls/crypto/pkcs1.py +++ b/scapy/layers/tls/crypto/pkcs1.py @@ -15,6 +15,7 @@ import os, popen2, tempfile import math, random, struct from scapy.config import conf, crypto_validator +from functools import reduce if conf.crypto_valid: from cryptography.exceptions import InvalidSignature from cryptography.hazmat.backends import default_backend @@ -163,7 +164,7 @@ def pkcs_mgf1(mgfSeed, maskLen, h): """ # steps are those of Appendix B.2.1 - if not _hashFuncParams.has_key(h): + if h not in _hashFuncParams: warning("pkcs_mgf1: invalid hash (%s) provided" % h) return None hLen = _hashFuncParams[h][0] @@ -415,7 +416,7 @@ class _EncryptAndVerifyRSA(object): # Set default parameters if not provided if h is None: # By default, sha1 h = "sha1" - if not _hashFuncParams.has_key(h): + if h not in _hashFuncParams: warning("Key._rsassa_pss_verify(): unknown hash function " "provided (%s)" % h) return False @@ -657,7 +658,7 @@ class _DecryptAndSignRSA(object): # Set default parameters if not provided if h is None: # By default, sha1 h = "sha1" - if not _hashFuncParams.has_key(h): + if h not in _hashFuncParams: warning("Key._rsassa_pss_sign(): unknown hash function " "provided (%s)" % h) return None diff --git a/scapy/layers/tls/crypto/suites.py b/scapy/layers/tls/crypto/suites.py index 7605a736e88ac40910ecc151095e7b9952d1f1a0..72452fd6cd08d44b8a5ed8463de73a2589f8e828 100644 --- a/scapy/layers/tls/crypto/suites.py +++ b/scapy/layers/tls/crypto/suites.py @@ -960,7 +960,7 @@ def get_usable_ciphersuites(l, kx): """ res = [] for c in l: - if _tls_cipher_suites_cls.has_key(c): + if c in _tls_cipher_suites_cls: ciph = _tls_cipher_suites_cls[c] if ciph.usable: #XXX select among RSA and ECDSA cipher suites diff --git a/scapy/layers/tls/handshake.py b/scapy/layers/tls/handshake.py index fb3edac72a580d3df29c586e1a2d84520f078d54..2a90e44e990ecd20e126e62226e7d3918c0234bf 100644 --- a/scapy/layers/tls/handshake.py +++ b/scapy/layers/tls/handshake.py @@ -144,7 +144,7 @@ class _CipherSuitesField(StrLenField): if (isinstance(x, _GenericCipherSuite) or isinstance(x, _GenericCipherSuiteMetaclass)): x = x.val - if type(x) is str: + if isinstance(x, str): x = self.s2i[x] return x @@ -153,7 +153,7 @@ class _CipherSuitesField(StrLenField): return self.i2s.get(x, fmt % x) def any2i(self, pkt, x): - if type(x) is not list: + if not isinstance(x, list): x = [x] return [self.any2i_one(pkt, z) for z in x] @@ -190,7 +190,7 @@ class _CompressionMethodsField(_CipherSuitesField): if (isinstance(x, _GenericComp) or isinstance(x, _GenericCompMetaclass)): x = x.val - if type(x) is str: + if isinstance(x, str): x = self.s2i[x] return x @@ -257,7 +257,7 @@ class TLS_Ext_PrettyPacketList(TLS_Ext_Unknown): begn = "%s %-10s%s " % (label_lvl+lvl, ncol(f.name), ct.punct("="),) reprval = f.i2repr(self,fvalue) - if type(reprval) is str: + if isinstance(reprval, str): reprval = reprval.replace("\n", "\n"+" "*(len(label_lvl) +len(lvl) +len(f.name) @@ -269,7 +269,7 @@ class TLS_Ext_PrettyPacketList(TLS_Ext_Unknown): fvalue = self.getfieldval(f.name) begn = "%s %-10s%s " % (label_lvl+lvl, ncol(f.name), ct.punct("="),) reprval = f.i2repr(self,fvalue) - if type(reprval) is str: + if isinstance(reprval, str): reprval = reprval.replace("\n", "\n"+" "*(len(label_lvl) +len(lvl) +len(f.name) @@ -379,7 +379,7 @@ class _TAListField(PacketListField): def m2i(self, pkt, m): idtype = ord(m[0]) cls = self.cls - if _tls_trusted_authority_cls.has_key(idtype): + if idtype in _tls_trusted_authority_cls: cls = _tls_trusted_authority_cls[idtype] return cls(m) @@ -426,7 +426,7 @@ class _StatusReqField(PacketListField): def m2i(self, pkt, m): idtype = pkt.stype cls = self.cls - if _cert_status_req_cls.has_key(idtype): + if idtype in _cert_status_req_cls: cls = _cert_status_req_cls[idtype] return cls(m) @@ -677,7 +677,7 @@ class _ExtensionsLenField(FieldLenField): # compute the length of remaining data to see if there are ext l = getattr(pkt, self.lfld) for fname in self.shifters: - if type(fname) is int: + if isinstance(fname, int): l -= fname else: l -= getattr(pkt, fname) @@ -859,7 +859,7 @@ class TLSServerHello(TLSClientHello): if self.cipher: cs_val = self.cipher - if not _tls_cipher_suites_cls.has_key(cs_val): + if cs_val not in _tls_cipher_suites_cls: warning("Unknown cipher suite %d from ServerHello" % cs_val) # we do not try to set a default nor stop the execution else: @@ -867,7 +867,7 @@ class TLSServerHello(TLSClientHello): if self.comp: comp_val = self.comp[0] - if not _tls_compression_algs_cls.has_key(comp_val): + if comp_val not in _tls_compression_algs_cls: err = "Unknown compression alg %d from ServerHello" % comp_val warning(err) comp_val = 0 @@ -941,7 +941,7 @@ class _ASN1CertListField(StrLenField): def i2m(self, pkt, i): def i2m_one(i): - if type(i) is str: + if isinstance(i, str): return i if isinstance(i, Cert): s = i.der @@ -955,7 +955,7 @@ class _ASN1CertListField(StrLenField): if i is None: return "" - if type(i) is str: + if isinstance(i, str): return i if isinstance(i, Cert): i = [i] @@ -1116,7 +1116,7 @@ class _CertAuthoritiesField(StrLenField): return res def i2m(self, pkt, i): - return "".join(map(lambda (x,y): struct.pack("!H", x) + y, i)) + return "".join(map(lambda x_y: struct.pack("!H", x_y[0]) + x_y[1], i)) def addfield(self, pkt, s, val): return s + self.i2m(pkt, val) @@ -1363,7 +1363,7 @@ class _StatusField(PacketField): def m2i(self, pkt, m): idtype = pkt.status_type cls = self.cls - if _cert_status_cls.has_key(idtype): + if idtype in _cert_status_cls: cls = _cert_status_cls[idtype] return cls(m) diff --git a/scapy/layers/tls/session.py b/scapy/layers/tls/session.py index a7951e07fb52d2c3a6f10effc61910de9957250f..a74dd41ab3b45616af7df918c2bef8ecbdd94fb9 100644 --- a/scapy/layers/tls/session.py +++ b/scapy/layers/tls/session.py @@ -530,7 +530,7 @@ class _tls_sessions(object): return h = session.hash() - if self.sessions.has_key(h): + if h in self.sessions: self.sessions[h].append(session) else: self.sessions[h] = [session] @@ -546,7 +546,7 @@ class _tls_sessions(object): def find(self, session): h = session.hash() - if self.sessions.has_key(h): + if h in self.sessions: for k in self.sessions[h]: if k.eq(session): if conf.tls_verbose: diff --git a/scapy/layers/x509.py b/scapy/layers/x509.py index ba713dfb5018997205d54bb6f9372827db5dd75a..eb1e64d3e0746c9554dd5cd4dddb118c81b0dfc2 100644 --- a/scapy/layers/x509.py +++ b/scapy/layers/x509.py @@ -648,7 +648,7 @@ class ASN1F_EXT_SEQUENCE(ASN1F_SEQUENCE): if not self.flexible_tag and len(s) > 0: err_msg = "extension sequence length issue" raise BER_Decoding_Error(err_msg, remaining=s) - except ASN1F_badsequence,e: + except ASN1F_badsequence as e: raise Exception("could not parse extensions") return remain diff --git a/scapy/main.py b/scapy/main.py index 098a53b6ffe0e84a19238b6d12a42083299aeb95..3c91cd341a30859e030cde830ba8455d96940107 100644 --- a/scapy/main.py +++ b/scapy/main.py @@ -29,10 +29,10 @@ def _probe_config_file(cf): def _read_config_file(cf): log_loading.debug("Loading config file [%s]" % cf) try: - execfile(cf) - except IOError,e: + exec(compile(open(cf).read(), cf, 'exec')) + except IOError as e: log_loading.warning("Cannot read config file [%s] [%s]" % (cf,e)) - except Exception,e: + except Exception as e: log_loading.exception("Error during evaluation of config file [%s]" % cf) @@ -68,7 +68,7 @@ def _load(module): for name, sym in mod.__dict__.iteritems(): if name[0] != '_': __builtin__.__dict__[name] = sym - except Exception,e: + except Exception as e: log_interactive.error(e) def load_module(name): @@ -130,11 +130,11 @@ def save_session(fname=None, session=None, pickleProto=-1): to_be_saved = session.copy() - if to_be_saved.has_key("__builtins__"): + if "__builtins__" in to_be_saved: del(to_be_saved["__builtins__"]) for k in to_be_saved.keys(): - if type(to_be_saved[k]) in [types.TypeType, types.ClassType, types.ModuleType]: + if type(to_be_saved[k]) in [type, type, types.ModuleType]: log_interactive.error("[%s] (%s) can't be saved." % (k, type(to_be_saved[k]))) del(to_be_saved[k]) @@ -236,7 +236,7 @@ def scapy_write_history_file(readline): if conf.histfile: try: readline.write_history_file(conf.histfile) - except IOError,e: + except IOError as e: try: warning("Could not write history to [%s]\n\t (%s)" % (conf.histfile,e)) tmp = utils.get_temp_file(keep=True) @@ -345,7 +345,7 @@ def interact(mydict=None,argv=None,mybanner=None,loglevel=20): raise getopt.GetoptError("Too many parameters : [%s]" % " ".join(opts[1])) - except getopt.GetoptError, msg: + except getopt.GetoptError as msg: log_loading.error(msg) sys.exit(1) @@ -373,7 +373,7 @@ def interact(mydict=None,argv=None,mybanner=None,loglevel=20): try: import IPython IPYTHON=True - except ImportError, e: + except ImportError as e: log_loading.warning("IPython not available. Using standard Python shell instead.") IPYTHON=False @@ -385,7 +385,7 @@ def interact(mydict=None,argv=None,mybanner=None,loglevel=20): args = [''] # IPython command line args (will be seen as sys.argv) ipshell = IPython.Shell.IPShellEmbed(args, banner = banner) ipshell(local_ns=session) - except AttributeError, e: + except AttributeError as e: pass # In the IPython cookbook, see 'Updating-code-for-use-with-IPython-0.11-and-later' diff --git a/scapy/modules/p0f.py b/scapy/modules/p0f.py index 6953dea42dc010c2fc366f4ff4b248e8e5119e32..39ce61905198cdde4f730547453b383925651b13 100644 --- a/scapy/modules/p0f.py +++ b/scapy/modules/p0f.py @@ -173,7 +173,7 @@ def packet2p0f(pkt): if ilen > 0: qqP = True else: - if type(option[0]) is str: + if isinstance(option[0], str): ooo += "?%i," % TCPOptions[1][option[0]] else: ooo += "?%i," % option[0] diff --git a/scapy/modules/queso.py b/scapy/modules/queso.py index 9c38f42735e3c27a6b92186d7b3e5755b162164d..aba6c248fd10672e8a70e743908bb296621ab193 100644 --- a/scapy/modules/queso.py +++ b/scapy/modules/queso.py @@ -56,7 +56,7 @@ class QuesoKnowledgeBase(KnowledgeBase): res = l[2:].split() res[-1] = quesoTCPflags(res[-1]) res = " ".join(res) - if not p.has_key(res): + if res not in p: p[res] = {} p = p[res] if p is not None: @@ -100,7 +100,7 @@ def queso_search(sig): while sig: s = sig.pop() p = p[s] - if p.has_key(""): + if "" in p: ret.append(p[""]) except KeyError: pass diff --git a/scapy/packet.py b/scapy/packet.py index 6bc1db5ce23fd599560dce2f8a9d3bf903d6fd12..588d9fbf02ec09978af88307d9c9a09ae7304db6 100644 --- a/scapy/packet.py +++ b/scapy/packet.py @@ -123,7 +123,7 @@ class Packet(BasePacket): self.dissection_done(self) for f, v in fields.iteritems(): self.fields[f] = self.get_field(f).any2i(self, v) - if type(post_transform) is list: + if isinstance(post_transform, list): self.post_transforms = post_transform elif post_transform is None: self.post_transforms = [] @@ -169,10 +169,10 @@ class Packet(BasePacket): self.payload = payload payload.add_underlayer(self) for t in self.aliastypes: - if payload.overload_fields.has_key(t): + if t in payload.overload_fields: self.overloaded_fields = payload.overload_fields[t] break - elif type(payload) is str: + elif isinstance(payload, str): self.payload = conf.raw_layer(load=payload) else: raise TypeError("payload must be either 'Packet' or 'str', not [%s]" % repr(payload)) @@ -229,7 +229,7 @@ class Packet(BasePacket): return v def setfieldval(self, attr, val): - if self.default_fields.has_key(attr): + if attr in self.default_fields: fld = self.get_field(attr) if fld is None: any2i = lambda x,y: y @@ -255,12 +255,12 @@ class Packet(BasePacket): return object.__setattr__(self, attr, val) def delfieldval(self, attr): - if self.fields.has_key(attr): + if attr in self.fields: del(self.fields[attr]) self.explicit = 0 # in case a default value must be explicited self.raw_packet_cache = None self.raw_packet_cache_fields = None - elif self.default_fields.has_key(attr): + elif attr in self.default_fields: pass elif attr == "payload": self.remove_payload() @@ -315,19 +315,19 @@ class Packet(BasePacket): cloneB = other.copy() cloneA.add_payload(cloneB) return cloneA - elif type(other) is str: + elif isinstance(other, str): return self/conf.raw_layer(load=other) else: return other.__rdiv__(self) __truediv__ = __div__ def __rdiv__(self, other): - if type(other) is str: + if isinstance(other, str): return conf.raw_layer(load=other)/self else: raise TypeError __rtruediv__ = __rdiv__ def __mul__(self, other): - if type(other) is int: + if isinstance(other, int): return [self]*other else: raise TypeError @@ -431,7 +431,7 @@ class Packet(BasePacket): if isinstance(f, ConditionalField) and not f._evalcond(self): continue p = f.addfield(self, p, self.getfieldval(f.name) ) - if type(p) is str: + if isinstance(p, str): r = p[len(q):] q = p else: @@ -805,7 +805,7 @@ class Packet(BasePacket): """True if other is an answer from self (self ==> other).""" if isinstance(other, Packet): return other < self - elif type(other) is str: + elif isinstance(other, str): return 1 else: raise TypeError((self, other)) @@ -813,7 +813,7 @@ class Packet(BasePacket): """True if self is an answer from other (other ==> self).""" if isinstance(other, Packet): return self.answers(other) - elif type(other) is str: + elif isinstance(other, str): return 1 else: raise TypeError((self, other)) @@ -858,10 +858,10 @@ class Packet(BasePacket): return self.payload.haslayer(cls) def getlayer(self, cls, nb=1, _track=None): """Return the nb^th layer that is an instance of cls.""" - if type(cls) is int: + if isinstance(cls, int): nb = cls+1 cls = None - if type(cls) is str and "." in cls: + if isinstance(cls, str) and "." in cls: ccls,fld = cls.split(".",1) else: ccls,fld = cls,None @@ -895,7 +895,7 @@ class Packet(BasePacket): return q def __getitem__(self, cls): - if type(cls) is slice: + if isinstance(cls, slice): lname = cls.start if cls.stop: ret = self.getlayer(cls.start, cls.stop) @@ -907,9 +907,9 @@ class Packet(BasePacket): lname=cls ret = self.getlayer(cls) if ret is None: - if type(lname) is Packet_metaclass: + if isinstance(lname, Packet_metaclass): lname = lname.__name__ - elif type(lname) is not str: + elif not isinstance(lname, str): lname = repr(lname) raise IndexError("Layer [%s] not found" % lname) return ret @@ -967,7 +967,7 @@ class Packet(BasePacket): ncol = ct.field_name vcol = ct.field_value fvalue = self.getfieldval(f.name) - if isinstance(fvalue, Packet) or (f.islist and f.holds_packets and type(fvalue) is list): + if isinstance(fvalue, Packet) or (f.islist and f.holds_packets and isinstance(fvalue, list)): s += "%s \\%-10s\\\n" % (label_lvl+lvl, ncol(f.name)) fvalue_gen = SetGen(fvalue,_iterpacket=0) for fvalue in fvalue_gen: @@ -977,7 +977,7 @@ class Packet(BasePacket): ncol(f.name), ct.punct("="),) reprval = f.i2repr(self,fvalue) - if type(reprval) is str: + if isinstance(reprval, str): reprval = reprval.replace("\n", "\n"+" "*(len(label_lvl) +len(lvl) +len(f.name) @@ -1135,7 +1135,7 @@ A side effect is that, to obtain "{" and "}" characters, you must use ret = "" if not found or self.__class__ in needed: ret = self.mysummary() - if type(ret) is tuple: + if isinstance(ret, tuple): ret,n = ret needed += n if ret or needed: @@ -1180,7 +1180,7 @@ A side effect is that, to obtain "{" and "}" characters, you must use fld = self.get_field(fn) if isinstance(fv, Packet): fv = fv.command() - elif fld.islist and fld.holds_packets and type(fv) is list: + elif fld.islist and fld.holds_packets and isinstance(fv, list): fv = "[%s]" % ",".join( map(Packet.command, fv)) elif isinstance(fld, FlagsField): fv = int(fv) @@ -1337,7 +1337,8 @@ def bind_layers(lower, upper, __fval=None, **fval): def split_bottom_up(lower, upper, __fval=None, **fval): if __fval is not None: fval.update(__fval) - def do_filter((f,u),upper=upper,fval=fval): + def do_filter(xxx_todo_changeme,upper=upper,fval=fval): + (f,u) = xxx_todo_changeme if u != upper: return True for k in fval: diff --git a/scapy/pipetool.py b/scapy/pipetool.py index 613ae614be3df441d8c771287180cf27da121089..03d452e987a5c84c1e03523f12cd0b1b89656a00 100644 --- a/scapy/pipetool.py +++ b/scapy/pipetool.py @@ -112,7 +112,7 @@ class PipeEngine: elif fd in sources: try: fd.deliver() - except Exception,e: + except Exception as e: log_interactive.exception("piping from %s failed: %s" % (fd.name, e)) else: if fd.exhausted(): diff --git a/scapy/plist.py b/scapy/plist.py index 7aed92175a9a047b76b8c92f3673a16cf0ec9fbc..a56434920a9cb5b132ca2c87d741795a398c0280 100644 --- a/scapy/plist.py +++ b/scapy/plist.py @@ -16,6 +16,7 @@ from scapy.base_classes import BasePacket,BasePacketList from scapy.utils import do_graph,hexdump,make_table,make_lined_table,make_tex_table,get_temp_file from scapy.consts import plt, MATPLOTLIB_INLINED, MATPLOTLIB_DEFAULT_PLOT_KARGS +from functools import reduce ############# @@ -77,7 +78,7 @@ class PacketList(BasePacketList): if isinstance(item,type) and issubclass(item,BasePacket): return self.__class__(filter(lambda x: item in self._elt2pkt(x),self.res), name="%s from %s"%(item.__name__,self.listname)) - if type(item) is slice: + if isinstance(item, slice): return self.__class__(self.res.__getitem__(item), name = "mod %s" % self.listname) return self.res.__getitem__(item) @@ -379,24 +380,24 @@ lfilter: truth function to apply to each packet to decide whether it will be dis gr += "# src nodes\n" for s in sl: n,l = sl[s]; n = 1+float(n-mins)/(maxs-mins) - gr += '"src.%s" [label = "%s", shape=box, fillcolor="#FF0000", style=filled, fixedsize=1, height=%.2f,width=%.2f];\n' % (`s`,`s`,n,n) + gr += '"src.%s" [label = "%s", shape=box, fillcolor="#FF0000", style=filled, fixedsize=1, height=%.2f,width=%.2f];\n' % (repr(s),repr(s),n,n) gr += "# event nodes\n" for e in el: n,l = el[e]; n = n = 1+float(n-mine)/(maxe-mine) - gr += '"evt.%s" [label = "%s", shape=circle, fillcolor="#00FFFF", style=filled, fixedsize=1, height=%.2f, width=%.2f];\n' % (`e`,`e`,n,n) + gr += '"evt.%s" [label = "%s", shape=circle, fillcolor="#00FFFF", style=filled, fixedsize=1, height=%.2f, width=%.2f];\n' % (repr(e),repr(e),n,n) for d in dl: n = dl[d]; n = n = 1+float(n-mind)/(maxd-mind) - gr += '"dst.%s" [label = "%s", shape=triangle, fillcolor="#0000ff", style=filled, fixedsize=1, height=%.2f, width=%.2f];\n' % (`d`,`d`,n,n) + gr += '"dst.%s" [label = "%s", shape=triangle, fillcolor="#0000ff", style=filled, fixedsize=1, height=%.2f, width=%.2f];\n' % (repr(d),repr(d),n,n) gr += "###\n" for s in sl: n,l = sl[s] for e in l: - gr += ' "src.%s" -> "evt.%s";\n' % (`s`,`e`) + gr += ' "src.%s" -> "evt.%s";\n' % (repr(s),repr(e)) for e in el: n,l = el[e] for d in l: - gr += ' "evt.%s" -> "dst.%s";\n' % (`e`,`d`) + gr += ' "evt.%s" -> "dst.%s";\n' % (repr(e),repr(d)) gr += "}" return do_graph(gr, **kargs) @@ -509,7 +510,7 @@ lfilter: truth function to apply to each packet to decide whether it will be dis """ delete_checksums = kargs.get("delete_checksums",False) x=PacketList(name="Replaced %s" % self.listname) - if type(args[0]) is not tuple: + if not isinstance(args[0], tuple): args = (args,) for p in self.res: p = self._elt2pkt(p) diff --git a/scapy/route.py b/scapy/route.py index df15b12b1d0e0362ae1c6565a47b860002970065..0195548d05fc2a6d3e34fbed8b82091b7062e4ab 100644 --- a/scapy/route.py +++ b/scapy/route.py @@ -128,7 +128,7 @@ class Route: def route(self,dest,verbose=None): - if type(dest) is list and dest: + if isinstance(dest, list) and dest: dest = dest[0] if dest in self.cache: return self.cache[dest] @@ -137,7 +137,7 @@ class Route: # Transform "192.168.*.1-5" to one IP of the set dst = dest.split("/")[0] dst = dst.replace("*","0") - while 1: + while True: l = dst.find("-") if l < 0: break diff --git a/scapy/sendrecv.py b/scapy/sendrecv.py index 1271b1303e80caaa7e25079caae2376db437ccb3..da0a98e7354dc54ff22d485541a53edcd2b35a2a 100644 --- a/scapy/sendrecv.py +++ b/scapy/sendrecv.py @@ -122,7 +122,7 @@ def sndrcv(pks, pkt, timeout = None, inter = 0, verbose=None, chainCC=0, retry=0 inmask = [rdpipe,pks] try: try: - while 1: + while True: if stoptime: remaintime = stoptime-time.time() if remaintime <= 0: @@ -226,7 +226,7 @@ def sndrcv(pks, pkt, timeout = None, inter = 0, verbose=None, chainCC=0, retry=0 def __gen_send(s, x, inter=0, loop=0, count=None, verbose=None, realtime=None, return_packets=False, *args, **kargs): - if type(x) is str: + if isinstance(x, str): x = conf.raw_layer(load=x) if not isinstance(x, Gen): x = SetGen(x) @@ -318,7 +318,7 @@ def sendpfast(x, pps=None, mbps=None, realtime=None, loop=0, file_cache=False, i subprocess.check_call(argv) except KeyboardInterrupt: log_interactive.info("Interrupted by user") - except Exception,e: + except Exception as e: log_interactive.error("while trying to exec [%s]: %s" % (argv[0],e)) finally: os.unlink(f) @@ -338,7 +338,7 @@ verbose: set verbosity level multi: whether to accept multiple answers for the same stimulus filter: provide a BPF filter iface: listen answers only on the given interface""" - if not kargs.has_key("timeout"): + if "timeout" not in kargs: kargs["timeout"] = -1 s = conf.L3socket(promisc=promisc, filter=filter, iface=iface, nofilter=nofilter) a,b=sndrcv(s,x,*args,**kargs) @@ -356,7 +356,7 @@ verbose: set verbosity level multi: whether to accept multiple answers for the same stimulus filter: provide a BPF filter iface: listen answers only on the given interface""" - if not kargs.has_key("timeout"): + if "timeout" not in kargs: kargs["timeout"] = -1 s=conf.L3socket(promisc=promisc, filter=filter, nofilter=nofilter, iface=iface) a,b=sndrcv(s,x,*args,**kargs) @@ -377,7 +377,7 @@ verbose: set verbosity level multi: whether to accept multiple answers for the same stimulus filter: provide a BPF filter iface: work only on the given interface""" - if not kargs.has_key("timeout"): + if "timeout" not in kargs: kargs["timeout"] = -1 if iface is None and iface_hint is not None: iface = conf.route.route(iface_hint)[0] @@ -397,7 +397,7 @@ verbose: set verbosity level multi: whether to accept multiple answers for the same stimulus filter: provide a BPF filter iface: work only on the given interface""" - if not kargs.has_key("timeout"): + if "timeout" not in kargs: kargs["timeout"] = -1 a,b=srp(*args,**kargs) if len(a) > 0: @@ -417,7 +417,7 @@ def __sr_loop(srfunc, pkts, prn=lambda x:x[1].summary(), prnfail=lambda x:x.summ if timeout is None: timeout = min(2*inter, 5) try: - while 1: + while True: parity ^= 1 col = [ct.even,ct.odd][parity] if count is not None: @@ -469,7 +469,7 @@ srloop(pkts, [prn], [inter], [count], ...) --> None""" return __sr_loop(srp, pkts, *args, **kargs) -def sndrcvflood(pks, pkt, prn=lambda (s,r):r.summary(), chainCC=0, store=1, unique=0): +def sndrcvflood(pks, pkt, prn=lambda s_r:s_r[1].summary(), chainCC=0, store=1, unique=0): if not isinstance(pkt, Gen): pkt = SetGen(pkt) tobesent = [p for p in pkt] @@ -485,7 +485,7 @@ def sndrcvflood(pks, pkt, prn=lambda (s,r):r.summary(), chainCC=0, store=1, uniq hsent[h] = [i] def send_in_loop(tobesent): - while 1: + while True: for p in tobesent: yield p @@ -494,7 +494,7 @@ def sndrcvflood(pks, pkt, prn=lambda (s,r):r.summary(), chainCC=0, store=1, uniq ssock = rsock = pks.fileno() try: - while 1: + while True: if conf.use_bpf: from scapy.arch.bpf.supersocket import bpf_select readyr = bpf_select([rsock]) @@ -597,7 +597,7 @@ interfaces) if offline is None: if L2socket is None: L2socket = conf.L2listen - if type(iface) is list: + if isinstance(iface, list): for i in iface: s = L2socket(type=ETH_P_ALL, iface=i, *arg, **karg) label[s] = i diff --git a/scapy/supersocket.py b/scapy/supersocket.py index 2a2c1107eaa82780a8714b7c074e26fdece07e86..5bd0f626ff3bbe72c6ef860c65c64ead47a8ec57 100644 --- a/scapy/supersocket.py +++ b/scapy/supersocket.py @@ -106,7 +106,7 @@ class L3RawSocket(SuperSocket): sx = str(x) x.sent_time = time.time() self.outs.sendto(sx,(x.dst,0)) - except socket.error,msg: + except socket.error as msg: log_runtime.error(msg) class SimpleSocket(SuperSocket): diff --git a/scapy/themes.py b/scapy/themes.py index c7d2a1ff5b78a186084823e27fa002ca3be7e8cb..bf7ae4760d3879cfaa3a0f1eb9aecf91e2f8522d 100644 --- a/scapy/themes.py +++ b/scapy/themes.py @@ -31,7 +31,7 @@ class Color: def create_styler(fmt=None, before="", after="", fmt2="%s"): def do_style(val, fmt=fmt, before=before, after=after, fmt2=fmt2): if fmt is None: - if type(val) is not str: + if not isinstance(val, str): val = str(val) else: val = fmt % val diff --git a/scapy/tools/UTscapy.py b/scapy/tools/UTscapy.py index 11ee4fdd5faa71baf4f5203957d34020a3903681..fb307b50df0a2197e5cdc1c26da008ce1dd7e047 100755 --- a/scapy/tools/UTscapy.py +++ b/scapy/tools/UTscapy.py @@ -370,9 +370,9 @@ def run_campaign(test_campaign, get_interactive_session, verb=3): try: if res is None or res: the_res= True - except Exception,msg: + except Exception as msg: t.output+="UTscapy: Error during result interpretation:\n" - t.output+="".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback,)) + t.output+="".join(traceback.format_exception(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2],)) if the_res: t.res = True res = "passed" @@ -713,7 +713,7 @@ def main(argv): elif opt == "-f": try: FORMAT = Format.from_string(optarg) - except KeyError,msg: + except KeyError as msg: raise getopt.GetoptError("Unknown output format %s" % msg) elif opt == "-t": TESTFILES.append(optarg) @@ -738,7 +738,7 @@ def main(argv): KW_KO = [data.kw_ko] try: FORMAT = Format.from_string(data.format) - except KeyError,msg: + except KeyError as msg: raise getopt.GetoptError("Unknown output format %s" % msg) TESTFILES = resolve_testfiles(TESTFILES) elif opt == "-o": @@ -764,17 +764,17 @@ def main(argv): print >>sys.stderr, "### Booting scapy..." try: from scapy import all as scapy - except ImportError,e: + except ImportError as e: raise getopt.GetoptError("cannot import [%s]: %s" % (SCAPY,e)) for m in MODULES: try: mod = import_module(m) __builtin__.__dict__.update(mod.__dict__) - except ImportError,e: + except ImportError as e: raise getopt.GetoptError("cannot import [%s]: %s" % (m,e)) - except getopt.GetoptError,msg: + except getopt.GetoptError as msg: print >>sys.stderr,"ERROR:",msg raise SystemExit diff --git a/scapy/tools/check_asdis.py b/scapy/tools/check_asdis.py index 2c1efa4c38d43b98d1791c3cf606c155af1f9008..4be9ef1bb369c901612fd51d6520a9fd1ab5233d 100755 --- a/scapy/tools/check_asdis.py +++ b/scapy/tools/check_asdis.py @@ -39,7 +39,7 @@ def main(argv): if PCAP_IN is None: raise getopt.GetoptError("Missing pcap file (-i)") - except getopt.GetoptError,e: + except getopt.GetoptError as e: print >>sys.stderr,"ERROR: %s" % e raise SystemExit @@ -72,7 +72,7 @@ def main(argv): p2 = str(p2d) except KeyboardInterrupt: raise - except Exception,e: + except Exception as e: print "Dissection error on packet %i" % i failed += 1 else: diff --git a/scapy/utils.py b/scapy/utils.py index 7c2bc23d31dab52c7d0674dae55a0f9f46fe6ae5..f20888642a90388d1070d826b58e47e3aa9a5eb5 100644 --- a/scapy/utils.py +++ b/scapy/utils.py @@ -56,9 +56,9 @@ def sane(x): def lhex(x): if type(x) in (int,long): return hex(x) - elif type(x) is tuple: + elif isinstance(x, tuple): return "(%s)" % ", ".join(map(lhex, x)) - elif type(x) is list: + elif isinstance(x, list): return "[%s]" % ", ".join(map(lhex, x)) else: return x @@ -480,7 +480,7 @@ def colgen(*lstcol,**kargs): if len(lstcol) < 2: lstcol *= 2 trans = kargs.get("trans", lambda x,y,z: (x,y,z)) - while 1: + while True: for i in xrange(len(lstcol)): for j in xrange(len(lstcol)): for k in xrange(len(lstcol)): @@ -522,7 +522,7 @@ class Enum_metaclass(type): def __new__(cls, name, bases, dct): rdict={} for k,v in dct.iteritems(): - if type(v) is int: + if isinstance(v, int): v = cls.element_class(k,v) dct[k] = v rdict[v] = k @@ -1016,7 +1016,7 @@ nano: use nanosecond-precision (requires libpcap >= 1.5.0) written to the dumpfile """ - if type(pkt) is str: + if isinstance(pkt, str): if not self.header_present: self._write_header(pkt) self._write_packet(pkt) @@ -1101,7 +1101,7 @@ re_extract_hexcap = re.compile("^((0x)?[0-9a-fA-F]{2,}[ :\t]{,3}|) *(([0-9a-fA-F def import_hexcap(): p = "" try: - while 1: + while True: l = raw_input().strip() try: p += re_extract_hexcap.match(l).groups()[2] @@ -1280,7 +1280,7 @@ def pretty_routes(rtlst, header, sortBy=0): # Append tag rtlst = header + rtlst # Detect column's width - colwidth = map(lambda x: max(map(lambda y: len(y), x)), apply(zip, rtlst)) + colwidth = map(lambda x: max(map(lambda y: len(y), x)), zip(*rtlst)) # Make text fit in box (if exist) # TODO: find a better and more precise way of doing this. That's currently working but very complicated width = get_terminal_width() @@ -1302,7 +1302,7 @@ def pretty_routes(rtlst, header, sortBy=0): return _r rtlst = [tuple([_crop(rtlst[j][i], colwidth[i]) for i in range(0, len(rtlst[j]))]) for j in range(0, len(rtlst))] # Recalculate column's width - colwidth = map(lambda x: max(map(lambda y: len(y), x)), apply(zip, rtlst)) + colwidth = map(lambda x: max(map(lambda y: len(y), x)), zip(*rtlst)) fmt = _space.join(map(lambda x: "%%-%ds"%x, colwidth)) rt = "\n".join(map(lambda x: fmt % x, rtlst)) return rt diff --git a/scapy/utils6.py b/scapy/utils6.py index 1c5a679df5ec04a586e4d18514a12dcd8a43139d..ace1db2ea55faf47a2fa55b54f72dab3896b1778 100644 --- a/scapy/utils6.py +++ b/scapy/utils6.py @@ -19,6 +19,7 @@ from scapy.utils import * from scapy.pton_ntop import * from scapy.volatile import RandMAC from scapy.error import warning +from functools import reduce def construct_source_candidate_set(addr, plen, laddr, loiface): @@ -289,7 +290,7 @@ def in6_getLinkScopedMcastAddr(addr, grpid=None, scope=2): if grpid is None: grpid = b'\x00\x00\x00\x00' else: - if type(grpid) is str: + if isinstance(grpid, str): if len(grpid) == 8: try: grpid = int(grpid, 16) & 0xffffffff diff --git a/scapy/volatile.py b/scapy/volatile.py index 3158258dcf06d928e94d417c041e181d202ea9a7..73892a72778f0984807f8f3754e6f2248dcb85d5 100644 --- a/scapy/volatile.py +++ b/scapy/volatile.py @@ -75,7 +75,7 @@ class VolatileValue: elif attr == "__cmp__": x = self._fix() def cmp2(y,x=x): - if type(x) != type(y): + if not isinstance(x, type(y)): return -1 return x.__cmp__(y) return cmp2 @@ -342,7 +342,7 @@ class RandOID(RandString): oid.append(str(self.idnum)) elif i == "**": oid += [str(self.idnum) for i in xrange(1 + self.depth)] - elif type(i) is tuple: + elif isinstance(i, tuple): oid.append(str(random.randrange(*i))) else: oid.append(i) @@ -383,7 +383,7 @@ class RandRegExp(RandField): r = "" mul = 1 for e in lst: - if type(e) is list: + if isinstance(e, list): if mul != 1: mul = mul-1 r += RandRegExp.stack_fix(e[1:]*mul, index) @@ -394,7 +394,7 @@ class RandRegExp(RandField): index[i] = f r += f mul = 1 - elif type(e) is tuple: + elif isinstance(e, tuple): kind,val = e if kind == "cite": r += index[val-1] @@ -433,7 +433,7 @@ class RandRegExp(RandField): elif c == '|': p = current[0] ch = p[-1] - if type(ch) is not tuple: + if not isinstance(ch, tuple): ch = ("choice",[current]) p[-1] = ch else: @@ -441,7 +441,7 @@ class RandRegExp(RandField): current = [p] elif c == ')': ch = current[0][-1] - if type(ch) is tuple: + if isinstance(ch, tuple): ch[1].append(current) index.append(current) current = current[0] @@ -515,10 +515,10 @@ class RandSingNum(RandSingularity): end = -end sign = -1 end_n = int(math.log(end)/math.log(2))+1 - return set([sign*2**i for i in xrange(end_n)]) + return {sign*2**i for i in xrange(end_n)} def __init__(self, mn, mx): - sing = set([0, mn, mx, int((mn+mx)/2)]) + sing = {0, mn, mx, int((mn+mx)/2)} sing |= self.make_power_of_two(mn) sing |= self.make_power_of_two(mx) for i in sing.copy(): @@ -630,7 +630,7 @@ class RandPool(RandField): pool = [] for p in args: w = 1 - if type(p) is tuple: + if isinstance(p, tuple): p,w = p pool += [p]*w self._pool = pool