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.service.util import Restorable, ConfigWriter, InitdHandler, \
13 TransactionalHandler, DictSubHandler, DictComposedSubHandler, call, ExecutionError
15 __all__ = ('VpnHandler', 'get_service')
18 def get_service(config):
19 return VpnHandler(config.vpn.pickle_dir, config.vpn.config_dir)
23 def __init__(self, vpn_src, ip, vpn_src_net, key):
26 self.src_net = vpn_src_net
31 return(self.name, self.ip, self.src_net, self.pub_key)
33 class HostHandler(DictComposedSubHandler):
35 handler_help = u"Manage hosts for a vpn"
36 _comp_subhandler_cont = 'vpns'
37 _comp_subhandler_attr = 'hosts'
38 _comp_subhandler_class = Host
42 def __init__(self, vpn_src, vpn_dst, vpn_src_ip, vpn_src_mask,
43 pub_key=None, priv_key=None):
44 self.vpn_src = vpn_src
45 self.vpn_dst = vpn_dst
46 self.vpn_src_ip = vpn_src_ip
47 self.vpn_src_mask = vpn_src_mask
48 self.pub_key = pub_key
49 self.priv_key = priv_key
54 return(self.vpn_src, self.vpn_dst, self.vpn_src_ip, self.vpn_src_mask, self.pub_key, self.priv_key)
56 def update(self, vpn_dst=None, vpn_src_ip=None, vpn_src_mask=None):
57 if vpn_dst is not None:
58 self.vpn_dst = vpn_dst
59 if vpn_src_ip is not None:
60 self.vpn_src_ip = vpn_src_ip
61 if vpn_src_mask is not None:
62 self.vpn_src_mask = vpn_src_mask
65 class VpnHandler(Restorable, ConfigWriter,
66 TransactionalHandler, DictSubHandler):
68 handler_help = u"Manage vpn service"
70 _cont_subhandler_attr = 'vpns'
71 _cont_subhandler_class = Vpn
73 _persistent_attrs = ('vpns','hosts')
75 _restorable_defaults = dict(
80 _config_writer_files = ('tinc.conf','tinc-up','host')
81 _config_writer_tpl_dir = path.join(path.dirname(__file__), 'templates')
83 def __init__(self, pickle_dir='.', config_dir='/etc/tinc'):
84 log.debug(u'VpnHandler(%r, %r)', pickle_dir, config_dir)
85 DictSubHandler.__init__(self, self)
86 self._config_writer_cfg_dir = config_dir
87 self._persistent_dir = pickle_dir
88 self._config_build_templates()
90 self.host = HostHandler(self)
92 @handler('usage: start <vpn_name>')
93 def start(self, vpn_src):
94 log.debug(u'VpnHandler.start(%r)', vpn_src)
95 if vpn_src in self.vpns:
96 call(('tincd','--net='+ vpn_src))
98 @handler('usage: stop <vpn_name>')
99 def stop(self, vpn_src):
100 log.debug(u'VpnHandler.stop(%r)', vpn_src)
101 if vpn_src in self.vpns:
102 pid_file = '/var/run/tinc.' + vpn_src + '.pid'
103 log.debug(u'VpnHandler.stop: getting pid from %r', pid_file)
104 if path.exists(pid_file):
105 pid = file(pid_file).readline()
106 pid = int(pid.strip())
108 log.debug(u'VpnHandler.stop: killing pid %r', pid)
109 os.kill(pid, signal.SIGTERM)
111 log.debug(u'VpnHandler.stop: error killing: %r', e)
113 log.debug(u'VpnHandler.stop: pid file not found')
115 def _write_config(self):
116 log.debug(u'VpnHandler._write_config()')
117 for v in self.vpns.values():
118 log.debug(u'VpnHandler._write_config: processing %r', v)
119 #chek whether it's been created or not.
121 if v.pub_key is None:
122 log.debug(u'VpnHandler._write_config: new VPN, generating '
125 log.debug(u'VpnHandler._write_config: creating dir %r',
126 path.join(self._config_writer_cfg_dir,
128 #first create the directory for the vpn
130 os.makedirs(path.join(self._config_writer_cfg_dir,
132 except (IOError, OSError), e:
133 if e.errno != errno.EEXIST:
134 raise HandlerError(u"Can't create VPN config "
135 "directory '%s' (%s)'"
136 % (e.filename, e.strerror))
137 #this command should generate 2 files inside the vpn
138 #dir, one rsa_key.priv and one rsa_key.pub
139 #for some reason debian does not work like this
140 # FIXME if the < /dev/null works, is magic!
141 log.debug(u'VpnHandler._write_config: creating key...')
142 call(('tincd', '-n', v.vpn_src, '-K', '<', '/dev/null'))
143 #open the created files and load the keys
145 f = file(path.join(self._config_writer_cfg_dir,
146 v.vpn_src, 'rsa_key.pub'),
150 except (IOError, OSError), e:
151 raise HandlerError(u"Can't read VPN key '%s' (%s)'"
152 % (e.filename, e.strerror))
156 except ExecutionError, e:
157 log.debug(u'VpnHandler._write_config: error executing '
158 'the command: %r', e)
163 self._write_single_config('tinc.conf',
164 path.join(v.vpn_src, 'tinc.conf'), vars)
165 self._write_single_config('tinc-up',
166 path.join(v.vpn_src, 'tinc-up'), vars)
167 for h in v.hosts.values():
172 self._write_single_config('host',
173 path.join(v.vpn_src, 'hosts', h.name), vars)
175 log.debug(u'VpnHandler._write_config: removing...')
177 # FIXME use os.unlink()
179 path.join(v.vpn_src, 'hosts', h.name)))
181 except ExecutionError, e:
182 log.debug(u'VpnHandler._write_config: error '
183 'removing files: %r', e)
185 #delete the vpn root at tinc dir
186 if path.exists('/etc/tinc/' + v.vpn_src):
188 call(('rm','-rf','/etc/tinc/' + v.vpn_src))
189 del self.vpns[v.vpn_src]
192 if __name__ == '__main__':
195 level = logging.DEBUG,
196 format = '%(asctime)s %(levelname)-8s %(message)s',
197 datefmt = '%H:%M:%S',
201 v.add('prueba','sarasa','192.168.0.188','255.255.255.0')
202 v.host.add('prueba', 'azazel' ,'192.168.0.77', '192.168.0.0',
203 'kjdhfkbdskljvkjblkbjeslkjbvkljbselvslberjhbvslbevlhb')