Prepare the peer db to separate the server advertisment and the getPeersLists
[re6stnet.git] / utils.py
1 #!/usr/bin/env python
2 import argparse, time, struct, socket
3 from OpenSSL import crypto
4
5 verbose = 0
6
7 def log(message, verbose_level):
8 if verbose >= verbose_level:
9 print time.strftime("%d-%m-%Y %H:%M:%S : " + message)
10
11 def binFromIp(ip):
12 ip1, ip2 = struct.unpack('>QQ', socket.inet_pton(socket.AF_INET6, ip))
13 return bin(ip1)[2:].rjust(64, '0') + bin(ip2)[2:].rjust(64, '0')
14
15 def ipFromBin(prefix):
16 prefix = hex(int(prefix, 2))[2:]
17 ip = ''
18 for i in xrange(0, len(prefix) - 1, 4):
19 ip += prefix[i:i+4] + ':'
20 return ip.rstrip(':')
21
22 def ipFromPrefix(vifibnet, prefix, prefix_len):
23 prefix = bin(int(prefix))[2:].rjust(prefix_len, '0')
24 ip_t = (vifibnet + prefix).ljust(128, '0')
25 return ipFromBin(ip_t)
26
27 def networkFromCa(ca_path):
28 # Get network prefix from ca.crt
29 with open(ca_path, 'r') as f:
30 ca = crypto.load_certificate(crypto.FILETYPE_PEM, f.read())
31 return bin(ca.get_serial_number())[3:]
32
33 def ipFromCert(network, cert_path):
34 # Get ip from cert.crt
35 with open(cert_path, 'r') as f:
36 cert = crypto.load_certificate(crypto.FILETYPE_PEM, f.read())
37 subject = cert.get_subject()
38 prefix, prefix_len = subject.CN.split('/')
39 return ipFromPrefix(network, prefix, int(prefix_len))
40
41 def ovpnArgs(optional_args, ca_path, cert_path):
42 # Treat openvpn arguments
43 if optional_args[0] == "--":
44 del optional_args[0]
45 optional_args.append('--ca')
46 optional_args.append(ca_path)
47 optional_args.append('--cert')
48 optional_args.append(cert_path)
49 return optional_args
50