Fix issues discovered by common python linters

Fix some issues discovered by common python linters including:
* switch `None` comparisons to use `is` rather than `==`. Identity !=
equality, and I've spent 40+ hours before tracking down a subtle bug
caused by exactly this issue. Note that this may introduce a problem if
one of the scripts is depending on this behavior, in which case the
comparison should be changed to `True`/`False` rather than `None`.
* Use `except Exception:` as bare `except:` statements have been
discouraged for years. Ideally for some of these we'd examine if there
were specific exceptions that should be caught, but for now I simply
caught all. Again, this could introduce very subtle behavioral changes
under Python 2, but IIUC, that was all fixed in Python 3, so safe to
move to `except Exception:`.
* Use more idiomatic `if not x in y`--> `if x not in y`
* Use more idiomatic 2 blank lines. I only did this at the beginning,
until I realized how overwhelming this was going to be to apply, then I
stopped.
* Add a TODO where an undefined function name is called, so will fail
whenever that code is run.
* Add more idiomatic spacing around `:`. This is also only partially
cleaned up, as I gave up when I saw how `asn2wrs.py` was clearly
infatuated with the construct.
* Various other small cleanups, removed some trailing whitespace and
improper indentation that wasn't a multiple of 4, etc.

There is still _much_ to do, but I haven't been heavily involved with
this project before, so thought this was a sufficient amount to put up
and see what the feedback is.

Linters that I have enabled which highlighted some of these issues
include:
* `pylint`
* `flake8`
* `pycodestyle`
This commit is contained in:
Jeff Widman 2020-09-20 22:44:41 -07:00
parent c5926c51e7
commit 8d7ebc732e
22 changed files with 258 additions and 239 deletions

View File

@ -31,14 +31,11 @@ other script-based formates beside VBScript
from __future__ import print_function from __future__ import print_function
import os
import sys import sys
import signal
import re import re
import argparse import argparse
import time import time
import struct import struct
import binascii
from threading import Thread from threading import Thread
ERROR_USAGE = 0 ERROR_USAGE = 0
@ -113,89 +110,89 @@ def extcap_config(interface, option):
values = [] values = []
multi_values = [] multi_values = []
args.append ( (0, '--delay', 'Time delay', 'Time delay between packages', 'integer', '{range=1,15}{default=5}') ) args.append((0, '--delay', 'Time delay', 'Time delay between packages', 'integer', '{range=1,15}{default=5}'))
args.append ( (1, '--message', 'Message', 'Package message content', 'string', '{required=true}{placeholder=Please enter a message here ...}') ) args.append((1, '--message', 'Message', 'Package message content', 'string', '{required=true}{placeholder=Please enter a message here ...}'))
args.append ( (2, '--verify', 'Verify', 'Verify package content', 'boolflag', '{default=yes}') ) args.append((2, '--verify', 'Verify', 'Verify package content', 'boolflag', '{default=yes}'))
args.append ( (3, '--remote', 'Remote Channel', 'Remote Channel Selector', 'selector', '{reload=true}{placeholder=Load interfaces ...}')) args.append((3, '--remote', 'Remote Channel', 'Remote Channel Selector', 'selector', '{reload=true}{placeholder=Load interfaces ...}'))
args.append ( (4, '--fake_ip', 'Fake IP Address', 'Use this ip address as sender', 'string', '{save=false}{validation=\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b}')) args.append((4, '--fake_ip', 'Fake IP Address', 'Use this ip address as sender', 'string', '{save=false}{validation=\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b}'))
args.append ( (5, '--ltest', 'Long Test', 'Long Test Value', 'long', '{default=123123123123123123}{group=Numeric Values}')) args.append((5, '--ltest', 'Long Test', 'Long Test Value', 'long', '{default=123123123123123123}{group=Numeric Values}'))
args.append ( (6, '--d1test', 'Double 1 Test', 'Long Test Value', 'double', '{default=123.456}{group=Numeric Values}')) args.append((6, '--d1test', 'Double 1 Test', 'Long Test Value', 'double', '{default=123.456}{group=Numeric Values}'))
args.append ( (7, '--d2test', 'Double 2 Test', 'Long Test Value', 'double', '{default= 123,456}{group=Numeric Values}')) args.append((7, '--d2test', 'Double 2 Test', 'Long Test Value', 'double', '{default= 123,456}{group=Numeric Values}'))
args.append ( (8, '--password', 'Password', 'Package message password', 'password', '') ) args.append((8, '--password', 'Password', 'Package message password', 'password', ''))
args.append ( (9, '--ts', 'Start Time', 'Capture start time', 'timestamp', '{group=Time / Log}') ) args.append((9, '--ts', 'Start Time', 'Capture start time', 'timestamp', '{group=Time / Log}'))
args.append ( (10, '--logfile', 'Log File Test', 'The Log File Test', 'fileselect', '{group=Time / Log}') ) args.append((10, '--logfile', 'Log File Test', 'The Log File Test', 'fileselect', '{group=Time / Log}'))
args.append ( (11, '--radio', 'Radio Test', 'Radio Test Value', 'radio', '{group=Selection}') ) args.append((11, '--radio', 'Radio Test', 'Radio Test Value', 'radio', '{group=Selection}'))
args.append ( (12, '--multi', 'MultiCheck Test', 'MultiCheck Test Value', 'multicheck', '{group=Selection}') ) args.append((12, '--multi', 'MultiCheck Test', 'MultiCheck Test Value', 'multicheck', '{group=Selection}'))
if ( option == "remote" ): if option == "remote":
values.append ( (3, "if1", "Remote Interface 1", "false" ) ) values.append((3, "if1", "Remote Interface 1", "false"))
values.append ( (3, "if2", "Remote Interface 2", "true" ) ) values.append((3, "if2", "Remote Interface 2", "true"))
values.append ( (3, "if3", "Remote Interface 3", "false" ) ) values.append((3, "if3", "Remote Interface 3", "false"))
values.append ( (3, "if4", "Remote Interface 4", "false" ) ) values.append((3, "if4", "Remote Interface 4", "false"))
if ( option == "radio" ): if option == "radio":
values.append ( (11, "r1", "Radio Option 1", "false" ) ) values.append((11, "r1", "Radio Option 1", "false"))
values.append ( (11, "r2", "Radio Option 2", "false" ) ) values.append((11, "r2", "Radio Option 2", "false"))
values.append ( (11, "r3", "Radio Option 3", "true" ) ) values.append((11, "r3", "Radio Option 3", "true"))
if ( len(option) <= 0 ): if len(option) <= 0:
for arg in args: for arg in args:
print ("arg {number=%d}{call=%s}{display=%s}{tooltip=%s}{type=%s}%s" % arg) print("arg {number=%d}{call=%s}{display=%s}{tooltip=%s}{type=%s}%s" % arg)
values.append ( (3, "if1", "Remote1", "true" ) ) values.append((3, "if1", "Remote1", "true"))
values.append ( (3, "if2", "Remote2", "false" ) ) values.append((3, "if2", "Remote2", "false"))
values.append ( (11, "r1", "Radio1", "false" ) ) values.append((11, "r1", "Radio1", "false"))
values.append ( (11, "r2", "Radio2", "true" ) ) values.append((11, "r2", "Radio2", "true"))
if ( len(option) <= 0 ): if len(option) <= 0:
multi_values.append ( ((12, "m1", "Checkable Parent 1", "false", "true" ), None) ) multi_values.append(((12, "m1", "Checkable Parent 1", "false", "true"), None))
multi_values.append ( ((12, "m1c1", "Checkable Child 1", "false", "true" ), "m1") ) multi_values.append(((12, "m1c1", "Checkable Child 1", "false", "true"), "m1"))
multi_values.append ( ((12, "m1c1g1", "Uncheckable Grandchild", "false", "false" ), "m1c1") ) multi_values.append(((12, "m1c1g1", "Uncheckable Grandchild", "false", "false"), "m1c1"))
multi_values.append ( ((12, "m1c2", "Checkable Child 2", "false", "true" ), "m1") ) multi_values.append(((12, "m1c2", "Checkable Child 2", "false", "true"), "m1"))
multi_values.append ( ((12, "m2", "Checkable Parent 2", "false", "true" ), None) ) multi_values.append(((12, "m2", "Checkable Parent 2", "false", "true"), None))
multi_values.append ( ((12, "m2c1", "Checkable Child 1", "false", "true" ), "m2") ) multi_values.append(((12, "m2c1", "Checkable Child 1", "false", "true"), "m2"))
multi_values.append ( ((12, "m2c1g1", "Checkable Grandchild", "false", "true" ), "m2c1") ) multi_values.append(((12, "m2c1g1", "Checkable Grandchild", "false", "true"), "m2c1"))
multi_values.append ( ((12, "m2c2", "Uncheckable Child 2", "false", "false" ), "m2") ) multi_values.append(((12, "m2c2", "Uncheckable Child 2", "false", "false"), "m2"))
multi_values.append ( ((12, "m2c2g1", "Uncheckable Grandchild", "false", "false" ), "m2c2") ) multi_values.append(((12, "m2c2g1", "Uncheckable Grandchild", "false", "false"), "m2c2"))
for value in values: for value in values:
print ("value {arg=%d}{value=%s}{display=%s}{default=%s}" % value) print("value {arg=%d}{value=%s}{display=%s}{default=%s}" % value)
for (value, parent) in multi_values: for (value, parent) in multi_values:
sentence = "value {arg=%d}{value=%s}{display=%s}{default=%s}{enabled=%s}" % value sentence = "value {arg=%d}{value=%s}{display=%s}{default=%s}{enabled=%s}" % value
extra = "{parent=%s}" % parent if parent else "" extra = "{parent=%s}" % parent if parent else ""
print ("".join((sentence, extra))) print("".join((sentence, extra)))
def extcap_version(): def extcap_version():
print ("extcap {version=1.0}{help=https://www.wireshark.org}{display=Example extcap interface}") print("extcap {version=1.0}{help=https://www.wireshark.org}{display=Example extcap interface}")
def extcap_interfaces(): def extcap_interfaces():
print ("extcap {version=1.0}{help=https://www.wireshark.org}{display=Example extcap interface}") print("extcap {version=1.0}{help=https://www.wireshark.org}{display=Example extcap interface}")
print ("interface {value=example1}{display=Example interface 1 for extcap}") print("interface {value=example1}{display=Example interface 1 for extcap}")
print ("interface {value=example2}{display=Example interface 2 for extcap}") print("interface {value=example2}{display=Example interface 2 for extcap}")
print ("control {number=%d}{type=string}{display=Message}{tooltip=Package message content. Must start with a capital letter.}{placeholder=Enter package message content here ...}{validation=^[A-Z]+}" % CTRL_ARG_MESSAGE) print("control {number=%d}{type=string}{display=Message}{tooltip=Package message content. Must start with a capital letter.}{placeholder=Enter package message content here ...}{validation=^[A-Z]+}" % CTRL_ARG_MESSAGE)
print ("control {number=%d}{type=selector}{display=Time delay}{tooltip=Time delay between packages}" % CTRL_ARG_DELAY) print("control {number=%d}{type=selector}{display=Time delay}{tooltip=Time delay between packages}" % CTRL_ARG_DELAY)
print ("control {number=%d}{type=boolean}{display=Verify}{default=true}{tooltip=Verify package content}" % CTRL_ARG_VERIFY) print("control {number=%d}{type=boolean}{display=Verify}{default=true}{tooltip=Verify package content}" % CTRL_ARG_VERIFY)
print ("control {number=%d}{type=button}{display=Turn on}{tooltip=Turn on or off}" % CTRL_ARG_BUTTON) print("control {number=%d}{type=button}{display=Turn on}{tooltip=Turn on or off}" % CTRL_ARG_BUTTON)
print ("control {number=%d}{type=button}{role=help}{display=Help}{tooltip=Show help}" % CTRL_ARG_HELP) print("control {number=%d}{type=button}{role=help}{display=Help}{tooltip=Show help}" % CTRL_ARG_HELP)
print ("control {number=%d}{type=button}{role=restore}{display=Restore}{tooltip=Restore default values}" % CTRL_ARG_RESTORE) print("control {number=%d}{type=button}{role=restore}{display=Restore}{tooltip=Restore default values}" % CTRL_ARG_RESTORE)
print ("control {number=%d}{type=button}{role=logger}{display=Log}{tooltip=Show capture log}" % CTRL_ARG_LOGGER) print("control {number=%d}{type=button}{role=logger}{display=Log}{tooltip=Show capture log}" % CTRL_ARG_LOGGER)
print ("value {control=%d}{value=1}{display=1}" % CTRL_ARG_DELAY) print("value {control=%d}{value=1}{display=1}" % CTRL_ARG_DELAY)
print ("value {control=%d}{value=2}{display=2}" % CTRL_ARG_DELAY) print("value {control=%d}{value=2}{display=2}" % CTRL_ARG_DELAY)
print ("value {control=%d}{value=3}{display=3}" % CTRL_ARG_DELAY) print("value {control=%d}{value=3}{display=3}" % CTRL_ARG_DELAY)
print ("value {control=%d}{value=4}{display=4}" % CTRL_ARG_DELAY) print("value {control=%d}{value=4}{display=4}" % CTRL_ARG_DELAY)
print ("value {control=%d}{value=5}{display=5}{default=true}" % CTRL_ARG_DELAY) print("value {control=%d}{value=5}{display=5}{default=true}" % CTRL_ARG_DELAY)
print ("value {control=%d}{value=60}{display=60}" % CTRL_ARG_DELAY) print("value {control=%d}{value=60}{display=60}" % CTRL_ARG_DELAY)
def extcap_dlts(interface): def extcap_dlts(interface):
if ( interface == '1' ): if interface == '1':
print ("dlt {number=147}{name=USER0}{display=Demo Implementation for Extcap}") print("dlt {number=147}{name=USER0}{display=Demo Implementation for Extcap}")
elif ( interface == '2' ): elif interface == '2':
print ("dlt {number=148}{name=USER1}{display=Demo Implementation for Extcap}") print("dlt {number=148}{name=USER1}{display=Demo Implementation for Extcap}")
def validate_capture_filter(capture_filter): def validate_capture_filter(capture_filter):
if capture_filter != "filter" and capture_filter != "valid": if capture_filter != "filter" and capture_filter != "valid":
@ -221,27 +218,27 @@ def unsigned(n):
def pcap_fake_header(): def pcap_fake_header():
header = bytearray() header = bytearray()
header += struct.pack('<L', int ('a1b2c3d4', 16 )) header += struct.pack('<L', int('a1b2c3d4', 16))
header += struct.pack('<H', unsigned(2) ) # Pcap Major Version header += struct.pack('<H', unsigned(2)) # Pcap Major Version
header += struct.pack('<H', unsigned(4) ) # Pcap Minor Version header += struct.pack('<H', unsigned(4)) # Pcap Minor Version
header += struct.pack('<I', int(0)) # Timezone header += struct.pack('<I', int(0)) # Timezone
header += struct.pack('<I', int(0)) # Accurancy of timestamps header += struct.pack('<I', int(0)) # Accurancy of timestamps
header += struct.pack('<L', int ('0000ffff', 16 )) # Max Length of capture frame header += struct.pack('<L', int('0000ffff', 16)) # Max Length of capture frame
header += struct.pack('<L', unsigned(1)) # Ethernet header += struct.pack('<L', unsigned(1)) # Ethernet
return header return header
# Calculates and returns the IP checksum based on the given IP Header # Calculates and returns the IP checksum based on the given IP Header
def ip_checksum(iph): def ip_checksum(iph):
#split into bytes #split into bytes
words = splitN(''.join(iph.split()),4) words = splitN(''.join(iph.split()), 4) # TODO splitN() func undefined, this code will fail
csum = 0; csum = 0
for word in words: for word in words:
csum += int(word, base=16) csum += int(word, base=16)
csum += (csum >> 16) csum += (csum >> 16)
csum = csum & 0xFFFF ^ 0xFFFF csum = csum & 0xFFFF ^ 0xFFFF
return csum return csum
def pcap_fake_package ( message, fake_ip ): def pcap_fake_package(message, fake_ip):
pcap = bytearray() pcap = bytearray()
#length = 14 bytes [ eth ] + 20 bytes [ ip ] + messagelength #length = 14 bytes [ eth ] + 20 bytes [ ip ] + messagelength
@ -249,35 +246,35 @@ def pcap_fake_package ( message, fake_ip ):
caplength = len(message) + 14 + 20 caplength = len(message) + 14 + 20
timestamp = int(time.time()) timestamp = int(time.time())
pcap += struct.pack('<L', unsigned(timestamp ) ) # timestamp seconds pcap += struct.pack('<L', unsigned(timestamp)) # timestamp seconds
pcap += struct.pack('<L', 0x00 ) # timestamp nanoseconds pcap += struct.pack('<L', 0x00) # timestamp nanoseconds
pcap += struct.pack('<L', unsigned(caplength ) ) # length captured pcap += struct.pack('<L', unsigned(caplength)) # length captured
pcap += struct.pack('<L', unsigned(caplength ) ) # length in frame pcap += struct.pack('<L', unsigned(caplength)) # length in frame
# ETH # ETH
pcap += struct.pack('h', 0 ) # source mac pcap += struct.pack('h', 0) # source mac
pcap += struct.pack('h', 0 ) # source mac pcap += struct.pack('h', 0) # source mac
pcap += struct.pack('h', 0 ) # source mac pcap += struct.pack('h', 0) # source mac
pcap += struct.pack('h', 0 ) # dest mac pcap += struct.pack('h', 0) # dest mac
pcap += struct.pack('h', 0 ) # dest mac pcap += struct.pack('h', 0) # dest mac
pcap += struct.pack('h', 0 ) # dest mac pcap += struct.pack('h', 0) # dest mac
pcap += struct.pack('<h', unsigned(8 )) # protocol (ip) pcap += struct.pack('<h', unsigned(8)) # protocol (ip)
# IP # IP
pcap += struct.pack('b', int ( '45', 16 )) # IP version pcap += struct.pack('b', int('45', 16)) # IP version
pcap += struct.pack('b', int ( '0', 16 )) # pcap += struct.pack('b', int('0', 16)) #
pcap += struct.pack('>H', unsigned(len(message)+20) ) # length of data + payload pcap += struct.pack('>H', unsigned(len(message)+20)) # length of data + payload
pcap += struct.pack('<H', int ( '0', 16 )) # Identification pcap += struct.pack('<H', int('0', 16)) # Identification
pcap += struct.pack('b', int ( '40', 16 )) # Don't fragment pcap += struct.pack('b', int('40', 16)) # Don't fragment
pcap += struct.pack('b', int ( '0', 16 )) # Fragment Offset pcap += struct.pack('b', int('0', 16)) # Fragment Offset
pcap += struct.pack('b', int ( '40', 16 )) pcap += struct.pack('b', int('40', 16))
pcap += struct.pack('B', 0xFE ) # Protocol (2 = unspecified) pcap += struct.pack('B', 0xFE) # Protocol (2 = unspecified)
pcap += struct.pack('<H', int ( '0000', 16 )) # Checksum pcap += struct.pack('<H', int('0000', 16)) # Checksum
parts = fake_ip.split('.') parts = fake_ip.split('.')
ipadr = (int(parts[0]) << 24) + (int(parts[1]) << 16) + (int(parts[2]) << 8) + int(parts[3]) ipadr = (int(parts[0]) << 24) + (int(parts[1]) << 16) + (int(parts[2]) << 8) + int(parts[3])
pcap += struct.pack('>L', ipadr ) # Source IP pcap += struct.pack('>L', ipadr) # Source IP
pcap += struct.pack('>L', int ( '7F000001', 16 )) # Dest IP pcap += struct.pack('>L', int('7F000001', 16)) # Dest IP
pcap += message pcap += message
return pcap return pcap
@ -291,14 +288,14 @@ def control_read(fn):
else: else:
payload = '' payload = ''
return arg, typ, payload return arg, typ, payload
except: except Exception:
return None, None, None return None, None, None
def control_read_thread(control_in, fn_out): def control_read_thread(control_in, fn_out):
global initialized, message, delay, verify, button, button_disabled global initialized, message, delay, verify, button, button_disabled
with open(control_in, 'rb', 0 ) as fn: with open(control_in, 'rb', 0) as fn:
arg = 0 arg = 0
while arg != None: while arg is not None:
arg, typ, payload = control_read(fn) arg, typ, payload = control_read(fn)
log = '' log = ''
if typ == CTRL_CMD_INITIALIZED: if typ == CTRL_CMD_INITIALIZED:
@ -318,7 +315,7 @@ def control_read_thread(control_in, fn_out):
elif arg == CTRL_ARG_BUTTON: elif arg == CTRL_ARG_BUTTON:
control_write(fn_out, CTRL_ARG_BUTTON, CTRL_CMD_DISABLE, "") control_write(fn_out, CTRL_ARG_BUTTON, CTRL_CMD_DISABLE, "")
button_disabled = True button_disabled = True
if button == True: if button:
control_write(fn_out, CTRL_ARG_BUTTON, CTRL_CMD_SET, "Turn on") control_write(fn_out, CTRL_ARG_BUTTON, CTRL_CMD_SET, "Turn on")
button = False button = False
log = "Button turned off" log = "Button turned off"
@ -350,7 +347,7 @@ def control_write_defaults(fn_out):
control_write(fn_out, CTRL_ARG_DELAY, CTRL_CMD_SET, str(int(delay))) control_write(fn_out, CTRL_ARG_DELAY, CTRL_CMD_SET, str(int(delay)))
control_write(fn_out, CTRL_ARG_VERIFY, CTRL_CMD_SET, struct.pack('B', verify)) control_write(fn_out, CTRL_ARG_VERIFY, CTRL_CMD_SET, struct.pack('B', verify))
for i in range(1,16): for i in range(1, 16):
item = '%d\x00%d sec' % (i, i) item = '%d\x00%d sec' % (i, i)
control_write(fn_out, CTRL_ARG_DELAY, CTRL_CMD_ADD, item) control_write(fn_out, CTRL_ARG_DELAY, CTRL_CMD_ADD, item)
@ -364,50 +361,50 @@ def extcap_capture(interface, fifo, control_in, control_out, in_delay, in_verify
counter = 1 counter = 1
fn_out = None fn_out = None
with open(fifo, 'wb', 0 ) as fh: with open(fifo, 'wb', 0) as fh:
fh.write (pcap_fake_header()) fh.write(pcap_fake_header())
if control_out != None: if control_out is not None:
fn_out = open(control_out, 'wb', 0) fn_out = open(control_out, 'wb', 0)
control_write(fn_out, CTRL_ARG_LOGGER, CTRL_CMD_SET, "Log started at " + time.strftime("%c") + "\n") control_write(fn_out, CTRL_ARG_LOGGER, CTRL_CMD_SET, "Log started at " + time.strftime("%c") + "\n")
if control_in != None: if control_in is not None:
# Start reading thread # Start reading thread
thread = Thread(target = control_read_thread, args = (control_in, fn_out)) thread = Thread(target=control_read_thread, args=(control_in, fn_out))
thread.start() thread.start()
if fn_out != None: if fn_out is not None:
control_write_defaults(fn_out) control_write_defaults(fn_out)
while True: while True:
if fn_out != None: if fn_out is not None:
log = "Received packet #" + str(counter) + "\n" log = "Received packet #" + str(counter) + "\n"
control_write(fn_out, CTRL_ARG_LOGGER, CTRL_CMD_ADD, log) control_write(fn_out, CTRL_ARG_LOGGER, CTRL_CMD_ADD, log)
counter = counter + 1 counter = counter + 1
if button_disabled == True: if button_disabled:
control_write(fn_out, CTRL_ARG_BUTTON, CTRL_CMD_ENABLE, "") control_write(fn_out, CTRL_ARG_BUTTON, CTRL_CMD_ENABLE, "")
control_write(fn_out, CTRL_ARG_NONE, CTRL_CMD_INFORMATION, "Turn action finished.") control_write(fn_out, CTRL_ARG_NONE, CTRL_CMD_INFORMATION, "Turn action finished.")
button_disabled = False button_disabled = False
out = ("%s|%04X%s|%s" % ( remote.strip(), len(message), message, verify )).encode("utf8") out = ("%s|%04X%s|%s" % (remote.strip(), len(message), message, verify)).encode("utf8")
fh.write (pcap_fake_package(out, fake_ip)) fh.write(pcap_fake_package(out, fake_ip))
time.sleep(delay) time.sleep(delay)
thread.join() thread.join()
if fn_out != None: if fn_out is not None:
fn_out.close() fn_out.close()
def extcap_close_fifo(fifo): def extcap_close_fifo(fifo):
# This is apparently needed to workaround an issue on Windows/macOS # This is apparently needed to workaround an issue on Windows/macOS
# where the message cannot be read. (really?) # where the message cannot be read. (really?)
fh = open(fifo, 'wb', 0 ) fh = open(fifo, 'wb', 0)
fh.close() fh.close()
#### ####
def usage(): def usage():
print ( "Usage: %s <--extcap-interfaces | --extcap-dlts | --extcap-interface | --extcap-config | --capture | --extcap-capture-filter | --fifo>" % sys.argv[0] ) print("Usage: %s <--extcap-interfaces | --extcap-dlts | --extcap-interface | --extcap-config | --capture | --extcap-capture-filter | --fifo>" % sys.argv[0] )
if __name__ == '__main__': if __name__ == '__main__':
interface = "" interface = ""
@ -448,54 +445,54 @@ if __name__ == '__main__':
try: try:
args, unknown = parser.parse_known_args() args, unknown = parser.parse_known_args()
except argparse.ArgumentError as exc: except argparse.ArgumentError as exc:
print( "%s: %s" % ( exc.argument.dest, exc.message ), file=sys.stderr) print("%s: %s" % (exc.argument.dest, exc.message), file=sys.stderr)
fifo_found = 0 fifo_found = 0
fifo = "" fifo = ""
for arg in sys.argv: for arg in sys.argv:
if (arg == "--fifo" or arg == "--extcap-fifo") : if arg == "--fifo" or arg == "--extcap-fifo":
fifo_found = 1 fifo_found = 1
elif ( fifo_found == 1 ): elif fifo_found == 1:
fifo = arg fifo = arg
break break
extcap_close_fifo(fifo) extcap_close_fifo(fifo)
sys.exit(ERROR_ARG) sys.exit(ERROR_ARG)
if ( len(sys.argv) <= 1 ): if len(sys.argv) <= 1:
parser.exit("No arguments given!") parser.exit("No arguments given!")
if ( args.extcap_version and not args.extcap_interfaces ): if args.extcap_version and not args.extcap_interfaces:
extcap_version() extcap_version()
sys.exit(0) sys.exit(0)
if ( args.extcap_interfaces == False and args.extcap_interface == None ): if not args.extcap_interfaces and args.extcap_interface is None:
parser.exit("An interface must be provided or the selection must be displayed") parser.exit("An interface must be provided or the selection must be displayed")
if ( args.extcap_capture_filter and not args.capture ): if args.extcap_capture_filter and not args.capture:
validate_capture_filter(args.extcap_capture_filter) validate_capture_filter(args.extcap_capture_filter)
sys.exit(0) sys.exit(0)
if ( args.extcap_interfaces == True or args.extcap_interface == None ): if args.extcap_interfaces or args.extcap_interface is None:
extcap_interfaces() extcap_interfaces()
sys.exit(0) sys.exit(0)
if ( len(unknown) > 1 ): if len(unknown) > 1:
print("Extcap Example %d unknown arguments given" % len(unknown) ) print("Extcap Example %d unknown arguments given" % len(unknown))
m = re.match ( 'example(\d+)', args.extcap_interface ) m = re.match('example(\d+)', args.extcap_interface)
if not m: if not m:
sys.exit(ERROR_INTERFACE) sys.exit(ERROR_INTERFACE)
interface = m.group(1) interface = m.group(1)
message = args.message message = args.message
if ( args.message == None or len(args.message) == 0 ): if args.message is None or len(args.message) == 0:
message = "Extcap Test" message = "Extcap Test"
fake_ip = args.fake_ip fake_ip = args.fake_ip
if ( args.fake_ip == None or len(args.fake_ip) < 7 or len(args.fake_ip.split('.')) != 4 ): if args.fake_ip is None or len(args.fake_ip) < 7 or len(args.fake_ip.split('.')) != 4:
fake_ip = "127.0.0.1" fake_ip = "127.0.0.1"
ts = args.ts ts = args.ts
if ( args.extcap_reload_option and len(args.extcap_reload_option) > 0 ): if args.extcap_reload_option and len(args.extcap_reload_option) > 0:
option = args.extcap_reload_option option = args.extcap_reload_option
if args.extcap_config: if args.extcap_config:

View File

@ -246,7 +246,7 @@ class _ExecutionScope(object):
for cleanup in self.finalizers: for cleanup in self.finalizers:
try: try:
cleanup() cleanup()
except: except Exception:
exceptions.append(sys.exc_info()[1]) exceptions.append(sys.exc_info()[1])
self.cache.clear() self.cache.clear()
self.finalizers.clear() self.finalizers.clear()

View File

@ -129,7 +129,7 @@ class SubprocessTestCase(unittest.TestCase):
for proc in self.processes: for proc in self.processes:
try: try:
proc.kill() proc.kill()
except: except Exception:
pass pass
def setUp(self): def setUp(self):

View File

@ -131,7 +131,7 @@ def check_capture_fifo(cmd_dumpcap):
try: try:
# If a previous test left its fifo laying around, e.g. from a failure, remove it. # If a previous test left its fifo laying around, e.g. from a failure, remove it.
os.unlink(fifo_file) os.unlink(fifo_file)
except: except Exception:
pass pass
os.mkfifo(fifo_file) os.mkfifo(fifo_file)
slow_dhcp_cmd = subprocesstest.cat_dhcp_command('slow') slow_dhcp_cmd = subprocesstest.cat_dhcp_command('slow')
@ -334,7 +334,7 @@ def check_dumpcap_pcapng_sections(cmd_dumpcap, cmd_tshark, capture_file):
# If a previous test left its fifo laying around, e.g. from a failure, remove it. # If a previous test left its fifo laying around, e.g. from a failure, remove it.
try: try:
os.unlink(fifo_file) os.unlink(fifo_file)
except: pass except Exception: pass
os.mkfifo(fifo_file) os.mkfifo(fifo_file)
cat_cmd = subprocesstest.cat_cap_file_command(in_files) cat_cmd = subprocesstest.cat_cap_file_command(in_files)
fifo_procs.append(self.startProcess(('{0} > {1}'.format(cat_cmd, fifo_file)), shell=True)) fifo_procs.append(self.startProcess(('{0} > {1}'.format(cat_cmd, fifo_file)), shell=True))

View File

@ -164,7 +164,7 @@ class case_tshark_dump_glossaries(subprocesstest.SubprocessTestCase):
for glossary in glossaries: for glossary in glossaries:
try: try:
self.log_fd.truncate() self.log_fd.truncate()
except: except Exception:
pass pass
self.assertRun((cmd_tshark, '-G', glossary), env=base_env) self.assertRun((cmd_tshark, '-G', glossary), env=base_env)
self.assertEqual(self.countOutput(count_stdout=False, count_stderr=True), 0, 'Found error output while printing glossary ' + glossary) self.assertEqual(self.countOutput(count_stdout=False, count_stderr=True), 0, 'Found error output while printing glossary ' + glossary)

View File

@ -23,7 +23,7 @@ class PacketList:
items within it.""" items within it."""
def __init__(self, children=None): def __init__(self, children=None):
if children == None: if children is None:
self.children = [] self.children = []
else: else:
self.children = children self.children = children
@ -61,7 +61,7 @@ class PacketList:
def get_items(self, name, items=None): def get_items(self, name, items=None):
"""Return all items that match the name 'name'. """Return all items that match the name 'name'.
They are returned in order of a depth-first-search.""" They are returned in order of a depth-first-search."""
if items == None: if items is None:
top_level = 1 top_level = 1
items = [] items = []
else: else:
@ -83,7 +83,7 @@ class PacketList:
before other protocols. For example, if you have an HTTP before other protocols. For example, if you have an HTTP
protocol, you can find all tcp.dstport fields *before* that HTTP protocol, you can find all tcp.dstport fields *before* that HTTP
protocol. This helps analyze in the presence of tunneled protocols.""" protocol. This helps analyze in the presence of tunneled protocols."""
if items == None: if items is None:
top_level = 1 top_level = 1
items = [] items = []
else: else:
@ -173,7 +173,7 @@ class Protocol(ProtoTreeItem):
def dump(self, fh=sys.stdout, indent=0): def dump(self, fh=sys.stdout, indent=0):
print >> fh, "%s<proto " % (" " * indent,), print >> fh, "%s<proto " % (" " * indent,),
ProtoTreeItem.dump(self, fh) ProtoTreeItem.dump(self, fh)
print >> fh, '>' print >> fh, '>'
@ -252,7 +252,7 @@ class ParseXML(xml.sax.handler.ContentHandler):
if len(self.element_stack) > 1: if len(self.element_stack) > 1:
parent_elem = self.element_stack[-1] parent_elem = self.element_stack[-1]
parent_elem.add_child(elem) parent_elem.add_child(elem)
self.chars = "" self.chars = ""
# If we just finished a Packet element, hand it to the # If we just finished a Packet element, hand it to the

View File

@ -319,7 +319,7 @@ reserved_words = {
} }
for k in list(static_tokens.keys()): for k in list(static_tokens.keys()):
if static_tokens [k] == None: if static_tokens [k] is None:
static_tokens [k] = k static_tokens [k] = k
StringTypes = ['Numeric', 'Printable', 'IA5', 'BMP', 'Universal', 'UTF8', StringTypes = ['Numeric', 'Printable', 'IA5', 'BMP', 'Universal', 'UTF8',
@ -1594,7 +1594,7 @@ class EthCtx:
name=self.eth_hf[f]['attr']['NAME'] name=self.eth_hf[f]['attr']['NAME']
try: # Python < 3 try: # Python < 3
trantab = maketrans("- ", "__") trantab = maketrans("- ", "__")
except: except Exception:
trantab = str.maketrans("- ", "__") trantab = str.maketrans("- ", "__")
name = name.translate(trantab) name = name.translate(trantab)
namelower = name.lower() namelower = name.lower()
@ -4132,7 +4132,7 @@ class SequenceOfType (SeqOfType):
# name, tag (None for no tag, EXPLICIT() for explicit), typ) # name, tag (None for no tag, EXPLICIT() for explicit), typ)
# or '' + (1,) for optional # or '' + (1,) for optional
sizestr = '' sizestr = ''
if self.size_constr != None: if self.size_constr is not None:
print("#Ignoring size constraint:", self.size_constr.subtype) print("#Ignoring size constraint:", self.size_constr.subtype)
return "%sasn1.SEQUENCE_OF (%s%s)" % (ctx.spaces (), return "%sasn1.SEQUENCE_OF (%s%s)" % (ctx.spaces (),
self.val.to_python (ctx), self.val.to_python (ctx),
@ -4267,7 +4267,7 @@ class SequenceType (SeqType):
# CHOICE or SEQUENCE_OF (where should the SEQUENCE_OF name come # CHOICE or SEQUENCE_OF (where should the SEQUENCE_OF name come
# from? for others, element or arm name would be fine) # from? for others, element or arm name would be fine)
seq_name = getattr (self, 'sequence_name', None) seq_name = getattr (self, 'sequence_name', None)
if seq_name == None: if seq_name is None:
seq_name = 'None' seq_name = 'None'
else: else:
seq_name = "'" + seq_name + "'" seq_name = "'" + seq_name + "'"
@ -4751,7 +4751,7 @@ class EnumeratedType (Type):
def eth_type_default_pars(self, ectx, tname): def eth_type_default_pars(self, ectx, tname):
pars = Type.eth_type_default_pars(self, ectx, tname) pars = Type.eth_type_default_pars(self, ectx, tname)
(root_num, ext_num, map_table) = self.get_vals_etc(ectx)[1:] (root_num, ext_num, map_table) = self.get_vals_etc(ectx)[1:]
if (self.ext != None): if self.ext is not None:
ext = 'TRUE' ext = 'TRUE'
else: else:
ext = 'FALSE' ext = 'FALSE'
@ -4767,7 +4767,7 @@ class EnumeratedType (Type):
def eth_type_default_table(self, ectx, tname): def eth_type_default_table(self, ectx, tname):
if (not ectx.Per() and not ectx.Oer()): return '' if (not ectx.Per() and not ectx.Oer()): return ''
map_table = self.get_vals_etc(ectx)[3] map_table = self.get_vals_etc(ectx)[3]
if (map_table == None): return '' if map_table is None: return ''
table = "static guint32 %(TABLE)s[%(ROOT_NUM)s+%(EXT_NUM)s] = {" table = "static guint32 %(TABLE)s[%(ROOT_NUM)s+%(EXT_NUM)s] = {"
table += ", ".join([str(v) for v in map_table]) table += ", ".join([str(v) for v in map_table])
table += "};\n" table += "};\n"
@ -8022,7 +8022,7 @@ def eth_main():
try: try:
data = data.decode(encoding) data = data.decode(encoding)
break break
except: except Exception:
warnings.warn_explicit("Decoding %s as %s failed, trying next." % (fn, encoding), UserWarning, '', 0) warnings.warn_explicit("Decoding %s as %s failed, trying next." % (fn, encoding), UserWarning, '', 0)
# Py2 compat, name.translate in eth_output_hf_arr fails with unicode # Py2 compat, name.translate in eth_output_hf_arr fails with unicode
if not isinstance(data, str): if not isinstance(data, str):

View File

@ -5,13 +5,14 @@
# #
# SPDX-License-Identifier: GPL-2.0-or-later # SPDX-License-Identifier: GPL-2.0-or-later
import argparse
import os import os
import re import re
import requests
import shutil import shutil
import subprocess
import argparse
import signal import signal
import subprocess
import requests
# This utility scans the dissector code for URLs, then attempts to # This utility scans the dissector code for URLs, then attempts to
# fetch the links. The results are shown in stdout, but also, at # fetch the links. The results are shown in stdout, but also, at
@ -38,6 +39,7 @@ def signal_handler(sig, frame):
should_exit = True should_exit = True
print('You pressed Ctrl+C - exiting') print('You pressed Ctrl+C - exiting')
signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGINT, signal_handler)
@ -127,7 +129,7 @@ links = []
files = [] files = []
def findLinksInFile(filename): def find_links_in_file(filename):
with open(filename, 'r') as f: with open(filename, 'r') as f:
for line_number, line in enumerate(f, start=1): for line_number, line in enumerate(f, start=1):
# TODO: not matching # TODO: not matching
@ -149,13 +151,13 @@ def findLinksInFile(filename):
# Scan the given folder for links to test. # Scan the given folder for links to test.
def findLinksInFolder(folder): def find_links_in_folder(folder):
# Look at files in sorted order, to give some idea of how far through it # Look at files in sorted order, to give some idea of how far through it
# is. # is.
for filename in sorted(os.listdir(folder)): for filename in sorted(os.listdir(folder)):
if filename.endswith('.c'): if filename.endswith('.c'):
global links global links
findLinksInFile(os.path.join(folder, filename)) find_links_in_file(os.path.join(folder, filename))
################################################################# #################################################################
@ -176,44 +178,44 @@ parser.add_argument('--verbose', action='store_true',
args = parser.parse_args() args = parser.parse_args()
def is_dissector_file(filename):
def isDissectorFile(filename): p = re.compile(r'epan/dissectors/packet-.*\.c')
p = re.compile('epan/dissectors/packet-.*\.c')
return p.match(filename) return p.match(filename)
# Get files from wherever command-line args indicate. # Get files from wherever command-line args indicate.
if args.file: if args.file:
# Fetch links from single file. # Fetch links from single file.
findLinksInFile(args.file) find_links_in_file(args.file)
elif args.commits: elif args.commits:
# Get files affected by specified number of commits. # Get files affected by specified number of commits.
command = ['git', 'diff', '--name-only', 'HEAD~' + args.commits] command = ['git', 'diff', '--name-only', 'HEAD~' + args.commits]
files = [f.decode('utf-8') files = [f.decode('utf-8')
for f in subprocess.check_output(command).splitlines()] for f in subprocess.check_output(command).splitlines()]
# Fetch links from files (dissectors files only) # Fetch links from files (dissectors files only)
files = list(filter(lambda f : isDissectorFile(f), files)) files = list(filter(lambda f: is_dissector_file(f), files))
for f in files: for f in files:
findLinksInFile(f) find_links_in_file(f)
elif args.open: elif args.open:
# Unstaged changes. # Unstaged changes.
command = ['git', 'diff', '--name-only'] command = ['git', 'diff', '--name-only']
files = [f.decode('utf-8') files = [f.decode('utf-8')
for f in subprocess.check_output(command).splitlines()] for f in subprocess.check_output(command).splitlines()]
files = list(filter(lambda f : isDissectorFile(f), files)) files = list(filter(lambda f: is_dissector_file(f), files))
# Staged changes. # Staged changes.
command = ['git', 'diff', '--staged', '--name-only'] command = ['git', 'diff', '--staged', '--name-only']
files_staged = [f.decode('utf-8') files_staged = [f.decode('utf-8')
for f in subprocess.check_output(command).splitlines()] for f in subprocess.check_output(command).splitlines()]
files_staged = list(filter(lambda f : isDissectorFile(f), files_staged)) files_staged = list(filter(lambda f: is_dissector_file(f), files_staged))
for f in files: for f in files:
findLinksInFile(f) find_links_in_file(f)
for f in files_staged: for f in files_staged:
if not f in files: if f not in files:
findLinksInFile(f) find_links_in_file(f)
files.append(f) files.append(f)
else: else:
# Find links from dissector folder. # Find links from dissector folder.
findLinksInFolder(os.path.join(os.path.dirname( find_links_in_folder(os.path.join(os.path.dirname(
__file__), '..', 'epan', 'dissectors')) __file__), '..', 'epan', 'dissectors'))

View File

@ -335,13 +335,13 @@ elif args.open:
files = [f.decode('utf-8') files = [f.decode('utf-8')
for f in subprocess.check_output(command).splitlines()] for f in subprocess.check_output(command).splitlines()]
# Only interested in dissector files. # Only interested in dissector files.
files = list(filter(lambda f : isDissectorFile(f), files)) files = list(filter(lambda f : is_dissector_file(f), files))
# Staged changes. # Staged changes.
command = ['git', 'diff', '--staged', '--name-only'] command = ['git', 'diff', '--staged', '--name-only']
files_staged = [f.decode('utf-8') files_staged = [f.decode('utf-8')
for f in subprocess.check_output(command).splitlines()] for f in subprocess.check_output(command).splitlines()]
# Only interested in dissector files. # Only interested in dissector files.
files_staged = list(filter(lambda f : isDissectorFile(f), files_staged)) files_staged = list(filter(lambda f : is_dissector_file(f), files_staged))
for f in files: for f in files:
files.append(f) files.append(f)
for f in files_staged: for f in files_staged:

View File

@ -88,7 +88,7 @@ def findItems(filename):
def isDissectorFile(filename): def is_dissector_file(filename):
p = re.compile('.*packet-.*\.c') p = re.compile('.*packet-.*\.c')
return p.match(filename) return p.match(filename)
@ -99,7 +99,7 @@ def findDissectorFilesInFolder(folder):
for f in sorted(os.listdir(folder)): for f in sorted(os.listdir(folder)):
if should_exit: if should_exit:
return return
if isDissectorFile(f): if is_dissector_file(f):
filename = os.path.join(folder, f) filename = os.path.join(folder, f)
files.append(filename) files.append(filename)
return files return files
@ -160,20 +160,20 @@ elif args.commits:
files = [f.decode('utf-8') files = [f.decode('utf-8')
for f in subprocess.check_output(command).splitlines()] for f in subprocess.check_output(command).splitlines()]
# Will examine dissector files only # Will examine dissector files only
files = list(filter(lambda f : isDissectorFile(f), files)) files = list(filter(lambda f : is_dissector_file(f), files))
elif args.open: elif args.open:
# Unstaged changes. # Unstaged changes.
command = ['git', 'diff', '--name-only'] command = ['git', 'diff', '--name-only']
files = [f.decode('utf-8') files = [f.decode('utf-8')
for f in subprocess.check_output(command).splitlines()] for f in subprocess.check_output(command).splitlines()]
# Only interested in dissector files. # Only interested in dissector files.
files = list(filter(lambda f : isDissectorFile(f), files)) files = list(filter(lambda f : is_dissector_file(f), files))
# Staged changes. # Staged changes.
command = ['git', 'diff', '--staged', '--name-only'] command = ['git', 'diff', '--staged', '--name-only']
files_staged = [f.decode('utf-8') files_staged = [f.decode('utf-8')
for f in subprocess.check_output(command).splitlines()] for f in subprocess.check_output(command).splitlines()]
# Only interested in dissector files. # Only interested in dissector files.
files_staged = list(filter(lambda f : isDissectorFile(f), files_staged)) files_staged = list(filter(lambda f : is_dissector_file(f), files_staged))
for f in files: for f in files:
files.append(f) files.append(f)
for f in files_staged: for f in files_staged:

View File

@ -192,7 +192,7 @@ class Item:
return return
n += 1 n += 1
except: except Exception:
# Sometimes, macro is used for item type so catch and keep going. # Sometimes, macro is used for item type so catch and keep going.
pass pass
@ -262,7 +262,7 @@ def find_items(filename, check_mask=False, check_label=False):
def isDissectorFile(filename): def is_dissector_file(filename):
p = re.compile('.*packet-.*\.c') p = re.compile('.*packet-.*\.c')
return p.match(filename) return p.match(filename)
@ -282,7 +282,7 @@ def findDissectorFilesInFolder(folder, dissector_files=[], recursive=False):
filename = os.path.join(folder, f) filename = os.path.join(folder, f)
dissector_files.append(filename) dissector_files.append(filename)
return [x for x in filter(isDissectorFile, dissector_files)] return [x for x in filter(is_dissector_file, dissector_files)]
@ -332,20 +332,20 @@ elif args.commits:
files = [f.decode('utf-8') files = [f.decode('utf-8')
for f in subprocess.check_output(command).splitlines()] for f in subprocess.check_output(command).splitlines()]
# Will examine dissector files only # Will examine dissector files only
files = list(filter(lambda f : isDissectorFile(f), files)) files = list(filter(lambda f : is_dissector_file(f), files))
elif args.open: elif args.open:
# Unstaged changes. # Unstaged changes.
command = ['git', 'diff', '--name-only'] command = ['git', 'diff', '--name-only']
files = [f.decode('utf-8') files = [f.decode('utf-8')
for f in subprocess.check_output(command).splitlines()] for f in subprocess.check_output(command).splitlines()]
# Only interested in dissector files. # Only interested in dissector files.
files = list(filter(lambda f : isDissectorFile(f), files)) files = list(filter(lambda f : is_dissector_file(f), files))
# Staged changes. # Staged changes.
command = ['git', 'diff', '--staged', '--name-only'] command = ['git', 'diff', '--staged', '--name-only']
files_staged = [f.decode('utf-8') files_staged = [f.decode('utf-8')
for f in subprocess.check_output(command).splitlines()] for f in subprocess.check_output(command).splitlines()]
# Only interested in dissector files. # Only interested in dissector files.
files_staged = list(filter(lambda f : isDissectorFile(f), files_staged)) files_staged = list(filter(lambda f : is_dissector_file(f), files_staged))
for f in files: for f in files:
files.append(f) files.append(f)
for f in files_staged: for f in files_staged:

View File

@ -16,9 +16,10 @@
# --protoshortname DUMB --protoabbrev dumb --license GPL-2.0-or-later --years "2019-2020" # --protoshortname DUMB --protoabbrev dumb --license GPL-2.0-or-later --years "2019-2020"
# #
import os
import argparse import argparse
from datetime import datetime from datetime import datetime
import os
parser = argparse.ArgumentParser(description='The Wireshark Dissector Generator') parser = argparse.ArgumentParser(description='The Wireshark Dissector Generator')
parser.add_argument("--name", help="The author of the dissector", required=True) parser.add_argument("--name", help="The author of the dissector", required=True)
@ -30,17 +31,21 @@ parser.add_argument("--license", help="The license for this dissector (please us
parser.add_argument("--years", help="Years of validity for the license. If omitted, the current year will be used") parser.add_argument("--years", help="Years of validity for the license. If omitted, the current year will be used")
parser.add_argument("-f", "--force", action='store_true', help="Force overwriting the dissector file if it already exists") parser.add_argument("-f", "--force", action='store_true', help="Force overwriting the dissector file if it already exists")
def wsdir(): def wsdir():
return os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) return os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
def output_file(args): def output_file(args):
return os.path.join(wsdir(), "epan/dissectors/packet-" + args.protoabbrev + ".c") return os.path.join(wsdir(), "epan/dissectors/packet-" + args.protoabbrev + ".c")
def read_skeleton(): def read_skeleton():
skeletonfile = os.path.join(wsdir(), "doc/packet-PROTOABBREV.c") skeletonfile = os.path.join(wsdir(), "doc/packet-PROTOABBREV.c")
print("Reading skeleton file: " + skeletonfile) print("Reading skeleton file: " + skeletonfile)
return open(skeletonfile).read() return open(skeletonfile).read()
def replace_fields(buffer, args): def replace_fields(buffer, args):
print("Replacing fields in skeleton") print("Replacing fields in skeleton")
output = buffer\ output = buffer\
@ -77,6 +82,7 @@ def replace_fields(buffer, args):
return output return output
def write_dissector(buffer, args): def write_dissector(buffer, args):
ofile = output_file(args) ofile = output_file(args)
if os.path.isfile(ofile) and not args.force: if os.path.isfile(ofile) and not args.force:
@ -84,6 +90,7 @@ def write_dissector(buffer, args):
print("Writing output file: " + ofile) print("Writing output file: " + ofile)
return open(ofile, "w").write(buffer) return open(ofile, "w").write(buffer)
def patch_makefile(args): def patch_makefile(args):
cmakefile = os.path.join(wsdir(), "epan/dissectors/CMakeLists.txt") cmakefile = os.path.join(wsdir(), "epan/dissectors/CMakeLists.txt")
print("Patching makefile: " + cmakefile) print("Patching makefile: " + cmakefile)
@ -104,6 +111,7 @@ def patch_makefile(args):
output += line output += line
open(cmakefile, "w").write(output) open(cmakefile, "w").write(output)
def print_header(): def print_header():
print("") print("")
print("**************************************************") print("**************************************************")
@ -117,12 +125,14 @@ def print_header():
print("**************************************************") print("**************************************************")
print("") print("")
def print_trailer(args): def print_trailer(args):
print("") print("")
print("The skeleton for the dissector of the " + args.protoshortname + " protocol has been generated.") print("The skeleton for the dissector of the " + args.protoshortname + " protocol has been generated.")
print("Please review/extend it to match your specific criterias.") print("Please review/extend it to match your specific criterias.")
print("") print("")
if __name__ == '__main__': if __name__ == '__main__':
print_header() print_header()
args = parser.parse_args() args = parser.parse_args()

View File

@ -47,7 +47,7 @@ def get_url_lines(url):
exit_msg("URL error fetching {0}: {1}".format(url, err.reason)) exit_msg("URL error fetching {0}: {1}".format(url, err.reason))
except OSError as err: except OSError as err:
exit_msg("OS error fetching {0}".format(url, err.strerror)) exit_msg("OS error fetching {0}".format(url, err.strerror))
except: except Exception:
exit_msg("Unexpected error:", sys.exc_info()[0]) exit_msg("Unexpected error:", sys.exc_info()[0])
return lines return lines

View File

@ -24,7 +24,7 @@ from textwrap import TextWrapper
try: try:
from HTMLParser import HTMLParser from HTMLParser import HTMLParser
from htmlentitydefs import name2codepoint from htmlentitydefs import name2codepoint
except: # Python 3 except ImportError: # Python 3
from html.parser import HTMLParser from html.parser import HTMLParser
from html.entities import name2codepoint from html.entities import name2codepoint
unichr = chr # for html entity handling unichr = chr # for html entity handling
@ -35,7 +35,7 @@ class TextHTMLParser(HTMLParser):
try: try:
# Python 3.4 # Python 3.4
HTMLParser. __init__(self, convert_charrefs=True) HTMLParser. __init__(self, convert_charrefs=True)
except: except Exception:
HTMLParser. __init__(self) HTMLParser. __init__(self)
# All text, concatenated # All text, concatenated
self.output_buffer = '' self.output_buffer = ''

View File

@ -14,11 +14,9 @@ import sys
import ijson import ijson
import operator import operator
import copy import copy
import os
import binascii import binascii
import array import array
import argparse import argparse
import subprocess
import string import string
import random import random
import math import math
@ -135,13 +133,13 @@ def read_py_function(name):
ind = len(line) - len(line.lstrip()) ind = len(line) - len(line.lstrip())
if (line.find("def " + name) != -1): if line.find("def " + name) != -1:
record = True record = True
indent = ind indent = ind
elif (record == True and indent == ind and len(line) > 1): elif record and indent == ind and len(line) > 1:
record = False record = False
if (record == True): if record:
s = s + line s = s + line
file.close() file.close()
@ -227,8 +225,8 @@ def py_generator(d, r, frame_name='frame_raw', frame_position=0):
for k, v in d.items(): for k, v in d.items():
# no recursion # no recursion
if ( k.endswith("_raw") or ("_raw_" in k) ): if k.endswith("_raw") or "_raw_" in k:
if (isinstance(v[1], (list, tuple)) or isinstance(v[2], (list, tuple)) ): if isinstance(v[1], (list, tuple)) or isinstance(v[2], (list, tuple)):
#i = 1; #i = 1;
for _v in v: for _v in v:
h = _v[0] h = _v[0]
@ -248,7 +246,7 @@ def py_generator(d, r, frame_name='frame_raw', frame_position=0):
fn = frame_name.replace('.', '_') fn = frame_name.replace('.', '_')
if (fn == key): if (fn == key):
fn = None fn = None
value = [fn , h, p, l, b, t] value = [fn, h, p, l, b, t]
r[key] = value r[key] = value
@ -328,7 +326,7 @@ def lsb(x):
def multiply_strings(original_string, new_string, mask): def multiply_strings(original_string, new_string, mask):
ret_string = new_string ret_string = new_string
if mask == None: if mask is None:
return ret_string return ret_string
for i in range(0, min(len(original_string), len(new_string), len(mask)), 2): for i in range(0, min(len(original_string), len(new_string), len(mask)), 2):
if mask[i:i + 2] == 'ff': if mask[i:i + 2] == 'ff':
@ -344,7 +342,7 @@ def multiply_strings(original_string, new_string, mask):
# b - bitmask # b - bitmask
# t - type # t - type
# frame_amask - optional, anonymization mask (00 - not anonymized byte, ff - anonymized byte) # frame_amask - optional, anonymization mask (00 - not anonymized byte, ff - anonymized byte)
def rewrite_frame(frame_raw, h, p, l, b, t, frame_amask = None): def rewrite_frame(frame_raw, h, p, l, b, t, frame_amask=None):
if p < 0 or l < 0 or h is None: if p < 0 or l < 0 or h is None:
return frame_raw return frame_raw
@ -389,14 +387,14 @@ def rewrite_frame(frame_raw, h, p, l, b, t, frame_amask = None):
# print "{0:08b}".format(M[i]), # print "{0:08b}".format(M[i]),
# print # print
j = 0; j = 0
for i in range(len(_H)): for i in range(len(_H)):
if (M[i] != 0): if (M[i] != 0):
v = H[j] << lsb(M[i]) v = H[j] << lsb(M[i])
# print "Debug: {0:08b}".format(v), # print "Debug: {0:08b}".format(v),
_H[i] = (_H[i] & ~M[i]) | (v & M[i]) _H[i] = (_H[i] & ~M[i]) | (v & M[i])
# print "Debug: " + str(_H[i]), # print "Debug: " + str(_H[i]),
j = j + 1; j = j + 1
# for i in range(len(_H)): # for i in range(len(_H)):
# print "{0:08b}".format(_H[i]), # print "{0:08b}".format(_H[i]),
@ -412,8 +410,8 @@ def rewrite_frame(frame_raw, h, p, l, b, t, frame_amask = None):
def assemble_frame(d, frame_time): def assemble_frame(d, frame_time):
input = d['frame_raw'][1] input = d['frame_raw'][1]
isFlat = False isFlat = False
linux_cooked_header = False; linux_cooked_header = False
while(isFlat == False): while not isFlat:
isFlat = True isFlat = True
_d = d.copy() _d = d.copy()
for key, val in _d.items(): for key, val in _d.items():
@ -424,7 +422,7 @@ def assemble_frame(d, frame_time):
t = val[5] # type t = val[5] # type
if (key == "sll_raw"): if (key == "sll_raw"):
linux_cooked_header = True; linux_cooked_header = True
# only if the node is not parent # only if the node is not parent
isParent = False isParent = False
@ -434,7 +432,7 @@ def assemble_frame(d, frame_time):
isFlat = False isFlat = False
break break
if (isParent == False and val[0] is not None): if not isParent and val[0] is not None:
d[val[0]][1] = rewrite_frame(d[val[0]][1], h, p, l, b, t) d[val[0]][1] = rewrite_frame(d[val[0]][1], h, p, l, b, t)
del d[key] del d[key]
@ -554,14 +552,14 @@ else:
anonymize = {} anonymize = {}
if args.mask: if args.mask:
for m in args.mask: for m in args.mask:
if not '_raw' in m: if '_raw' not in m:
print("Error: The specified fields by -m switch should be raw fields. " + m + " does not have _raw suffix") print("Error: The specified fields by -m switch should be raw fields. " + m + " does not have _raw suffix")
sys.exit() sys.exit()
af = AnonymizedField(m, 0) af = AnonymizedField(m, 0)
anonymize[af.field] = af anonymize[af.field] = af
if args.anonymize: if args.anonymize:
for a in args.anonymize: for a in args.anonymize:
if not '_raw' in a: if '_raw' not in a:
print("Error: The specified fields by -a switch should be raw fields. " + a + " does not have _raw suffix") print("Error: The specified fields by -a switch should be raw fields. " + a + " does not have _raw suffix")
sys.exit() sys.exit()
af = AnonymizedField(a, 1) af = AnonymizedField(a, 1)
@ -577,13 +575,13 @@ if salt is None:
salt = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(10)) salt = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(10))
# Generate pcap # Generate pcap
if args.python == False: if args.python is False:
pcap_out = scapy.PcapWriter(outfile, append=False, sync=False) pcap_out = scapy.PcapWriter(outfile, append=False, sync=False)
# Iterate over packets in JSON # Iterate over packets in JSON
for packet in ijson.items(data_file, "item", buf_size=200000): for packet in ijson.items(data_file, "item", buf_size=200000):
_list = [] _list = []
linux_cooked_header = False; linux_cooked_header = False
# get flat raw fields into _list # get flat raw fields into _list
for raw in raw_flat_collector(packet['_source']['layers']): for raw in raw_flat_collector(packet['_source']['layers']):
@ -635,7 +633,7 @@ if args.python == False:
# anonymize fields # anonymize fields
if (raw[5] in anonymize): if (raw[5] in anonymize):
[_h, _h_mask] = anonymize[raw[5]].anonymize_field(_h, _t, salt) [_h, _h_mask] = anonymize[raw[5]].anonymize_field(_h, _t, salt)
# print("Debug: " + str(raw)) # print("Debug: " + str(raw))
frame_raw = rewrite_frame(frame_raw, _h, _p, _l, _b, _t, frame_amask) frame_raw = rewrite_frame(frame_raw, _h, _p, _l, _b, _t, frame_amask)
@ -654,8 +652,8 @@ if args.python == False:
# for Linux cooked header replace dest MAC and remove two bytes to reconstruct normal frame using text2pcap # for Linux cooked header replace dest MAC and remove two bytes to reconstruct normal frame using text2pcap
if (linux_cooked_header): if (linux_cooked_header):
frame_raw = "000000000000" + frame_raw[6 * 2:] # replce dest MAC frame_raw = "000000000000" + frame_raw[6 * 2:] # replce dest MAC
frame_raw = frame_raw[:12 * 2] + "" + frame_raw[14 * 2:] # remove two bytes before Protocol frame_raw = frame_raw[:12 * 2] + "" + frame_raw[14 * 2:] # remove two bytes before Protocol
# Testing: remove comment to compare input and output for not modified json # Testing: remove comment to compare input and output for not modified json
if (args.verbose and input_frame_raw != frame_raw): if (args.verbose and input_frame_raw != frame_raw):
@ -687,7 +685,7 @@ else:
#print "packet = " + str(packet['_source']['layers']) #print "packet = " + str(packet['_source']['layers'])
py_generator(packet['_source']['layers'], r) py_generator(packet['_source']['layers'], r)
for key, value in r.items() : for key, value in r.items():
f.write(" d['" + key + "'] =",) f.write(" d['" + key + "'] =",)
f.write(" " + str(value) + "\n") f.write(" " + str(value) + "\n")

View File

@ -52,7 +52,7 @@ def open_url(url):
req = urllib.request.Request(url, headers=req_headers) req = urllib.request.Request(url, headers=req_headers)
response = urllib.request.urlopen(req) response = urllib.request.urlopen(req)
body = response.read().decode('UTF-8', 'replace') body = response.read().decode('UTF-8', 'replace')
except: except Exception:
exit_msg('Error opening ' + url) exit_msg('Error opening ' + url)
return (body, dict(response.info())) return (body, dict(response.info()))
@ -208,7 +208,7 @@ def main():
try: try:
tmpl_fd = io.open(template_path, 'r', encoding='UTF-8') tmpl_fd = io.open(template_path, 'r', encoding='UTF-8')
except: except Exception:
exit_msg("Couldn't open template file for reading ({}) ".format(template_path)) exit_msg("Couldn't open template file for reading ({}) ".format(template_path))
for tmpl_line in tmpl_fd: for tmpl_line in tmpl_fd:
tmpl_line = tmpl_line.strip() tmpl_line = tmpl_line.strip()
@ -265,7 +265,7 @@ def main():
try: try:
manuf_fd = io.open(manuf_path, 'w', encoding='UTF-8') manuf_fd = io.open(manuf_path, 'w', encoding='UTF-8')
except: except Exception:
exit_msg("Couldn't open manuf file for reading ({}) ".format(manuf_path)) exit_msg("Couldn't open manuf file for reading ({}) ".format(manuf_path))
manuf_fd.write(u"# This file was generated by running ./tools/make-manuf.py.\n") manuf_fd.write(u"# This file was generated by running ./tools/make-manuf.py.\n")

View File

@ -64,19 +64,19 @@ def parse_rows(svc_fd):
try: try:
sn_pos = headers.index('Service Name') sn_pos = headers.index('Service Name')
except: except Exception:
sn_pos = 0 sn_pos = 0
try: try:
pn_pos = headers.index('Port Number') pn_pos = headers.index('Port Number')
except: except Exception:
pn_pos = 1 pn_pos = 1
try: try:
tp_pos = headers.index('Transport Protocol') tp_pos = headers.index('Transport Protocol')
except: except Exception:
tp_pos = 2 tp_pos = 2
try: try:
desc_pos = headers.index('Description') desc_pos = headers.index('Description')
except: except Exception:
desc_pos = 3 desc_pos = 3
services_map = {} services_map = {}
@ -176,7 +176,7 @@ def main(argv):
else: else:
req = urllib.request.urlopen(svc_url) req = urllib.request.urlopen(svc_url)
svc_fd = codecs.getreader('utf8')(req) svc_fd = codecs.getreader('utf8')(req)
except: except Exception:
exit_msg('Error opening ' + svc_url) exit_msg('Error opening ' + svc_url)
body = parse_rows(svc_fd) body = parse_rows(svc_fd)

View File

@ -173,7 +173,7 @@ class NamedList:
def Name(self, new_name = None): def Name(self, new_name = None):
"Get/Set name of list" "Get/Set name of list"
if new_name != None: if new_name is not None:
self.name = new_name self.name = new_name
return self.name return self.name
@ -183,7 +183,7 @@ class NamedList:
def Null(self): def Null(self):
"Is there no list (different from an empty list)?" "Is there no list (different from an empty list)?"
return self.list == None return self.list is None
def Empty(self): def Empty(self):
"It the list empty (different from a null list)?" "It the list empty (different from a null list)?"
@ -253,7 +253,7 @@ class PTVC(NamedList):
ptvc_rec = PTVCRecord(field, length, endianness, var, repeat, req_cond, info_str, code) ptvc_rec = PTVCRecord(field, length, endianness, var, repeat, req_cond, info_str, code)
if expected_offset == None: if expected_offset is None:
expected_offset = offset expected_offset = offset
elif expected_offset == -1: elif expected_offset == -1:
@ -381,7 +381,7 @@ class PTVCRecord:
req_cond = "NO_REQ_COND" req_cond = "NO_REQ_COND"
else: else:
req_cond = global_req_cond[self.req_cond] req_cond = global_req_cond[self.req_cond]
assert req_cond != None assert req_cond is not None
if isinstance(self.field, struct): if isinstance(self.field, struct):
return self.field.ReferenceString(var, repeat, req_cond) return self.field.ReferenceString(var, repeat, req_cond)
@ -489,7 +489,7 @@ class NCP:
def FunctionCode(self, part=None): def FunctionCode(self, part=None):
"Returns the function code for this NCP packet." "Returns the function code for this NCP packet."
if part == None: if part is None:
return self.__code__ return self.__code__
elif part == 'high': elif part == 'high':
if self.HasSubFunction(): if self.HasSubFunction():
@ -685,7 +685,7 @@ class NCP:
realizes that because Python lists are the input and realizes that because Python lists are the input and
output.""" output."""
if codes == None: if codes is None:
return self.codes return self.codes
# Sanity check # Sanity check
@ -729,7 +729,7 @@ def srec(field, endianness=None, **kw):
def _rec(start, length, field, endianness, kw): def _rec(start, length, field, endianness, kw):
# If endianness not explicitly given, use the field's # If endianness not explicitly given, use the field's
# default endiannes. # default endiannes.
if endianness == None: if endianness is None:
endianness = field.Endianness() endianness = field.Endianness()
# Setting a var? # Setting a var?
@ -804,7 +804,7 @@ class Type:
return self.ftype return self.ftype
def Display(self, newval=None): def Display(self, newval=None):
if newval != None: if newval is not None:
self.disp = newval self.disp = newval
return self.disp return self.disp
@ -6786,7 +6786,7 @@ static expert_field ei_ncp_address_type = EI_INIT;
req_cond_size = "NO_REQ_COND_SIZE" req_cond_size = "NO_REQ_COND_SIZE"
else: else:
req_cond_size = pkt.ReqCondSize() req_cond_size = pkt.ReqCondSize()
if req_cond_size == None: if req_cond_size is None:
msg.write("NCP packet %s needs a ReqCondSize*() call\n" \ msg.write("NCP packet %s needs a ReqCondSize*() call\n" \
% (pkt.CName(),)) % (pkt.CName(),))
sys.exit(1) sys.exit(1)
@ -8626,7 +8626,7 @@ def main():
msg.write("Defined %d NCP types.\n" % (len(packets),)) msg.write("Defined %d NCP types.\n" % (len(packets),))
produce_code() produce_code()
except: except Exception:
traceback.print_exc(20, msg) traceback.print_exc(20, msg)
try: try:
out_file.close() out_file.close()

View File

@ -13,6 +13,7 @@ import os
import stat import stat
import time import time
class OutputFile: class OutputFile:
TIMER_MAX = 99999.9 TIMER_MAX = 99999.9
@ -28,11 +29,11 @@ class OutputFile:
def PrintPacket(self, timestamp, datalines): def PrintPacket(self, timestamp, datalines):
# What do to with the timestamp? I need more data about what # What do to with the timestamp? I need more data about what
# the netscreen timestamp is, then I can generate one for the text file. # the netscreen timestamp is, then I can generate one for the text file.
# print "TS:", timestamp.group("time") # print("TS:", timestamp.group("time"))
try: try:
timestamp = float(timestamp.group("time")) timestamp = float(timestamp.group("time"))
except ValueError: except ValueError:
sys.exit("Unable to convert '%s' to floating point." % \ sys.exit("Unable to convert '%s' to floating point." %
(timestamp,)) (timestamp,))
# Did we wrap around the timeer max? # Did we wrap around the timeer max?
@ -63,12 +64,14 @@ class OutputFile:
# Blank line # Blank line
print >> self.fh print >> self.fh
# Find a timestamp line # Find a timestamp line
re_timestamp = re.compile(r"^(?P<time>\d+\.\d): [\w/]+\((?P<io>.)\)(:| len=)") re_timestamp = re.compile(r"^(?P<time>\d+\.\d): [\w/]+\((?P<io>.)\)(:| len=)")
# Find a hex dump line # Find a hex dump line
re_hex_line = re.compile(r"(?P<hex>([0-9a-f]{2} ){1,16})\s+(?P<ascii>.){1,16}") re_hex_line = re.compile(r"(?P<hex>([0-9a-f]{2} ){1,16})\s+(?P<ascii>.){1,16}")
def run(input_filename, output_filename): def run(input_filename, output_filename):
try: try:
ifh = open(input_filename, "r") ifh = open(input_filename, "r")
@ -122,11 +125,13 @@ def usage():
print >> sys.stderr, "Usage: netscreen2dump.py netscreen-dump-file new-dump-file" print >> sys.stderr, "Usage: netscreen2dump.py netscreen-dump-file new-dump-file"
sys.exit(1) sys.exit(1)
def main(): def main():
if len(sys.argv) != 3: if len(sys.argv) != 3:
usage() usage()
run(sys.argv[1], sys.argv[2]) run(sys.argv[1], sys.argv[2])
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -46,7 +46,7 @@ class BackTrace:
# what we expect it should be. # what we expect it should be.
frame_num = int(m.group("num")) frame_num = int(m.group("num"))
if frame_num != frame_will_be: if frame_num != frame_will_be:
sys.exit("Found frame %d instead of %d" % \ sys.exit("Found frame %d instead of %d" %
(frame_num, frame_will_be)) (frame_num, frame_will_be))
# Find the function name. XXX - need to handle '???' # Find the function name. XXX - need to handle '???'
@ -193,7 +193,7 @@ def run_gdb(*commands):
except IOError, err: except IOError, err:
try: try:
os.unlink(fname) os.unlink(fname)
except: except Exception:
pass pass
sys.exit("Cannot close %s: %s" % (fname, err)) sys.exit("Cannot close %s: %s" % (fname, err))
@ -207,17 +207,17 @@ def run_gdb(*commands):
except OSError, err: except OSError, err:
try: try:
os.unlink(fname) os.unlink(fname)
except: except Exception:
pass pass
sys.exit("Cannot run gdb: %s" % (err,)) sys.exit("Cannot run gdb: %s" % (err,))
# Get gdb's output # Get gdb's output
result = pipe.readlines() result = pipe.readlines()
error = pipe.close() error = pipe.close()
if error != None: if error is not None:
try: try:
os.unlink(fname) os.unlink(fname)
except: except Exception:
pass pass
sys.exit("gdb returned an exit value of %s" % (error,)) sys.exit("gdb returned an exit value of %s" % (error,))
@ -225,7 +225,7 @@ def run_gdb(*commands):
# Remove the temp file and return the results # Remove the temp file and return the results
try: try:
os.unlink(fname) os.unlink(fname)
except: except Exception:
pass pass
return result return result
@ -341,7 +341,7 @@ def make_cap_file(pkt_data, lnk_t):
except IOError, err: except IOError, err:
try: try:
os.unlink(fname) os.unlink(fname)
except: except Exception:
pass pass
sys.exit("Cannot close %s: %s" % (fname, err)) sys.exit("Cannot close %s: %s" % (fname, err))
@ -354,14 +354,14 @@ def make_cap_file(pkt_data, lnk_t):
except OSError, err: except OSError, err:
try: try:
os.unlink(fname) os.unlink(fname)
except: except Exception:
pass pass
sys.exit("Cannot run text2pcap: %s" % (err,)) sys.exit("Cannot run text2pcap: %s" % (err,))
# Remove the temp file # Remove the temp file
try: try:
os.unlink(fname) os.unlink(fname)
except: except Exception:
pass pass
if retval == 0: if retval == 0:
@ -448,7 +448,7 @@ def main():
else: else:
assert 0 assert 0
if output_file == None: if output_file is None:
usage() usage()
if len(args) != 2: if len(args) != 2:

View File

@ -22,6 +22,7 @@ Ported to Python from rdps.c.
import sys import sys
import os.path import os.path
def ps_clean_string(raw_str): def ps_clean_string(raw_str):
ps_str = '' ps_str = ''
for c in raw_str: for c in raw_str:
@ -35,29 +36,35 @@ def ps_clean_string(raw_str):
ps_str += c ps_str += c
return ps_str return ps_str
def start_code(fd, func): def start_code(fd, func):
script_name = os.path.split(__file__)[-1] script_name = os.path.split(__file__)[-1]
fd.write("void print_ps_%s(FILE *fd) {\n" % func) fd.write("void print_ps_%s(FILE *fd) {\n" % func)
def write_code(fd, raw_str): def write_code(fd, raw_str):
ps_str = ps_clean_string(raw_str) ps_str = ps_clean_string(raw_str)
fd.write("\tfprintf(fd, \"%s\");\n" % ps_str) fd.write("\tfprintf(fd, \"%s\");\n" % ps_str)
def end_code(fd): def end_code(fd):
fd.write("}\n\n\n") fd.write("}\n\n\n")
def exit_err(msg=None, *param): def exit_err(msg=None, *param):
if msg is not None: if msg is not None:
sys.stderr.write(msg % param) sys.stderr.write(msg % param)
sys.exit(1) sys.exit(1)
# Globals # Globals
STATE_NULL = 'null' STATE_NULL = 'null'
STATE_PREAMBLE = 'preamble' STATE_PREAMBLE = 'preamble'
STATE_FINALE = 'finale' STATE_FINALE = 'finale'
def main(): def main():
state = STATE_NULL; state = STATE_NULL
if len(sys.argv) != 3: if len(sys.argv) != 3:
exit_err("%s: input_file output_file\n", __file__) exit_err("%s: input_file output_file\n", __file__)

View File

@ -51,7 +51,7 @@ def main():
if not 'wireshark-' in tag_cp.stdout: if not 'wireshark-' in tag_cp.stdout:
print('Wireshark release tag not found') print('Wireshark release tag not found')
sys.exit(1) sys.exit(1)
except: except Exception:
print('`git tag` returned {}:'.format(tag_cp.returncode)) print('`git tag` returned {}:'.format(tag_cp.returncode))
raise raise
@ -61,7 +61,7 @@ def main():
check=True, check=True,
encoding='UTF-8', encoding='UTF-8',
stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout
except: except Exception:
print('Unable to fetch most recent rc0.') print('Unable to fetch most recent rc0.')
raise raise
@ -69,7 +69,7 @@ def main():
ver_m = re.match('v(\d+\.\d+)\.(\d+)rc0.*', cur_rc0) ver_m = re.match('v(\d+\.\d+)\.(\d+)rc0.*', cur_rc0)
maj_min = ver_m.group(1) maj_min = ver_m.group(1)
next_micro = ver_m.group(2) next_micro = ver_m.group(2)
except: except Exception:
print('Unable to fetch major.minor version.') print('Unable to fetch major.minor version.')
raise raise
@ -90,7 +90,7 @@ def main():
encoding='UTF-8', encoding='UTF-8',
stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.strip() stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.strip()
release_tag_l.append(release_tag_fmt.format(maj_min, micro, tag_date)) release_tag_l.append(release_tag_fmt.format(maj_min, micro, tag_date))
except: except Exception:
print('Unable to fetch release tag') print('Unable to fetch release tag')
raise raise