chiark / gitweb /
move more stuff
[hippotat.git] / server
diff --git a/server b/server
index 1a9049b845131db9c6148373e6f121853fd60e9a..66de6e5b794d14113193f2b2560805938142e257 100755 (executable)
--- a/server
+++ b/server
-#!/usr/bin/python2
+#!/usr/bin/python3
 
-from twisted.web.server import Site
-from twisted.web.resource import Resource
+from hippotat import *
+
+import sys
+import os
+
+import twisted.internet
+import twisted.internet.endpoints
 from twisted.web.server import NOT_DONE_YET
-from twisted.internet import reactor
 
-import ConfigParser
-import ipaddress
+#import twisted.web.server import Site
+#from twisted.web.resource import Resource
 
-clients = { }
+import syslog
 
-def ipaddress(input):
-  try:
-    r = ipaddress.IPv4Address(input)
-  except AddressValueError:
-    r = ipaddress.IPv6Address(input)
-  return r
+clients = { }
 
-def ipnetwork(input):
-  try:
-    r = ipaddress.IPv4Network(input)
-  except NetworkValueError:
-    r = ipaddress.IPv6Network(input)
-  return r
-
-defcfg = u'''
-[default]
-max_batch_down: 65536
-max_queue_time: 10
-max_request_time: 54
-
-[global]
-max_batch_down: 262144
-max_queue_time: 121
-max_request_time: 121
+defcfg = '''
+[DEFAULT]
+max_batch_down = 65536
+max_queue_time = 10
+max_request_time = 54
+target_requests_outstanding = 3
+
+[virtual]
+mtu = 1500
+# network
+# [host]
+# [relay]
+
+[server]
+ipif = userv root ipif %(host)s,%(relay)s,%(mtu)s,slip %(network)s
+addrs = 127.0.0.1 ::1
+port = 8099
+
+[limits]
+max_batch_down = 262144
+max_queue_time = 121
+max_request_time = 121
+target_requests_outstanding = 10
 '''
 
+#---------- "router" ----------
+
+def route(packet, saddr, daddr):
+  print('TRACE ', saddr, daddr, packet)
+  try: client = clients[daddr]
+  except KeyError: dclient = None
+  if dclient is not None:
+    dclient.queue_outbound(packet)
+  elif saddr.is_link_local or daddr.is_link_local:
+    log_discard(packet, saddr, daddr, 'link-local')
+  elif daddr == host or daddr not in network:
+    print('TRACE INBOUND ', saddr, daddr, packet)
+    queue_inbound(packet)
+  elif daddr == relay:
+    log_discard(packet, saddr, daddr, 'relay')
+  else:
+    log_discard(packet, saddr, daddr, 'no client')
+
+def log_discard(packet, saddr, daddr, why):
+  print('DROP ', saddr, daddr, why)
+#  syslog.syslog(syslog.LOG_DEBUG,
+#                'discarded packet %s -> %s (%s)' % (saddr, daddr, why))
+
+#---------- client ----------
+
 class Client():
-  def __init__(ip, cs):
+  def __init__(self, ip, cs):
     # instance data members
     self._ip = ip
     self._cs = cs
     self.pw = cfg.get(cs, 'password')
-    # plus:
-    #  .cfg[<config-key>]
-    self.cfg = { }
-    for k in ('max_batch_down','max_queue_time','max_request_time'):
+    self._rq = collections.deque() # requests
+    # self._pq = PacketQueue(...)
+    # plus from config:
+    #  .max_batch_down
+    #  .max_queue_time
+    #  .max_request_time
+    #  .target_requests_outstanding
+    for k in ('max_batch_down','max_queue_time','max_request_time',
+              'target_requests_outstanding'):
       req = cfg.getint(cs, k)
-      limit = cfg.getint('global',k)
-      self.cfg[k] = min(req, limit)
+      limit = cfg.getint('limits',k)
+      self.__dict__[k] = min(req, limit)
+    self._pq = PacketQueue(self.max_queue_time)
+
+    def process_arriving_data(self, d):
+      for packet in slip.decode(d):
+        (saddr, daddr) = packet_addrs(packet)
+        if saddr != self._ip:
+          raise ValueError('wrong source address %s' % saddr)
+        route(packet, saddr, daddr)
+
+    def _req_cancel(self, request):
+      request.finish()
+
+    def _req_error(self, err, request):
+      self._req_cancel(request)
+
+    def queue_outbound(self, packet):
+      self._pq.append(packet)
+
+    def http_request(self, request):
+      request.setHeader('Content-Type','application/octet-stream')
+      reactor.callLater(self.max_request_time, self._req_cancel, request)
+      request.notifyFinish().addErrback(self._req_error, request)
+      self._rq.append(request)
+      self._check_outbound()
+
+    def _check_outbound(self):
+      while True:
+        try: request = self._rq[0]
+        except IndexError: request = None
+        if request and request.finished:
+          self._rq.popleft()
+          continue
+
+        if not self._pq.nonempty():
+          # no packets, oh well
+          continue
+
+        if request is None:
+          # no request
+          break
+
+        # request, and also some non-expired packets
+        while True:
+          packet = self.pq.popleft()
+          if packet is None: break
+
+          encoded = slip.encode(packet)
+          
+          if request.sentLength > 0:
+            if (request.sentLength + len(slip.delimiter)
+                + len(encoded) > self.max_batch_down):
+              break
+            request.write(slip.delimiter)
+
+          request.write(encoded)
+          self._pq.popLeft()
+
+        assert(request.sentLength)
+        self._rq.popLeft()
+        request.finish()
+        # round again, looking for more to do
+
+      while len(self._rq) > self.target_requests_outstanding:
+        request = self._rq.popleft()
+        request.finish()
+
+class IphttpResource(twisted.web.resource.Resource):
+  isLeaf = True
+  def render_POST(self, request):
+    # find client, update config, etc.
+    ci = ipaddr(request.args['i'])
+    c = clients[ci]
+    pw = request.args['pw']
+    if pw != c.pw: raise ValueError('bad password')
 
-    def process_arriving_data(d):
-      
+    # update config
+    for r, w in (('mbd', 'max_batch_down'),
+                 ('mqt', 'max_queue_time'),
+                 ('mrt', 'max_request_time'),
+                 ('tro', 'target_requests_outstanding')):
+      try: v = request.args[r]
+      except KeyError: continue
+      v = int(v)
+      c.__dict__[w] = v
 
+    try: d = request.args['d']
+    except KeyError: d = ''
+
+    c.process_arriving_data(d)
+    c.new_request(request)
+
+  def render_GET(self, request):
+    return b'<html><body>hippotat</body></html>'
+
+def start_http():
+  resource = IphttpResource()
+  site = twisted.web.server.Site(resource)
+  for addrspec in cfg.get('server','addrs').split():
+    try:
+      addr = ipaddress.IPv4Address(addrspec)
+      endpointfactory = twisted.internet.endpoints.TCP4ServerEndpoint
+    except AddressValueError:
+      addr = ipaddress.IPv6Address(addrspec)
+      endpointfactory = twisted.internet.endpoints.TCP6ServerEndpoint
+    ep = endpointfactory(reactor, cfg.getint('server','port'), addr)
+    crash_on_defer(ep.listen(site))
+
+#---------- config and setup ----------
+        
 def process_cfg():
   global network
-  global ourself
+  global host
+  global relay
+  global ipif_command
 
   network = ipnetwork(cfg.get('virtual','network'))
+  if network.num_addresses < 3 + 2:
+    raise ValueError('network needs at least 2^3 addresses')
+
+  try:
+    host = cfg.get('virtual','host')
+  except NoOptionError:
+    host = next(network.hosts())
+
   try:
-    ourself = cfg.get('virtual','server')
-  except ConfigParser.NoOptionError:
-    ourself = network.hosts().next()
+    relay = cfg.get('virtual','relay')
+  except NoOptionError:
+    for search in network.hosts():
+      if search == host: continue
+      relay = search
+      break
 
   for cs in cfg.sections():
     if not (':' in cs or '.' in cs): continue
-    ci = ipaddress(cs)
+    ci = ipaddr(cs)
     if ci not in network:
       raise ValueError('client %s not in network' % ci)
     if ci in clients:
       raise ValueError('multiple client cfg sections for %s' % ci)
     clients[ci] = Client(ci, cs)
 
-class FormPage(Resource):
-  def render_POST(self, request):
-    # find client, update config, etc.
-    ci = ipaddress(request.args['i'])
-    c = clients[ci]
-    pw = request.args['pw']
-    if pw != c.pw: raise ValueError('bad password')
+  global mtu
+  mtu = cfg.get('virtual','mtu')
 
-    # update config
-    for r, w in (('mbd', 'max_batch_down'),
-                 ('mqt', 'max_queue_time'),
-                 ('mrt', 'max_request_time')):
-      try: v = request.args[r]
-      except KeyError: continue
-      v = int(v)
-      c.cfg[w] = v
+  iic_vars = { }
+  for k in ('host','relay','mtu','network'):
+    iic_vars[k] = globals()[k]
 
-    try: d = request.args['d']
-    except KeyError: d = ''
+  ipif_command = cfg.get('server','ipif', vars=iic_vars)
 
-    c.process_arriving_data(d)
+def startup():
+  common_startup(defcfg)
+  process_cfg()
+  start_ipif(ipif_command, route)
+  start_http()
 
-    reactor.
+startup()
+common_run()