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