Halberd.conflib

Package Halberd :: Module conflib |
[hide private]
[frames] | no frames]

# Source Code for Module Halberd.conflib

      1  # -*- coding: iso-8859-1 -*-
      2
      3  """Configuration file management module.
      4
      5  Halberd uses configuration files to store relevant information needed for
      6  certain protocols (SSL) or modes of operation (proxy, distributed
      7  client/server, etc.).
      8
      9  This module takes care of reading and writing configuration files.
     10
     11  @var default_proxy_port: Default TCP port to listen when acting as a proxy.
     12  @type default_proxy_port: C{int}
     13  """
     14
     15  # Copyright (C) 2004, 2005, 2006, 2010  Juan M. Bello Rivas <jmbr@superadditive.com>
     16  #
     17  # This program is free software; you can redistribute it and/or modify
     18  # it under the terms of the GNU General Public License as published by
     19  # the Free Software Foundation; either version 2 of the License, or
     20  # (at your option) any later version.
     21  #
     22  # This program is distributed in the hope that it will be useful,
     23  # but WITHOUT ANY WARRANTY; without even the implied warranty of
     24  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     25  # GNU General Public License for more details.
     26  #
     27  # You should have received a copy of the GNU General Public License
     28  # along with this program; if not, write to the Free Software
     29  # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
     30
     31
     32  import os
     33  import ConfigParser
     34
     35
     36  default_proxy_port = 8080
     37
     38  default_conf = r"""
     39  # ============================================================================
     40  # halberd configuration file.
     41  # ============================================================================
     42
     43  [proxy]
     44
     45  address:
     46  port: 8080
     47
     48  [ssl]
     49
     50  keyfile:
     51  certfile:
     52  """
     53
     54
     55 -class InvalidConfFile(Exception):
     56      """Invalid configuration file.
     57      """
     58
     59
     60 -class ConfReader:
     61      """Takes care of turning configuration files into meaningful information.
     62      """
     63
     64 -    def __init__(self):
     65          self.__dict = {}
     66          self.__conf = None
     67
     68          self.confparser = ConfigParser.SafeConfigParser()
     69
     70 -    def open(self, fname):
     71          """Opens the configuration file.
     72
     73          @param fname: Pathname to the configuration file.
     74          @type fname: C{str}
     75
     76          @raise InvalidConfFile: In case the passed file is not a valid one.
     77          """
     78          self.__conf = open(os.path.expanduser(fname), 'r')
     79          try:
     80              self.confparser.readfp(self.__conf, fname)
     81          except ConfigParser.MissingSectionHeaderError, msg:
     82              raise InvalidConfFile, msg
     83
     84 -    def close(self):
     85          """Release the configuration file's descriptor.
     86          """
     87          if self.__conf:
     88              self.__conf.close()
     89
     90
     91 -    def _getAddr(self, sectname, default_port):
     92          """Read a network address from the given section.
     93          """
     94          section = self.__dict[sectname]
     95          addr = section.get('address', '')
     96          try:
     97              port = int(section.get('port', default_port))
     98          except ValueError:
     99              port = default_port
    100
    101          return (addr, port)
    102
    103 -    def parse(self):
    104          """Parses the configuration file.
    105          """
    106          assert self.__conf, 'The configuration file is not open'
    107
    108          proxy_serv_addr = ()
    109
    110          # The orthodox way of doing this is via ConfigParser.get*() but those
    111          # methods lack the convenience of dict.get. While another approach
    112          # could be to subclass ConfigParser I think it's overkill for the
    113          # current situation.
    114          for section in self.confparser.sections():
    115              sec = self.__dict.setdefault(section, {})
    116              for name, value in self.confparser.items(section):
    117                  sec.setdefault(name, value)
    118
    119          if self.__dict.has_key('proxy'):
    120              proxy_serv_addr = self._getAddr('proxy', default_proxy_port)
    121
    122          keyfile = self.__dict['ssl'].get('keyfile', None)
    123          certfile = self.__dict['ssl'].get('certfile', None)
    124
    125          if keyfile == '':
    126              keyfile = None
    127          if certfile == '':
    128              certfile = None
    129
    130          return proxy_serv_addr, keyfile, certfile
    131
    132 -    def writeDefault(self, conf_file):
    133          """Write a bare-bones configuration file
    134
    135          @param conf_file: Target file where the default conf. will be written.
    136          @type conf_file: C{str}
    137          """
    138          assert conf_file and isinstance(conf_file, basestring)
    139
    140          conf_fp = open(conf_file, 'w')
    141          conf_fp.write(default_conf)
    142          conf_fp.close()
    143
    144
    145 -    def __del__(self):
    146          self.close()
    147
    148
    149  # vim: ts=4 sw=4 et
    150