Debian Codegraph @

ipapython/config.py

raw
1 # Authors: Karl MacMillan <[email protected]>
2 #
3 # Copyright (C) 2007 Red Hat
4 # see file 'COPYING' for use and warranty information
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 #
19 from __future__ import absolute_import
20
21 # pylint: disable=deprecated-module, disable=unused-import
22 from optparse import (Option, Values, OptionGroup, OptionParser, SUPPRESS_HELP,
23 IndentedHelpFormatter, OptionValueError, make_option)
24 # pylint: enable=deprecated-module
25 from copy import copy
26 from configparser import ConfigParser as SafeConfigParser
27 from urllib.parse import urlsplit
28 import functools
29
30 from dns.exception import DNSException
31 import dns.name
32
33 from ipaplatform.paths import paths
34 from ipapython.dn import DN
35 from ipapython.dnsutil import query_srv
36 from ipapython.ipautil import CheckedIPAddress, CheckedIPAddressLoopback
37
38
39 class IPAConfigError(Exception):
40 def __init__(self, msg=''):
41 self.msg = msg
42 Exception.__init__(self, msg)
43
44 def __repr__(self):
45 return self.msg
46
47 __str__ = __repr__
48
49 class IPAFormatter(IndentedHelpFormatter):
50 """Our own optparse formatter that indents multiple lined usage string."""
51 def format_usage(self, usage):
52 usage_string = "Usage:"
53 spacing = " " * len(usage_string)
54 lines = usage.split("\n")
55 ret = "%s %s\n" % (usage_string, lines[0])
56 for line in lines[1:]:
57 ret += "%s %s\n" % (spacing, line)
58 return ret
59
60
61 def check_ip_option(option, opt, value, allow_loopback=False):
62 try:
63 if allow_loopback:
64 return CheckedIPAddressLoopback(value)
65 else:
66 return CheckedIPAddress(value)
67 except Exception as e:
68 raise OptionValueError("option {}: invalid IP address {}: {}"
69 .format(opt, value, e))
70
71 def check_dn_option(option, opt, value):
72 try:
73 return DN(value)
74 except Exception as e:
75 raise OptionValueError("option %s: invalid DN: %s" % (opt, e))
76
77
78 def check_constructor(option, opt, value):
79 con = option.constructor
80 assert con is not None, "Oops! Developer forgot to set 'constructor' kwarg"
81 try:
82 return con(value)
83 except Exception as e:
84 raise OptionValueError("option {} invalid: {}".format(opt, e))
85
86
87 class IPAOption(Option):
88 """
89 optparse.Option subclass with support of options labeled as
90 security-sensitive such as passwords.
91 """
92 ATTRS = Option.ATTRS + ["sensitive", "constructor"]
93 TYPES = Option.TYPES + ("ip", "dn", "constructor", "ip_with_loopback")
94 TYPE_CHECKER = copy(Option.TYPE_CHECKER)
95 TYPE_CHECKER["ip"] = check_ip_option
96 TYPE_CHECKER["ip_with_loopback"] = functools.partial(check_ip_option,
97 allow_loopback=True)
98 TYPE_CHECKER["dn"] = check_dn_option
99 TYPE_CHECKER["constructor"] = check_constructor
100
101
102 class IPAOptionParser(OptionParser):
103 """
104 optparse.OptionParser subclass that uses IPAOption by default
105 for storing options.
106 """
107 def __init__(self,
108 usage=None,
109 option_list=None,
110 option_class=IPAOption,
111 version=None,
112 conflict_handler="error",
113 description=None,
114 formatter=None,
115 add_help_option=True,
116 prog=None,
117 epilog=None):
118 OptionParser.__init__(self, usage=usage, option_list=option_list,
119 option_class=option_class, version=version,
120 conflict_handler=conflict_handler,
121 description=description, formatter=formatter,
122 add_help_option=add_help_option, prog=prog,
123 epilog=epilog)
124
125 def get_safe_opts(self, opts):
126 """
127 Returns all options except those with sensitive=True in the same
128 fashion as parse_args would
129 """
130 all_opts_dict = {
131 o.dest: o for o in self._get_all_options()
132 if hasattr(o, 'sensitive')
133 }
134 safe_opts_dict = {}
135
136 for option, value in opts.__dict__.items():
137 if not all_opts_dict[option].sensitive:
138 safe_opts_dict[option] = value
139
140 return Values(safe_opts_dict)
141
142 def verify_args(parser, args, needed_args = None):
143 """Verify that we have all positional arguments we need, if not, exit."""
144 if needed_args:
145 needed_list = needed_args.split(" ")
146 else:
147 needed_list = []
148 len_need = len(needed_list)
149 len_have = len(args)
150 if len_have > len_need:
151 parser.error("too many arguments")
152 elif len_have < len_need:
153 parser.error("no %s specified" % needed_list[len_have])
154
155
156 class IPAConfig:
157 def __init__(self):
158 self.default_realm = None
159 self.default_server = []
160 self.default_domain = None
161
162 def get_realm(self):
163 if self.default_realm:
164 return self.default_realm
165 else:
166 raise IPAConfigError("no default realm")
167
168 def get_server(self):
169 if len(self.default_server):
170 return self.default_server
171 else:
172 raise IPAConfigError("no default server")
173
174 def get_domain(self):
175 if self.default_domain:
176 return self.default_domain
177 else:
178 raise IPAConfigError("no default domain")
179
180 # Global library config
181 config = IPAConfig()
182
183 def __parse_config(discover_server = True):
184 p = SafeConfigParser()
185 p.read(paths.IPA_DEFAULT_CONF)
186
187 try:
188 if not config.default_realm:
189 config.default_realm = p.get("global", "realm")
190 except Exception:
191 pass
192 if discover_server:
193 try:
194 s = p.get("global", "xmlrpc_uri")
195 server = urlsplit(s)
196 config.default_server.append(server.netloc)
197 except Exception:
198 pass
199 try:
200 if not config.default_domain:
201 config.default_domain = p.get("global", "domain")
202 except Exception:
203 pass
204
205 def __discover_config(discover_server = True):
206 servers = []
207 try:
208 if not config.default_domain:
209 # try once with REALM -> domain
210 domain = str(config.default_realm).lower()
211 name = "_ldap._tcp." + domain
212
213 try:
214 servers = query_srv(name)
215 except DNSException:
216 # try cycling on domain components of FQDN
217 # pylint: disable=ipa-forbidden-import
218 from ipalib.constants import FQDN
219 # pylint: enable=ipa-forbidden-import
220 try:
221 domain = dns.name.from_text(FQDN)
222 except DNSException:
223 return False
224
225 while True:
226 domain = domain.parent()
227
228 if str(domain) == '.':
229 return False
230 name = "_ldap._tcp.%s" % domain
231 try:
232 servers = query_srv(name)
233 break
234 except DNSException:
235 pass
236
237 config.default_domain = str(domain).rstrip(".")
238
239 if discover_server:
240 if not servers:
241 name = "_ldap._tcp.%s." % config.default_domain
242 try:
243 servers = query_srv(name)
244 except DNSException:
245 pass
246
247 for server in servers:
248 hostname = str(server.target).rstrip(".")
249 config.default_server.append(hostname)
250
251 except Exception:
252 pass
253 return None
254
255
256 def add_standard_options(parser):
257 parser.add_option("--realm", dest="realm", help="Override default IPA realm")
258 parser.add_option("--server", dest="server",
259 help="Override default FQDN of IPA server")
260 parser.add_option("--domain", dest="domain", help="Override default IPA DNS domain")
261
262 def init_config(options=None):
263 if options:
264 config.default_realm = options.realm
265 config.default_domain = options.domain
266 if options.server:
267 config.default_server.extend(options.server.split(","))
268
269 if len(config.default_server):
270 discover_server = False
271 else:
272 discover_server = True
273 __parse_config(discover_server)
274 __discover_config(discover_server)
275
276 # make sure the server list only contains unique items
277 new_server = []
278 for server in config.default_server:
279 if server not in new_server:
280 new_server.append(server)
281 config.default_server = new_server
282
283 if not config.default_realm:
284 raise IPAConfigError("IPA realm not found in DNS, in the config file (/etc/ipa/default.conf) or on the command line.")
285 if not config.default_server:
286 raise IPAConfigError("IPA server not found in DNS, in the config file (/etc/ipa/default.conf) or on the command line.")
287 if not config.default_domain:
288 raise IPAConfigError("IPA domain not found in the config file (/etc/ipa/default.conf) or on the command line.")