chiark / gitweb /
init script fixes
[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 #@ import sys; sys.path.append('@PYBUILD_INSTALL_DIR@')
29 from hippotatlib import *
30
31 import os
32 import tempfile
33 import atexit
34 import shutil
35 import subprocess
36
37 import twisted.internet
38 from twisted.web.server import NOT_DONE_YET
39
40 import twisted.web.static
41
42 import hippotatlib.ownsource
43 from hippotatlib.ownsource import SourceShipmentPreparer
44
45 #import twisted.web.server import Site
46 #from twisted.web.resource import Resource
47
48 import syslog
49
50 cleanups = [ ]
51
52 clients = { }
53
54 #---------- "router" ----------
55
56 def route(packet, iface, saddr, daddr):
57   def lt(dest):
58     log_debug(DBG.ROUTE, 'route: %s -> %s: %s' % (saddr,daddr,dest), d=packet)
59   try: dclient = clients[daddr]
60   except KeyError: dclient = None
61   if dclient is not None:
62     lt('client')
63     dclient.queue_outbound(packet)
64   elif daddr == c.vaddr or daddr not in c.vnetwork:
65     lt('inbound')
66     queue_inbound(ipif, packet)
67   elif daddr == c.relay:
68     lt('discard relay')
69     log_discard(packet, iface, saddr, daddr, 'relay')
70   else:
71     lt('discard no-client')
72     log_discard(packet, iface, saddr, daddr, 'no-client')
73
74 #---------- client ----------
75
76 class Client():
77   def __init__(self, ip, cc):
78     # instance data members
79     self._ip = ip
80     self.cc = cc
81     self._rq = collections.deque() # requests
82     self._pq = PacketQueue(str(ip), self.cc.max_queue_time)
83
84     if ip not in c.vnetwork:
85       raise ValueError('client %s not in vnetwork' % ip)
86
87     if ip in clients:
88       raise ValueError('multiple client cfg sections for %s' % ip)
89     clients[ip] = self
90
91     self._log(DBG.INIT, 'new')
92
93   def _log(self, dflag, msg, **kwargs):
94     log_debug(dflag, ('client %s: ' % self._ip)+msg, **kwargs)
95
96   def process_arriving_data(self, d):
97     self._log(DBG.FLOW, "req data (enc'd)", d=d)
98     if not len(d): return
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)
103       route(packet, self._ip, saddr, daddr)
104
105   def _req_cancel(self, request):
106     self._log(DBG.HTTP_CTRL, 'cancel', idof=request)
107     request.finish()
108
109   def _req_error(self, err, request):
110     self._log(DBG.HTTP_CTRL, 'error %s' % err, idof=request)
111     self._req_cancel(request)
112
113   def queue_outbound(self, packet):
114     self._pq.append(packet)
115     self._check_outbound()
116
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
122   def new_request(self, request):
123     request.setHeader('Content-Type','application/octet-stream')
124     cl = reactor.callLater(self.cc.http_timeout, self._req_cancel, request)
125     nf = request.notifyFinish()
126     nf.addErrback(self._req_error, request)
127     nf.addCallback(self._req_fin, request, cl)
128     self._rq.append(request)
129     self._check_outbound()
130
131   def _req_write(self, req, d):
132     self._log(DBG.HTTP, 'req_write ', idof=req, d=d)
133     req.write(d)
134
135   def _check_outbound(self):
136     log_debug(DBG.HTTP_CTRL, 'CHKO')
137     while True:
138       try: request = self._rq[0]
139       except IndexError: request = None
140       if request and request.finished:
141         self._log(DBG.HTTP_CTRL, 'CHKO req finished, discard', idof=request)
142         self._rq.popleft()
143         continue
144
145       if not self._pq.nonempty():
146         # no packets, oh well
147         self._log(DBG.HTTP_CTRL, 'CHKO no packets, OUT-DONE', idof=request)
148         break
149
150       if request is None:
151         # no request
152         self._log(DBG.HTTP_CTRL, 'CHKO no request, OUT-DONE', idof=request)
153         break
154
155       self._log(DBG.HTTP_CTRL, 'CHKO processing', idof=request)
156       # request, and also some non-expired packets
157       self._pq.process((lambda: request.sentLength),
158                        (lambda d: self._req_write(request, d)),
159                        self.cc.max_batch_down)
160
161       assert(request.sentLength)
162       self._rq.popleft()
163       request.finish()
164       self._log(DBG.HTTP, 'complete', idof=request)
165       # round again, looking for more to do
166
167     while len(self._rq) > self.cc.target_requests_outstanding:
168       request = self._rq.popleft()
169       self._log(DBG.HTTP, 'CHKO above target, returning empty', idof=request)
170       request.finish()
171
172 def process_request(request, desca):
173   # find client, update config, etc.
174   metadata = request.args[b'm'][0]
175   metadata = metadata.split(b'\r\n')
176   (ci_s, pw, tro, cto) = metadata[0:4]
177   desca['m[0,2:3]'] = [ci_s, tro, cto]
178   ci_s = ci_s.decode('utf-8')
179   tro = int(tro); desca['tro']= tro
180   cto = int(cto); desca['cto']= cto
181   ci = ipaddr(ci_s)
182   desca['ci'] = ci
183   cl = clients[ci]
184   if pw != cl.cc.password: raise ValueError('bad password')
185   desca['pwok']=True
186
187   if tro != cl.cc.target_requests_outstanding:
188     raise ValueError('tro must be %d' % cl.cc.target_requests_outstanding)
189
190   if cto < cl.cc.http_timeout:
191     raise ValueError('cto must be >= %d' % cl.cc.http_timeout)
192
193   try:
194     d = request.args[b'd'][0]
195     desca['d'] = d
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)
202
203   d = mime_translate(d)
204
205   cl.process_arriving_data(d)
206   cl.new_request(request)
207
208 def log_http(desca, msg, **kwargs):
209   try:
210     kwargs['d'] = desca['d']
211     del desca['d']
212   except KeyError:
213     pass
214   log_debug(DBG.HTTP, msg + repr(desca), **kwargs)
215
216 class 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
222 class IphttpResource(NotStupidResource):
223   def render_POST(self, request):
224     log_debug(DBG.HTTP_FULL,
225               'req recv: ' + repr(request) + ' ' + repr(request.args),
226               idof=id(request))
227     desca = {'d': None}
228     try: process_request(request, desca)
229     except Exception as e:
230       emsg = traceback.format_exc()
231       log_http(desca, 'RETURNING EXCEPTION ' + emsg)
232       request.setHeader('Content-Type','text/plain; charset="utf-8"')
233       request.setResponseCode(400)
234       return (emsg + ' # ' + repr(desca) + '\r\n').encode('utf-8')
235     log_debug(DBG.HTTP_CTRL, '...', idof=id(request))
236     return NOT_DONE_YET
237
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
244   def render_GET(self, request):
245     log_debug(DBG.HTTP, 'GET request')
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')
257
258 def start_http():
259   resource = IphttpResource()
260   site = twisted.web.server.Site(resource)
261
262   for sa in c.saddrs:
263     ep = sa.make_endpoint()
264     crash_on_defer(ep.listen(site))
265     log_debug(DBG.INIT, 'listening on %s' % sa)
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)
277   if DBG.OWNSOURCE in debug_set: ssp.stream_debug = sys.stdout
278   ssp.download_packages = opts.ownsource >= 2
279   if opts.ownsource >= 1: ssp.generate()
280
281   for ix in (0,1):
282     bn = ssp.output_names[ix]
283     op = ssp.output_paths[ix]
284     if op is None: continue
285     resource.hippotat_sources[ix] = bn
286     subresource =twisted.web.static.File(op)
287     resource.putChild(bn.encode('utf-8'), subresource)
288
289   reactor.callLater(0.1, (lambda: log.info('hippotatd started', dflag=False)))
290
291 #---------- config and setup ----------
292
293 def process_cfg(_opts, putative_servers, putative_clients):
294   global opts
295   opts = _opts
296
297   global c
298   c = ConfigResults()
299   c.server = cfg.get('SERVER','server')
300
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)
305
306   for (ci,cs) in putative_clients.items():
307     cc = ConfigResults()
308     sections = cfg_process_client_common(cc,c.server,cs,ci)
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')
312     Client(ci, cc)
313
314   try:
315     c.vrelay = cfg.get(c.server, 'vrelay')
316   except NoOptionError:
317     for search in c.vnetwork.hosts():
318       if search == c.vaddr: continue
319       c.vrelay = search
320       break
321
322   cfg_process_ipif(c,
323                    [c.server, 'DEFAULT'],
324                    (('local','vaddr'),
325                     ('peer', 'vrelay'),
326                     ('rnets','vnetwork')))
327
328   if opts.printconfig is not None:
329     try: val = cfg.get(c.server, opts.printconfig)
330     except NoOptionError: pass
331     else: print(val)
332     sys.exit(0)
333
334 def catch_termination():
335   def run_cleanups():
336     for cleanup in cleanups:
337       cleanup()
338
339   atexit.register(run_cleanups)
340
341   def signal_handler(name, sig, *args):
342     signal.signal(sig, signal.SIG_DFL)
343     print('exiting due to %s' % name, file=sys.stderr)
344     run_cleanups()
345     os.kill(os.getpid(), sig)
346     raise RuntimeError('did not die due to signal %s !' % name)
347
348   for sig in (signal.SIGINT, signal.SIGTERM):
349     signal.signal(sig, partial(signal_handler, sig.name))
350
351 def daemonise():
352   global syslogfacility
353   if opts.daemon and opts.syslogfacility is None:
354     opts.syslogfacility = 'daemon'
355
356   if opts.syslogfacility is not None:
357     facilnum = syslog.__dict__['LOG_' + opts.syslogfacility.upper()]
358     syslog.openlog('hippotatd',
359                    facility=facilnum,
360                    logoption=syslog.LOG_PID)
361     def emit(event):
362       m = twisted.logger.formatEvent(event)
363       #print(repr(event), m, file=org_stderr)
364       level = event.get('log_level')
365       if   event.get('dflag',None) is not None: sl = syslog.LOG_DEBUG
366       elif level == LogLevel.critical         : sl = syslog.LOG_CRIT
367       elif level == LogLevel.error            : sl = syslog.LOG_ERR
368       elif level == LogLevel.warn             : sl = syslog.LOG_WARNING
369       else                                    : sl = syslog.LOG_INFO
370       syslog.syslog(sl,m)
371     glp = twisted.logger.globalLogPublisher
372     glp.addObserver(emit)
373     log_debug(DBG.INIT, 'starting to log to syslog')
374
375   #log.crit('daemonic hippotatd crashed', dflag=False)
376   if opts.daemon:
377     daemonic_reactor = (twisted.internet.interfaces.IReactorDaemonize
378                         .providedBy(reactor))
379     if daemonic_reactor: reactor.beforeDaemonize()
380     if opts.pidfile is not None:
381       pidfile_h = open(opts.pidfile, 'w')
382     rfd, wfd = os.pipe()
383     childpid = os.fork()
384     if childpid:
385       # we are the parent
386       os.close(wfd)
387       st = os.read(rfd, 1)
388       try:
389         st = st[0]
390       except IndexError:
391         st = 127
392         log.critical('daemonic hippotatd crashed', dflag=False)
393       os._exit(st)
394     os.close(rfd)
395     os.setsid()
396     grandchildpid = os.fork()
397     if grandchildpid:
398       # we are the intermediate child
399       if opts.pidfile is not None:
400         print(grandchildpid, file=pfh)
401         pfh.close()
402       os._exit(0)
403
404     mypid = os.getpid()
405     pfh.close()
406                                                                         
407     logger = subprocess.Popen(['logger','-d',
408                                '-t','hippotat(stderr)',
409                                '--id=%d' % mypid,
410                                '-p',opts.syslogfacility + '.err'],
411                               stdin=subprocess.PIPE,
412                               stdout=subprocess.DEVNULL,
413                               stderr=subprocess.DEVNULL,
414                               restore_signals=True)
415     
416     nullfd = os.open('/dev/null', os.O_RDWR)
417     os.dup2(nullfd, 0)
418     os.dup2(nullfd, 1)
419     os.dup2(logger.stdin.fileno(), 2)
420     os.close(nullfd)
421     if daemonic_reactor: reactor.afterDaemonize()
422     log_debug(DBG.INIT, 'daemonised')
423     os.write(wfd, b'\0')
424     os.close(wfd)
425
426   if opts.syslogfacility is not None:
427     glp.removeObserver(hippotatlib.file_log_observer)
428
429 optparser.add_option('--ownsource', default=2,
430                      action='store_const', dest='ownsource', const=2,
431                      help='source download fully enabled (default)')
432
433 optparser.add_option('--ownsource-local',
434                      action='store_const', dest='ownsource', const=1,
435                      help='source download is local source code only')
436
437 optparser.add_option('--no-ownsource',
438                      action='store_const', dest='ownsource', const=0,
439                      help='source download disabled (for testing only)')
440
441 optparser.add_option('--daemon',
442                      action='store_true', dest='daemon', default=False,
443                      help='daemonize (and log to syslog)')
444
445 optparser.add_option('--pidfile',
446                      nargs=1, type='string',
447                      action='store', dest='pidfile', default=None,
448                      help='write pid to this file')
449
450 optparser.add_option('--syslog-facility',
451                      nargs=1, type='string',action='store',
452                      metavar='FACILITY', dest='syslogfacility',
453                      default=None,
454                      help='log to syslog, with specified facility')
455
456 optparser.add_option('--print-config',
457                      nargs=1, type='string',action='store',
458                      metavar='OPTION', dest='printconfig',
459                      default=None,
460                      help='print one config option value and exit')
461
462 common_startup(process_cfg)
463 catch_termination()
464 start_http()
465 daemonise()
466 ipif = start_ipif(c.ipif_command, (lambda p,s,d: route(p,"[ipif]",s,d)))
467 common_run()