1 # vim: set encoding=utf-8 et sw=4 sts=4 :
7 import logging ; log = logging.getLogger('pymin.services.vpn')
9 from pymin.seqtools import Sequence
10 from pymin.dispatcher import Handler, handler, HandlerError
11 from pymin.service.util import Restorable, ConfigWriter, InitdHandler, \
12 TransactionalHandler, DictSubHandler, DictComposedSubHandler, call, ExecutionError
14 __all__ = ('VpnHandler', 'get_service')
17 def get_service(config):
18 return VpnHandler(config.vpn.pickle_dir, config.vpn.config_dir)
22 def __init__(self, vpn_src, ip, vpn_src_net, key):
25 self.src_net = vpn_src_net
30 return(self.name, self.ip, self.src_net, self.pub_key)
32 class HostHandler(DictComposedSubHandler):
34 handler_help = u"Manage hosts for a vpn"
35 _comp_subhandler_cont = 'vpns'
36 _comp_subhandler_attr = 'hosts'
37 _comp_subhandler_class = Host
41 def __init__(self, vpn_src, vpn_dst, vpn_src_ip, vpn_src_mask,
42 pub_key=None, priv_key=None):
43 self.vpn_src = vpn_src
44 self.vpn_dst = vpn_dst
45 self.vpn_src_ip = vpn_src_ip
46 self.vpn_src_mask = vpn_src_mask
47 self.pub_key = pub_key
48 self.priv_key = priv_key
53 return(self.vpn_src, self.vpn_dst, self.vpn_src_ip, self.vpn_src_mask, self.pub_key, self.priv_key)
55 def update(self, vpn_dst=None, vpn_src_ip=None, vpn_src_mask=None):
56 if vpn_dst is not None:
57 self.vpn_dst = vpn_dst
58 if vpn_src_ip is not None:
59 self.vpn_src_ip = vpn_src_ip
60 if vpn_src_mask is not None:
61 self.vpn_src_mask = vpn_src_mask
64 class VpnHandler(Restorable, ConfigWriter,
65 TransactionalHandler, DictSubHandler):
67 handler_help = u"Manage vpn service"
69 _cont_subhandler_attr = 'vpns'
70 _cont_subhandler_class = Vpn
72 _persistent_attrs = ('vpns','hosts')
74 _restorable_defaults = dict(
79 _config_writer_files = ('tinc.conf','tinc-up','host')
80 _config_writer_tpl_dir = path.join(path.dirname(__file__), 'templates')
82 def __init__(self, pickle_dir='.', config_dir='/etc/tinc'):
83 log.debug(u'VpnHandler(%r, %r)', pickle_dir, config_dir)
84 DictSubHandler.__init__(self, self)
85 self._config_writer_cfg_dir = config_dir
86 self._persistent_dir = pickle_dir
87 self._config_build_templates()
89 self.host = HostHandler(self)
91 @handler('usage: start <vpn_name>')
92 def start(self, vpn_src):
93 log.debug(u'VpnHandler.start(%r)', vpn_src)
94 if vpn_src in self.vpns:
95 call(('tincd','--net='+ vpn_src))
97 @handler('usage: stop <vpn_name>')
98 def stop(self, vpn_src):
99 log.debug(u'VpnHandler.stop(%r)', vpn_src)
100 if vpn_src in self.vpns:
101 pid_file = '/var/run/tinc.' + vpn_src + '.pid'
102 log.debug(u'VpnHandler.stop: getting pid from %r', pid_file)
103 if path.exists(pid_file):
104 pid = file(pid_file).readline()
105 pid = int(pid.strip())
107 log.debug(u'VpnHandler.stop: killing pid %r', pid)
108 os.kill(pid, signal.SIGTERM)
110 log.debug(u'VpnHandler.stop: error killing: %r', e)
112 log.debug(u'VpnHandler.stop: pid file not found')
114 def _write_config(self):
115 log.debug(u'VpnHandler._write_config()')
116 for v in self.vpns.values():
117 log.debug(u'VpnHandler._write_config: processing %r', v)
118 #chek whether it's been created or not.
120 if v.pub_key is None:
121 log.debug(u'VpnHandler._write_config: new VPN, generating '
124 log.debug(u'VpnHandler._write_config: creating dir %r',
125 path.join(self._config_writer_cfg_dir,
127 #first create the directory for the vpn
129 os.makedirs(path.join(self._config_writer_cfg_dir,
131 except (IOError, OSError), e:
132 if e.errno != errno.EEXIST:
133 raise HandlerError(u"Can't create VPN config "
134 "directory '%s' (%s)'"
135 % (e.filename, e.strerror))
136 #this command should generate 2 files inside the vpn
137 #dir, one rsa_key.priv and one rsa_key.pub
138 #for some reason debian does not work like this
139 # FIXME if the < /dev/null works, is magic!
140 log.debug(u'VpnHandler._write_config: creating key...')
141 call(('tincd', '-n', v.vpn_src, '-K', '<', '/dev/null'))
142 #open the created files and load the keys
144 f = file(path.join(self._config_writer_cfg_dir,
145 v.vpn_src, 'rsa_key.pub'),
149 except (IOError, OSError), e:
150 raise HandlerError(u"Can't read VPN key '%s' (%s)'"
151 % (e.filename, e.strerror))
155 except ExecutionError, e:
156 log.debug(u'VpnHandler._write_config: error executing '
157 'the command: %r', e)
162 self._write_single_config('tinc.conf',
163 path.join(v.vpn_src, 'tinc.conf'), vars)
164 self._write_single_config('tinc-up',
165 path.join(v.vpn_src, 'tinc-up'), vars)
166 for h in v.hosts.values():
171 self._write_single_config('host',
172 path.join(v.vpn_src, 'hosts', h.name), vars)
174 log.debug(u'VpnHandler._write_config: removing...')
176 # FIXME use os.unlink()
178 path.join(v.vpn_src, 'hosts', h.name)))
180 except ExecutionError, e:
181 log.debug(u'VpnHandler._write_config: error '
182 'removing files: %r', e)
184 #delete the vpn root at tinc dir
185 if path.exists('/etc/tinc/' + v.vpn_src):
187 call(('rm','-rf','/etc/tinc/' + v.vpn_src))
188 del self.vpns[v.vpn_src]
191 if __name__ == '__main__':
194 level = logging.DEBUG,
195 format = '%(asctime)s %(levelname)-8s %(message)s',
196 datefmt = '%H:%M:%S',
200 v.add('prueba','sarasa','192.168.0.188','255.255.255.0')
201 v.host.add('prueba', 'azazel' ,'192.168.0.77', '192.168.0.0',
202 'kjdhfkbdskljvkjblkbjeslkjbvkljbselvslberjhbvslbevlhb')