chiark / gitweb /
reorg SlipStreamDecoder again
[hippotat.git] / server
1 #!/usr/bin/python3
2
3 from hippotat import *
4
5 import os
6
7 import twisted.internet
8 from twisted.web.server import NOT_DONE_YET
9
10 #import twisted.web.server import Site
11 #from twisted.web.resource import Resource
12
13 import syslog
14
15 clients = { }
16
17 #---------- "router" ----------
18
19 def route(packet, saddr, daddr):
20   print('TRACE ', saddr, daddr, packet)
21   try: client = clients[daddr]
22   except KeyError: dclient = None
23   if dclient is not None:
24     dclient.queue_outbound(packet)
25   elif daddr == c.server or daddr not in c.network:
26     print('TRACE INBOUND ', saddr, daddr, packet)
27     queue_inbound(packet)
28   elif daddr == relay:
29     log_discard(packet, saddr, daddr, 'relay')
30   else:
31     log_discard(packet, saddr, daddr, 'no client')
32
33 #---------- client ----------
34
35 class Client():
36   def __init__(self, ip, cs, pw):
37     # instance data members
38     self._ip = ip
39     self._cs = cs
40     self.pw = pw
41     self._rq = collections.deque() # requests
42     # self._pq = PacketQueue(...)
43     # plus from config:
44     #  .max_batch_down
45     #  .max_queue_time
46     #  .max_request_time
47     #  .target_requests_outstanding
48
49     if ip not in c.network:
50       raise ValueError('client %s not in network' % ip)
51
52     for k in ('max_batch_down','max_queue_time','max_request_time',
53               'target_requests_outstanding'):
54       req = cfg.getint(cs, k)
55       limit = cfg.getint('limits',k)
56       self.__dict__[k] = min(req, limit)
57
58     self._pq = PacketQueue(self.max_queue_time)
59
60     if ip in clients:
61       raise ValueError('multiple client cfg sections for %s' % ip)
62     clients[ip] = self
63
64   def process_arriving_data(self, d):
65     for packet in slip.decode(d):
66       (saddr, daddr) = packet_addrs(packet)
67       if saddr != self._ip:
68         raise ValueError('wrong source address %s' % saddr)
69       route(packet, saddr, daddr)
70
71   def _req_cancel(self, request):
72     request.finish()
73
74   def _req_error(self, err, request):
75     self._req_cancel(request)
76
77   def queue_outbound(self, packet):
78     self._pq.append(packet)
79     self._check_outbound()
80
81   def http_request(self, request):
82     request.setHeader('Content-Type','application/octet-stream')
83     reactor.callLater(self.max_request_time, self._req_cancel, request)
84     request.notifyFinish().addErrback(self._req_error, request)
85     self._rq.append(request)
86     self._check_outbound()
87
88   def _check_outbound(self):
89     while True:
90       try: request = self._rq[0]
91       except IndexError: request = None
92       if request and request.finished:
93         self._rq.popleft()
94         continue
95
96       if not self._pq.nonempty():
97         # no packets, oh well
98         continue
99
100       if request is None:
101         # no request
102         break
103
104       # request, and also some non-expired packets
105       self._pq.process((lambda: request.sentLength),
106                        request.write,
107                        self.max_batch_down)
108
109       assert(request.sentLength)
110       self._rq.popLeft()
111       request.finish()
112       # round again, looking for more to do
113
114     while len(self._rq) > self.target_requests_outstanding:
115       request = self._rq.popleft()
116       request.finish()
117
118 class IphttpResource(twisted.web.resource.Resource):
119   isLeaf = True
120   def render_POST(self, request):
121     # find client, update config, etc.
122     metadata = request.args['m']
123     (ci_s, pw, tro) = metadata.split(b'\n')[0:3]
124     ci = ipaddr(ci_s)
125     cl = clients[ci]
126     if pw != cl.pw: raise ValueError('bad password')
127
128     if pw != cl.target_requests_outstanding:
129       raise ...
130
131     try: d = request.args['d']
132     except KeyError: d = ''
133
134     cl.process_arriving_data(d)
135     cl.new_request(request)
136
137   def render_GET(self, request):
138     return b'<html><body>hippotat</body></html>'
139
140 def start_http():
141   resource = IphttpResource()
142   site = twisted.web.server.Site(resource)
143   for sa in c.saddrs:
144     ep = sa.make_endpoint()
145     crash_on_defer(ep.listen(site))
146
147 #---------- config and setup ----------
148         
149 def process_cfg():
150   process_cfg_common_always()
151   process_cfg_server()
152   process_cfg_network()
153
154   try:
155     c.relay = cfg.get('virtual','relay')
156   except NoOptionError:
157     for search in c.network.hosts():
158       if search == c.server: continue
159       c.relay = search
160       break
161
162   process_cfg_saddrs()
163   process_cfg_clients(Client)
164
165   process_cfg_ipif('server',
166                    (('local','server'),
167                     ('peer', 'relay'),
168                     ('rnets','network')))
169
170 common_startup()
171 process_cfg()
172 start_ipif(c.ipif_command, route)
173 start_http()
174 common_run()