4 ### Build a CDB file from configuration file
6 ### (c) 2007 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 it under
14 ### the terms of the GNU General Public License as published by the Free
15 ### Software Foundation; either version 3 of the License, or (at your
16 ### option) any later version.
18 ### TrIPE is distributed in the hope that it will be useful, but WITHOUT
19 ### ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
20 ### FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
23 ### You should have received a copy of the GNU General Public License
24 ### along with TrIPE. If not, see <https://www.gnu.org/licenses/>.
28 ###--------------------------------------------------------------------------
29 ### External dependencies.
32 from optparse import OptionParser
34 from sys import stdin, stdout, exit, argv
37 from cStringIO import StringIO
39 ###--------------------------------------------------------------------------
42 class CDBFake (object):
43 """Like cdbmake, but just outputs data suitable for cdb-map."""
44 def __init__(me, file = stdout):
46 def add(me, key, value):
47 me.file.write('%s:%s\n' % (key, value))
51 ###--------------------------------------------------------------------------
52 ### A bulk DNS resolver.
54 class BulkResolver (object):
56 Resolve a number of DNS names in parallel.
58 The BulkResovler resolves a number of hostnames in parallel. Using it
59 works in three phases:
61 1. You call prepare(HOSTNAME) a number of times, to feed in the hostnames
64 2. You call run() to actually drive the resolver.
66 3. You call lookup(HOSTNAME) to get the address you wanted. This will
67 fail with KeyError if the resolver couldn't resolve the HOSTNAME.
71 """Initialize the resolver."""
75 def prepare(me, host):
76 """Prime the resolver to resolve the name HOST."""
77 if host not in me._resolvers:
78 me._resolvers[host] = M.SelResolveByName \
80 lambda name, alias, addr:
81 me._resolved(host, addr[0]),
82 lambda: me._resolved(host, None))
85 """Run the background DNS resolver until it's finished."""
91 Fetch the address corresponding to HOST.
93 addr = me._namemap[host]
98 def _resolved(me, host, addr):
99 """Callback function: remember that ADDR is the address for HOST."""
100 me._namemap[host] = addr
101 del me._resolvers[host]
103 ###--------------------------------------------------------------------------
104 ### The configuration parser.
106 ## Match a comment or empty line.
107 RX_COMMENT = RX.compile(r'(?x) ^ \s* (?: $ | [;#])')
109 ## Match a section group header.
110 RX_GRPHDR = RX.compile(r'(?x) ^ \s* \[ (.*) \] \s* $')
112 ## Match an assignment line.
113 RX_ASSGN = RX.compile(r'''(?x) ^
114 ([^\s:=] (?: [^:=]* [^\s:=])?)
119 ## Match a continuation line.
120 RX_CONT = RX.compile(r'''(?x) ^ \s+
124 ## Match a $(VAR) configuration variable reference; group 1 is the VAR.
125 RX_REF = RX.compile(r'(?x) \$ \( ([^)]+) \)')
127 ## Match a $[HOST] name resolution reference; group 1 is the HOST.
128 RX_RESOLVE = RX.compile(r'(?x) \$ \[ ([^]]+) \]')
130 class ConfigSyntaxError (Exception):
131 def __init__(me, fname, lno, msg):
136 return '%s:%d: %s' % (me.fname, me.lno, me.msg)
139 return ' -> '.join(["`%s'" % hop for hop in path])
141 class AmbiguousOptionError (Exception):
142 def __init__(me, key, patha, vala, pathb, valb):
144 me.patha, me.vala = patha, vala
145 me.pathb, me.valb = pathb, valb
147 return "Ambiguous answer resolving key `%s': " \
148 "path %s yields `%s' but %s yields `%s'" % \
149 (me.key, _fmt_path(me.patha), me.vala, _fmt_path(me.pathb), me.valb)
151 class InheritanceCycleError (Exception):
152 def __init__(me, key, path):
156 return "Found a cycle %s looking up key `%s'" % \
157 (_fmt_path(me.path), me.key)
159 class MissingSectionException (Exception):
160 def __init__(me, sec):
163 return "Section `%s' not found" % (me.sec)
165 class MissingKeyException (Exception):
166 def __init__(me, sec, key):
170 return "Key `%s' not found in section `%s'" % (me.key, me.sec)
172 class ConfigSection (object):
174 A section in a configuration parser.
176 This is where a lot of the nitty-gritty stuff actually happens. The
177 `MyConfigParser' knows a lot about the internals of this class, which saves
178 on building a complicated interface.
181 def __init__(me, name, cp):
182 """Initialize a new, empty section with a given NAME and parent CP."""
187 def _expand(me, string, resolvep):
189 Expands $(...) and (optionally) $[...] placeholders in STRING.
191 RESOLVEP is a boolean switch: do we bother to tax the resolver or not?
192 This is turned off by MyConfigParser's resolve() method while it's
193 collecting hostnames to be resolved.
195 string = RX_REF.sub \
196 (lambda m: me.get(m.group(1), resolvep), string)
198 string = RX_RESOLVE.sub(lambda m: me._cp._resolver.lookup(m.group(1)),
202 def has_option(me, key):
204 Decide whether this section has a configuration key KEY.
206 This version of the method properly handles the @inherit key.
208 return key == 'name' or me._get(key)[0] is not None
210 def _get(me, key, map = None, path = None):
212 Low-level option-fetching method.
214 Fetch the value for the named KEY in this section, or maybe (recursively)
215 a section which it inherits from.
217 Returns a pair VALUE, PATH. The value is not expanded; nor do we check
218 for the special `name' key. The caller is expected to do these things.
219 Returns None if no value could be found.
222 ## If we weren't given a memoization map or path, then we'd better make
224 if map is None: map = {}
225 if path is None: path = []
227 ## Extend the path to cover us, but remember to remove us again when
228 ## we've finished. If we need to pass the current path back upwards,
229 ## then remember to take a copy.
233 ## If we've been this way before on another pass through then return
234 ## the value we found then. If we're still thinking about it then
235 ## we've found a cycle.
236 try: threadp, value = map[me.name]
237 except KeyError: pass
239 if threadp: raise InheritanceCycleError(key, path[:])
241 ## See whether the answer is ready waiting for us.
242 try: v = me._itemmap[key]
243 except KeyError: pass
244 else: return v, path[:]
246 ## No, apparently, not. Find out our list of parents.
248 parents = [me._cp.section(p) for p in
249 me._itemmap['@inherit'].replace(',', ' ').split()]
253 ## Initially we have no idea.
257 ## Go through our parents and ask them what they think.
258 map[me.name] = True, None
261 ## See whether we get an answer. If not, keep on going.
262 v, pp = p._get(key, map, path)
263 if v is None: continue
265 ## If we got an answer, check that it matches any previous ones.
270 raise AmbiguousOptionError(key, winner, value, pp, v)
272 ## That's the best we could manage.
273 map[me.name] = False, value
277 ## Remove us from the path again.
280 def get(me, key, resolvep = True):
282 Retrieve the value of KEY from this section.
285 ## Special handling for the `name' key.
287 value = me._itemmap.get('name', me.name)
289 value, _ = me._get(key)
291 raise MissingKeyException(me.name, key)
293 ## Expand the value and return it.
294 return me._expand(value, resolvep)
296 def items(me, resolvep = True):
298 Return a list of (NAME, VALUE) items in this section.
300 This extends the default method by handling the inheritance chain.
303 ## Initialize for a depth-first walk of the inheritance graph.
308 ## Visit nodes, collecting their keys. Don't believe the values:
309 ## resolving inheritance is too hard to do like this.
311 sec = me._cp.section(stack.pop())
312 if sec.name in visited: continue
313 visited[sec.name] = True
315 for key, value in sec._itemmap.iteritems():
316 if key == '@inherit': stack += value.replace(',', ' ').split()
319 ## Now collect the values for the known keys, one by one.
321 for key in d: items.append((key, me.get(key, resolvep)))
326 class MyConfigParser (object):
328 A more advanced configuration parser.
330 This has four major enhancements over the standard ConfigParser which are
333 * It recognizes `@inherits' keys and follows them when expanding a
336 * It recognizes `$(VAR)' references to configuration variables during
337 expansion and processes them correctly.
339 * It recognizes `$[HOST]' name-resolver requests and handles them
342 * Its parsing behaviour is well-defined.
346 1. Call parse(FILENAME) to slurp in the configuration data.
348 2. Call resolve() to collect the hostnames which need to be resolved and
349 actually do the name resolution.
351 3. Call sections() to get a list of the configuration sections, or
352 section(NAME) to find a named section.
354 4. Call get(ITEM) on a section to collect the results, or items() to
360 Initialize a new, empty configuration parser.
363 me._resolver = BulkResolver()
367 Parse configuration from a file F.
370 ## Initial parser state.
376 ## An unpleasant hack. Python makes it hard to capture a value in a
377 ## variable and examine it in a single action, and this is the best that
380 def match(rx): m[0] = rx.match(line); return m[0]
382 ## Commit a key's value when we've determined that there are no further
383 ## continuation lines.
385 if key is not None: sect._itemmap[key] = val.getvalue()
387 ## Work through all of the input lines.
391 if match(RX_COMMENT):
392 ## A comment or a blank line. Nothing doing. (This means that we
393 ## leave out blank lines which look like they might be continuation
398 elif match(RX_GRPHDR):
399 ## A section header. Flush out any previous value and set up the new
404 try: sect = me._sectmap[name]
405 except KeyError: sect = me._sectmap[name] = ConfigSection(name, me)
408 elif match(RX_ASSGN):
409 ## A new assignment. Flush out the old one, and set up to store this
413 raise ConfigSyntaxError(f.name, lno, 'no active section to update')
416 val = StringIO(); val.write(m[0].group(2))
419 ## A continuation line. Accumulate the value.
422 raise ConfigSyntaxError(f.name, lno, 'no config value to continue')
423 val.write('\n'); val.write(m[0].group(1))
428 raise ConfigSyntaxError(f.name, lno, 'incomprehensible line')
430 ## Don't forget to commit any final value material.
433 def section(me, name):
434 """Return a ConfigSection with the given NAME."""
435 try: return me._sectmap[name]
436 except KeyError: raise MissingSectionException(name)
439 """Yield the known sections."""
440 return me._sectmap.itervalues()
444 Works out all of the hostnames which need resolving and resolves them.
446 Until you call this, attempts to fetch configuration items which need to
447 resolve hostnames will fail!
449 for sec in me.sections():
450 for key, value in sec.items(resolvep = False):
451 for match in RX_RESOLVE.finditer(value):
452 me._resolver.prepare(match.group(1))
455 ###--------------------------------------------------------------------------
456 ### Command-line handling.
458 def inputiter(things):
460 Iterate over command-line arguments, returning corresponding open files.
462 If none were given, or one is `-', assume standard input; if one is a
463 directory, scan it for files other than backups; otherwise return the
468 if OS.isatty(stdin.fileno()):
469 M.die('no input given, and stdin is a terminal')
475 elif OS.path.isdir(thing):
476 for item in OS.listdir(thing):
477 if item.endswith('~') or item.endswith('#'):
479 name = OS.path.join(thing, item)
480 if not OS.path.isfile(name):
486 def parse_options(argv = argv):
488 Parse command-line options, returning a pair (OPTS, ARGS).
491 op = OptionParser(usage = '%prog [-c CDB] INPUT...',
492 version = '%%prog (tripe, version %s)' % VERSION)
493 op.add_option('-c', '--cdb', metavar = 'CDB',
494 dest = 'cdbfile', default = None,
495 help = 'Compile output into a CDB file.')
496 opts, args = op.parse_args(argv)
499 ###--------------------------------------------------------------------------
504 Read the configuration files and return the accumulated result.
506 We make sure that all hostnames have been properly resolved.
508 conf = MyConfigParser()
509 for f in inputiter(args):
514 def output(conf, cdb):
516 Output the configuration information CONF to the database CDB.
518 This is where the special `user' and `auto' database entries get set.
521 for sec in sorted(conf.sections(), key = lambda sec: sec.name):
522 if sec.name.startswith('@'):
524 elif sec.name.startswith('$'):
527 label = 'P%s' % sec.name
528 if sec.has_option('auto') and \
529 sec.get('auto') in ('y', 'yes', 't', 'true', '1', 'on'):
530 auto.append(sec.name)
531 if sec.has_option('user'):
532 cdb.add('U%s' % sec.get('user'))
533 url = M.URLEncode(laxp = True, semip = True)
534 for key, value in sorted(sec.items(), key = lambda (k, v): k):
535 if not key.startswith('@'):
536 url.encode(key, ' '.join(M.split(value)[0]))
537 cdb.add(label, url.result)
538 cdb.add('%AUTO', ' '.join(auto))
543 opts, args = parse_options()
545 cdb = CDB.cdbmake(opts.cdbfile, opts.cdbfile + '.new')
548 conf = getconf(args[1:])
551 if __name__ == '__main__':
554 ###----- That's all, folks --------------------------------------------------