2 # -*- coding: utf-8 -*-
14 from nepi.util import server
16 class TunProtoBase(object):
17 def __init__(self, local, peer, home_path, key):
18 # Weak references, since ifaces do have a reference to the
19 # tunneling protocol implementation - we don't want strong
20 # circular references.
21 self.peer = weakref.ref(peer)
22 self.local = weakref.ref(local)
28 self.home_path = home_path
39 raise RuntimeError, "Lost reference to peering interfaces before launching"
41 raise RuntimeError, "Unconnected TUN - missing node"
43 # Make sure all the paths are created where
44 # they have to be created for deployment
45 cmd = "mkdir -p %s" % (server.shell_escape(self.home_path),)
46 (out,err),proc = server.popen_ssh_command(
48 host = local.node.hostname,
50 user = local.node.slicename,
52 ident_key = local.node.ident_path,
53 server_key = local.node.server_key
57 raise RuntimeError, "Failed to set up TUN forwarder: %s %s" % (out,err,)
60 def _install_scripts(self):
64 raise RuntimeError, "Lost reference to peering interfaces before launching"
66 raise RuntimeError, "Unconnected TUN - missing node"
68 # Install the tun_connect script and tunalloc utility
69 from nepi.util import tunchannel
71 os.path.join(os.path.dirname(__file__), 'scripts', 'tun_connect.py'),
72 os.path.join(os.path.dirname(__file__), 'scripts', 'tunalloc.c'),
73 re.sub(r"([.]py)[co]$", r'\1', tunchannel.__file__, 1), # pyc/o files are version-specific
76 local.node.slicename, local.node.hostname,
77 os.path.join(self.home_path,'.'),)
78 (out,err),proc = server.popen_scp(
81 ident_key = local.node.ident_path,
82 server_key = local.node.server_key
86 raise RuntimeError, "Failed upload TUN connect script %r: %s %s" % (sources, out,err,)
89 "cd %(home)s && gcc -fPIC -shared tunalloc.c -o tunalloc.so"
91 "wget -q -c -O python-passfd-src.tar.gz %(passfd_url)s && "
92 "mkdir -p python-passfd && "
93 "cd python-passfd && "
94 "tar xzf ../python-passfd-src.tar.gz --strip-components=1 && "
95 "python setup.py build && "
96 "python setup.py install --install-lib .. "
98 if local.tun_proto == "fd" else ""
101 'home' : server.shell_escape(self.home_path),
102 'passfd_url' : "http://yans.pl.sophia.inria.fr/code/hgwebdir.cgi/python-passfd/archive/2a6472c64c87.tar.gz",
104 (out,err),proc = server.popen_ssh_command(
106 host = local.node.hostname,
108 user = local.node.slicename,
110 ident_key = local.node.ident_path,
111 server_key = local.node.server_key
115 raise RuntimeError, "Failed to set up TUN forwarder: %s %s" % (out,err,)
117 def launch(self, check_proto, listen, extra_args=[]):
121 if not peer or not local:
122 raise RuntimeError, "Lost reference to peering interfaces before launching"
124 peer_port = peer.tun_port
125 peer_addr = peer.tun_addr
126 peer_proto= peer.tun_proto
128 local_port = self.port
129 local_cap = local.capture
130 local_addr = local.address
131 local_mask = local.netprefix
132 local_snat = local.snat
133 local_txq = local.txqueuelen
135 if check_proto != peer_proto:
136 raise RuntimeError, "Peering protocol mismatch: %s != %s" % (check_proto, peer_proto)
138 if not listen and ((peer_proto != 'fd' and not peer_port) or not peer_addr):
139 raise RuntimeError, "Misconfigured peer: %s" % (peer,)
141 if listen and ((peer_proto != 'fd' and not local_port) or not local_addr or not local_mask):
142 raise RuntimeError, "Misconfigured TUN: %s" % (local,)
144 args = ["python", "tun_connect.py",
145 "-m", str(self.mode),
146 "-A", str(local_addr),
147 "-M", str(local_mask)]
149 if check_proto == 'fd':
150 passfd_arg = str(peer_addr)
151 if passfd_arg.startswith('\x00'):
152 # cannot shell_encode null characters :(
153 passfd_arg = "base64:"+base64.b64encode(passfd_arg)
155 passfd_arg = '$HOME/'+server.shell_escape(passfd_arg)
157 "--pass-fd", passfd_arg
161 "-p", str(local_port if listen else peer_port),
168 args.extend(("-Q",str(local_txq)))
170 args.extend(map(str,extra_args))
171 if not listen and check_proto != 'fd':
172 args.append(str(peer_addr))
175 self._install_scripts()
177 # Start process in a "daemonized" way, using nohup and heavy
178 # stdin/out redirection to avoid connection issues
179 (out,err),proc = rspawn.remote_spawn(
183 home = self.home_path,
185 stdout = 'capture' if local_cap else '/dev/null',
186 stderr = rspawn.STDOUT,
189 host = local.node.hostname,
191 user = local.node.slicename,
193 ident_key = local.node.ident_path,
194 server_key = local.node.server_key
198 raise RuntimeError, "Failed to set up TUN: %s %s" % (out,err,)
202 def _launch_and_wait(self, *p, **kw):
205 self.launch(*p, **kw)
207 # Wait for the process to be started
208 while self.status() == rspawn.NOT_STARTED:
211 # Wait for the connection to be established
213 for spin in xrange(30):
214 if self.status() != rspawn.RUNNING:
217 (out,err),proc = server.popen_ssh_command(
218 "cd %(home)s ; grep -c Connected capture" % dict(
219 home = server.shell_escape(self.home_path)),
220 host = local.node.hostname,
222 user = local.node.slicename,
224 ident_key = local.node.ident_path,
225 server_key = local.node.server_key
231 if out.strip() != '0':
236 def async_launch(self, check_proto, listen, extra_args=[]):
237 if not self._launcher:
238 self._launcher = threading.Thread(
239 target = self._launch_and_wait,
240 args = (check_proto, listen, extra_args))
241 self._launcher.start()
243 def async_launch_wait(self):
245 self._launcher.join()
246 if not self._started:
247 raise RuntimeError, "Failed to launch TUN forwarder"
248 elif not self._started:
255 raise RuntimeError, "Lost reference to local interface"
258 # NOTE: wait a bit for the pidfile to be created
259 if self._started and not self._pid or not self._ppid:
260 pidtuple = rspawn.remote_check_pid(
261 os.path.join(self.home_path,'pid'),
262 host = local.node.hostname,
264 user = local.node.slicename,
266 ident_key = local.node.ident_path,
267 server_key = local.node.server_key
271 self._pid, self._ppid = pidtuple
277 raise RuntimeError, "Lost reference to local interface"
280 if not self._started:
281 return rspawn.NOT_STARTED
282 elif not self._pid or not self._ppid:
283 return rspawn.NOT_STARTED
285 status = rspawn.remote_status(
286 self._pid, self._ppid,
287 host = local.node.hostname,
289 user = local.node.slicename,
291 ident_key = local.node.ident_path
299 raise RuntimeError, "Lost reference to local interface"
301 status = self.status()
302 if status == rspawn.RUNNING:
303 # kill by ppid+pid - SIGTERM first, then try SIGKILL
305 self._pid, self._ppid,
306 host = local.node.hostname,
308 user = local.node.slicename,
310 ident_key = local.node.ident_path,
311 server_key = local.node.server_key,
315 def sync_trace(self, local_dir, whichtrace):
316 if whichtrace != 'packets':
324 local_path = os.path.join(local_dir, 'capture')
326 # create parent local folders
327 proc = subprocess.Popen(
328 ["mkdir", "-p", os.path.dirname(local_path)],
329 stdout = open("/dev/null","w"),
330 stdin = open("/dev/null","r"))
333 raise RuntimeError, "Failed to synchronize trace: %s %s" % (out,err,)
336 (out,err),proc = server.popen_scp(
337 '%s@%s:%s' % (local.node.slicename, local.node.hostname,
338 os.path.join(self.home_path, 'capture')),
342 ident_key = local.node.ident_path,
343 server_key = local.node.server_key
347 raise RuntimeError, "Failed to synchronize trace: %s %s" % (out,err,)
356 eg: set up listening ports
358 raise NotImplementedError
366 raise NotImplementedError
372 raise NotImplementedError
375 class TunProtoUDP(TunProtoBase):
376 def __init__(self, local, peer, home_path, key, listening):
377 super(TunProtoUDP, self).__init__(local, peer, home_path, key)
378 self.listening = listening
384 self.async_launch('udp', False, ("-u",str(self.port)))
389 class TunProtoFD(TunProtoBase):
390 def __init__(self, local, peer, home_path, key, listening):
391 super(TunProtoFD, self).__init__(local, peer, home_path, key)
392 self.listening = listening
398 self.async_launch('fd', False)
403 class TunProtoTCP(TunProtoBase):
404 def __init__(self, local, peer, home_path, key, listening):
405 super(TunProtoTCP, self).__init__(local, peer, home_path, key)
406 self.listening = listening
410 self.async_launch('tcp', True)
413 if not self.listening:
414 # make sure our peer is ready
416 if peer and peer.peer_proto_impl:
417 peer.peer_proto_impl.async_launch_wait()
419 if not self._started:
420 self.launch('tcp', False)
422 # make sure WE are ready
423 self.async_launch_wait()
430 class TapProtoUDP(TunProtoUDP):
431 def __init__(self, local, peer, home_path, key, listening):
432 super(TapProtoUDP, self).__init__(local, peer, home_path, key, listening)
435 class TapProtoTCP(TunProtoTCP):
436 def __init__(self, local, peer, home_path, key, listening):
437 super(TapProtoTCP, self).__init__(local, peer, home_path, key, listening)
440 class TapProtoFD(TunProtoFD):
441 def __init__(self, local, peer, home_path, key, listening):
442 super(TapProtoFD, self).__init__(local, peer, home_path, key, listening)