1 # vim: set encoding=utf-8 et sw=4 sts=4 :
7 import logging ; log = logging.getLogger('pymin.services.vpn')
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
17 def __init__(self, vpn_src, ip, vpn_src_net, key):
20 self.src_net = vpn_src_net
25 return(self.name, self.ip, self.src_net, self.pub_key)
27 class HostHandler(DictComposedSubHandler):
29 handler_help = u"Manage hosts for a vpn"
30 _comp_subhandler_cont = 'vpns'
31 _comp_subhandler_attr = 'hosts'
32 _comp_subhandler_class = Host
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
48 return(self.vpn_src, self.vpn_dst, self.vpn_src_ip, self.vpn_src_mask, self.pub_key, self.priv_key)
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
59 class VpnHandler(Restorable, ConfigWriter,
60 TransactionalHandler, DictSubHandler):
62 handler_help = u"Manage vpn service"
64 _cont_subhandler_attr = 'vpns'
65 _cont_subhandler_class = Vpn
67 _persistent_attrs = ('vpns','hosts')
69 _restorable_defaults = dict(
74 _config_writer_files = ('tinc.conf','tinc-up','host')
75 _config_writer_tpl_dir = path.join(path.dirname(__file__), 'templates')
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()
84 self.host = HostHandler(self)
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))
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())
102 log.debug(u'VpnHandler.stop: killing pid %r', pid)
103 os.kill(pid, signal.SIGTERM)
105 log.debug(u'VpnHandler.stop: error killing: %r', e)
107 log.debug(u'VpnHandler.stop: pid file not found')
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.
115 if v.pub_key is None:
116 log.debug(u'VpnHandler._write_config: new VPN, generating '
119 log.debug(u'VpnHandler._write_config: creating dir %r',
120 path.join(self._config_writer_cfg_dir,
122 #first create the directory for the vpn
124 os.makedirs(path.join(self._config_writer_cfg_dir,
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
139 f = file(path.join(self._config_writer_cfg_dir,
140 v.vpn_src, 'rsa_key.pub'),
144 except (IOError, OSError), e:
145 raise HandlerError(u"Can't read VPN key '%s' (%s)'"
146 % (e.filename, e.strerror))
150 except ExecutionError, e:
151 log.debug(u'VpnHandler._write_config: error executing '
152 'the command: %r', e)
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():
166 self._write_single_config('host',
167 path.join(v.vpn_src, 'hosts', h.name), vars)
169 log.debug(u'VpnHandler._write_config: removing...')
171 # FIXME use os.unlink()
173 path.join(v.vpn_src, 'hosts', h.name)))
175 except ExecutionError, e:
176 log.debug(u'VpnHandler._write_config: error '
177 'removing files: %r', e)
179 #delete the vpn root at tinc dir
180 if path.exists('/etc/tinc/' + v.vpn_src):
182 call(('rm','-rf','/etc/tinc/' + v.vpn_src))
183 del self.vpns[v.vpn_src]
186 if __name__ == '__main__':
189 level = logging.DEBUG,
190 format = '%(asctime)s %(levelname)-8s %(message)s',
191 datefmt = '%H:%M:%S',
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')