The trunk can use the main server again (for the time being).
[switzerland.git] / switzerland / common / util.py
blob17f617bb05cc6b231c4007c23189b91f4c9ee66e
1 # Handy routines for Switzerland
3 import binascii
4 import os
5 import platform
6 import sys
7 import traceback
8 import threading
9 import logging
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)
20 PROTOCOLS = {
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)
26 5: 'ST', # Stream
27 6: 'TCP', # Transmission Control
28 7: 'CBT', # CBT
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
33 12: 'PUP', # PUP
34 13: 'ARGUS', # ARGUS
35 14: 'EMCON', # EMCON
36 15: 'XNET', # Cross Net Debugger
37 16: 'CHAOS', # Chaos
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
57 36: 'XTP', # XTP
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
62 41: 'IPv6', # Ipv6
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
70 49: 'BNA', # BNA
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
78 57: 'SKIP', # SKIP
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
83 62: 'CFTP', # CFTP
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
102 81: 'VMTP', # VMTP
103 82: 'SECURE-VMTP', # SECURE-VMTP
104 83: 'VINES', # VINES
105 84: 'TTP', # TTP
106 85: 'NSFNET-IGP', # NSFNET-IGP
107 86: 'DGP', # Dissimilar Gateway Protocol
108 87: 'TCF', # TCF
109 88: 'EIGRP', # EIGRP
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
121 100: 'GMTP', # GMTP
122 101: 'IFMP', # Ipsilon Flow Management Protocol
123 102: 'PNNI', # PNNI over IP
124 103: 'PIM', # Protocol Independent Multicast
125 104: 'ARIS', # ARIS
126 105: 'SCPS', # SCPS
127 106: 'QNX', # QNX
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
141 120: 'UTI', # UTI
142 121: 'SMP', # Simple Message Protocol
143 122: 'SM', # SM
144 123: 'PTP', # Performance Transparency Protocol
145 124: 'ISIS over IPv4',
146 125: 'FIRE',
147 126: 'CRTP', # Combat Radio Transport Protocol
148 127: 'CRUDP', # Combat Radio User Datagram
149 128: 'SSCOPMCE',
150 129: 'IPLT',
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',
157 136: 'UDPLite',
158 137: 'MPLS-in-IP',
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
164 # 255: Reserved
168 if platform.system() == 'Windows':
169 try:
170 import win32api, win32process, win32con
171 except:
172 print 'Please install the python win32 extensions'
173 print '(see INSTALL.txt for details)'
174 sys.exit(1)
176 class DebugMe(Exception):
177 pass
179 def writable(path):
180 try:
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.
186 try:
187 import tempfile
188 f = tempfile.TemporaryFile(dir=path)
189 f.close()
190 except OSError:
191 return False
193 return True
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):
201 pass
203 def bin2int(str):
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')
212 def debugger():
213 import pdb
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
220 print."""
222 str = repr(data_structure)
223 if len(str) > 103:
224 str = str[:100] + "..."
225 return str
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]
241 if pid == None:
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"""
250 self.fn = fn
251 self.respawn = respawn
252 if handle_control_c:
253 self.handle_control_c = handle_control_c
254 else:
255 self.handle_control_c = self.fallback_handler
256 threading.Thread.__init__(self)
257 self.setDaemon(True)
259 def fallback_handler(self):
260 sys.stderr.write("Unhandled control-c:\n%s" % traceback.format_exc())
262 def run(self):
263 keep_running = True
264 while keep_running:
265 keep_running = False
266 try:
267 try:
268 self.fn()
269 except KeyboardInterrupt:
270 self.handle_control_c()
271 except:
272 if self.respawn:
273 log.error("Respawning thread after exception:\n%s" %
274 traceback.format_exc())
275 keep_running = True
276 else:
277 raise
279 def hexhex(thing):
280 """Coerce an arugment in to hexadecimal, by hook or by crook"""
282 tries = ""
283 try:
284 return hex(thing)
285 except TypeError:
286 tries += traceback.format_exc()
287 try:
288 return "0x" + binascii.hexlify(thing)
289 except TypeError:
290 tries += traceback.format_exc()
291 try:
292 return "0x" + binascii.hexlify(thing.tostring())
293 except TypeError:
294 tries += traceback.format_exc()
295 # desperate measures
296 msg = "I don't know how to convert a %s (%s) into hex\n" % \
297 (`type(thing)`, `thing`)
298 #msg += "Attempts:\n" + tries
299 raise Exception(msg)