chiark / gitweb /
hippotatd: --ownsource-local etc. options
[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   # instantiator should set
238   # self.hippotat_sources = (source_names[0], source_names[1])
239   def __init__(self):
240     self.hippotat_sources = [None, None]
241     super().__init__()
242
243   def render_GET(self, request):
244     log_debug(DBG.HTTP, 'GET request')
245     s = '<html><body>hippotat\n'
246     (s0,s1) = self.hippotat_sources
247     if s0:
248       s += '<p><a href="%s">source</a>\n' % s0
249       if self.hippotat_sources[1]:
250         s += ('(and that of dependency <a href="%s">packages</a>)\n' % s1)
251       s += 'available'
252     else:
253       s += 'TESTING'
254     s += '</body></html>'
255     return s.encode('utf-8')
256
257 def start_http():
258   resource = IphttpResource()
259   site = twisted.web.server.Site(resource)
260
261   for sa in c.saddrs:
262     ep = sa.make_endpoint()
263     crash_on_defer(ep.listen(site))
264     log_debug(DBG.INIT, 'listening on %s' % sa)
265
266   td = tempfile.mkdtemp()
267
268   def cleanup():
269     try: shutil.rmtree(td)
270     except FileNotFoundError: pass
271     
272   cleanups.append(cleanup)
273
274   ssp = SourceShipmentPreparer(td)
275   ssp.logger = partial(log_debug, DBG.OWNSOURCE)
276   if DBG.OWNSOURCE in debug_set: ssp.stream_debug = sys.stdout
277   ssp.download_packages = opts.ownsource >= 2
278   if opts.ownsource >= 1: ssp.generate()
279
280   for ix in (0,1):
281     bn = ssp.output_names[ix]
282     op = ssp.output_paths[ix]
283     if op is None: continue
284     resource.hippotat_sources[ix] = bn
285     subresource =twisted.web.static.File(op)
286     resource.putChild(bn.encode('utf-8'), subresource)
287
288   reactor.callLater(0.1, (lambda: log.info('hippotatd started', dflag=False)))
289
290 #---------- config and setup ----------
291
292 def process_cfg(_opts, putative_servers, putative_clients):
293   global opts
294   opts = _opts
295
296   global c
297   c = ConfigResults()
298   c.server = cfg.get('SERVER','server')
299
300   cfg_process_common(c, c.server)
301   cfg_process_saddrs(c, c.server)
302   cfg_process_vnetwork(c, c.server)
303   cfg_process_vaddr(c, c.server)
304
305   for (ci,cs) in putative_clients.items():
306     cc = ConfigResults()
307     sections = cfg_process_client_common(cc,c.server,cs,ci)
308     if not sections: continue
309     cfg_process_client_limited(cc,c.server,sections, 'max_batch_down')
310     cfg_process_client_limited(cc,c.server,sections, 'max_queue_time')
311     Client(ci, cc)
312
313   try:
314     c.vrelay = cfg.get(c.server, 'vrelay')
315   except NoOptionError:
316     for search in c.vnetwork.hosts():
317       if search == c.vaddr: continue
318       c.vrelay = search
319       break
320
321   cfg_process_ipif(c,
322                    [c.server, 'DEFAULT'],
323                    (('local','vaddr'),
324                     ('peer', 'vrelay'),
325                     ('rnets','vnetwork')))
326
327 def catch_termination():
328   def run_cleanups():
329     for cleanup in cleanups:
330       cleanup()
331
332   atexit.register(run_cleanups)
333
334   def signal_handler(name, sig, *args):
335     signal.signal(sig, signal.SIG_DFL)
336     print('exiting due to %s' % name, file=sys.stderr)
337     run_cleanups()
338     os.kill(os.getpid(), sig)
339     raise RuntimeError('did not die due to signal %s !' % name)
340
341   for sig in (signal.SIGINT, signal.SIGTERM):
342     signal.signal(sig, partial(signal_handler, sig.name))
343
344 optparser.add_option('--ownsource', default=2,
345                      action='store_const', dest='ownsource', const=2,
346                      help='source download fully enabled (default)')
347
348 optparser.add_option('--ownsource-local',
349                      action='store_const', dest='ownsource', const=1,
350                      help='source download is local source code only')
351
352 optparser.add_option('--no-ownsource',
353                      action='store_const', dest='ownsource', const=0,
354                      help='source download disabled (for testing only)')
355
356 common_startup(process_cfg)
357 catch_termination()
358 ipif = start_ipif(c.ipif_command, (lambda p,s,d: route(p,"[ipif]",s,d)))
359 start_http()
360 common_run()