| 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 base64 |
| 21 |
from ansible.errors import AnsibleConnectionFailure, AnsibleError, AnsibleActionFail |
| 22 |
from ansible.module_utils.common.text.converters import to_bytes, to_text |
| 23 |
from ansible.module_utils.parsing.convert_bool import boolean |
| 24 |
from ansible.plugins.action import ActionBase |
| 25 |
from ansible.utils.display import Display |
| 26 |
from ansible.utils.hashing import checksum, checksum_s, md5, secure_hash |
| 27 |
from ansible.utils.path import makedirs_safe, is_subpath |
| 28 |
|
| 29 |
display = Display() |
| 30 |
|
| 31 |
|
| 32 |
class ActionModule(ActionBase): |
| 33 |
|
| 34 |
def run(self, tmp=None, task_vars=None): |
| 35 |
""" handler for fetch operations """ |
| 36 |
if task_vars is None: |
| 37 |
task_vars = dict() |
| 38 |
|
| 39 |
result = super(ActionModule, self).run(tmp, task_vars) |
| 40 |
del tmp # tmp no longer has any effect |
| 41 |
|
| 42 |
try: |
| 43 |
if self._task.check_mode: |
| 44 |
return dict( |
| 45 |
msg='check mode not (yet) supported for this module', |
| 46 |
changed=False, |
| 47 |
skipped=True, # deprecated: description='remove this skipped return', core_version='2.25' |
| 48 |
) |
| 49 |
|
| 50 |
source = self._task.args.get('src', None) |
| 51 |
original_dest = dest = self._task.args.get('dest', None) |
| 52 |
flat = boolean(self._task.args.get('flat'), strict=False) |
| 53 |
fail_on_missing = boolean(self._task.args.get('fail_on_missing', True), strict=False) |
| 54 |
validate_checksum = boolean(self._task.args.get('validate_checksum', True), strict=False) |
| 55 |
|
| 56 |
msg = '' |
| 57 |
# FIXME: validate source and dest are strings; use basic.py and module specs |
| 58 |
if not isinstance(source, str): |
| 59 |
msg = "Invalid type supplied for source option, it must be a string" |
| 60 |
|
| 61 |
if not isinstance(dest, str): |
| 62 |
msg = "Invalid type supplied for dest option, it must be a string" |
| 63 |
|
| 64 |
if source is None or dest is None: |
| 65 |
msg = "src and dest are required" |
| 66 |
|
| 67 |
if msg: |
| 68 |
raise AnsibleActionFail(msg) |
| 69 |
|
| 70 |
source = self._connection._shell.join_path(source) |
| 71 |
source = self._remote_expand_user(source) |
| 72 |
|
| 73 |
remote_stat = {} |
| 74 |
remote_checksum = None |
| 75 |
if not self._connection.become: |
| 76 |
# Get checksum for the remote file. Don't bother if using become as slurp will be used. |
| 77 |
# Follow symlinks because fetch always follows symlinks |
| 78 |
try: |
| 79 |
remote_stat = self._execute_remote_stat(source, all_vars=task_vars, follow=True) |
| 80 |
except AnsibleConnectionFailure: |
| 81 |
raise |
| 82 |
except AnsibleError as ae: |
| 83 |
result['changed'] = False |
| 84 |
result['file'] = source |
| 85 |
if fail_on_missing: |
| 86 |
result['failed'] = True |
| 87 |
result['msg'] = to_text(ae) |
| 88 |
else: |
| 89 |
result['msg'] = "%s, ignored" % to_text(ae, errors='surrogate_or_replace') |
| 90 |
|
| 91 |
return result |
| 92 |
|
| 93 |
remote_checksum = remote_stat.get('checksum') |
| 94 |
if remote_stat.get('exists'): |
| 95 |
if remote_stat.get('isdir'): |
| 96 |
result['failed'] = True |
| 97 |
result['changed'] = False |
| 98 |
result['msg'] = "remote file is a directory, fetch cannot work on directories" |
| 99 |
|
| 100 |
# Historically, these don't fail because you may want to transfer |
| 101 |
# a log file that possibly MAY exist but keep going to fetch other |
| 102 |
# log files. Today, this is better achieved by adding |
| 103 |
# ignore_errors or failed_when to the task. Control the behaviour |
| 104 |
# via fail_when_missing |
| 105 |
if not fail_on_missing: |
| 106 |
result['msg'] += ", not transferring, ignored" |
| 107 |
del result['changed'] |
| 108 |
del result['failed'] |
| 109 |
|
| 110 |
return result |
| 111 |
|
| 112 |
# use slurp if permissions are lacking or privilege escalation is needed |
| 113 |
remote_data = None |
| 114 |
if remote_checksum in (None, '1', ''): |
| 115 |
slurpres = self._execute_module(module_name='ansible.legacy.slurp', module_args=dict(src=source), task_vars=task_vars) |
| 116 |
if slurpres.get('failed'): |
| 117 |
if not fail_on_missing: |
| 118 |
result['file'] = source |
| 119 |
result['changed'] = False |
| 120 |
else: |
| 121 |
result.update(slurpres) |
| 122 |
|
| 123 |
if 'not found' in slurpres.get('msg', ''): |
| 124 |
result['msg'] = "the remote file does not exist, not transferring, ignored" |
| 125 |
elif slurpres.get('msg', '').lower().startswith('source is a directory'): |
| 126 |
result['msg'] = "remote file is a directory, fetch cannot work on directories" |
| 127 |
|
| 128 |
return result |
| 129 |
else: |
| 130 |
if slurpres['encoding'] == 'base64': |
| 131 |
remote_data = base64.b64decode(slurpres['content']) |
| 132 |
if remote_data is not None: |
| 133 |
remote_checksum = checksum_s(remote_data) |
| 134 |
|
| 135 |
# calculate the destination name |
| 136 |
if os.path.sep not in self._connection._shell.join_path('a', ''): |
| 137 |
source_local = source.replace('\\', '/') |
| 138 |
else: |
| 139 |
source_local = source |
| 140 |
|
| 141 |
# ensure we only use file name, avoid relative paths |
| 142 |
if not is_subpath(dest, original_dest): |
| 143 |
# TODO: ? dest = os.path.expanduser(dest.replace(('../',''))) |
| 144 |
raise AnsibleActionFail("Detected directory traversal, expected to be contained in '%s' but got '%s'" % (original_dest, dest)) |
| 145 |
|
| 146 |
if flat: |
| 147 |
if os.path.isdir(to_bytes(dest, errors='surrogate_or_strict')) and not dest.endswith(os.sep): |
| 148 |
raise AnsibleActionFail("dest is an existing directory, use a trailing slash if you want to fetch src into that directory") |
| 149 |
if dest.endswith(os.sep): |
| 150 |
# if the path ends with "/", we'll use the source filename as the |
| 151 |
# destination filename |
| 152 |
base = os.path.basename(source_local) |
| 153 |
dest = os.path.join(dest, base) |
| 154 |
|
| 155 |
if os.path.isdir(to_bytes(dest, errors='surrogate_or_strict')): |
| 156 |
raise AnsibleActionFail( |
| 157 |
f"calculated dest '{dest}' is an existing directory, use another path that does not point to an existing directory") |
| 158 |
if not dest.startswith("/"): |
| 159 |
# if dest does not start with "/", we'll assume a relative path |
| 160 |
dest = self._loader.path_dwim(dest) |
| 161 |
else: |
| 162 |
# files are saved in dest dir, with a subdir for each host, then the filename |
| 163 |
if 'inventory_hostname' in task_vars: |
| 164 |
target_name = task_vars['inventory_hostname'] |
| 165 |
else: |
| 166 |
target_name = self._play_context.remote_addr |
| 167 |
dest = "%s/%s/%s" % (self._loader.path_dwim(dest), target_name, source_local) |
| 168 |
|
| 169 |
dest = os.path.normpath(dest) |
| 170 |
|
| 171 |
# calculate checksum for the local file |
| 172 |
local_checksum = checksum(dest) |
| 173 |
|
| 174 |
if remote_checksum != local_checksum: |
| 175 |
# create the containing directories, if needed |
| 176 |
makedirs_safe(os.path.dirname(dest)) |
| 177 |
|
| 178 |
# fetch the file and check for changes |
| 179 |
if remote_data is None: |
| 180 |
self._connection.fetch_file(source, dest) |
| 181 |
else: |
| 182 |
try: |
| 183 |
with open(to_bytes(dest, errors='surrogate_or_strict'), 'wb') as f: |
| 184 |
f.write(remote_data) |
| 185 |
except OSError as ex: |
| 186 |
raise AnsibleActionFail("Failed to fetch the file.") from ex |
| 187 |
new_checksum = secure_hash(dest) |
| 188 |
# For backwards compatibility. We'll return None on FIPS enabled systems |
| 189 |
try: |
| 190 |
new_md5 = md5(dest) |
| 191 |
except ValueError: |
| 192 |
new_md5 = None |
| 193 |
|
| 194 |
if validate_checksum and new_checksum != remote_checksum: |
| 195 |
result.update(dict(failed=True, md5sum=new_md5, |
| 196 |
msg="checksum mismatch", file=source, dest=dest, remote_md5sum=None, |
| 197 |
checksum=new_checksum, remote_checksum=remote_checksum)) |
| 198 |
else: |
| 199 |
result.update({'changed': True, 'md5sum': new_md5, 'file': source, 'dest': dest, |
| 200 |
'remote_md5sum': None, 'checksum': new_checksum, |
| 201 |
'remote_checksum': remote_checksum}) |
| 202 |
else: |
| 203 |
# For backwards compatibility. We'll return None on FIPS enabled systems |
| 204 |
try: |
| 205 |
local_md5 = md5(dest) |
| 206 |
except ValueError: |
| 207 |
local_md5 = None |
| 208 |
result.update(dict(changed=False, md5sum=local_md5, file=source, dest=dest, checksum=local_checksum)) |
| 209 |
|
| 210 |
finally: |
| 211 |
self._remove_tmp_path(self._connection._shell.tmpdir) |
| 212 |
|
| 213 |
return result |