]> git.llucax.com Git - software/pymin.git/blob - pymin/services/vpn/__init__.py
Use the "virual deletion" facilities from XxxSubHandler (fixes #23).
[software/pymin.git] / pymin / services / vpn / __init__.py
1 # vim: set encoding=utf-8 et sw=4 sts=4 :
2
3 import os
4 import errno
5 import signal
6 from os import path
7 import logging ; log = logging.getLogger('pymin.services.vpn')
8
9
10 from pymin.seqtools import Sequence
11 from pymin.dispatcher import Handler, handler, HandlerError
12 from pymin.services.util import Restorable, ConfigWriter, InitdHandler, \
13                                 TransactionalHandler, DictSubHandler, DictComposedSubHandler, call, ExecutionError
14
15
16 class Host(Sequence):
17     def __init__(self, vpn_src, ip, vpn_src_net, key):
18         self.name = vpn_src
19         self.ip = ip
20         self.src_net = vpn_src_net
21         self.pub_key = key
22         self._delete = False
23
24     def as_tuple(self):
25         return(self.name, self.ip, self.src_net, self.pub_key)
26
27 class HostHandler(DictComposedSubHandler):
28
29     handler_help = u"Manage hosts for a vpn"
30     _comp_subhandler_cont = 'vpns'
31     _comp_subhandler_attr = 'hosts'
32     _comp_subhandler_class = Host
33
34
35 class Vpn(Sequence):
36     def __init__(self, vpn_src, vpn_dst, vpn_src_ip, vpn_src_mask,
37                     pub_key=None, priv_key=None):
38         self.vpn_src = vpn_src
39         self.vpn_dst = vpn_dst
40         self.vpn_src_ip = vpn_src_ip
41         self.vpn_src_mask = vpn_src_mask
42         self.pub_key = pub_key
43         self.priv_key = priv_key
44         self.hosts = dict()
45         self._delete = False
46
47     def as_tuple(self):
48         return(self.vpn_src, self.vpn_dst, self.vpn_src_ip, self.vpn_src_mask, self.pub_key, self.priv_key)
49
50     def update(self, vpn_dst=None, vpn_src_ip=None, vpn_src_mask=None):
51         if vpn_dst is not None:
52             self.vpn_dst = vpn_dst
53         if vpn_src_ip is not None:
54             self.vpn_src_ip = vpn_src_ip
55         if vpn_src_mask is not None:
56             self.vpn_src_mask = vpn_src_mask
57
58
59 class VpnHandler(Restorable, ConfigWriter,
60                    TransactionalHandler, DictSubHandler):
61
62     handler_help = u"Manage vpn service"
63
64     _cont_subhandler_attr = 'vpns'
65     _cont_subhandler_class = Vpn
66
67     _persistent_attrs = ('vpns','hosts')
68
69     _restorable_defaults = dict(
70             vpns = dict(),
71             hosts = dict(),
72     )
73
74     _config_writer_files = ('tinc.conf','tinc-up','host')
75     _config_writer_tpl_dir = path.join(path.dirname(__file__), 'templates')
76
77     def __init__(self,  pickle_dir='.', config_dir='/etc/tinc'):
78         log.debug(u'VpnHandler(%r, %r)', pickle_dir, config_dir)
79         DictSubHandler.__init__(self, self)
80         self._config_writer_cfg_dir = config_dir
81         self._persistent_dir = pickle_dir
82         self._config_build_templates()
83         self._restore()
84         self.host = HostHandler(self)
85
86     @handler('usage: start <vpn_name>')
87     def start(self, vpn_src):
88         log.debug(u'VpnHandler.start(%r)', vpn_src)
89         if vpn_src in self.vpns:
90             call(('tincd','--net='+ vpn_src))
91
92     @handler('usage: stop <vpn_name>')
93     def stop(self, vpn_src):
94         log.debug(u'VpnHandler.stop(%r)', vpn_src)
95         if vpn_src in self.vpns:
96             pid_file = '/var/run/tinc.' + vpn_src + '.pid'
97             log.debug(u'VpnHandler.stop: getting pid from %r', pid_file)
98             if path.exists(pid_file):
99                 pid = file(pid_file).readline()
100                 pid = int(pid.strip())
101                 try:
102                     log.debug(u'VpnHandler.stop: killing pid %r', pid)
103                     os.kill(pid, signal.SIGTERM)
104                 except OSError:
105                     log.debug(u'VpnHandler.stop: error killing: %r', e)
106             else:
107                 log.debug(u'VpnHandler.stop: pid file not found')
108
109     def _write_config(self):
110         log.debug(u'VpnHandler._write_config()')
111         for v in self.vpns.values():
112             log.debug(u'VpnHandler._write_config: processing %r', v)
113             #chek whether it's been created or not.
114             if not v._delete:
115                 if v.pub_key is None:
116                     log.debug(u'VpnHandler._write_config: new VPN, generating '
117                                 'key...')
118                     try:
119                         log.debug(u'VpnHandler._write_config: creating dir %r',
120                                     path.join(self._config_writer_cfg_dir,
121                                                 v.vpn_src ,'hosts'))
122                         #first create the directory for the vpn
123                         try:
124                             os.makedirs(path.join(self._config_writer_cfg_dir,
125                                                   v.vpn_src, 'hosts'))
126                         except (IOError, OSError), e:
127                             if e.errno != errno.EEXIST:
128                                 raise HandlerError(u"Can't create VPN config "
129                                                    "directory '%s' (%s)'"
130                                                     % (e.filename, e.strerror))
131                         #this command should generate 2 files inside the vpn
132                         #dir, one rsa_key.priv and one rsa_key.pub
133                         #for some reason debian does not work like this
134                         # FIXME if the < /dev/null works, is magic!
135                         log.debug(u'VpnHandler._write_config: creating key...')
136                         call(('tincd', '-n', v.vpn_src, '-K', '<', '/dev/null'))
137                         #open the created files and load the keys
138                         try:
139                             f = file(path.join(self._config_writer_cfg_dir,
140                                                v.vpn_src, 'rsa_key.pub'),
141                                      'r')
142                             pub = f.read()
143                             f.close()
144                         except (IOError, OSError), e:
145                             raise HandlerError(u"Can't read VPN key '%s' (%s)'"
146                                                 % (e.filename, e.strerror))
147
148                         v.pub_key = pub
149                         v.priv_key = priv
150                     except ExecutionError, e:
151                         log.debug(u'VpnHandler._write_config: error executing '
152                                     'the command: %r', e)
153
154                 vars = dict(
155                     vpn = v,
156                 )
157                 self._write_single_config('tinc.conf',
158                                 path.join(v.vpn_src, 'tinc.conf'), vars)
159                 self._write_single_config('tinc-up',
160                                 path.join(v.vpn_src, 'tinc-up'), vars)
161                 for h in v.hosts.values():
162                     if not h._delete:
163                         vars = dict(
164                             host = h,
165                         )
166                         self._write_single_config('host',
167                                 path.join(v.vpn_src, 'hosts', h.name), vars)
168                     else:
169                         log.debug(u'VpnHandler._write_config: removing...')
170                         try:
171                             # FIXME use os.unlink()
172                             call(('rm','-f',
173                                     path.join(v.vpn_src, 'hosts', h.name)))
174                             del v.hosts[h.name]
175                         except ExecutionError, e:
176                             log.debug(u'VpnHandler._write_config: error '
177                                     'removing files: %r', e)
178             else:
179                 #delete the vpn root at tinc dir
180                 if path.exists('/etc/tinc/' + v.vpn_src):
181                     self.stop(v.vpn_src)
182                     call(('rm','-rf','/etc/tinc/' + v.vpn_src))
183                     del self.vpns[v.vpn_src]
184
185
186 if __name__ == '__main__':
187
188     logging.basicConfig(
189         level   = logging.DEBUG,
190         format  = '%(asctime)s %(levelname)-8s %(message)s',
191         datefmt = '%H:%M:%S',
192     )
193
194     v = VpnHandler()
195     v.add('prueba','sarasa','192.168.0.188','255.255.255.0')
196     v.host.add('prueba', 'azazel' ,'192.168.0.77', '192.168.0.0',
197                 'kjdhfkbdskljvkjblkbjeslkjbvkljbselvslberjhbvslbevlhb')
198     v.commit()
199