chiark / gitweb /
2daf0b0223a2f692a1494629cd4db39890440f3c
[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       while True:
106         packet = self.pq.popleft()
107         if packet is None: break
108
109         encoded = slip.encode(packet)
110         
111         if request.sentLength > 0:
112           if (request.sentLength + len(slip.delimiter)
113               + len(encoded) > self.max_batch_down):
114             break
115           request.write(slip.delimiter)
116
117         request.write(encoded)
118         self._pq.popLeft()
119
120       assert(request.sentLength)
121       self._rq.popLeft()
122       request.finish()
123       # round again, looking for more to do
124
125     while len(self._rq) > self.target_requests_outstanding:
126       request = self._rq.popleft()
127       request.finish()
128
129 class IphttpResource(twisted.web.resource.Resource):
130   isLeaf = True
131   def render_POST(self, request):
132     # find client, update config, etc.
133     metadata = request.args['m']
134     (ci_s, pw, tro) = metadata.split(b'\n')[0:3]
135     ci = ipaddr(ci_s)
136     cl = clients[ci]
137     if pw != cl.pw: raise ValueError('bad password')
138
139     if pw != cl.target_requests_outstanding:
140       raise ...
141
142     try: d = request.args['d']
143     except KeyError: d = ''
144
145     cl.process_arriving_data(d)
146     cl.new_request(request)
147
148   def render_GET(self, request):
149     return b'<html><body>hippotat</body></html>'
150
151 def start_http():
152   resource = IphttpResource()
153   site = twisted.web.server.Site(resource)
154   for sa in c.saddrs:
155     ep = sa.make_endpoint()
156     crash_on_defer(ep.listen(site))
157
158 #---------- config and setup ----------
159         
160 def process_cfg():
161   process_cfg_common_always()
162   process_cfg_server()
163   process_cfg_network()
164
165   try:
166     c.relay = cfg.get('virtual','relay')
167   except NoOptionError:
168     for search in c.network.hosts():
169       if search == c.server: continue
170       c.relay = search
171       break
172
173   process_cfg_saddrs()
174   process_cfg_clients(Client)
175
176   process_cfg_ipif('server',
177                    (('local','server'),
178                     ('peer', 'relay'),
179                     ('rnets','network')))
180
181 common_startup()
182 process_cfg()
183 start_ipif(c.ipif_command, route)
184 start_http()
185 common_run()