hippotatd: support syslog
[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 39import twisted.web.static
ec2c9312 40import twisted.python.syslog
99e6411f 41
4a780703
IJ
42import hippotatlib.ownsource
43from hippotatlib.ownsource import SourceShipmentPreparer
44
5da7763e
IJ
45#import twisted.web.server import Site
46#from twisted.web.resource import Resource
3fba9787 47
c4b6d990
IJ
48import syslog
49
4a780703
IJ
50cleanups = [ ]
51
b0cfbfce 52clients = { }
3fba9787 53
5da7763e
IJ
54#---------- "router" ----------
55
a8827d59 56def route(packet, iface, saddr, daddr):
d579a048 57 def lt(dest):
8c3b6620 58 log_debug(DBG.ROUTE, 'route: %s -> %s: %s' % (saddr,daddr,dest), d=packet)
84e763c7 59 try: dclient = clients[daddr]
5da7763e
IJ
60 except KeyError: dclient = None
61 if dclient is not None:
d579a048 62 lt('client')
5da7763e 63 dclient.queue_outbound(packet)
8d374606 64 elif daddr == c.vaddr or daddr not in c.vnetwork:
d579a048 65 lt('inbound')
909e0ff3 66 queue_inbound(ipif, packet)
74934d63 67 elif daddr == c.relay:
d579a048 68 lt('discard relay')
a8827d59 69 log_discard(packet, iface, saddr, daddr, 'relay')
5da7763e 70 else:
d579a048 71 lt('discard no-client')
a8827d59 72 log_discard(packet, iface, saddr, daddr, 'no-client')
5da7763e 73
5da7763e 74#---------- client ----------
c4b6d990 75
ec88b1f1 76class Client():
8d374606 77 def __init__(self, ip, cc):
ec88b1f1
IJ
78 # instance data members
79 self._ip = ip
8d374606 80 self.cc = cc
0ac316c8 81 self._rq = collections.deque() # requests
74934d63 82 self._pq = PacketQueue(str(ip), self.cc.max_queue_time)
88487243 83
8d374606 84 if ip not in c.vnetwork:
c7f134ce 85 raise ValueError('client %s not in vnetwork' % ip)
88487243 86
88487243
IJ
87 if ip in clients:
88 raise ValueError('multiple client cfg sections for %s' % ip)
89 clients[ip] = self
90
8c3b6620
IJ
91 self._log(DBG.INIT, 'new')
92
b68c0739
IJ
93 def _log(self, dflag, msg, **kwargs):
94 log_debug(dflag, ('client %s: ' % self._ip)+msg, **kwargs)
d579a048 95
88487243 96 def process_arriving_data(self, d):
e8fcf3b7 97 self._log(DBG.FLOW, "req data (enc'd)", d=d)
8718b02c 98 if not len(d): return
88487243
IJ
99 for packet in slip.decode(d):
100 (saddr, daddr) = packet_addrs(packet)
101 if saddr != self._ip:
102 raise ValueError('wrong source address %s' % saddr)
a8827d59 103 route(packet, self._ip, saddr, daddr)
88487243
IJ
104
105 def _req_cancel(self, request):
8718b02c 106 self._log(DBG.HTTP_CTRL, 'cancel', idof=request)
88487243
IJ
107 request.finish()
108
109 def _req_error(self, err, request):
8718b02c 110 self._log(DBG.HTTP_CTRL, 'error %s' % err, idof=request)
88487243
IJ
111 self._req_cancel(request)
112
113 def queue_outbound(self, packet):
114 self._pq.append(packet)
ca732796 115 self._check_outbound()
88487243 116
7432045d
IJ
117 def _req_fin(self, dummy, request, cl):
118 self._log(DBG.HTTP_CTRL, '_req_fin ' + repr(dummy), idof=request)
119 try: cl.cancel()
120 except twisted.internet.error.AlreadyCalled: pass
121
d579a048 122 def new_request(self, request):
88487243 123 request.setHeader('Content-Type','application/octet-stream')
74934d63 124 cl = reactor.callLater(self.cc.http_timeout, self._req_cancel, request)
7432045d
IJ
125 nf = request.notifyFinish()
126 nf.addErrback(self._req_error, request)
127 nf.addCallback(self._req_fin, request, cl)
88487243
IJ
128 self._rq.append(request)
129 self._check_outbound()
130
3d003cdd
IJ
131 def _req_write(self, req, d):
132 self._log(DBG.HTTP, 'req_write ', idof=req, d=d)
133 req.write(d)
134
88487243 135 def _check_outbound(self):
8718b02c 136 log_debug(DBG.HTTP_CTRL, 'CHKO')
88487243
IJ
137 while True:
138 try: request = self._rq[0]
139 except IndexError: request = None
140 if request and request.finished:
8c3b6620 141 self._log(DBG.HTTP_CTRL, 'CHKO req finished, discard', idof=request)
88487243
IJ
142 self._rq.popleft()
143 continue
144
145 if not self._pq.nonempty():
146 # no packets, oh well
8c3b6620 147 self._log(DBG.HTTP_CTRL, 'CHKO no packets, OUT-DONE', idof=request)
d579a048 148 break
88487243
IJ
149
150 if request is None:
151 # no request
8c3b6620 152 self._log(DBG.HTTP_CTRL, 'CHKO no request, OUT-DONE', idof=request)
88487243
IJ
153 break
154
8c3b6620 155 self._log(DBG.HTTP_CTRL, 'CHKO processing', idof=request)
88487243 156 # request, and also some non-expired packets
7b07f0b5 157 self._pq.process((lambda: request.sentLength),
3d003cdd 158 (lambda d: self._req_write(request, d)),
74934d63 159 self.cc.max_batch_down)
0ac316c8 160
88487243 161 assert(request.sentLength)
84e763c7 162 self._rq.popleft()
88487243 163 request.finish()
8c3b6620 164 self._log(DBG.HTTP, 'complete', idof=request)
88487243 165 # round again, looking for more to do
0ac316c8 166
74934d63 167 while len(self._rq) > self.cc.target_requests_outstanding:
88487243 168 request = self._rq.popleft()
8c3b6620 169 self._log(DBG.HTTP, 'CHKO above target, returning empty', idof=request)
88487243 170 request.finish()
650a3251 171
d579a048 172def process_request(request, desca):
a4e03162 173 # find client, update config, etc.
5dd3275b 174 metadata = request.args[b'm'][0]
00192d6a 175 metadata = metadata.split(b'\r\n')
ba5630fd
IJ
176 (ci_s, pw, tro, cto) = metadata[0:4]
177 desca['m[0,2:3]'] = [ci_s, tro, cto]
a9a369c7 178 ci_s = ci_s.decode('utf-8')
ba5630fd
IJ
179 tro = int(tro); desca['tro']= tro
180 cto = int(cto); desca['cto']= cto
a4e03162 181 ci = ipaddr(ci_s)
d579a048 182 desca['ci'] = ci
a4e03162 183 cl = clients[ci]
74934d63 184 if pw != cl.cc.password: raise ValueError('bad password')
b68c0739 185 desca['pwok']=True
1672ded0 186
74934d63
IJ
187 if tro != cl.cc.target_requests_outstanding:
188 raise ValueError('tro must be %d' % cl.cc.target_requests_outstanding)
5da7763e 189
74934d63
IJ
190 if cto < cl.cc.http_timeout:
191 raise ValueError('cto must be >= %d' % cl.cc.http_timeout)
ba5630fd 192
d579a048 193 try:
e8fcf3b7 194 d = request.args[b'd'][0]
d579a048 195 desca['d'] = d
19f5f9b5
IJ
196 desca['dlen'] = len(d)
197 except KeyError:
198 d = b''
199 desca['dlen'] = None
200
201 log_http(desca, 'processing', idof=id(request), d=d)
5da7763e 202
6f387df3
IJ
203 d = mime_translate(d)
204
a4e03162
IJ
205 cl.process_arriving_data(d)
206 cl.new_request(request)
5da7763e 207
19f5f9b5 208def log_http(desca, msg, **kwargs):
8c3b6620 209 try:
19f5f9b5 210 kwargs['d'] = desca['d']
8c3b6620
IJ
211 del desca['d']
212 except KeyError:
19f5f9b5
IJ
213 pass
214 log_debug(DBG.HTTP, msg + repr(desca), **kwargs)
8c3b6620 215
eb113b2c
IJ
216class NotStupidResource(twisted.web.resource.Resource):
217 # why this is not the default is a mystery!
218 def getChild(self, name, request):
219 if name == b'': return self
220 else: return twisted.web.resource.Resource.getChild(name, request)
221
222class IphttpResource(NotStupidResource):
a4e03162 223 def render_POST(self, request):
297b3ebf
IJ
224 log_debug(DBG.HTTP_FULL,
225 'req recv: ' + repr(request) + ' ' + repr(request.args),
226 idof=id(request))
d579a048
IJ
227 desca = {'d': None}
228 try: process_request(request, desca)
0d10f35f 229 except Exception as e:
68afd97b 230 emsg = traceback.format_exc()
6f387df3 231 log_http(desca, 'RETURNING EXCEPTION ' + emsg)
0d10f35f
IJ
232 request.setHeader('Content-Type','text/plain; charset="utf-8"')
233 request.setResponseCode(400)
a9a369c7 234 return (emsg + ' # ' + repr(desca) + '\r\n').encode('utf-8')
19f5f9b5 235 log_debug(DBG.HTTP_CTRL, '...', idof=id(request))
d579a048 236 return NOT_DONE_YET
84f2d011 237
b80a8f5c
IJ
238 # instantiator should set
239 # self.hippotat_sources = (source_names[0], source_names[1])
240 def __init__(self):
241 self.hippotat_sources = [None, None]
242 super().__init__()
243
8e279651 244 def render_GET(self, request):
d579a048 245 log_debug(DBG.HTTP, 'GET request')
3c506501
IJ
246 s = '<html><body>hippotat\n'
247 (s0,s1) = self.hippotat_sources
248 if s0:
249 s += '<p><a href="%s">source</a>\n' % s0
250 if self.hippotat_sources[1]:
251 s += ('(and that of dependency <a href="%s">packages</a>)\n' % s1)
252 s += 'available'
253 else:
254 s += 'TESTING'
255 s += '</body></html>'
256 return s.encode('utf-8')
99e6411f 257
5da7763e
IJ
258def start_http():
259 resource = IphttpResource()
b11c6e7a 260 site = twisted.web.server.Site(resource)
a7d05900 261
88487243
IJ
262 for sa in c.saddrs:
263 ep = sa.make_endpoint()
b11c6e7a 264 crash_on_defer(ep.listen(site))
d579a048 265 log_debug(DBG.INIT, 'listening on %s' % sa)
a7d05900
IJ
266
267 td = tempfile.mkdtemp()
268
269 def cleanup():
270 try: shutil.rmtree(td)
271 except FileNotFoundError: pass
272
273 cleanups.append(cleanup)
274
275 ssp = SourceShipmentPreparer(td)
276 ssp.logger = partial(log_debug, DBG.OWNSOURCE)
ff0fc3fa 277 if DBG.OWNSOURCE in debug_set: ssp.stream_debug = sys.stdout
3c506501
IJ
278 ssp.download_packages = opts.ownsource >= 2
279 if opts.ownsource >= 1: ssp.generate()
a7d05900 280
b80a8f5c
IJ
281 for ix in (0,1):
282 bn = ssp.output_names[ix]
283 op = ssp.output_paths[ix]
3c506501 284 if op is None: continue
b80a8f5c
IJ
285 resource.hippotat_sources[ix] = bn
286 subresource =twisted.web.static.File(op)
287 resource.putChild(bn.encode('utf-8'), subresource)
a7d05900 288
1e43fae0 289 reactor.callLater(0.1, (lambda: log.info('hippotatd started', dflag=False)))
5da7763e
IJ
290
291#---------- config and setup ----------
4a780703 292
1cc6968f
IJ
293def process_cfg(_opts, putative_servers, putative_clients):
294 global opts
295 opts = _opts
296
8d374606 297 global c
c7fb640e
IJ
298 c = ConfigResults()
299 c.server = cfg.get('SERVER','server')
300
8d374606
IJ
301 cfg_process_common(c, c.server)
302 cfg_process_saddrs(c, c.server)
303 cfg_process_vnetwork(c, c.server)
304 cfg_process_vaddr(c, c.server)
c7fb640e
IJ
305
306 for (ci,cs) in putative_clients.items():
307 cc = ConfigResults()
74934d63 308 sections = cfg_process_client_common(cc,c.server,cs,ci)
c7fb640e
IJ
309 if not sections: continue
310 cfg_process_client_limited(cc,c.server,sections, 'max_batch_down')
311 cfg_process_client_limited(cc,c.server,sections, 'max_queue_time')
74934d63 312 Client(ci, cc)
e75e9c17
IJ
313
314 try:
74934d63 315 c.vrelay = cfg.get(c.server, 'vrelay')
e2d41dc1 316 except NoOptionError:
8d374606
IJ
317 for search in c.vnetwork.hosts():
318 if search == c.vaddr: continue
74934d63 319 c.vrelay = search
e75e9c17 320 break
3fba9787 321
8d374606 322 cfg_process_ipif(c,
c7fb640e
IJ
323 [c.server, 'DEFAULT'],
324 (('local','vaddr'),
325 ('peer', 'vrelay'),
326 ('rnets','vnetwork')))
5bae5ba3 327
4a780703
IJ
328def catch_termination():
329 def run_cleanups():
330 for cleanup in cleanups:
331 cleanup()
332
333 atexit.register(run_cleanups)
334
335 def signal_handler(name, sig, *args):
336 signal.signal(sig, signal.SIG_DFL)
337 print('exiting due to %s' % name, file=sys.stderr)
338 run_cleanups()
339 os.kill(os.getpid(), sig)
340 raise RuntimeError('did not die due to signal %s !' % name)
341
342 for sig in (signal.SIGINT, signal.SIGTERM):
343 signal.signal(sig, partial(signal_handler, sig.name))
344
ec2c9312
IJ
345def daemonise():
346 global syslogfacility
347 if opts.daemon and opts.syslogfacility is None:
348 opts.syslogfacility = 'daemon'
349
350 if opts.syslogfacility is not None:
351 facilnum = syslog.__dict__['LOG_' + opts.syslogfacility.upper()]
352 syslog.openlog('hippotatd',
353 facility=facilnum,
354 logoption=syslog.LOG_PID)
355 def emit(event):
356 m = twisted.logger.formatEvent(event)
357 #print(repr(event), m, file=org_stderr)
358 level = event.get('log_level')
359 if event.get('dflag',None) is not None: sl = syslog.LOG_DEBUG
360 elif level == LogLevel.critical : sl = syslog.LOG_CRIT
361 elif level == LogLevel.error : sl = syslog.LOG_ERR
362 elif level == LogLevel.warn : sl = syslog.LOG_WARNING
363 else : sl = syslog.LOG_INFO
364 syslog.syslog(sl,m)
365 glp = twisted.logger.globalLogPublisher
366 glp.addObserver(emit)
367 log_debug(DBG.INIT, 'starting to log to syslog')
368
369 glp.removeObserver(hippotatlib.file_log_observer)
370
3c506501
IJ
371optparser.add_option('--ownsource', default=2,
372 action='store_const', dest='ownsource', const=2,
373 help='source download fully enabled (default)')
374
375optparser.add_option('--ownsource-local',
376 action='store_const', dest='ownsource', const=1,
377 help='source download is local source code only')
378
379optparser.add_option('--no-ownsource',
380 action='store_const', dest='ownsource', const=0,
381 help='source download disabled (for testing only)')
382
ec2c9312
IJ
383optparser.add_option('--syslog-facility',
384 nargs=1, type='string',action='store',
385 metavar='FACILITY', dest='syslogfacility',
386 default=None,
387 help='log to syslog, with specified facility')
388
5510890e 389common_startup(process_cfg)
4a780703 390catch_termination()
909e0ff3 391ipif = start_ipif(c.ipif_command, (lambda p,s,d: route(p,"[ipif]",s,d)))
87a7c0c7 392start_http()
ec2c9312 393daemonise()
ae7c7784 394common_run()