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
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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
56 """Invalid configuration file.
57 """
58
59
61 """Takes care of turning configuration files into meaningful information.
62 """
63
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
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
104 """Parses the configuration file.
105 """
106 assert self.__conf, 'The configuration file is not open'
107
108 proxy_serv_addr = ()
109
110
111
112
113
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
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
147
148
149
150