chiark / gitweb /
ownsrc debugging
[hippotat.git] / hippotatd
1 #!/usr/bin/python3
2 #
3 # Hippotat - Asinine IP Over HTTP program
4 # ./hippotatd - server main program
5 #
6 # Copyright 2017 Ian Jackson
7 #
8 # AGPLv3+ + CAFv2+
9 #
10 #    This program is free software: you can redistribute it and/or
11 #    modify it under the terms of the GNU Affero General Public
12 #    License as published by the Free Software Foundation, either
13 #    version 3 of the License, or (at your option) any later version,
14 #    with the "CAF Login Exception" as published by Ian Jackson
15 #    (version 2, or at your option any later version) as an Additional
16 #    Permission.
17 #
18 #    This program is distributed in the hope that it will be useful,
19 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
20 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21 #    Affero General Public License for more details.
22 #
23 #    You should have received a copy of the GNU Affero General Public
24 #    License and the CAF Login Exception along with this program, in
25 #    the file AGPLv3+CAFv2.  If not, email Ian Jackson
26 #    <ijackson@chiark.greenend.org.uk>.
27
28
29 from hippotatlib import *
30
31 import os
32 import tempfile
33 import atexit
34 import shutil
35
36 import twisted.internet
37 from twisted.web.server import NOT_DONE_YET
38
39 import twisted.web.static
40
41 import hippotatlib.ownsource
42 from hippotatlib.ownsource import SourceShipmentPreparer
43
44 #import twisted.web.server import Site
45 #from twisted.web.resource import Resource
46
47 import syslog
48
49 cleanups = [ ]
50
51 clients = { }
52
53 #---------- "router" ----------
54
55 def route(packet, iface, saddr, daddr):
56   def lt(dest):
57     log_debug(DBG.ROUTE, 'route: %s -> %s: %s' % (saddr,daddr,dest), d=packet)
58   try: dclient = clients[daddr]
59   except KeyError: dclient = None
60   if dclient is not None:
61     lt('client')
62     dclient.queue_outbound(packet)
63   elif daddr == c.vaddr or daddr not in c.vnetwork:
64     lt('inbound')
65     queue_inbound(ipif, packet)
66   elif daddr == c.relay:
67     lt('discard relay')
68     log_discard(packet, iface, saddr, daddr, 'relay')
69   else:
70     lt('discard no-client')
71     log_discard(packet, iface, saddr, daddr, 'no-client')
72
73 #---------- client ----------
74
75 class Client():
76   def __init__(self, ip, cc):
77     # instance data members
78     self._ip = ip
79     self.cc = cc
80     self._rq = collections.deque() # requests
81     self._pq = PacketQueue(str(ip), self.cc.max_queue_time)
82
83     if ip not in c.vnetwork:
84       raise ValueError('client %s not in vnetwork' % ip)
85
86     if ip in clients:
87       raise ValueError('multiple client cfg sections for %s' % ip)
88     clients[ip] = self
89
90     self._log(DBG.INIT, 'new')
91
92   def _log(self, dflag, msg, **kwargs):
93     log_debug(dflag, ('client %s: ' % self._ip)+msg, **kwargs)
94
95   def process_arriving_data(self, d):
96     self._log(DBG.FLOW, "req data (enc'd)", d=d)
97     if not len(d): return
98     for packet in slip.decode(d):
99       (saddr, daddr) = packet_addrs(packet)
100       if saddr != self._ip:
101         raise ValueError('wrong source address %s' % saddr)
102       route(packet, self._ip, saddr, daddr)
103
104   def _req_cancel(self, request):
105     self._log(DBG.HTTP_CTRL, 'cancel', idof=request)
106     request.finish()
107
108   def _req_error(self, err, request):
109     self._log(DBG.HTTP_CTRL, 'error %s' % err, idof=request)
110     self._req_cancel(request)
111
112   def queue_outbound(self, packet):
113     self._pq.append(packet)
114     self._check_outbound()
115
116   def _req_fin(self, dummy, request, cl):
117     self._log(DBG.HTTP_CTRL, '_req_fin ' + repr(dummy), idof=request)
118     try: cl.cancel()
119     except twisted.internet.error.AlreadyCalled: pass
120
121   def new_request(self, request):
122     request.setHeader('Content-Type','application/octet-stream')
123     cl = reactor.callLater(self.cc.http_timeout, self._req_cancel, request)
124     nf = request.notifyFinish()
125     nf.addErrback(self._req_error, request)
126     nf.addCallback(self._req_fin, request, cl)
127     self._rq.append(request)
128     self._check_outbound()
129
130   def _req_write(self, req, d):
131     self._log(DBG.HTTP, 'req_write ', idof=req, d=d)
132     req.write(d)
133
134   def _check_outbound(self):
135     log_debug(DBG.HTTP_CTRL, 'CHKO')
136     while True:
137       try: request = self._rq[0]
138       except IndexError: request = None
139       if request and request.finished:
140         self._log(DBG.HTTP_CTRL, 'CHKO req finished, discard', idof=request)
141         self._rq.popleft()
142         continue
143
144       if not self._pq.nonempty():
145         # no packets, oh well
146         self._log(DBG.HTTP_CTRL, 'CHKO no packets, OUT-DONE', idof=request)
147         break
148
149       if request is None:
150         # no request
151         self._log(DBG.HTTP_CTRL, 'CHKO no request, OUT-DONE', idof=request)
152         break
153
154       self._log(DBG.HTTP_CTRL, 'CHKO processing', idof=request)
155       # request, and also some non-expired packets
156       self._pq.process((lambda: request.sentLength),
157                        (lambda d: self._req_write(request, d)),
158                        self.cc.max_batch_down)
159
160       assert(request.sentLength)
161       self._rq.popleft()
162       request.finish()
163       self._log(DBG.HTTP, 'complete', idof=request)
164       # round again, looking for more to do
165
166     while len(self._rq) > self.cc.target_requests_outstanding:
167       request = self._rq.popleft()
168       self._log(DBG.HTTP, 'CHKO above target, returning empty', idof=request)
169       request.finish()
170
171 def process_request(request, desca):
172   # find client, update config, etc.
173   metadata = request.args[b'm'][0]
174   metadata = metadata.split(b'\r\n')
175   (ci_s, pw, tro, cto) = metadata[0:4]
176   desca['m[0,2:3]'] = [ci_s, tro, cto]
177   ci_s = ci_s.decode('utf-8')
178   tro = int(tro); desca['tro']= tro
179   cto = int(cto); desca['cto']= cto
180   ci = ipaddr(ci_s)
181   desca['ci'] = ci
182   cl = clients[ci]
183   if pw != cl.cc.password: raise ValueError('bad password')
184   desca['pwok']=True
185
186   if tro != cl.cc.target_requests_outstanding:
187     raise ValueError('tro must be %d' % cl.cc.target_requests_outstanding)
188
189   if cto < cl.cc.http_timeout:
190     raise ValueError('cto must be >= %d' % cl.cc.http_timeout)
191
192   try:
193     d = request.args[b'd'][0]
194     desca['d'] = d
195     desca['dlen'] = len(d)
196   except KeyError:
197     d = b''
198     desca['dlen'] = None
199
200   log_http(desca, 'processing', idof=id(request), d=d)
201
202   d = mime_translate(d)
203
204   cl.process_arriving_data(d)
205   cl.new_request(request)
206
207 def log_http(desca, msg, **kwargs):
208   try:
209     kwargs['d'] = desca['d']
210     del desca['d']
211   except KeyError:
212     pass
213   log_debug(DBG.HTTP, msg + repr(desca), **kwargs)
214
215 class NotStupidResource(twisted.web.resource.Resource):
216   # why this is not the default is a mystery!
217   def getChild(self, name, request):
218     if name == b'': return self
219     else: return twisted.web.resource.Resource.getChild(name, request)
220
221 class IphttpResource(NotStupidResource):
222   def render_POST(self, request):
223     log_debug(DBG.HTTP_FULL,
224               'req recv: ' + repr(request) + ' ' + repr(request.args),
225               idof=id(request))
226     desca = {'d': None}
227     try: process_request(request, desca)
228     except Exception as e:
229       emsg = traceback.format_exc()
230       log_http(desca, 'RETURNING EXCEPTION ' + emsg)
231       request.setHeader('Content-Type','text/plain; charset="utf-8"')
232       request.setResponseCode(400)
233       return (emsg + ' # ' + repr(desca) + '\r\n').encode('utf-8')
234     log_debug(DBG.HTTP_CTRL, '...', idof=id(request))
235     return NOT_DONE_YET
236
237   def render_GET(self, request):
238     log_debug(DBG.HTTP, 'GET request')
239     return b'''
240 <html><body>
241 hippotat
242 <p>
243 <a href="source">source</a>
244 (and that of dependency <a href="srcpkgs">packages</a>)
245 available
246 </body></html>
247 '''
248
249 def start_http():
250   resource = IphttpResource()
251   site = twisted.web.server.Site(resource)
252
253   for sa in c.saddrs:
254     ep = sa.make_endpoint()
255     crash_on_defer(ep.listen(site))
256     log_debug(DBG.INIT, 'listening on %s' % sa)
257
258   td = tempfile.mkdtemp()
259
260   def cleanup():
261     try: shutil.rmtree(td)
262     except FileNotFoundError: pass
263     
264   cleanups.append(cleanup)
265
266   ssp = SourceShipmentPreparer(td)
267   ssp.logger = partial(log_debug, DBG.OWNSOURCE)
268   if DBG.OWNSOURCE in debug_set: ssp.stream_debug = sys.stdout
269   ssp.generate()
270
271   resource.putChild(b'source',  twisted.web.static.File(ssp.output_paths[0]))
272   resource.putChild(b'srcpkgs', twisted.web.static.File(ssp.output_paths[1]))
273
274   reactor.callLater(0.1, (lambda: log.info('hippotatd started', dflag=False)))
275
276 #---------- config and setup ----------
277
278 def process_cfg(putative_servers, putative_clients):
279   global c
280   c = ConfigResults()
281   c.server = cfg.get('SERVER','server')
282
283   cfg_process_common(c, c.server)
284   cfg_process_saddrs(c, c.server)
285   cfg_process_vnetwork(c, c.server)
286   cfg_process_vaddr(c, c.server)
287
288   for (ci,cs) in putative_clients.items():
289     cc = ConfigResults()
290     sections = cfg_process_client_common(cc,c.server,cs,ci)
291     if not sections: continue
292     cfg_process_client_limited(cc,c.server,sections, 'max_batch_down')
293     cfg_process_client_limited(cc,c.server,sections, 'max_queue_time')
294     Client(ci, cc)
295
296   try:
297     c.vrelay = cfg.get(c.server, 'vrelay')
298   except NoOptionError:
299     for search in c.vnetwork.hosts():
300       if search == c.vaddr: continue
301       c.vrelay = search
302       break
303
304   cfg_process_ipif(c,
305                    [c.server, 'DEFAULT'],
306                    (('local','vaddr'),
307                     ('peer', 'vrelay'),
308                     ('rnets','vnetwork')))
309
310 def catch_termination():
311   def run_cleanups():
312     for cleanup in cleanups:
313       cleanup()
314
315   atexit.register(run_cleanups)
316
317   def signal_handler(name, sig, *args):
318     signal.signal(sig, signal.SIG_DFL)
319     print('exiting due to %s' % name, file=sys.stderr)
320     run_cleanups()
321     os.kill(os.getpid(), sig)
322     raise RuntimeError('did not die due to signal %s !' % name)
323
324   for sig in (signal.SIGINT, signal.SIGTERM):
325     signal.signal(sig, partial(signal_handler, sig.name))
326
327 common_startup(process_cfg)
328 catch_termination()
329 ipif = start_ipif(c.ipif_command, (lambda p,s,d: route(p,"[ipif]",s,d)))
330 start_http()
331 common_run()