1# Copyright: (c) 2017, Ansible Project
2# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4from __future__ import (absolute_import, division, print_function)
5__metaclass__ = type
6
7import atexit
8import io
9import os
10import os.path
11import sys
12import stat
13import tempfile
14import traceback
15from collections import namedtuple
16
17from yaml import load as yaml_load
18try:
19    # use C version if possible for speedup
20    from yaml import CSafeLoader as SafeLoader
21except ImportError:
22    from yaml import SafeLoader
23
24from ansible.config.data import ConfigData
25from ansible.errors import AnsibleOptionsError, AnsibleError
26from ansible.module_utils._text import to_text, to_bytes, to_native
27from ansible.module_utils.common._collections_compat import Sequence
28from ansible.module_utils.six import PY3, string_types
29from ansible.module_utils.six.moves import configparser
30from ansible.module_utils.parsing.convert_bool import boolean
31from ansible.parsing.quoting import unquote
32from ansible.parsing.yaml.objects import AnsibleVaultEncryptedUnicode
33from ansible.utils import py3compat
34from ansible.utils.path import cleanup_tmp_file, makedirs_safe, unfrackpath
35
36
37Plugin = namedtuple('Plugin', 'name type')
38Setting = namedtuple('Setting', 'name value origin type')
39
40INTERNAL_DEFS = {'lookup': ('_terms',)}
41
42
43def _get_entry(plugin_type, plugin_name, config):
44    ''' construct entry for requested config '''
45    entry = ''
46    if plugin_type:
47        entry += 'plugin_type: %s ' % plugin_type
48        if plugin_name:
49            entry += 'plugin: %s ' % plugin_name
50    entry += 'setting: %s ' % config
51    return entry
52
53
54# FIXME: see if we can unify in module_utils with similar function used by argspec
55def ensure_type(value, value_type, origin=None):
56    ''' return a configuration variable with casting
57    :arg value: The value to ensure correct typing of
58    :kwarg value_type: The type of the value.  This can be any of the following strings:
59        :boolean: sets the value to a True or False value
60        :bool: Same as 'boolean'
61        :integer: Sets the value to an integer or raises a ValueType error
62        :int: Same as 'integer'
63        :float: Sets the value to a float or raises a ValueType error
64        :list: Treats the value as a comma separated list.  Split the value
65            and return it as a python list.
66        :none: Sets the value to None
67        :path: Expands any environment variables and tilde's in the value.
68        :tmppath: Create a unique temporary directory inside of the directory
69            specified by value and return its path.
70        :temppath: Same as 'tmppath'
71        :tmp: Same as 'tmppath'
72        :pathlist: Treat the value as a typical PATH string.  (On POSIX, this
73            means colon separated strings.)  Split the value and then expand
74            each part for environment variables and tildes.
75        :pathspec: Treat the value as a PATH string. Expands any environment variables
76            tildes's in the value.
77        :str: Sets the value to string types.
78        :string: Same as 'str'
79    '''
80
81    errmsg = ''
82    basedir = None
83    if origin and os.path.isabs(origin) and os.path.exists(to_bytes(origin)):
84        basedir = origin
85
86    if value_type:
87        value_type = value_type.lower()
88
89    if value is not None:
90        if value_type in ('boolean', 'bool'):
91            value = boolean(value, strict=False)
92
93        elif value_type in ('integer', 'int'):
94            value = int(value)
95
96        elif value_type == 'float':
97            value = float(value)
98
99        elif value_type == 'list':
100            if isinstance(value, string_types):
101                value = [x.strip() for x in value.split(',')]
102            elif not isinstance(value, Sequence):
103                errmsg = 'list'
104
105        elif value_type == 'none':
106            if value == "None":
107                value = None
108
109            if value is not None:
110                errmsg = 'None'
111
112        elif value_type == 'path':
113            if isinstance(value, string_types):
114                value = resolve_path(value, basedir=basedir)
115            else:
116                errmsg = 'path'
117
118        elif value_type in ('tmp', 'temppath', 'tmppath'):
119            if isinstance(value, string_types):
120                value = resolve_path(value, basedir=basedir)
121                if not os.path.exists(value):
122                    makedirs_safe(value, 0o700)
123                prefix = 'ansible-local-%s' % os.getpid()
124                value = tempfile.mkdtemp(prefix=prefix, dir=value)
125                atexit.register(cleanup_tmp_file, value, warn=True)
126            else:
127                errmsg = 'temppath'
128
129        elif value_type == 'pathspec':
130            if isinstance(value, string_types):
131                value = value.split(os.pathsep)
132
133            if isinstance(value, Sequence):
134                value = [resolve_path(x, basedir=basedir) for x in value]
135            else:
136                errmsg = 'pathspec'
137
138        elif value_type == 'pathlist':
139            if isinstance(value, string_types):
140                value = [x.strip() for x in value.split(',')]
141
142            if isinstance(value, Sequence):
143                value = [resolve_path(x, basedir=basedir) for x in value]
144            else:
145                errmsg = 'pathlist'
146
147        elif value_type in ('str', 'string'):
148            if isinstance(value, (string_types, AnsibleVaultEncryptedUnicode)):
149                value = unquote(to_text(value, errors='surrogate_or_strict'))
150            else:
151                errmsg = 'string'
152
153        # defaults to string type
154        elif isinstance(value, (string_types, AnsibleVaultEncryptedUnicode)):
155            value = unquote(to_text(value, errors='surrogate_or_strict'))
156
157        if errmsg:
158            raise ValueError('Invalid type provided for "%s": %s' % (errmsg, to_native(value)))
159
160    return to_text(value, errors='surrogate_or_strict', nonstring='passthru')
161
162
163# FIXME: see if this can live in utils/path
164def resolve_path(path, basedir=None):
165    ''' resolve relative or 'variable' paths '''
166    if '{{CWD}}' in path:  # allow users to force CWD using 'magic' {{CWD}}
167        path = path.replace('{{CWD}}', os.getcwd())
168
169    return unfrackpath(path, follow=False, basedir=basedir)
170
171
172# FIXME: generic file type?
173def get_config_type(cfile):
174
175    ftype = None
176    if cfile is not None:
177        ext = os.path.splitext(cfile)[-1]
178        if ext in ('.ini', '.cfg'):
179            ftype = 'ini'
180        elif ext in ('.yaml', '.yml'):
181            ftype = 'yaml'
182        else:
183            raise AnsibleOptionsError("Unsupported configuration file extension for %s: %s" % (cfile, to_native(ext)))
184
185    return ftype
186
187
188# FIXME: can move to module_utils for use for ini plugins also?
189def get_ini_config_value(p, entry):
190    ''' returns the value of last ini entry found '''
191    value = None
192    if p is not None:
193        try:
194            value = p.get(entry.get('section', 'defaults'), entry.get('key', ''), raw=True)
195        except Exception:  # FIXME: actually report issues here
196            pass
197    return value
198
199
200def find_ini_config_file(warnings=None):
201    ''' Load INI Config File order(first found is used): ENV, CWD, HOME, /usr/local/etc/ansible '''
202    # FIXME: eventually deprecate ini configs
203
204    if warnings is None:
205        # Note: In this case, warnings does nothing
206        warnings = set()
207
208    # A value that can never be a valid path so that we can tell if ANSIBLE_CONFIG was set later
209    # We can't use None because we could set path to None.
210    SENTINEL = object
211
212    potential_paths = []
213
214    # Environment setting
215    path_from_env = os.getenv("ANSIBLE_CONFIG", SENTINEL)
216    if path_from_env is not SENTINEL:
217        path_from_env = unfrackpath(path_from_env, follow=False)
218        if os.path.isdir(to_bytes(path_from_env)):
219            path_from_env = os.path.join(path_from_env, "ansible.cfg")
220        potential_paths.append(path_from_env)
221
222    # Current working directory
223    warn_cmd_public = False
224    try:
225        cwd = os.getcwd()
226        perms = os.stat(cwd)
227        cwd_cfg = os.path.join(cwd, "ansible.cfg")
228        if perms.st_mode & stat.S_IWOTH:
229            # Working directory is world writable so we'll skip it.
230            # Still have to look for a file here, though, so that we know if we have to warn
231            if os.path.exists(cwd_cfg):
232                warn_cmd_public = True
233        else:
234            potential_paths.append(to_text(cwd_cfg, errors='surrogate_or_strict'))
235    except OSError:
236        # If we can't access cwd, we'll simply skip it as a possible config source
237        pass
238
239    # Per user location
240    potential_paths.append(unfrackpath("~/.ansible.cfg", follow=False))
241
242    # System location
243    potential_paths.append("/usr/local/etc/ansible/ansible.cfg")
244
245    for path in potential_paths:
246        b_path = to_bytes(path)
247        if os.path.exists(b_path) and os.access(b_path, os.R_OK):
248            break
249    else:
250        path = None
251
252    # Emit a warning if all the following are true:
253    # * We did not use a config from ANSIBLE_CONFIG
254    # * There's an ansible.cfg in the current working directory that we skipped
255    if path_from_env != path and warn_cmd_public:
256        warnings.add(u"Ansible is being run in a world writable directory (%s),"
257                     u" ignoring it as an ansible.cfg source."
258                     u" For more information see"
259                     u" https://docs.ansible.com/ansible/devel/reference_appendices/config.html#cfg-in-world-writable-dir"
260                     % to_text(cwd))
261
262    return path
263
264
265def _add_base_defs_deprecations(base_defs):
266    '''Add deprecation source 'ansible.builtin' to deprecations in base.yml'''
267    def process(entry):
268        if 'deprecated' in entry:
269            entry['deprecated']['collection_name'] = 'ansible.builtin'
270
271    for dummy, data in base_defs.items():
272        process(data)
273        for section in ('ini', 'env', 'vars'):
274            if section in data:
275                for entry in data[section]:
276                    process(entry)
277
278
279class ConfigManager(object):
280
281    DEPRECATED = []
282    WARNINGS = set()
283
284    def __init__(self, conf_file=None, defs_file=None):
285
286        self._base_defs = {}
287        self._plugins = {}
288        self._parsers = {}
289
290        self._config_file = conf_file
291        self.data = ConfigData()
292
293        self._base_defs = self._read_config_yaml_file(defs_file or ('%s/base.yml' % os.path.dirname(__file__)))
294        _add_base_defs_deprecations(self._base_defs)
295
296        if self._config_file is None:
297            # set config using ini
298            self._config_file = find_ini_config_file(self.WARNINGS)
299
300        # consume configuration
301        if self._config_file:
302            # initialize parser and read config
303            self._parse_config_file()
304
305        # update constants
306        self.update_config_data()
307
308    def _read_config_yaml_file(self, yml_file):
309        # TODO: handle relative paths as relative to the directory containing the current playbook instead of CWD
310        # Currently this is only used with absolute paths to the `ansible/config` directory
311        yml_file = to_bytes(yml_file)
312        if os.path.exists(yml_file):
313            with open(yml_file, 'rb') as config_def:
314                return yaml_load(config_def, Loader=SafeLoader) or {}
315        raise AnsibleError(
316            "Missing base YAML definition file (bad install?): %s" % to_native(yml_file))
317
318    def _parse_config_file(self, cfile=None):
319        ''' return flat configuration settings from file(s) '''
320        # TODO: take list of files with merge/nomerge
321
322        if cfile is None:
323            cfile = self._config_file
324
325        ftype = get_config_type(cfile)
326        if cfile is not None:
327            if ftype == 'ini':
328                kwargs = {}
329                if PY3:
330                    kwargs['inline_comment_prefixes'] = (';',)
331                self._parsers[cfile] = configparser.ConfigParser(**kwargs)
332                with open(to_bytes(cfile), 'rb') as f:
333                    try:
334                        cfg_text = to_text(f.read(), errors='surrogate_or_strict')
335                    except UnicodeError as e:
336                        raise AnsibleOptionsError("Error reading config file(%s) because the config file was not utf8 encoded: %s" % (cfile, to_native(e)))
337                try:
338                    if PY3:
339                        self._parsers[cfile].read_string(cfg_text)
340                    else:
341                        cfg_file = io.StringIO(cfg_text)
342                        self._parsers[cfile].readfp(cfg_file)
343                except configparser.Error as e:
344                    raise AnsibleOptionsError("Error reading config file (%s): %s" % (cfile, to_native(e)))
345            # FIXME: this should eventually handle yaml config files
346            # elif ftype == 'yaml':
347            #     with open(cfile, 'rb') as config_stream:
348            #         self._parsers[cfile] = yaml.safe_load(config_stream)
349            else:
350                raise AnsibleOptionsError("Unsupported configuration file type: %s" % to_native(ftype))
351
352    def _find_yaml_config_files(self):
353        ''' Load YAML Config Files in order, check merge flags, keep origin of settings'''
354        pass
355
356    def get_plugin_options(self, plugin_type, name, keys=None, variables=None, direct=None):
357
358        options = {}
359        defs = self.get_configuration_definitions(plugin_type, name)
360        for option in defs:
361            options[option] = self.get_config_value(option, plugin_type=plugin_type, plugin_name=name, keys=keys, variables=variables, direct=direct)
362
363        return options
364
365    def get_plugin_vars(self, plugin_type, name):
366
367        pvars = []
368        for pdef in self.get_configuration_definitions(plugin_type, name).values():
369            if 'vars' in pdef and pdef['vars']:
370                for var_entry in pdef['vars']:
371                    pvars.append(var_entry['name'])
372        return pvars
373
374    def get_configuration_definition(self, name, plugin_type=None, plugin_name=None):
375
376        ret = {}
377        if plugin_type is None:
378            ret = self._base_defs.get(name, None)
379        elif plugin_name is None:
380            ret = self._plugins.get(plugin_type, {}).get(name, None)
381        else:
382            ret = self._plugins.get(plugin_type, {}).get(plugin_name, {}).get(name, None)
383
384        return ret
385
386    def get_configuration_definitions(self, plugin_type=None, name=None):
387        ''' just list the possible settings, either base or for specific plugins or plugin '''
388
389        ret = {}
390        if plugin_type is None:
391            ret = self._base_defs
392        elif name is None:
393            ret = self._plugins.get(plugin_type, {})
394        else:
395            ret = self._plugins.get(plugin_type, {}).get(name, {})
396
397        return ret
398
399    def _loop_entries(self, container, entry_list):
400        ''' repeat code for value entry assignment '''
401
402        value = None
403        origin = None
404        for entry in entry_list:
405            name = entry.get('name')
406            try:
407                temp_value = container.get(name, None)
408            except UnicodeEncodeError:
409                self.WARNINGS.add(u'value for config entry {0} contains invalid characters, ignoring...'.format(to_text(name)))
410                continue
411            if temp_value is not None:  # only set if entry is defined in container
412                # inline vault variables should be converted to a text string
413                if isinstance(temp_value, AnsibleVaultEncryptedUnicode):
414                    temp_value = to_text(temp_value, errors='surrogate_or_strict')
415
416                value = temp_value
417                origin = name
418
419                # deal with deprecation of setting source, if used
420                if 'deprecated' in entry:
421                    self.DEPRECATED.append((entry['name'], entry['deprecated']))
422
423        return value, origin
424
425    def get_config_value(self, config, cfile=None, plugin_type=None, plugin_name=None, keys=None, variables=None, direct=None):
426        ''' wrapper '''
427
428        try:
429            value, _drop = self.get_config_value_and_origin(config, cfile=cfile, plugin_type=plugin_type, plugin_name=plugin_name,
430                                                            keys=keys, variables=variables, direct=direct)
431        except AnsibleError:
432            raise
433        except Exception as e:
434            raise AnsibleError("Unhandled exception when retrieving %s:\n%s" % (config, to_native(e)), orig_exc=e)
435        return value
436
437    def get_config_value_and_origin(self, config, cfile=None, plugin_type=None, plugin_name=None, keys=None, variables=None, direct=None):
438        ''' Given a config key figure out the actual value and report on the origin of the settings '''
439        if cfile is None:
440            # use default config
441            cfile = self._config_file
442
443        # Note: sources that are lists listed in low to high precedence (last one wins)
444        value = None
445        origin = None
446
447        defs = self.get_configuration_definitions(plugin_type, plugin_name)
448        if config in defs:
449
450            aliases = defs[config].get('aliases', [])
451
452            # direct setting via plugin arguments, can set to None so we bypass rest of processing/defaults
453            direct_aliases = []
454            if direct:
455                direct_aliases = [direct[alias] for alias in aliases if alias in direct]
456            if direct and config in direct:
457                value = direct[config]
458                origin = 'Direct'
459            elif direct and direct_aliases:
460                value = direct_aliases[0]
461                origin = 'Direct'
462
463            else:
464                # Use 'variable overrides' if present, highest precedence, but only present when querying running play
465                if variables and defs[config].get('vars'):
466                    value, origin = self._loop_entries(variables, defs[config]['vars'])
467                    origin = 'var: %s' % origin
468
469                # use playbook keywords if you have em
470                if value is None and keys:
471                    if config in keys:
472                        value = keys[config]
473                        keyword = config
474
475                    elif aliases:
476                        for alias in aliases:
477                            if alias in keys:
478                                value = keys[alias]
479                                keyword = alias
480                                break
481
482                    if value is not None:
483                        origin = 'keyword: %s' % keyword
484
485                # env vars are next precedence
486                if value is None and defs[config].get('env'):
487                    value, origin = self._loop_entries(py3compat.environ, defs[config]['env'])
488                    origin = 'env: %s' % origin
489
490                # try config file entries next, if we have one
491                if self._parsers.get(cfile, None) is None:
492                    self._parse_config_file(cfile)
493
494                if value is None and cfile is not None:
495                    ftype = get_config_type(cfile)
496                    if ftype and defs[config].get(ftype):
497                        if ftype == 'ini':
498                            # load from ini config
499                            try:  # FIXME: generalize _loop_entries to allow for files also, most of this code is dupe
500                                for ini_entry in defs[config]['ini']:
501                                    temp_value = get_ini_config_value(self._parsers[cfile], ini_entry)
502                                    if temp_value is not None:
503                                        value = temp_value
504                                        origin = cfile
505                                        if 'deprecated' in ini_entry:
506                                            self.DEPRECATED.append(('[%s]%s' % (ini_entry['section'], ini_entry['key']), ini_entry['deprecated']))
507                            except Exception as e:
508                                sys.stderr.write("Error while loading ini config %s: %s" % (cfile, to_native(e)))
509                        elif ftype == 'yaml':
510                            # FIXME: implement, also , break down key from defs (. notation???)
511                            origin = cfile
512
513                # set default if we got here w/o a value
514                if value is None:
515                    if defs[config].get('required', False):
516                        if not plugin_type or config not in INTERNAL_DEFS.get(plugin_type, {}):
517                            raise AnsibleError("No setting was provided for required configuration %s" %
518                                               to_native(_get_entry(plugin_type, plugin_name, config)))
519                    else:
520                        value = defs[config].get('default')
521                        origin = 'default'
522                        # skip typing as this is a templated default that will be resolved later in constants, which has needed vars
523                        if plugin_type is None and isinstance(value, string_types) and (value.startswith('{{') and value.endswith('}}')):
524                            return value, origin
525
526            # ensure correct type, can raise exceptions on mismatched types
527            try:
528                value = ensure_type(value, defs[config].get('type'), origin=origin)
529            except ValueError as e:
530                if origin.startswith('env:') and value == '':
531                    # this is empty env var for non string so we can set to default
532                    origin = 'default'
533                    value = ensure_type(defs[config].get('default'), defs[config].get('type'), origin=origin)
534                else:
535                    raise AnsibleOptionsError('Invalid type for configuration option %s: %s' %
536                                              (to_native(_get_entry(plugin_type, plugin_name, config)), to_native(e)))
537
538            # deal with deprecation of the setting
539            if 'deprecated' in defs[config] and origin != 'default':
540                self.DEPRECATED.append((config, defs[config].get('deprecated')))
541        else:
542            raise AnsibleError('Requested entry (%s) was not defined in configuration.' % to_native(_get_entry(plugin_type, plugin_name, config)))
543
544        return value, origin
545
546    def initialize_plugin_configuration_definitions(self, plugin_type, name, defs):
547
548        if plugin_type not in self._plugins:
549            self._plugins[plugin_type] = {}
550
551        self._plugins[plugin_type][name] = defs
552
553    def update_config_data(self, defs=None, configfile=None):
554        ''' really: update constants '''
555
556        if defs is None:
557            defs = self._base_defs
558
559        if configfile is None:
560            configfile = self._config_file
561
562        if not isinstance(defs, dict):
563            raise AnsibleOptionsError("Invalid configuration definition type: %s for %s" % (type(defs), defs))
564
565        # update the constant for config file
566        self.data.update_setting(Setting('CONFIG_FILE', configfile, '', 'string'))
567
568        origin = None
569        # env and config defs can have several entries, ordered in list from lowest to highest precedence
570        for config in defs:
571            if not isinstance(defs[config], dict):
572                raise AnsibleOptionsError("Invalid configuration definition '%s': type is %s" % (to_native(config), type(defs[config])))
573
574            # get value and origin
575            try:
576                value, origin = self.get_config_value_and_origin(config, configfile)
577            except Exception as e:
578                # Printing the problem here because, in the current code:
579                # (1) we can't reach the error handler for AnsibleError before we
580                #     hit a different error due to lack of working config.
581                # (2) We don't have access to display yet because display depends on config
582                #     being properly loaded.
583                #
584                # If we start getting double errors printed from this section of code, then the
585                # above problem #1 has been fixed.  Revamp this to be more like the try: except
586                # in get_config_value() at that time.
587                sys.stderr.write("Unhandled error:\n %s\n\n" % traceback.format_exc())
588                raise AnsibleError("Invalid settings supplied for %s: %s\n" % (config, to_native(e)), orig_exc=e)
589
590            # set the constant
591            self.data.update_setting(Setting(config, value, origin, defs[config].get('type', 'string')))
592