Debian Codegraph @

lib/ansible/utils/path.py

raw
1 # (c) 2012-2014, Michael DeHaan <[email protected]>
2 #
3 # This file is part of Ansible
4 #
5 # Ansible is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Ansible is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
17 from __future__ import annotations
18
19 import os
20 import shutil
21
22 from ansible.errors import AnsibleError
23 from ansible.module_utils.common.text.converters import to_bytes, to_text
24
25
26 __all__ = ['unfrackpath', 'makedirs_safe']
27
28
29 def unfrackpath(path: str, follow: bool = True, basedir: str | None = None) -> str:
30 """
31 Returns a path that is free of symlinks (if follow=True), environment variables, relative path traversals and symbols (~)
32
33 :arg path: A byte or text string representing a path to be canonicalized
34 :arg follow: A boolean to indicate of symlinks should be resolved or not
35 :arg basedir: A byte string, text string, PathLike object, or `None`
36 representing where a relative path should be resolved from.
37 `None` will be substituted for the current working directory.
38 :raises UnicodeDecodeError: If the canonicalized version of the path
39 contains non-utf8 byte sequences.
40 :rtype: A text string (unicode on pyyhon2, str on python3).
41 :returns: An absolute path with symlinks, environment variables, and tilde
42 expanded. Note that this does not check whether a path exists.
43
44 example::
45 '$HOME/../../var/mail' becomes '/var/spool/mail'
46 """
47
48 if basedir is None:
49 basedir = os.getcwd()
50 elif os.path.isfile(basedir):
51 basedir = os.path.dirname(basedir)
52
53 final_path = os.path.expanduser(os.path.expandvars(path))
54
55 if not os.path.isabs(final_path):
56 final_path = os.path.join(basedir, final_path)
57
58 if follow:
59 final_path = os.path.realpath(final_path)
60
61 return os.path.normpath(final_path)
62
63
64 def makedirs_safe(path, mode=None):
65 """
66 A *potentially insecure* way to ensure the existence of a directory chain. The "safe" in this function's name
67 refers only to its ability to ignore `EEXIST` in the case of multiple callers operating on the same part of
68 the directory chain. This function is not safe to use under world-writable locations when the first level of the
69 path to be created contains a predictable component. Always create a randomly-named element first if there is any
70 chance the parent directory might be world-writable (eg, /tmp) to prevent symlink hijacking and potential
71 disclosure or modification of sensitive file contents.
72
73 :arg path: A byte or text string representing a directory chain to be created
74 :kwarg mode: If given, the mode to set the directory to
75 :raises AnsibleError: If the directory cannot be created and does not already exist.
76 :raises UnicodeDecodeError: if the path is not decodable in the utf-8 encoding.
77 """
78
79 rpath = unfrackpath(path)
80 b_rpath = to_bytes(rpath)
81 if not os.path.exists(b_rpath):
82 try:
83 if mode:
84 os.makedirs(b_rpath, mode, exist_ok=True)
85 else:
86 os.makedirs(b_rpath, exist_ok=True)
87 except OSError as ex:
88 raise AnsibleError(f"Unable to create local directories {rpath!r}.") from ex
89
90
91 def basedir(source):
92 """ returns directory for inventory or playbook """
93 source = to_bytes(source, errors='surrogate_or_strict')
94 dname = None
95 if os.path.isdir(source):
96 dname = source
97 elif source in [None, '', '.']:
98 dname = os.getcwd()
99 elif os.path.isfile(source):
100 dname = os.path.dirname(source)
101
102 if dname:
103 # don't follow symlinks for basedir, enables source reuse
104 dname = os.path.abspath(dname)
105
106 return to_text(dname, errors='surrogate_or_strict')
107
108
109 def cleanup_tmp_file(path, warn=False):
110 """
111 Removes temporary file or directory. Optionally display a warning if unable
112 to remove the file or directory.
113
114 :arg path: Path to file or directory to be removed
115 :kwarg warn: Whether or not to display a warning when the file or directory
116 cannot be removed
117 """
118 try:
119 if os.path.exists(path):
120 try:
121 if os.path.isdir(path):
122 shutil.rmtree(path)
123 elif os.path.isfile(path):
124 os.unlink(path)
125 except Exception as e:
126 if warn:
127 # Importing here to avoid circular import
128 from ansible.utils.display import Display
129 display = Display()
130 display.display(u'Unable to remove temporary file {0}'.format(to_text(e)))
131 except Exception:
132 pass
133
134
135 def is_subpath(child, parent, real=False):
136 """
137 Compares paths to check if one is contained in the other
138 :arg: child: Path to test
139 :arg parent; Path to test against
140 """
141 test = False
142
143 abs_child = unfrackpath(child, follow=False)
144 abs_parent = unfrackpath(parent, follow=False)
145
146 if real:
147 abs_child = os.path.realpath(abs_child)
148 abs_parent = os.path.realpath(abs_parent)
149
150 c = abs_child.split(os.path.sep)
151 p = abs_parent.split(os.path.sep)
152
153 try:
154 test = c[:len(p)] == p
155 except IndexError:
156 # child is shorter than parent so cannot be subpath
157 pass
158
159 return test