hippotatd: --ownsource-local etc. options
[hippotat] / hippotatd
CommitLineData
094ee3a2 1#!/usr/bin/python3
0256fc10
IJ
2#
3# Hippotat - Asinine IP Over HTTP program
4# ./hippotatd - server main program
5#
6# Copyright 2017 Ian Jackson
7#
f85d143f 8# AGPLv3+ + CAFv2+
0256fc10 9#
f85d143f
IJ
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.
0256fc10 17#
f85d143f
IJ
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>.
0256fc10 27
3fba9787 28
5a37bac8 29from hippotatlib import *
aa663282 30
e2d41dc1 31import os
4a780703
IJ
32import tempfile
33import atexit
34import shutil
e2d41dc1 35
e2d41dc1 36import twisted.internet
e2d41dc1 37from twisted.web.server import NOT_DONE_YET
e2d41dc1 38
99e6411f
IJ
39import twisted.web.static
40
4a780703
IJ
41import hippotatlib.ownsource
42from hippotatlib.ownsource import SourceShipmentPreparer
43
5da7763e
IJ
44#import twisted.web.server import Site
45#from twisted.web.resource import Resource
3fba9787 46
c4b6d990
IJ
47import syslog
48
4a780703
IJ
49cleanups = [ ]
50
b0cfbfce 51clients = { }
3fba9787 52
5da7763e
IJ
53#---------- "router" ----------
54
a8827d59 55def route(packet, iface, saddr, daddr):
d579a048 56 def lt(dest):
8c3b6620 57 log_debug(DBG.ROUTE, 'route: %s -> %s: %s' % (saddr,daddr,dest), d=packet)
84e763c7 58 try: dclient = clients[daddr]
5da7763e
IJ
59 except KeyError: dclient = None
60 if dclient is not None:
d579a048 61 lt('client')
5da7763e 62 dclient.queue_outbound(packet)
8d374606 63 elif daddr == c.vaddr or daddr not in c.vnetwork:
d579a048 64 lt('inbound')
909e0ff3 65 queue_inbound(ipif, packet)
74934d63 66 elif daddr == c.relay:
d579a048 67 lt('discard relay')
a8827d59 68 log_discard(packet, iface, saddr, daddr, 'relay')
5da7763e 69 else:
d579a048 70 lt('discard no-client')
a8827d59 71 log_discard(packet, iface, saddr, daddr, 'no-client')
5da7763e 72
5da7763e 73#---------- client ----------
c4b6d990 74
ec88b1f1 75class Client():
8d374606 76 def __init__(self, ip, cc):
ec88b1f1
IJ
77 # instance data members
78 self._ip = ip
8d374606 79 self.cc = cc
0ac316c8 80 self._rq = collections.deque() # requests
74934d63 81 self._pq = PacketQueue(str(ip), self.cc.max_queue_time)
88487243 82
8d374606 83 if ip not in c.vnetwork:
c7f134ce 84 raise ValueError('client %s not in vnetwork' % ip)
88487243 85
88487243
IJ
86 if ip in clients:
87 raise ValueError('multiple client cfg sections for %s' % ip)
88 clients[ip] = self
89
8c3b6620
IJ
90 self._log(DBG.INIT, 'new')
91
b68c0739
IJ
92 def _log(self, dflag, msg, **kwargs):
93 log_debug(dflag, ('client %s: ' % self._ip)+msg, **kwargs)
d579a048 94
88487243 95 def process_arriving_data(self, d):
e8fcf3b7 96 self._log(DBG.FLOW, "req data (enc'd)", d=d)
8718b02c 97 if not len(d): return
88487243
IJ
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)
a8827d59 102 route(packet, self._ip, saddr, daddr)
88487243
IJ
103
104 def _req_cancel(self, request):
8718b02c 105 self._log(DBG.HTTP_CTRL, 'cancel', idof=request)
88487243
IJ
106 request.finish()
107
108 def _req_error(self, err, request):
8718b02c 109 self._log(DBG.HTTP_CTRL, 'error %s' % err, idof=request)
88487243
IJ
110 self._req_cancel(request)
111
112 def queue_outbound(self, packet):
113 self._pq.append(packet)
ca732796 114 self._check_outbound()
88487243 115
7432045d
IJ
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
d579a048 121 def new_request(self, request):
88487243 122 request.setHeader('Content-Type','application/octet-stream')
74934d63 123 cl = reactor.callLater(self.cc.http_timeout, self._req_cancel, request)
7432045d
IJ
124 nf = request.notifyFinish()
125 nf.addErrback(self._req_error, request)
126 nf.addCallback(self._req_fin, request, cl)
88487243
IJ
127 self._rq.append(request)
128 self._check_outbound()
129
3d003cdd
IJ
130 def _req_write(self, req, d):
131 self._log(DBG.HTTP, 'req_write ', idof=req, d=d)
132 req.write(d)
133
88487243 134 def _check_outbound(self):
8718b02c 135 log_debug(DBG.HTTP_CTRL, 'CHKO')
88487243
IJ
136 while True:
137 try: request = self._rq[0]
138 except IndexError: request = None
139 if request and request.finished:
8c3b6620 140 self._log(DBG.HTTP_CTRL, 'CHKO req finished, discard', idof=request)
88487243
IJ
141 self._rq.popleft()
142 continue
143
144 if not self._pq.nonempty():
145 # no packets, oh well
8c3b6620 146 self._log(DBG.HTTP_CTRL, 'CHKO no packets, OUT-DONE', idof=request)
d579a048 147 break
88487243
IJ
148
149 if request is None:
150 # no request
8c3b6620 151 self._log(DBG.HTTP_CTRL, 'CHKO no request, OUT-DONE', idof=request)
88487243
IJ
152 break
153
8c3b6620 154 self._log(DBG.HTTP_CTRL, 'CHKO processing', idof=request)
88487243 155 # request, and also some non-expired packets
7b07f0b5 156 self._pq.process((lambda: request.sentLength),
3d003cdd 157 (lambda d: self._req_write(request, d)),
74934d63 158 self.cc.max_batch_down)
0ac316c8 159
88487243 160 assert(request.sentLength)
84e763c7 161 self._rq.popleft()
88487243 162 request.finish()
8c3b6620 163 self._log(DBG.HTTP, 'complete', idof=request)
88487243 164 # round again, looking for more to do
0ac316c8 165
74934d63 166 while len(self._rq) > self.cc.target_requests_outstanding:
88487243 167 request = self._rq.popleft()
8c3b6620 168 self._log(DBG.HTTP, 'CHKO above target, returning empty', idof=request)
88487243 169 request.finish()
650a3251 170
d579a048 171def process_request(request, desca):
a4e03162 172 # find client, update config, etc.
5dd3275b 173 metadata = request.args[b'm'][0]
00192d6a 174 metadata = metadata.split(b'\r\n')
ba5630fd
IJ
175 (ci_s, pw, tro, cto) = metadata[0:4]
176 desca['m[0,2:3]'] = [ci_s, tro, cto]
a9a369c7 177 ci_s = ci_s.decode('utf-8')
ba5630fd
IJ
178 tro = int(tro); desca['tro']= tro
179 cto = int(cto); desca['cto']= cto
a4e03162 180 ci = ipaddr(ci_s)
d579a048 181 desca['ci'] = ci
a4e03162 182 cl = clients[ci]
74934d63 183 if pw != cl.cc.password: raise ValueError('bad password')
b68c0739 184 desca['pwok']=True
1672ded0 185
74934d63
IJ
186 if tro != cl.cc.target_requests_outstanding:
187 raise ValueError('tro must be %d' % cl.cc.target_requests_outstanding)
5da7763e 188
74934d63
IJ
189 if cto < cl.cc.http_timeout:
190 raise ValueError('cto must be >= %d' % cl.cc.http_timeout)
ba5630fd 191
d579a048 192 try:
e8fcf3b7 193 d = request.args[b'd'][0]
d579a048 194 desca['d'] = d
19f5f9b5
IJ
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)
5da7763e 201
6f387df3
IJ
202 d = mime_translate(d)
203
a4e03162
IJ
204 cl.process_arriving_data(d)
205 cl.new_request(request)
5da7763e 206
19f5f9b5 207def log_http(desca, msg, **kwargs):
8c3b6620 208 try:
19f5f9b5 209 kwargs['d'] = desca['d']
8c3b6620
IJ
210 del desca['d']
211 except KeyError:
19f5f9b5
IJ
212 pass
213 log_debug(DBG.HTTP, msg + repr(desca), **kwargs)
8c3b6620 214
eb113b2c
IJ
215class 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
221class IphttpResource(NotStupidResource):
a4e03162 222 def render_POST(self, request):
297b3ebf
IJ
223 log_debug(DBG.HTTP_FULL,
224 'req recv: ' + repr(request) + ' ' + repr(request.args),
225 idof=id(request))
d579a048
IJ
226 desca = {'d': None}
227 try: process_request(request, desca)
0d10f35f 228 except Exception as e:
68afd97b 229 emsg = traceback.format_exc()
6f387df3 230 log_http(desca, 'RETURNING EXCEPTION ' + emsg)
0d10f35f
IJ
231 request.setHeader('Content-Type','text/plain; charset="utf-8"')
232 request.setResponseCode(400)
a9a369c7 233 return (emsg + ' # ' + repr(desca) + '\r\n').encode('utf-8')
19f5f9b5 234 log_debug(DBG.HTTP_CTRL, '...', idof=id(request))
d579a048 235 return NOT_DONE_YET
84f2d011 236
b80a8f5c
IJ
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
8e279651 243 def render_GET(self, request):
d579a048 244 log_debug(DBG.HTTP, 'GET request')
3c506501
IJ
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')
99e6411f 256
5da7763e
IJ
257def start_http():
258 resource = IphttpResource()
b11c6e7a 259 site = twisted.web.server.Site(resource)
a7d05900 260
88487243
IJ
261 for sa in c.saddrs:
262 ep = sa.make_endpoint()
b11c6e7a 263 crash_on_defer(ep.listen(site))
d579a048 264 log_debug(DBG.INIT, 'listening on %s' % sa)
a7d05900
IJ
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)
ff0fc3fa 276 if DBG.OWNSOURCE in debug_set: ssp.stream_debug = sys.stdout
3c506501
IJ
277 ssp.download_packages = opts.ownsource >= 2
278 if opts.ownsource >= 1: ssp.generate()
a7d05900 279
b80a8f5c
IJ
280 for ix in (0,1):
281 bn = ssp.output_names[ix]
282 op = ssp.output_paths[ix]
3c506501 283 if op is None: continue
b80a8f5c
IJ
284 resource.hippotat_sources[ix] = bn
285 subresource =twisted.web.static.File(op)
286 resource.putChild(bn.encode('utf-8'), subresource)
a7d05900 287
1e43fae0 288 reactor.callLater(0.1, (lambda: log.info('hippotatd started', dflag=False)))
5da7763e
IJ
289
290#---------- config and setup ----------
4a780703 291
1cc6968f
IJ
292def process_cfg(_opts, putative_servers, putative_clients):
293 global opts
294 opts = _opts
295
8d374606 296 global c
c7fb640e
IJ
297 c = ConfigResults()
298 c.server = cfg.get('SERVER','server')
299
8d374606
IJ
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)
c7fb640e
IJ
304
305 for (ci,cs) in putative_clients.items():
306 cc = ConfigResults()
74934d63 307 sections = cfg_process_client_common(cc,c.server,cs,ci)
c7fb640e
IJ
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')
74934d63 311 Client(ci, cc)
e75e9c17
IJ
312
313 try:
74934d63 314 c.vrelay = cfg.get(c.server, 'vrelay')
e2d41dc1 315 except NoOptionError:
8d374606
IJ
316 for search in c.vnetwork.hosts():
317 if search == c.vaddr: continue
74934d63 318 c.vrelay = search
e75e9c17 319 break
3fba9787 320
8d374606 321 cfg_process_ipif(c,
c7fb640e
IJ
322 [c.server, 'DEFAULT'],
323 (('local','vaddr'),
324 ('peer', 'vrelay'),
325 ('rnets','vnetwork')))
5bae5ba3 326
4a780703
IJ
327def 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
3c506501
IJ
344optparser.add_option('--ownsource', default=2,
345 action='store_const', dest='ownsource', const=2,
346 help='source download fully enabled (default)')
347
348optparser.add_option('--ownsource-local',
349 action='store_const', dest='ownsource', const=1,
350 help='source download is local source code only')
351
352optparser.add_option('--no-ownsource',
353 action='store_const', dest='ownsource', const=0,
354 help='source download disabled (for testing only)')
355
5510890e 356common_startup(process_cfg)
4a780703 357catch_termination()
909e0ff3 358ipif = start_ipif(c.ipif_command, (lambda p,s,d: route(p,"[ipif]",s,d)))
87a7c0c7 359start_http()
ae7c7784 360common_run()