4 ### Service for automatically tracking network connection status
6 ### (c) 2010 Straylight/Edgeware
9 ###----- Licensing notice ---------------------------------------------------
11 ### This file is part of Trivial IP Encryption (TrIPE).
13 ### TrIPE is free software; you can redistribute it and/or modify
14 ### it under the terms of the GNU General Public License as published by
15 ### the Free Software Foundation; either version 2 of the License, or
16 ### (at your option) any later version.
18 ### TrIPE 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
21 ### GNU General Public License for more details.
23 ### You should have received a copy of the GNU General Public License
24 ### along with TrIPE; if not, write to the Free Software Foundation,
25 ### Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
29 ###--------------------------------------------------------------------------
30 ### External dependencies.
32 from ConfigParser import RawConfigParser
33 from optparse import OptionParser
40 for i in ['mainloop', 'mainloop.glib']:
41 __import__('dbus.%s' % i)
43 from struct import pack, unpack
46 ##__import__('rmcr').__debug = True
48 ###--------------------------------------------------------------------------
51 class struct (object):
52 """A simple container object."""
53 def __init__(me, **kw):
54 me.__dict__.update(kw)
56 def toposort(cmp, things):
58 Generate the THINGS in an order consistent with a given partial order.
60 The function CMP(X, Y) should return true if X must precede Y, and false if
61 it doesn't care. If X and Y are equal then it should return false.
63 The THINGS may be any finite iterable; it is converted to a list
67 ## Make sure we can index the THINGS, and prepare an ordering table.
68 ## What's going on? The THINGS might not have a helpful equality
69 ## predicate, so it's easier to work with indices. The ordering table will
70 ## remember which THINGS (by index) are considered greater than other
74 order = [{} for i in xrange(n)]
75 rorder = [{} for i in xrange(n)]
78 if i != j and cmp(things[i], things[j]):
82 ## Now we can do the sort.
87 if order[i] is not None:
89 if len(order[i]) == 0:
97 ###--------------------------------------------------------------------------
98 ### Parse the configuration file.
100 ## Hmm. Should I try to integrate this with the peers database? It's not a
101 ## good fit; it'd need special hacks in tripe-newpeers. And the use case for
102 ## this service are largely going to be satellite notes, I don't think
103 ## scalability's going to be a problem.
105 class Config (object):
107 Represents a configuration file.
109 The most interesting thing is probably the `groups' slot, which stores a
110 list of pairs (NAME, PATTERNS); the NAME is a string, and the PATTERNS a
111 list of (TAG, PEER, ADDR, MASK) triples. The implication is that there
112 should be precisely one peer with a name matching NAME-*, and that it
113 should be NAME-TAG, where (TAG, PEER, ADDR, MASK) is the first triple such
114 that the host's primary IP address (if PEER is None -- or the IP address it
115 would use for communicating with PEER) is within the network defined by
119 def __init__(me, file):
121 Construct a new Config object, reading the given FILE.
124 me._fwatch = M.FWatch(file)
129 See whether the configuration file has been updated.
131 if me._fwatch.update():
136 Internal function to update the configuration from the underlying file.
139 ## Read the configuration. We have no need of the fancy substitutions,
140 ## so turn them all off.
141 cp = RawConfigParser()
144 ## Save the test address. Make sure it's vaguely sensible. The default
145 ## is probably good for most cases, in fact, since that address isn't
146 ## actually in use. Note that we never send packets to the test address;
147 ## we just use it to discover routing information.
148 if cp.has_option('DEFAULT', 'test-addr'):
149 testaddr = cp.get('DEFAULT', 'test-addr')
150 S.inet_aton(testaddr)
154 ## Scan the configuration file and build the groups structure.
156 for sec in cp.sections():
158 for tag in cp.options(sec):
159 spec = cp.get(sec, tag).split()
161 ## Parse the entry into peer and network.
168 ## Syntax of a net is ADDRESS/MASK, where ADDRESS is a dotted-quad,
169 ## and MASK is either a dotted-quad or a single integer N indicating
170 ## a mask with N leading ones followed by trailing zeroes.
171 slash = net.index('/')
172 addr, = unpack('>L', S.inet_aton(net[:slash]))
173 if net.find('.', slash + 1) >= 0:
174 mask, = unpack('>L', S.inet_aton(net[:slash]))
176 n = int(net[slash + 1:], 10)
177 mask = (1 << 32) - (1 << 32 - n)
178 pats.append((tag, peer, addr & mask, mask))
180 ## Annoyingly, RawConfigParser doesn't preserve the order of options.
181 ## In order to make things vaguely sane, we topologically sort the
182 ## patterns so that more specific patterns are checked first.
183 pats = list(toposort(lambda (t, p, a, m), (tt, pp, aa, mm): \
185 (p == pp and m == (m | mm) and aa == (a & mm)),
187 groups.append((sec, pats))
190 me.testaddr = testaddr
193 ### This will be a configuration file.
196 ###--------------------------------------------------------------------------
197 ### Responding to a network up/down event.
201 Return the local IP address used for talking to PEER.
203 sk = S.socket(S.AF_INET, S.SOCK_DGRAM)
206 sk.connect((peer, 1))
207 addr, _ = sk.getsockname()
208 addr, = unpack('>L', S.inet_aton(addr))
219 upness, reason = _kick.get()
221 ## Make sure the configuration file is up-to-date. Don't worry if we
222 ## can't do anything useful.
225 except Exception, exc:
226 SM.warn('conntrack', 'config-file-error',
227 exc.__class__.__name__, str(exc))
229 ## Find the current list of peers.
232 ## Work out the primary IP address.
234 addr = localaddr(CF.testaddr)
240 ## Now decide what to do.
242 for g, pp in CF.groups:
244 ## Find out which peer in the group ought to be active.
248 for t, p, a, m in pp:
249 if p is None or not upness:
253 if upness and ip is None and \
254 ipq is not None and (ipq & m) == a:
256 if t == 'down' or t.startswith('down/'):
264 ## Shut down the wrong ones.
267 what = map.get(p, 'leave')
274 except T.TripeError, exc:
275 if exc.args[0] == 'unknown-peer':
276 ## Inherently racy; don't worry about this.
282 ## Start the right one if necessary.
283 if want is not None and (not found or ip != lastip.get(g, None)):
286 SM.svcsubmit('connect', 'active', want)
287 except T.TripeError, exc:
288 SM.warn('conntrack', 'connect-failed', want, *exc.args)
292 ## Commit the changes.
294 SM.notify('conntrack', upness and 'up' or 'down', *reason)
295 for c in changes: c()
297 def netupdown(upness, reason):
299 Add or kill peers according to whether the network is up or down.
301 UPNESS is true if the network is up, or false if it's down.
304 _kick.put((upness, reason))
306 ###--------------------------------------------------------------------------
307 ### NetworkManager monitor.
309 NM_NAME = 'org.freedesktop.NetworkManager'
310 NM_PATH = '/org/freedesktop/NetworkManager'
312 NMCA_IFACE = NM_NAME + '.Connection.Active'
314 NM_STATE_CONNECTED = 3
316 class NetworkManagerMonitor (object):
318 Watch NetworkManager signals for changes in network state.
321 ## Strategy. There are two kinds of interesting state transitions for us.
322 ## The first one is the global are-we-connected state, which we'll use to
323 ## toggle network upness on a global level. The second is which connection
324 ## has the default route, which we'll use to tweak which peer in the peer
325 ## group is active. The former is most easily tracked using the signal
326 ## org.freedesktop.NetworkManager.StateChanged; for the latter, we track
327 ## org.freedesktop.NetworkManager.Connection.Active.PropertiesChanged and
328 ## look for when a new connection gains the default route.
332 nm = bus.get_object(NM_NAME, NM_PATH)
333 state = nm.Get(NM_IFACE, 'State')
334 if state == NM_STATE_CONNECTED:
335 netupdown(True, ['nm', 'initially-connected'])
337 netupdown(False, ['nm', 'initially-disconnected'])
338 except D.DBusException:
340 bus.add_signal_receiver(me._nm_state, 'StateChanged', NM_IFACE,
342 bus.add_signal_receiver(me._nm_connchange,
343 'PropertiesChanged', NMCA_IFACE,
346 def _nm_state(me, state):
347 if state == NM_STATE_CONNECTED:
348 netupdown(True, ['nm', 'connected'])
350 netupdown(False, ['nm', 'disconnected'])
352 def _nm_connchange(me, props):
353 if props.get('Default', False):
354 netupdown(True, ['nm', 'default-connection-change'])
356 ###--------------------------------------------------------------------------
359 ICD_NAME = 'com.nokia.icd'
360 ICD_PATH = '/com/nokia/icd'
363 class MaemoICdMonitor (object):
365 Watch ICd signals for changes in network state.
368 ## Strategy. ICd only handles one connection at a time in steady state,
369 ## though when switching between connections, it tries to bring the new one
370 ## up before shutting down the old one. This makes life a bit easier than
371 ## it is with NetworkManager. On the other hand, the notifications are
372 ## relative to particular connections only, and the indicator that the old
373 ## connection is down (`IDLE') comes /after/ the new one comes up
374 ## (`CONNECTED'), so we have to remember which one is active.
378 icd = bus.get_object(ICD_NAME, ICD_PATH)
380 iap = icd.get_ipinfo(dbus_interface = ICD_IFACE)[0]
382 netupdown(True, ['icd', 'initially-connected', iap])
383 except D.DBusException:
385 netupdown(False, ['icd', 'initially-disconnected'])
386 except D.DBusException:
388 bus.add_signal_receiver(me._icd_state, 'status_changed', ICD_IFACE,
391 def _icd_state(me, iap, ty, state, hunoz):
392 if state == 'CONNECTED':
394 netupdown(True, ['icd', 'connected', iap])
395 elif state == 'IDLE' and iap == me._iap:
397 netupdown(False, ['icd', 'idle'])
399 ###--------------------------------------------------------------------------
400 ### D-Bus connection tracking.
402 class DBusMonitor (object):
404 Maintains a connection to the system D-Bus, and watches for signals.
406 If the connection is initially down, or drops for some reason, we retry
407 periodically (every five seconds at the moment). If the connection
408 resurfaces, we reattach the monitors.
413 Initialise the object and try to establish a connection to the bus.
416 me._loop = D.mainloop.glib.DBusGMainLoop()
417 me._state = 'startup'
422 Add a monitor object to watch for signals.
424 MON.attach(BUS) is called, with BUS being the connection to the system
425 bus. MON should query its service's current status and watch for
429 if me._bus is not None:
432 def _reconnect(me, hunoz = None):
434 Start connecting to the bus.
436 If we fail the first time, retry periodically.
438 if me._state == 'startup':
439 T.aside(SM.notify, 'conntrack', 'dbus-connection', 'startup')
440 elif me._state == 'connected':
441 T.aside(SM.notify, 'conntrack', 'dbus-connection', 'lost')
443 T.aside(SM.notify, 'conntrack', 'dbus-connection',
444 'state=%s' % me._state)
445 me._state == 'reconnecting'
447 if me._try_connect():
448 G.timeout_add_seconds(5, me._try_connect)
450 def _try_connect(me):
452 Actually make a connection attempt.
454 If we succeed, attach the monitors.
457 addr = OS.getenv('TRIPE_CONNTRACK_BUS')
458 if addr == 'SESSION':
459 bus = D.SessionBus(mainloop = me._loop, private = True)
460 elif addr is not None:
461 bus = D.bus.BusConnection(addr, mainloop = me._loop)
463 bus = D.SystemBus(mainloop = me._loop, private = True)
466 except D.DBusException, e:
469 me._state = 'connected'
470 bus.call_on_disconnection(me._reconnect)
471 T.aside(SM.notify, 'conntrack', 'dbus-connection', 'connected')
474 ###--------------------------------------------------------------------------
477 class GIOWatcher (object):
479 Monitor I/O events using glib.
481 def __init__(me, conn, mc = G.main_context_default()):
485 def connected(me, sock):
486 me._watch = G.io_add_watch(sock, G.IO_IN,
487 lambda *hunoz: me._conn.receive())
488 def disconnected(me):
489 G.source_remove(me._watch)
492 me._mc.iteration(True)
494 SM.iowatch = GIOWatcher(SM)
498 Service initialization.
500 Add the D-Bus monitor here, because we might send commands off immediately,
501 and we want to make sure the server connection is up.
504 T.Coroutine(kickpeers, name = 'kickpeers').switch()
506 DBM.addmon(NetworkManagerMonitor())
507 DBM.addmon(MaemoICdMonitor())
508 G.timeout_add_seconds(30, lambda: (netupdown(True, ['interval-timer'])
513 Parse the command-line options.
515 Automatically changes directory to the requested configdir, and turns on
516 debugging. Returns the options object.
518 op = OptionParser(usage = '%prog [-a FILE] [-d DIR]',
519 version = '%%prog %s' % VERSION)
521 op.add_option('-a', '--admin-socket',
522 metavar = 'FILE', dest = 'tripesock', default = T.tripesock,
523 help = 'Select socket to connect to [default %default]')
524 op.add_option('-d', '--directory',
525 metavar = 'DIR', dest = 'dir', default = T.configdir,
526 help = 'Select current diretory [default %default]')
527 op.add_option('-c', '--config',
528 metavar = 'FILE', dest = 'conf', default = 'conntrack.conf',
529 help = 'Select configuration [default %default]')
530 op.add_option('--daemon', dest = 'daemon',
531 default = False, action = 'store_true',
532 help = 'Become a daemon after successful initialization')
533 op.add_option('--debug', dest = 'debug',
534 default = False, action = 'store_true',
535 help = 'Emit debugging trace information')
536 op.add_option('--startup', dest = 'startup',
537 default = False, action = 'store_true',
538 help = 'Being called as part of the server startup')
540 opts, args = op.parse_args()
541 if args: op.error('no arguments permitted')
543 T._debug = opts.debug
546 ## Service table, for running manually.
547 def cmd_updown(upness):
548 return lambda *args: T.defer(netupdown, upness, ['manual'] + list(args))
549 service_info = [('conntrack', VERSION, {
550 'up': (0, None, '', cmd_updown(True)),
551 'down': (0, None, '', cmd_updown(False))
554 if __name__ == '__main__':
555 opts = parse_options()
556 CF = Config(opts.conf)
557 T.runservices(opts.tripesock, service_info,
558 init = init, daemon = opts.daemon)
560 ###----- That's all, folks --------------------------------------------------