Debian Codegraph @

lib/ansible/plugins/shell/__init__.py

raw
1 # (c) 2016 RedHat
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 dataclasses
20 import os
21 import os.path
22 import re
23 import secrets
24 import shlex
25 import time
26
27 from ansible.errors import AnsibleError
28 from ansible.module_utils.common.text.converters import to_native
29 from ansible.plugins import AnsiblePlugin
30 from ansible.utils.display import Display
31
32 display = Display()
33
34 _USER_HOME_PATH_RE = re.compile(r'^~[_.A-Za-z0-9][-_.A-Za-z0-9]*$')
35
36
37 @dataclasses.dataclass(frozen=True, kw_only=True, slots=True)
38 class _ShellCommand:
39 """Internal type returned by shell subsystems that may require both an execution payload and a command (eg powershell)."""
40 command: str
41 input_data: bytes | None = None
42
43
44 class ShellBase(AnsiblePlugin):
45 def __init__(self):
46
47 super(ShellBase, self).__init__()
48
49 # Not used but here for backwards compatibility.
50 # ansible.posix.fish uses (but does not actually use) this value.
51 # https://github.com/ansible-collections/ansible.posix/blob/f41f08e9e3d3129e709e122540b5ae6bc19932be/plugins/shell/fish.py#L38-L39
52 self.env = {}
53 self.tmpdir = None
54 self.executable = None
55
56 def _normalize_system_tmpdirs(self):
57 # Normalize the tmp directory strings. We don't use expanduser/expandvars because those
58 # can vary between remote user and become user. Therefore the safest practice will be for
59 # this to always be specified as full paths)
60 normalized_paths = [d.rstrip('/') for d in self.get_option('system_tmpdirs')]
61
62 # Make sure all system_tmpdirs are absolute otherwise they'd be relative to the login dir
63 # which is almost certainly going to fail in a cornercase.
64 if not all(os.path.isabs(d) for d in normalized_paths):
65 raise AnsibleError('The configured system_tmpdirs contains a relative path: {0}. All'
66 ' system_tmpdirs must be absolute'.format(to_native(normalized_paths)))
67
68 self.set_option('system_tmpdirs', normalized_paths)
69
70 def set_options(self, task_keys=None, var_options=None, direct=None):
71
72 super(ShellBase, self).set_options(task_keys=task_keys, var_options=var_options, direct=direct)
73
74 # We can remove the try: except in the future when we make ShellBase a proper subset of
75 # *all* shells. Right now powershell and third party shells which do not use the
76 # shell_common documentation fragment (and so do not have system_tmpdirs) will fail
77 try:
78 self._normalize_system_tmpdirs()
79 except KeyError:
80 pass
81
82 @staticmethod
83 def _generate_temp_dir_name():
84 return 'ansible-tmp-%s-%s-%s' % (time.time(), os.getpid(), secrets.randbelow(2**48))
85
86 def env_prefix(self, **kwargs):
87 return ' '.join(['%s=%s' % (k, self.quote(str(v))) for k, v in kwargs.items()])
88
89 def join_path(self, *args):
90 return os.path.join(*args)
91
92 # some shells (eg, powershell) are snooty about filenames/extensions, this lets the shell plugin have a say
93 def get_remote_filename(self, pathname):
94 base_name = os.path.basename(pathname.strip())
95 return base_name.strip()
96
97 def path_has_trailing_slash(self, path):
98 return path.endswith('/')
99
100 def chmod(self, paths, mode):
101 cmd = ['chmod', mode]
102 cmd.extend(paths)
103 return self.join(cmd)
104
105 def chown(self, paths, user):
106 cmd = ['chown', user]
107 cmd.extend(paths)
108 return self.join(cmd)
109
110 def chgrp(self, paths, group):
111 cmd = ['chgrp', group]
112 cmd.extend(paths)
113 return self.join(cmd)
114
115 def set_user_facl(self, paths, user, mode):
116 """Only sets acls for users as that's really all we need"""
117 cmd = ['setfacl', '-m', 'u:%s:%s' % (user, mode)]
118 cmd.extend(paths)
119 return self.join(cmd)
120
121 def remove(self, path, recurse=False):
122 path = self.quote(path)
123 cmd = 'rm -f '
124 if recurse:
125 cmd += '-r '
126 return cmd + "%s %s" % (path, self._SHELL_REDIRECT_ALLNULL)
127
128 def exists(self, path):
129 cmd = ['test', '-e', self.quote(path)]
130 return ' '.join(cmd)
131
132 def mkdtemp(
133 self,
134 basefile: str | None = None,
135 system: bool = False,
136 mode: int = 0o700,
137 tmpdir: str | None = None,
138 ) -> str:
139 if not basefile:
140 basefile = self.__class__._generate_temp_dir_name()
141
142 # When system is specified we have to create this in a directory where
143 # other users can read and access the tmp directory.
144 # This is because we use system to create tmp dirs for unprivileged users who are
145 # sudo'ing to a second unprivileged user.
146 # The 'system_tmpdirs' setting defines directories we can use for this purpose
147 # the default are, /tmp and /var/tmp.
148 # So we only allow one of those locations if system=True, using the
149 # passed in tmpdir if it is valid or the first one from the setting if not.
150
151 if system:
152 if tmpdir:
153 tmpdir = tmpdir.rstrip('/')
154
155 if tmpdir in self.get_option('system_tmpdirs'):
156 basetmpdir = tmpdir
157 else:
158 basetmpdir = self.get_option('system_tmpdirs')[0]
159 else:
160 if tmpdir is None:
161 basetmpdir = self.get_option('remote_tmp')
162 else:
163 basetmpdir = tmpdir
164
165 basetmp = self.join_path(basetmpdir, basefile)
166
167 # use mkdir -p to ensure parents exist, but mkdir fullpath to ensure last one is created by us
168 cmd = 'mkdir -p %s echo %s %s' % (self._SHELL_SUB_LEFT, basetmpdir, self._SHELL_SUB_RIGHT)
169 cmd += '%s mkdir %s echo %s %s' % (self._SHELL_AND, self._SHELL_SUB_LEFT, basetmp, self._SHELL_SUB_RIGHT)
170 cmd += ' %s echo %s=%s echo %s %s' % (self._SHELL_AND, basefile, self._SHELL_SUB_LEFT, basetmp, self._SHELL_SUB_RIGHT)
171
172 # change the umask in a subshell to achieve the desired mode
173 # also for directories created with `mkdir -p`
174 if mode:
175 tmp_umask = 0o777 & ~mode
176 cmd = '%s umask %o %s %s %s' % (self._SHELL_GROUP_LEFT, tmp_umask, self._SHELL_AND, cmd, self._SHELL_GROUP_RIGHT)
177
178 return cmd
179
180 def _mkdtemp2(
181 self,
182 basefile: str | None = None,
183 system: bool = False,
184 mode: int = 0o700,
185 tmpdir: str | None = None,
186 ) -> _ShellCommand:
187 """Gets command info to create a temporary directory.
188
189 This is an internal API that should not be used publicly.
190
191 :args basefile: The base name of the temporary directory.
192 :args system: If True, create the directory in a system-wide location.
193 :args mode: The permissions mode for the directory.
194 :args tmpdir: The directory in which to create the temporary directory.
195 :returns: The shell command to run to create the temp directory.
196 """
197 cmd = self.mkdtemp(basefile=basefile, system=system, mode=mode, tmpdir=tmpdir)
198 return _ShellCommand(command=cmd, input_data=None)
199
200 def expand_user(
201 self,
202 user_home_path: str,
203 username: str = '',
204 ) -> str:
205 """ Return a command to expand tildes in a path
206
207 It can be either "~" or "~username". We just ignore $HOME
208 We use the POSIX definition of a username:
209 http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap03.html#tag_03_426
210 http://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap03.html#tag_03_276
211
212 Falls back to 'current working directory' as we assume 'home is where the remote user ends up'
213 """
214
215 # Check that the user_path to expand is safe
216 if user_home_path != '~':
217 if not _USER_HOME_PATH_RE.match(user_home_path):
218 user_home_path = self.quote(user_home_path)
219 elif username:
220 # if present the user name is appended to resolve "that user's home"
221 user_home_path += username
222
223 return 'echo %s' % user_home_path
224
225 def _expand_user2(
226 self,
227 user_home_path: str,
228 username: str = '',
229 ) -> _ShellCommand:
230 """Gets command to expand user path.
231
232 This is an internal API that should not be used publicly.
233
234 :args user_home_path: The path to expand.
235 :args username: The username to use for expansion.
236 :returns: The shell command to run to get the expanded user path.
237 """
238 cmd = self.expand_user(user_home_path, username=username)
239 return _ShellCommand(command=cmd, input_data=None)
240
241 def pwd(self):
242 """Return the working directory after connecting"""
243 return 'echo %spwd%s' % (self._SHELL_SUB_LEFT, self._SHELL_SUB_RIGHT)
244
245 def build_module_command(self, env_string, shebang, cmd, arg_path=None):
246 env_string = env_string.strip()
247 if env_string:
248 env_string += ' '
249
250 if shebang is None:
251 shebang = ''
252
253 cmd_parts = [
254 shebang.removeprefix('#!').strip(),
255 cmd.strip(),
256 arg_path,
257 ]
258
259 cleaned_up_cmd = self.join(
260 stripped_cmd_part for raw_cmd_part in cmd_parts
261 if raw_cmd_part and (stripped_cmd_part := raw_cmd_part.strip())
262 )
263 return ''.join((env_string, cleaned_up_cmd))
264
265 def append_command(self, cmd, cmd_to_append):
266 """Append an additional command if supported by the shell"""
267
268 if self._SHELL_AND:
269 cmd += ' %s %s' % (self._SHELL_AND, cmd_to_append)
270
271 return cmd
272
273 def wrap_for_exec(self, cmd):
274 """wrap script execution with any necessary decoration (eg '&' for quoted powershell script paths)"""
275 display.deprecated(
276 msg='The Shell.wrap_for_exec method is deprecated.',
277 help_text="Contact plugin author to update their plugin to not use this method.",
278 version='2.24',
279 )
280 return cmd
281
282 def quote(self, cmd: str) -> str:
283 """Returns a shell-escaped string that can be safely used as one token in a shell command line"""
284 return shlex.quote(cmd)
285
286 def join(self, cmd_parts: list[str]) -> str:
287 """Returns a shell-escaped string from a list that can be safely used in a shell command line"""
288 return shlex.join(cmd_parts)