chiark / gitweb /
move ipif slip process handling
[hippotat.git] / hippotat / __init__.py
index ee844cd53faa83b09602c3231043b2d9fb588861..2b13003994fa6bf3464e8f039df0aa2d81f82736 100644 (file)
@@ -1,10 +1,13 @@
 # -*- python -*-
 
-import hippotat.slip as slip
+import twisted
+from twisted.internet import reactor
 
 import ipaddress
 from ipaddress import AddressValueError
 
+import hippotat.slip as slip
+
 #---------- packet parsing ----------
 
 def packet_addrs(packet):
@@ -38,3 +41,35 @@ def ipnetwork(input):
   except NetworkValueError:
     r = ipaddress.IPv6Network(input)
   return r
+
+#---------- ipif (SLIP) subprocess ----------
+
+class _IpifProcessProtocol(twisted.internet.protocol.ProcessProtocol):
+  def __init__(self, router):
+    self._buffer = b''
+    self._router = router
+  def connectionMade(self): pass
+  def outReceived(self, data):
+    #print('RECV ', repr(data))
+    self._buffer += data
+    packets = slip.decode(self._buffer)
+    self._buffer = packets.pop()
+    for packet in packets:
+      if not len(packet): continue
+      (saddr, daddr) = packet_addrs(packet)
+      self._router(packet, saddr, daddr)
+  def processEnded(self, status):
+    status.raiseException()
+
+def start_ipif(command, router):
+  global ipif
+  ipif = _IpifProcessProtocol(router)
+  reactor.spawnProcess(ipif,
+                       '/bin/sh',['sh','-xc', command],
+                       childFDs={0:'w', 1:'r', 2:2})
+
+def queue_inbound(packet):
+  ipif.transport.write(slip.delimiter)
+  ipif.transport.write(slip.encode(packet))
+  ipif.transport.write(slip.delimiter)
+