Change protocol to discover addresses of peers to connect to
[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, **kw):
8 if log_level:
9 logging.basicConfig(level=logging_levels[log_level-1],
10 format='%(asctime)s %(levelname)-9s %(message)s',
11 datefmt='%d-%m-%Y %H:%M:%S', **kw)
12 else:
13 logging.disable(logging.CRITICAL)
14 logging.addLevelName(5, 'TRACE')
15 logging.trace = lambda *args, **kw: logging.log(5, *args, **kw)
16
17 class ArgParser(argparse.ArgumentParser):
18
19 def convert_arg_line_to_args(self, arg_line):
20 arg_line = arg_line.split('#')[0].rstrip()
21 if arg_line:
22 if arg_line.startswith('@'):
23 yield arg_line
24 return
25 for arg in ('--' + arg_line.lstrip('--')).split():
26 if arg.strip():
27 yield arg
28
29 def binFromIp(ip):
30 ip1, ip2 = struct.unpack('>QQ', socket.inet_pton(socket.AF_INET6, ip))
31 return bin(ip1)[2:].rjust(64, '0') + bin(ip2)[2:].rjust(64, '0')
32
33
34 def ipFromBin(prefix, suffix=''):
35 ip = prefix + suffix.rjust(128 - len(prefix), '0')
36 return socket.inet_ntop(socket.AF_INET6,
37 struct.pack('>QQ', int(ip[:64], 2), int(ip[64:], 2)))
38
39 def networkFromCa(ca_path):
40 # Get network prefix from ca.crt
41 with open(ca_path, 'r') as f:
42 ca = crypto.load_certificate(crypto.FILETYPE_PEM, f.read())
43 return bin(ca.get_serial_number())[3:]
44
45 def ipFromCert(network, cert_path):
46 # Get ip from cert.crt
47 with open(cert_path, 'r') as f:
48 cert = crypto.load_certificate(crypto.FILETYPE_PEM, f.read())
49 subject = cert.get_subject()
50 prefix, prefix_len = subject.CN.split('/')
51 prefix = bin(int(prefix))[2:].rjust(int(prefix_len), '0')
52 return ipFromBin(network + prefix, '1'), prefix
53
54 def address_str(address):
55 return ';'.join(map(','.join, address))
56
57
58 def address_list(address_list):
59 return list(tuple(address.split(','))
60 for address in address_list.split(';'))
61
62
63 def binFromSubnet(subnet):
64 p, l = subnet.split('/')
65 return bin(int(p))[2:].rjust(int(l), '0')