X-Git-Url: http://www.chiark.greenend.org.uk/ucgi/~ian/git?p=hippotat.git;a=blobdiff_plain;f=server;h=6a71bfd5b8f1452da80e2ad0c7efcb8de553bd7d;hp=6da5be4d7acfe5596d3141e1d64124f378a221ad;hb=e8fcf3b7494f214242f8a0a8fe9c72fe7f7a27b1;hpb=1d023c89e4379225b5d71e565b93f537e119ab75 diff --git a/server b/server index 6da5be4..6a71bfd 100755 --- a/server +++ b/server @@ -2,7 +2,6 @@ from hippotat import * -import sys import os import twisted.internet @@ -13,55 +12,29 @@ from twisted.web.server import NOT_DONE_YET import syslog -clients = { } +import traceback -defcfg = ''' -[DEFAULT] -max_batch_down = 65536 -max_queue_time = 10 -max_request_time = 54 -target_requests_outstanding = 3 -ipif = userv root ipif %(local)s,%(peer)s,%(mtu)s,slip %(rnets)s - -[virtual] -mtu = 1500 -# network -# [server] -# [relay] - -[server] -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 -''' +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 == c.server or daddr not in c.network: - print('TRACE INBOUND ', saddr, daddr, packet) + 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)) + lt('discard no-client') + log_discard(packet, iface, saddr, daddr, 'no-client') #---------- client ---------- @@ -87,29 +60,40 @@ class Client(): req = cfg.getint(cs, k) limit = cfg.getint('limits',k) self.__dict__[k] = min(req, limit) - self._pq = PacketQueue(self.max_queue_time) + + 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, saddr, daddr) + 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 http_request(self, request): + 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) @@ -117,72 +101,95 @@ class Client(): 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 - continue + 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 - 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() + self._pq.process((lambda: request.sentLength), + request.write, + self.max_batch_down) assert(request.sentLength) - self._rq.popLeft() + self._rq.popleft() request.finish() + self._log(DBG.HTTP, 'complete', idof=request) # 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'), - ('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) + 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'hippotat' def start_http(): @@ -191,6 +198,7 @@ def start_http(): 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 ---------- @@ -212,10 +220,10 @@ def process_cfg(): process_cfg_ipif('server', (('local','server'), - ('peer','relay'), + ('peer', 'relay'), ('rnets','network'))) -common_startup(defcfg) +common_startup() process_cfg() start_ipif(c.ipif_command, route) start_http()