1 # Handy routines for Switzerland
11 log
= logging
.getLogger('util')
14 # FIXME: It is perhaps best to move the PROTOCOLS dict to a separate file. Note
15 # that doing so will require the function prot_name to be updated.
17 # Protocol number/name pairs.
18 # Source: http://www.iana.org/assignments/protocol-numbers
19 # (last updated 2008-04-18)
21 0: 'HOPOPT', # IPv6 Hop-by-Hop Option
22 1: 'ICMP', # Internet Control Message
23 2: 'IGMP', # Internet Group Management
24 3: 'GGP', # Gateway-to-Gateway
25 4: 'IP', # IP in IP (encapsulation)
27 6: 'TCP', # Transmission Control
29 8: 'EGP', # Exterior Gateway Protocol
30 9: 'IGP', # any private interior gateway (used by Cisco for their IGRP)
31 10: 'BBN-RCC-MON', # BBN RCC Monitoring
32 11: 'NVP-II', # Network Voice Protocol
36 15: 'XNET', # Cross Net Debugger
38 17: 'UDP', # User Datagram
39 18: 'MUX', # Multiplexing
40 19: 'DCN-MEAS', # DCN Measurement Subsystems
41 20: 'HMP', # Host Monitoring
42 21: 'PRM', # Packet Radio Measurement
43 22: 'XNS-IDP', # XEROX NS IDP
44 23: 'TRUNK-1', # Trunk-1
45 24: 'TRUNK-2', # Trunk-2
46 25: 'LEAF-1', # Leaf-1
47 26: 'LEAF-2', # Leaf-2
48 27: 'RDP', # Reliable Data Protocol
49 28: 'IRTP', # Internet Reliable Transaction
50 29: 'ISO-TP4', # ISO Transport Protocol Class 4
51 30: 'NETBLT', # Bulk Data Transfer Protocol
52 31: 'MFE-NSP', # MFE Network Services Protocol
53 32: 'MERIT-INP', # MERIT Internodal Protocol
54 33: 'DCCP', # Datagram Congestion Control Protocol
55 34: '3PC', # Third Party Connect Protocol
56 35: 'IDPR', # Inter-Domain Policy Routing Protocol
58 37: 'DDP', # Datagram Delivery Protocol
59 38: 'IDPR-CMTP', # IDPR Control Message Transport Proto
60 39: 'TP++', # TP++ Transport Protocol
61 40: 'IL', # IL Transport Protocol
63 42: 'SDRP', # Source Demand Routing Protocol
64 43: 'IPv6-Route', # Routing Header for IPv6
65 44: 'IPv6-Frag', # Fragment Header for IPv6
66 45: 'IDRP', # Inter-Domain Routing Protocol
67 46: 'RSVP', # Reservation Protocol
68 47: 'GRE', # General Routing Encapsulation
69 48: 'DSR', # Dynamic Source Routing Protocol
71 50: 'ESP', # Encap Security Payload
72 51: 'AH', # Authentication Header
73 52: 'I-NLSP', # Integrated Net Layer Security TUBA
74 53: 'SWIPE', # IP with Encryption
75 54: 'NARP', # NBMA Address Resolution Protocol
76 55: 'MOBILE', # IP Mobility
77 56: 'TLSP', # Transport Layer Security Protocol using Kryptonet key management
79 58: 'IPv6-ICMP', # ICMP for IPv6
80 59: 'IPv6-NoNxt', # No Next Header for IPv6
81 60: 'IPv6-Opts', # Destination Options for IPv6
82 # 61: any host internal protocol
84 # 63: any local network
85 64: 'SAT-EXPAK', # SATNET and Backroom EXPAK
86 65: 'KRYPTOLAN', # Kryptolan
87 66: 'RVD', # MIT Remote Virtual Disk Protocol
88 67: 'IPPC', # Internet Pluribus Packet Core
89 # 68: any distributed file system
90 69: 'SAT-MON', # SATNET Monitoring
91 70: 'VISA', # VISA Protocol
92 71: 'IPCV', # Internet Packet Core Utility
93 72: 'CPNX', # Computer Protocol Network Executive
94 73: 'CPHB', # Computer Protocol Heart Beat
95 74: 'WSN', # Wang Span Network
96 75: 'PVP', # Packet Video Protocol
97 76: 'BR-SAT-MON', # Backroom SATNET Monitoring
98 77: 'SUN-ND', # SUN ND PROTOCOL-Temporary
99 78: 'WB-MON', # WIDEBAND Monitoring
100 79: 'WB-EXPAK', # WIDEBAND EXPAK
101 80: 'ISO-IP', # ISO Internet Protocol
103 82: 'SECURE-VMTP', # SECURE-VMTP
106 85: 'NSFNET-IGP', # NSFNET-IGP
107 86: 'DGP', # Dissimilar Gateway Protocol
110 89: 'OSPFIGP', # OSPFIGP
111 90: 'Sprite-RPC', # Sprite RPC Protocol
112 91: 'LARP', # Locus Address Resolution Protocol
113 92: 'MTP', # Multicast Transport Protocol
114 93: 'AX.25', # AX.25 Frames
115 94: 'IPIP', # IP-within-IP Encapsulation Protocol
116 95: 'MICP', # Mobile Internetworking Control Pro.
117 96: 'SCC-SP', # Semaphore Communications Sec. Pro.
118 97: 'ETHERIP', # Ethernet-within-IP Encapsulation
119 98: 'ENCAP', # Encapsulation Header
120 # 99: any private encryption scheme
122 101: 'IFMP', # Ipsilon Flow Management Protocol
123 102: 'PNNI', # PNNI over IP
124 103: 'PIM', # Protocol Independent Multicast
128 107: 'A/N', # Active Networks
129 108: 'IPComp', # IP Payload Compression Protocol
130 109: 'SNP', # Sitara Networks Protocol
131 110: 'Compaq-Peer', # Compaq Peer Protocol
132 111: 'IPX-in-IP', # IPX in IP
133 112: 'VRRP', # Virtual Router Redundancy Protocol
134 113: 'PGM', # PGM Reliable Transport Protocol
135 # 114: any 0-hop protocol
136 115: 'L2TP', # Layer Two Tunneling Protocol
137 116: 'DDX', # D-II Data Exchange (DDX)
138 117: 'IATP', # Interactive Agent Transfer Protocol
139 118: 'STP', # Schedule Transfer Protocol
140 119: 'SRP', # SpectraLink Radio Protocol
142 121: 'SMP', # Simple Message Protocol
144 123: 'PTP', # Performance Transparency Protocol
145 124: 'ISIS over IPv4',
147 126: 'CRTP', # Combat Radio Transport Protocol
148 127: 'CRUDP', # Combat Radio User Datagram
151 130: 'SPS', # Secure Packet Shield
152 131: 'PIPE', # Private IP Encapsulation within IP
153 132: 'SCTP', # Stream Control Transmission Protocol
154 133: 'FC', # Fibre Channel
155 134: 'RSVP-E2E-IGNORE',
156 135: 'Mobility Header',
159 138: 'manet', # MANET Protocols
160 139: 'HIP', # Host Identity Protocol
161 # 140-252: Unassigned
162 # 253: Use for experimentation and testing
163 # 254: Use for experimentation and testing
168 if platform
.system() == 'Windows':
170 import win32api
, win32process
, win32con
172 print 'Please install the python win32 extensions'
173 print '(see INSTALL.txt for details)'
176 class DebugMe(Exception):
181 return os
.access(path
, os
.W_OK
)
182 except AttributeError:
183 # http://docs.python.org/library/os.html claims availability of
184 # os.access on both Unix and Windows. For any other exotic operating
185 # systems, the following hack may work.
188 f
= tempfile
.TemporaryFile(dir=path
)
195 def prot_name(prot_num
):
196 """Called from outside: return the name of a protocol number, if we can."""
198 return PROTOCOLS
.get(int(prot_num
), str(prot_num
))
200 class VersionMismatch(Exception):
204 """Convert a raw string to an int (Yuck!!!)"""
206 return int(eval("0x" + binascii
.hexlify(str)))
208 def check_python_version():
209 if platform
.python_version_tuple() < ['2', '5']:
210 raise VersionMismatch('expecting python version 2.5 or later')
214 error
, value
, traceback
= sys
.exc_info()
215 print "Invoking debugger after", error
, value
216 pdb
.post_mortem(traceback
)
218 def screensafe(data_structure
):
219 """Return a representation of an untrusted data structure that's okay to
222 str = repr(data_structure
)
224 str = str[:100] + "..."
227 def set_win32_priority(pid
=None, priority
=1):
228 """Set The Priority of a Windows Process.
230 Priority is a value between 0-5 where 2 is normal priority. Default sets
231 the priority of the current python process but can take any valid process
235 priorityclasses
= [win32process
.IDLE_PRIORITY_CLASS
,
236 win32process
.BELOW_NORMAL_PRIORITY_CLASS
,
237 win32process
.NORMAL_PRIORITY_CLASS
,
238 win32process
.ABOVE_NORMAL_PRIORITY_CLASS
,
239 win32process
.HIGH_PRIORITY_CLASS
,
240 win32process
.REALTIME_PRIORITY_CLASS
]
242 pid
= win32api
.GetCurrentProcessId()
243 handle
= win32api
.OpenProcess(win32con
.PROCESS_ALL_ACCESS
, True, pid
)
244 win32process
.SetPriorityClass(handle
, priorityclasses
[priority
])
246 class ThreadLauncher(threading
.Thread
):
247 def __init__(self
, fn
, handle_control_c
=None, respawn
=False):
248 """fn is run in its own thread; handle_control_c is a exit callback"""
251 self
.respawn
= respawn
253 self
.handle_control_c
= handle_control_c
255 self
.handle_control_c
= self
.fallback_handler
256 threading
.Thread
.__init
__(self
)
259 def fallback_handler(self
):
260 sys
.stderr
.write("Unhandled control-c:\n%s" % traceback
.format_exc())
269 except KeyboardInterrupt:
270 self
.handle_control_c()
273 log
.error("Respawning thread after exception:\n%s" %
274 traceback
.format_exc())
280 """Coerce an arugment in to hexadecimal, by hook or by crook"""
286 tries
+= traceback
.format_exc()
288 return "0x" + binascii
.hexlify(thing
)
290 tries
+= traceback
.format_exc()
292 return "0x" + binascii
.hexlify(thing
.tostring())
294 tries
+= traceback
.format_exc()
296 msg
= "I don't know how to convert a %s (%s) into hex\n" % \
297 (`
type(thing
)`
, `thing`
)
298 #msg += "Attempts:\n" + tries