Bugfixes
[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 %(levelname)-9s %(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 class ArgParser(argparse.ArgumentParser):
15
16 def convert_arg_line_to_args(self, arg_line):
17 arg_line = arg_line.split('#')[0].rstrip()
18 if arg_line:
19 if arg_line.startswith('@'):
20 yield arg_line
21 return
22 for arg in ('--' + arg_line.lstrip('--')).split():
23 if arg.strip():
24 yield arg
25
26 def binFromIp(ip):
27 ip1, ip2 = struct.unpack('>QQ', socket.inet_pton(socket.AF_INET6, ip))
28 return bin(ip1)[2:].rjust(64, '0') + bin(ip2)[2:].rjust(64, '0')
29
30
31 def ipFromBin(prefix):
32 prefix = hex(int(prefix, 2))[2:]
33 ip = ''
34 for i in xrange(0, len(prefix) - 1, 4):
35 ip += prefix[i:i + 4] + ':'
36 return ip.rstrip(':')
37
38
39 def ipFromPrefix(re6stnet, prefix, prefix_len):
40 prefix = bin(int(prefix))[2:].rjust(prefix_len, '0')
41 ip_t = (re6stnet + prefix).ljust(127, '0').ljust(128, '1')
42 return ipFromBin(ip_t), prefix
43
44
45 def networkFromCa(ca_path):
46 # Get network prefix from ca.crt
47 with open(ca_path, 'r') as f:
48 ca = crypto.load_certificate(crypto.FILETYPE_PEM, f.read())
49 return bin(ca.get_serial_number())[3:]
50
51
52 def ipFromCert(network, cert_path):
53 # Get ip from cert.crt
54 with open(cert_path, 'r') as f:
55 cert = crypto.load_certificate(crypto.FILETYPE_PEM, f.read())
56 subject = cert.get_subject()
57 prefix, prefix_len = subject.CN.split('/')
58 return ipFromPrefix(network, prefix, int(prefix_len))
59
60
61 def address_str(address):
62 return ';'.join(map(','.join, address))
63
64
65 def address_list(address_list):
66 return list(tuple(address.split(','))
67 for address in address_list.split(';'))
68
69
70 def binFromSubnet(subnet):
71 prefix, subnet_size = subnet.split('/')
72 binary = bin(int(prefix))[2:]
73 binary = ('0' * (int(subnet_size) - len(binary))) + binary
74 return binary