Implement automatic renewal of client certificate
[re6stnet.git] / re6st / utils.py
1 import argparse, calendar, errno, logging, os, shlex, signal, socket
2 import struct, subprocess, textwrap, threading, time
3
4 logging_levels = logging.WARNING, logging.INFO, logging.DEBUG, 5
5
6 class FileHandler(logging.FileHandler):
7
8 _reopen = False
9
10 def release(self):
11 try:
12 if self._reopen:
13 self._reopen = False
14 self.close()
15 self._open()
16 finally:
17 self.lock.release()
18 # In the rare case _reopen is set just before the lock was released
19 if self._reopen and self.lock.acquire(0):
20 self.release()
21
22 def async_reopen(self, *_):
23 self._reopen = True
24 if self.lock.acquire(0):
25 self.release()
26
27 def setupLog(log_level, filename=None, **kw):
28 if log_level and filename:
29 makedirs(os.path.dirname(filename))
30 handler = FileHandler(filename)
31 sig = handler.async_reopen
32 else:
33 handler = logging.StreamHandler()
34 sig = signal.SIG_IGN
35 handler.setFormatter(logging.Formatter(
36 '%(asctime)s %(levelname)-9s %(message)s', '%d-%m-%Y %H:%M:%S'))
37 root = logging.getLogger()
38 root.addHandler(handler)
39 signal.signal(signal.SIGUSR1, sig)
40 if log_level:
41 root.setLevel(logging_levels[log_level-1])
42 else:
43 logging.disable(logging.CRITICAL)
44 logging.addLevelName(5, 'TRACE')
45 logging.trace = lambda *args, **kw: logging.log(5, *args, **kw)
46
47
48 class HelpFormatter(argparse.ArgumentDefaultsHelpFormatter):
49
50 def _get_help_string(self, action):
51 return super(HelpFormatter, self)._get_help_string(action) \
52 if action.default else action.help
53
54 def _split_lines(self, text, width):
55 """Preserves new lines in option descriptions"""
56 lines = []
57 for text in text.splitlines():
58 lines += textwrap.wrap(text, width)
59 return lines
60
61 def _fill_text(self, text, width, indent):
62 """Preserves new lines in other descriptions"""
63 kw = dict(width=width, initial_indent=indent, subsequent_indent=indent)
64 return '\n'.join(textwrap.fill(t, **kw) for t in text.splitlines())
65
66 class ArgParser(argparse.ArgumentParser):
67
68 class _HelpFormatter(HelpFormatter):
69
70 def _format_actions_usage(self, actions, groups):
71 r = HelpFormatter._format_actions_usage(self, actions, groups)
72 if actions and actions[0].option_strings:
73 r = '[@OPTIONS_FILE] ' + r
74 return r
75
76 _ca_help = "Certificate authority (CA) file in .pem format." \
77 " Serial number defines the prefix of the network."
78
79 def convert_arg_line_to_args(self, arg_line):
80 if arg_line.split('#', 1)[0].rstrip():
81 if arg_line.startswith('@'):
82 yield arg_line
83 return
84 arg_line = shlex.split(arg_line)
85 arg = '--' + arg_line.pop(0)
86 yield arg[arg not in self._option_string_actions:]
87 for arg in arg_line:
88 yield arg
89
90 def __init__(self, **kw):
91 super(ArgParser, self).__init__(formatter_class=self._HelpFormatter,
92 epilog="""Options can be read from a file. For example:
93 $ cat OPTIONS_FILE
94 ca /etc/re6stnet/ca.crt""", **kw)
95
96
97 class Popen(subprocess.Popen):
98
99 def stop(self):
100 self.terminate()
101 t = threading.Timer(5, self.kill)
102 t.start()
103 r = self.wait()
104 t.cancel()
105 return r
106
107
108 def makedirs(path):
109 try:
110 os.makedirs(path)
111 except OSError, e:
112 if e.errno != errno.EEXIST:
113 raise
114
115 def binFromIp(ip):
116 ip1, ip2 = struct.unpack('>QQ', socket.inet_pton(socket.AF_INET6, ip))
117 return bin(ip1)[2:].rjust(64, '0') + bin(ip2)[2:].rjust(64, '0')
118
119
120 def ipFromBin(ip, suffix=''):
121 suffix_len = 128 - len(ip)
122 if suffix_len > 0:
123 ip += suffix.rjust(suffix_len, '0')
124 elif suffix_len:
125 sys.exit("Prefix exceeds 128 bits")
126 return socket.inet_ntop(socket.AF_INET6,
127 struct.pack('>QQ', int(ip[:64], 2), int(ip[64:], 2)))
128
129 def networkFromCa(ca):
130 return bin(ca.get_serial_number())[3:]
131
132 def subnetFromCert(cert):
133 return cert.get_subject().CN
134
135 def notAfter(cert):
136 return calendar.timegm(time.strptime(cert.get_notAfter(),'%Y%m%d%H%M%SZ'))
137
138 def dump_address(address):
139 return ';'.join(map(','.join, address))
140
141 def parse_address(address_list):
142 for address in address_list.split(';'):
143 try:
144 ip, port, proto = address.split(',')
145 yield ip, str(port), proto
146 except ValueError, e:
147 logging.warning("Failed to parse node address %r (%s)",
148 address, e)
149
150 def binFromSubnet(subnet):
151 p, l = subnet.split('/')
152 return bin(int(p))[2:].rjust(int(l), '0')
153
154 def decrypt(key_path, data):
155 p = subprocess.Popen(
156 ('openssl', 'rsautl', '-decrypt', '-inkey', key_path),
157 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
158 out, err = p.communicate(data)
159 if p.returncode:
160 raise subprocess.CalledProcessError(p.returncode, err)
161 return out
162
163 def encrypt(cert, data):
164 r, w = os.pipe()
165 try:
166 threading.Thread(target=os.write, args=(w, cert)).start()
167 p = subprocess.Popen(('openssl', 'rsautl', '-encrypt', '-certin',
168 '-inkey', '/proc/self/fd/%u' % r),
169 stdin=subprocess.PIPE, stdout=subprocess.PIPE)
170 out, err = p.communicate(data)
171 finally:
172 os.close(r)
173 os.close(w)
174 if p.returncode:
175 raise subprocess.CalledProcessError(p.returncode, err)
176 return out