chiark / gitweb /
wip
[hippotat.git] / server
diff --git a/server b/server
index de28624..6a71bfd 100755 (executable)
--- a/server
+++ b/server
 #!/usr/bin/python3
 
-import signal
-signal.signal(signal.SIGINT, signal.SIG_DFL)
+from hippotat import *
 
-import sys
 import os
 
-import twisted
 import twisted.internet
-import twisted.internet.endpoints
-from twisted.internet import reactor
 from twisted.web.server import NOT_DONE_YET
-from twisted.logger import LogLevel
-
-import ipaddress
-from ipaddress import AddressValueError
 
 #import twisted.web.server import Site
 #from twisted.web.resource import Resource
 
-from optparse import OptionParser
-from configparser import ConfigParser
-from configparser import NoOptionError
-
-import collections
-
 import syslog
 
-clients = { }
-
-def ipaddr(input):
-  try:
-    r = ipaddress.IPv4Address(input)
-  except AddressValueError:
-    r = ipaddress.IPv6Address(input)
-  return r
+import traceback
 
-def ipnetwork(input):
-  try:
-    r = ipaddress.IPv4Network(input)
-  except NetworkValueError:
-    r = ipaddress.IPv6Network(input)
-  return r
-
-defcfg = '''
-[DEFAULT]
-max_batch_down = 65536
-max_queue_time = 10
-max_request_time = 54
-
-[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
-'''
-
-#---------- error handling ----------
-
-def crash(err):
-  print('CRASH ', err, file=sys.stderr)
-  try: reactor.stop()
-  except twisted.internet.error.ReactorNotRunning: pass
-
-def crash_on_defer(defer):
-  defer.addErrback(lambda err: crash(err))
-
-def crash_on_critical(event):
-  if event.get('log_level') >= LogLevel.critical:
-    crash(twisted.logger.formatEvent(event))
+clients = { }
 
 #---------- "router" ----------
 
-def route(packet, saddr, daddr):
-  print('TRACE ', saddr, daddr, packet)
-  try: client = clients[daddr]
+def route(packet, iface, saddr, daddr):
+  def lt(dest):
+    log_debug(DBG.ROUTE, 'route: %s -> %s: %s' % (saddr,daddr,dest), d=packet)
+  try: dclient = clients[daddr]
   except KeyError: dclient = None
   if dclient is not None:
+    lt('client')
     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)
+  elif daddr == c.server or daddr not in c.network:
+    lt('inbound')
     queue_inbound(packet)
   elif daddr == relay:
-    log_discard(packet, saddr, daddr, 'relay')
+    lt('discard relay')
+    log_discard(packet, iface, 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))
-
-#---------- ipif (slip subprocess) ----------
-
-class IpifProcessProtocol(twisted.internet.protocol.ProcessProtocol):
-  def __init__(self):
-    self._buffer = b''
-  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)
-      route(packet, saddr, daddr)
-  def processEnded(self, status):
-    status.raiseException()
-
-def start_ipif():
-  global ipif
-  ipif = IpifProcessProtocol()
-  reactor.spawnProcess(ipif,
-                       '/bin/sh',['sh','-xc', ipif_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)
-
-#---------- SLIP handling ----------
-
-slip_end = b'\300'
-slip_esc = b'\333'
-slip_esc_end = b'\334'
-slip_esc_esc = b'\335'
-slip_delimiter = slip_end
-
-def slip_encode(packet):
-  return (packet
-          .replace(slip_esc, slip_esc + slip_esc_esc)
-          .replace(slip_end, slip_esc + slip_esc_end))
-
-def slip_decode(data):
-  print('DECODE ', repr(data))
-  out = []
-  for packet in data.split(slip_end):
-    pdata = b''
-    while True:
-      eix = packet.find(slip_esc)
-      if eix == -1:
-        pdata += packet
-        break
-      #print('ESC ', repr((pdata, packet, eix)))
-      pdata += packet[0 : eix]
-      ck = packet[eix+1]
-      if   ck == slip_esc_esc: pdata += slip_esc
-      elif ck == slip_esc_end: pdata += slip_end
-      else: raise ValueError('invalid SLIP escape')
-      packet = packet[eix+2 : ]
-    out.append(pdata)
-  print('DECODED ', repr(out))
-  return out
-
-#---------- packet parsing ----------
-
-def packet_addrs(packet):
-  version = packet[0] >> 4
-  if version == 4:
-    addrlen = 4
-    saddroff = 3*4
-    factory = ipaddress.IPv4Address
-  elif version == 6:
-    addrlen = 16
-    saddroff = 2*4
-    factory = ipaddress.IPv6Address
-  else:
-    raise ValueError('unsupported IP version %d' % version)
-  saddr = factory(packet[ saddroff           : saddroff + addrlen   ])
-  daddr = factory(packet[ saddroff + addrlen : saddroff + addrlen*2 ])
-  return (saddr, daddr)
+    lt('discard no-client')
+    log_discard(packet, iface, saddr, daddr, 'no-client')
 
 #---------- client ----------
 
 class Client():
-  def __init__(self, ip, cs):
+  def __init__(self, ip, cs, pw):
     # instance data members
     self._ip = ip
     self._cs = cs
-    self.pw = cfg.get(cs, 'password')
+    self.pw = pw
     self._rq = collections.deque() # requests
-    self._pq = collections.deque() # packets
+    # self._pq = PacketQueue(...)
     # plus from config:
     #  .max_batch_down
     #  .max_queue_time
     #  .max_request_time
-    for k in ('max_batch_down','max_queue_time','max_request_time'):
+    #  .target_requests_outstanding
+
+    if ip not in c.network:
+      raise ValueError('client %s not in network' % ip)
+
+    for k in ('max_batch_down','max_queue_time','max_request_time',
+              'target_requests_outstanding'):
       req = cfg.getint(cs, k)
       limit = cfg.getint('limits',k)
       self.__dict__[k] = min(req, limit)
 
-    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)
+    self._pq = PacketQueue(str(ip), self.max_queue_time)
+
+    if ip in clients:
+      raise ValueError('multiple client cfg sections for %s' % ip)
+    clients[ip] = self
+
+    self._log(DBG.INIT, 'new')
+
+  def _log(self, dflag, msg, **kwargs):
+    log_debug(dflag, ('client %s: ' % self._ip)+msg, **kwargs)
+
+  def process_arriving_data(self, d):
+    self._log(DBG.FLOW, "req data (enc'd)", d=d)
+    if not len(d): return
+    for packet in slip.decode(d):
+      (saddr, daddr) = packet_addrs(packet)
+      if saddr != self._ip:
+        raise ValueError('wrong source address %s' % saddr)
+      route(packet, self._ip, saddr, daddr)
+
+  def _req_cancel(self, request):
+    self._log(DBG.HTTP_CTRL, 'cancel', idof=request)
+    request.finish()
+
+  def _req_error(self, err, request):
+    self._log(DBG.HTTP_CTRL, 'error %s' % err, idof=request)
+    self._req_cancel(request)
+
+  def queue_outbound(self, packet):
+    self._pq.append(packet)
+    self._check_outbound()
+
+  def new_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):
+    log_debug(DBG.HTTP_CTRL, 'CHKO')
+    while True:
+      try: request = self._rq[0]
+      except IndexError: request = None
+      if request and request.finished:
+        self._log(DBG.HTTP_CTRL, 'CHKO req finished, discard', idof=request)
+        self._rq.popleft()
+        continue
+
+      if not self._pq.nonempty():
+        # no packets, oh well
+        self._log(DBG.HTTP_CTRL, 'CHKO no packets, OUT-DONE', idof=request)
+        break
+
+      if request is None:
+        # no request
+        self._log(DBG.HTTP_CTRL, 'CHKO no request, OUT-DONE', idof=request)
+        break
+
+      self._log(DBG.HTTP_CTRL, 'CHKO processing', idof=request)
+      # request, and also some non-expired packets
+      self._pq.process((lambda: request.sentLength),
+                       request.write,
+                       self.max_batch_down)
 
-    def _req_cancel(self, request):
+      assert(request.sentLength)
+      self._rq.popleft()
       request.finish()
+      self._log(DBG.HTTP, 'complete', idof=request)
+      # round again, looking for more to do
 
-    def _req_error(self, err, request):
-      self._req_cancel(request)
-
-    def queue_outbound(self, packet):
-      self._pq.append((time.monotonic(), 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
-
-        # now request is an unfinished request, or None
-        try: (queuetime, packet) = self._pq[0]
-        except IndexError:
-          # no packets, oh well
-          break
-
-        age = time.monotonic() - queuetime
-        if age > self.max_queue_time:
-          self._pq.popleft()
-          continue
-
-        if request is None:
-          # no request
-          break
-
-        # request, and also some non-expired packets
-        while True:
-          try: (dummy, packet) = self._pq[0]
-          except IndexError: 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()
+      self._log(DBG.HTTP, 'CHKO above target, returning empty', idof=request)
+      request.finish()
+
+def process_request(request, desca):
+  # find client, update config, etc.
+  metadata = request.args[b'm'][0]
+  metadata = metadata.split(b'\r\n')
+  (ci_s, pw, tro) = metadata[0:3]
+  desca['m[0,2]'] = [ci_s, tro]
+  ci_s = ci_s.decode('utf-8')
+  tro = int(tro)
+  desca['tro']= tro
+  ci = ipaddr(ci_s)
+  desca['ci'] = ci
+  cl = clients[ci]
+  if pw != cl.pw: raise ValueError('bad password')
+  desca['pwok']=True
+
+  if tro != cl.target_requests_outstanding:
+    raise ValueError('tro must be %d' % cl.target_requests_outstanding)
+
+  try:
+    d = request.args[b'd'][0]
+    desca['d'] = d
+  except KeyError: d = b''
+
+  cl.process_arriving_data(d)
+  cl.new_request(request)
+
+def log_http(desca, msg):
+  try:
+    d = desca['d']
+    del desca['d']
+  except KeyError:
+    d = None
+  log_debug(DBG.HTTP, msg + repr(desca), d=d)
 
 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')
-
-    # 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.__dict__[w] = v
-
-    try: d = request.args['d']
-    except KeyError: d = ''
-
-    c.process_arriving_data(d)
-    c.new_request(request)
+    log_debug(DBG.HTTP_FULL,
+              'req recv: ' + repr(request) + ' ' + repr(request.args),
+              idof=id(request))
+    desca = {'d': None}
+    try: process_request(request, desca)
+    except Exception as e:
+      emsg = traceback.format_exc()
+      log_http(desca, 'EXCEPTION ' + emsg)
+      request.setHeader('Content-Type','text/plain; charset="utf-8"')
+      request.setResponseCode(400)
+      return (emsg + ' # ' + repr(desca) + '\r\n').encode('utf-8')
+    log_http(desca, '... [%s]' % id(request))
+    return NOT_DONE_YET
+
+  def render_GET(self, request):
+    log_debug(DBG.HTTP, 'GET request')
+    return b'<html><body>hippotat</body></html>'
 
 def start_http():
   resource = IphttpResource()
-  sitefactory = 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(sitefactory))
+  site = twisted.web.server.Site(resource)
+  for sa in c.saddrs:
+    ep = sa.make_endpoint()
+    crash_on_defer(ep.listen(site))
+    log_debug(DBG.INIT, 'listening on %s' % sa)
 
 #---------- config and setup ----------
         
 def process_cfg():
-  global network
-  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')
+  process_cfg_common_always()
+  process_cfg_server()
+  process_cfg_network()
 
   try:
-    host = cfg.get('virtual','host')
+    c.relay = cfg.get('virtual','relay')
   except NoOptionError:
-    host = next(network.hosts())
-
-  try:
-    relay = cfg.get('virtual','relay')
-  except NoOptionError:
-    for search in network.hosts():
-      if search == host: continue
-      relay = search
+    for search in c.network.hosts():
+      if search == c.server: continue
+      c.relay = search
       break
 
-  for cs in cfg.sections():
-    if not (':' in cs or '.' in cs): continue
-    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)
-
-  global mtu
-  mtu = cfg.get('virtual','mtu')
-
-  iic_vars = { }
-  for k in ('host','relay','mtu','network'):
-    iic_vars[k] = globals()[k]
-
-  ipif_command = cfg.get('server','ipif', vars=iic_vars)
-
-def startup():
-  global cfg
-
-  op = OptionParser()
-  op.add_option('-c', '--config', dest='configfile',
-                default='/etc/hippottd/server.conf')
-  global opts
-  (opts, args) = op.parse_args()
-  if len(args): op.error('no non-option arguments please')
-
-  twisted.logger.globalLogPublisher.addObserver(crash_on_critical)
-
-  cfg = ConfigParser()
-  cfg.read_string(defcfg)
-  cfg.read(opts.configfile)
-  process_cfg()
+  process_cfg_saddrs()
+  process_cfg_clients(Client)
 
-  start_ipif()
-  start_http()
+  process_cfg_ipif('server',
+                   (('local','server'),
+                    ('peer', 'relay'),
+                    ('rnets','network')))
 
-startup()
-reactor.run()
-print('CRASHED (end)', file=sys.stderr)
+common_startup()
+process_cfg()
+start_ipif(c.ipif_command, route)
+start_http()
+common_run()