Fixed some syntax bugs
[re6stnet.git] / utils.py
1 import argparse, time, struct, socket, logging
2 from OpenSSL import crypto
3
4 logging_levels = logging.WARNING, logging.INFO, logging.DEBUG, 5
5
6 def setupLog(log_level):
7 logging.basicConfig(level=logging_levels[log_level],
8 format='%(asctime)s : %(message)s',
9 datefmt='%d-%m-%Y %H:%M:%S')
10 logging.addLevelName(5, 'TRACE')
11 logging.trace = lambda *args, **kw: logging.log(5, *args, **kw)
12
13 def binFromIp(ip):
14 ip1, ip2 = struct.unpack('>QQ', socket.inet_pton(socket.AF_INET6, ip))
15 return bin(ip1)[2:].rjust(64, '0') + bin(ip2)[2:].rjust(64, '0')
16
17 def ipFromBin(prefix):
18 prefix = hex(int(prefix, 2))[2:]
19 ip = ''
20 for i in xrange(0, len(prefix) - 1, 4):
21 ip += prefix[i:i+4] + ':'
22 return ip.rstrip(':')
23
24 def ipFromPrefix(vifibnet, prefix, prefix_len):
25 prefix = bin(int(prefix))[2:].rjust(prefix_len, '0')
26 ip_t = (vifibnet + prefix).ljust(127, '0').ljust(128, '1')
27 return ipFromBin(ip_t), prefix
28
29 def networkFromCa(ca_path):
30 # Get network prefix from ca.crt
31 with open(ca_path, 'r') as f:
32 ca = crypto.load_certificate(crypto.FILETYPE_PEM, f.read())
33 return bin(ca.get_serial_number())[3:]
34
35 def ipFromCert(network, cert_path):
36 # Get ip from cert.crt
37 with open(cert_path, 'r') as f:
38 cert = crypto.load_certificate(crypto.FILETYPE_PEM, f.read())
39 subject = cert.get_subject()
40 prefix, prefix_len = subject.CN.split('/')
41 return ipFromPrefix(network, prefix, int(prefix_len))
42
43 def address_str(address_set):
44 return ';'.join(map(','.join, address_set))
45
46 def address_list(address_list):
47 return list(tuple(address.split(','))
48 for address in address_list.split(';'))