chiark / gitweb /
wip
[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: dclient = 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 def process_request(request):
119   # find client, update config, etc.
120   metadata = request.args['m']
121   (ci_s, pw, tro) = metadata.split(b'\n')[0:3]
122   ci = ipaddr(ci_s)
123   cl = clients[ci]
124   if pw != cl.pw: raise ValueError('bad password')
125
126   if pw != cl.target_requests_outstanding:
127     raise ...
128
129   try: d = request.args['d']
130   except KeyError: d = ''
131
132   cl.process_arriving_data(d)
133   cl.new_request(request)
134
135 class IphttpResource(twisted.web.resource.Resource):
136   isLeaf = True
137   def render_POST(self, request):
138     try: process_request(request)
139     except Exception as e:
140       request.setHeader('Content-Type','text/plain; charset="utf-8"')
141       request.setResponseCode(400)
142       return str(e).encode('utf-8')
143
144   def render_GET(self, request):
145     return b'<html><body>hippotat</body></html>'
146
147 def start_http():
148   resource = IphttpResource()
149   site = twisted.web.server.Site(resource)
150   for sa in c.saddrs:
151     ep = sa.make_endpoint()
152     crash_on_defer(ep.listen(site))
153
154 #---------- config and setup ----------
155         
156 def process_cfg():
157   process_cfg_common_always()
158   process_cfg_server()
159   process_cfg_network()
160
161   try:
162     c.relay = cfg.get('virtual','relay')
163   except NoOptionError:
164     for search in c.network.hosts():
165       if search == c.server: continue
166       c.relay = search
167       break
168
169   process_cfg_saddrs()
170   process_cfg_clients(Client)
171
172   process_cfg_ipif('server',
173                    (('local','server'),
174                     ('peer', 'relay'),
175                     ('rnets','network')))
176
177 common_startup()
178 process_cfg()
179 start_ipif(c.ipif_command, route)
180 start_http()
181 common_run()