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