Debian Codegraph @

lib/ansible/modules/get_url.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright: (c) 2012, Jan-Piet Mens <jpmens () gmail.com>
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import annotations
7
8
9 DOCUMENTATION = r"""
10 ---
11 module: get_url
12 short_description: Downloads files from HTTP, HTTPS, or FTP to node
13 description:
14 - Downloads files from HTTP, HTTPS, or FTP to the remote server. The remote
15 server I(must) have direct access to the remote resource.
16 - By default, if an environment variable E(<protocol>_proxy) is set on
17 the target host, requests will be sent through that proxy. This
18 behaviour can be overridden by setting a variable for this task
19 (see R(setting the environment,playbooks_environment)),
20 or by using the use_proxy option.
21 - HTTP redirects can redirect from HTTP to HTTPS so you should be sure that
22 your proxy environment for both protocols is correct.
23 - From Ansible 2.4 when run with C(--check), it will do a HEAD request to validate the URL but
24 will not download the entire file or verify it against hashes and will report incorrect changed status.
25 - For Windows targets, use the M(ansible.windows.win_get_url) module instead.
26 version_added: '0.6'
27 options:
28 ciphers:
29 description:
30 - SSL/TLS Ciphers to use for the request.
31 - 'When a list is provided, all ciphers are joined in order with C(:).'
32 - See the L(OpenSSL Cipher List Format,https://www.openssl.org/docs/manmaster/man1/openssl-ciphers.html#CIPHER-LIST-FORMAT)
33 for more details.
34 - The available ciphers is dependent on the Python and OpenSSL/LibreSSL versions.
35 type: list
36 elements: str
37 version_added: '2.14'
38 decompress:
39 description:
40 - Whether to attempt to decompress gzip content-encoded responses.
41 type: bool
42 default: true
43 version_added: '2.14'
44 url:
45 description:
46 - HTTP, HTTPS, or FTP URL in the form C((http|https|ftp)://[user[:pass]]@host.domain[:port]/path).
47 type: str
48 required: true
49 dest:
50 description:
51 - Absolute path of where to download the file to.
52 - If O(dest) is a directory, either the server provided filename or, if
53 none provided, the base name of the URL on the remote server will be
54 used. If a directory, O(force) has no effect.
55 - If O(dest) is a directory, the file will always be downloaded
56 (regardless of the O(force) and O(checksum) option), but
57 replaced only if the contents changed.
58 type: path
59 required: true
60 tmp_dest:
61 description:
62 - Absolute path of where temporary file is downloaded to.
63 - When run on Ansible 2.5 or greater, path defaults to ansible's C(remote_tmp) setting.
64 - When run on Ansible prior to 2.5, it defaults to E(TMPDIR), E(TEMP) or E(TMP) env variables or a platform specific value.
65 - U(https://docs.python.org/3/library/tempfile.html#tempfile.tempdir).
66 type: path
67 version_added: '2.1'
68 force:
69 description:
70 - If V(true) and O(dest) is not a directory, will download the file every
71 time and replace the file if the contents change. If V(false), the file
72 will only be downloaded if the destination does not exist. Generally
73 should be V(true) only for small local files.
74 - Prior to 0.6, this module behaved as if V(true) was the default.
75 type: bool
76 default: no
77 version_added: '0.7'
78 backup:
79 description:
80 - Create a backup file including the timestamp information so you can get
81 the original file back if you somehow clobbered it incorrectly.
82 type: bool
83 default: no
84 version_added: '2.1'
85 checksum:
86 description:
87 - 'If a checksum is passed to this parameter, the digest of the
88 destination file will be calculated after it is downloaded to ensure
89 its integrity and verify that the transfer completed successfully.
90 Format: <algorithm>:<checksum|url>, for example C(checksum="sha256:D98291AC[...]B6DC7B97"),
91 C(checksum="sha256:http://example.com/path/sha256sum.txt").'
92 - If you worry about portability, only the sha1 algorithm is available
93 on all platforms and python versions.
94 - The Python C(hashlib) module is responsible for providing the available algorithms.
95 The choices vary based on Python version and OpenSSL version.
96 - On systems running in FIPS compliant mode, the C(md5) algorithm may be unavailable.
97 - Additionally, if a checksum is supplied to this parameter, and the file exists under
98 the O(dest) location, the C(destination_checksum) would be calculated; and if
99 checksum equals C(destination_checksum), the file download would be skipped
100 (unless O(force=true)). If the checksum does not equal C(destination_checksum),
101 the destination file is replaced with the newly downloaded file.
102 - If the checksum URL requires username and password, O(url_username) and O(url_password) are used
103 to download the checksum file.
104 type: str
105 default: ''
106 version_added: "2.0"
107 use_proxy:
108 description:
109 - if V(false), it will not use a proxy, even if one is defined in
110 an environment variable on the target hosts.
111 type: bool
112 default: yes
113 validate_certs:
114 description:
115 - If V(false), SSL certificates will not be validated.
116 - This should only be used on personally controlled sites using self-signed certificates.
117 type: bool
118 default: yes
119 timeout:
120 description:
121 - Timeout in seconds for URL request.
122 type: int
123 default: 10
124 version_added: '1.8'
125 headers:
126 description:
127 - Add custom HTTP headers to a request in hash/dict format.
128 - The hash/dict format was added in Ansible 2.6.
129 - Previous versions used a C("key:value,key:value") string format.
130 - The C("key:value,key:value") string format is deprecated and has been removed in version 2.10.
131 type: dict
132 version_added: '2.0'
133 url_username:
134 description:
135 - The username for use in HTTP basic authentication.
136 - This parameter can be used without O(url_password) for sites that allow empty passwords.
137 - Since version 2.8 you can also use the O(username) alias for this option.
138 type: str
139 aliases: ['username']
140 version_added: '1.6'
141 url_password:
142 description:
143 - The password for use in HTTP basic authentication.
144 - If the O(url_username) parameter is not specified, the O(url_password) parameter will not be used.
145 - Since version 2.8 you can also use the O(password) alias for this option.
146 type: str
147 aliases: ['password']
148 version_added: '1.6'
149 force_basic_auth:
150 description:
151 - Force the sending of the Basic authentication header upon initial request.
152 - httplib2, the library used by the uri module only sends authentication information when a webservice
153 responds to an initial request with a 401 status. Since some basic auth services do not properly
154 send a 401, logins will fail.
155 type: bool
156 default: no
157 version_added: '2.0'
158 client_cert:
159 description:
160 - PEM formatted certificate chain file to be used for SSL client authentication.
161 - This file can also include the key as well, and if the key is included, O(client_key) is not required.
162 type: path
163 version_added: '2.4'
164 client_key:
165 description:
166 - PEM formatted file that contains your private key to be used for SSL client authentication.
167 - If O(client_cert) contains both the certificate and key, this option is not required.
168 type: path
169 version_added: '2.4'
170 http_agent:
171 description:
172 - Header to identify as, generally appears in web server logs.
173 type: str
174 default: ansible-httpget
175 unredirected_headers:
176 description:
177 - A list of header names that will not be sent on subsequent redirected requests. This list is case
178 insensitive. By default all headers will be redirected. In some cases it may be beneficial to list
179 headers such as C(Authorization) here to avoid potential credential exposure.
180 default: []
181 type: list
182 elements: str
183 version_added: '2.12'
184 use_gssapi:
185 description:
186 - Use GSSAPI to perform the authentication, typically this is for Kerberos or Kerberos through Negotiate
187 authentication.
188 - Requires the Python library L(gssapi,https://github.com/pythongssapi/python-gssapi) to be installed.
189 - Credentials for GSSAPI can be specified with O(url_username)/O(url_password) or with the GSSAPI env var
190 E(KRB5CCNAME) that specified a custom Kerberos credential cache.
191 - NTLM authentication is I(not) supported even if the GSSAPI mech for NTLM has been installed.
192 type: bool
193 default: no
194 version_added: '2.11'
195 use_netrc:
196 description:
197 - Determining whether to use credentials from C(~/.netrc) file.
198 - By default C(.netrc) is used with Basic authentication headers.
199 - When V(false), C(.netrc) credentials are ignored.
200 type: bool
201 default: true
202 version_added: '2.14'
203 # informational: requirements for nodes
204 extends_documentation_fragment:
205 - files
206 - action_common_attributes
207 attributes:
208 check_mode:
209 details: the changed status will reflect comparison to an empty source file
210 support: partial
211 diff_mode:
212 support: none
213 platform:
214 platforms: posix
215 notes:
216 - For Windows targets, use the M(ansible.windows.win_get_url) module instead.
217 seealso:
218 - module: ansible.builtin.uri
219 - module: ansible.windows.win_get_url
220 author:
221 - Jan-Piet Mens (@jpmens)
222 """
223
224 EXAMPLES = r"""
225 - name: Download foo.conf
226 ansible.builtin.get_url:
227 url: http://example.com/path/file.conf
228 dest: /etc/foo.conf
229 mode: '0440'
230
231 - name: Download file and force basic auth
232 ansible.builtin.get_url:
233 url: http://example.com/path/file.conf
234 dest: /etc/foo.conf
235 force_basic_auth: yes
236
237 - name: Download file with custom HTTP headers
238 ansible.builtin.get_url:
239 url: http://example.com/path/file.conf
240 dest: /etc/foo.conf
241 headers:
242 key1: one
243 key2: two
244
245 - name: Download file with check (sha256)
246 ansible.builtin.get_url:
247 url: http://example.com/path/file.conf
248 dest: /etc/foo.conf
249 checksum: sha256:b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c
250
251 - name: Download file with check (md5)
252 ansible.builtin.get_url:
253 url: http://example.com/path/file.conf
254 dest: /etc/foo.conf
255 checksum: md5:66dffb5228a211e61d6d7ef4a86f5758
256
257 - name: Download file with checksum url (sha256)
258 ansible.builtin.get_url:
259 url: http://example.com/path/file.conf
260 dest: /etc/foo.conf
261 checksum: sha256:http://example.com/path/sha256sum.txt
262
263 - name: Download file from a file path
264 ansible.builtin.get_url:
265 url: file:///tmp/a_file.txt
266 dest: /tmp/afilecopy.txt
267
268 - name: < Fetch file that requires authentication.
269 username/password only available since 2.8, in older versions you need to use url_username/url_password
270 ansible.builtin.get_url:
271 url: http://example.com/path/file.conf
272 dest: /etc/foo.conf
273 username: bar
274 password: '{{ mysecret }}'
275 """
276
277 RETURN = r"""
278 backup_file:
279 description: name of backup file created after download
280 returned: changed and if backup=yes
281 type: str
282 sample: /path/to/file.txt.2015-02-12@22:09~
283 checksum_dest:
284 description: sha1 checksum of the file after copy
285 returned: success
286 type: str
287 sample: 6e642bb8dd5c2e027bf21dd923337cbb4214f827
288 checksum_src:
289 description: sha1 checksum of the file
290 returned: success
291 type: str
292 sample: 6e642bb8dd5c2e027bf21dd923337cbb4214f827
293 dest:
294 description: destination file/path
295 returned: success
296 type: str
297 sample: /path/to/file.txt
298 elapsed:
299 description: The number of seconds that elapsed while performing the download
300 returned: always
301 type: int
302 sample: 23
303 gid:
304 description: group id of the file
305 returned: success
306 type: int
307 sample: 100
308 group:
309 description: group of the file
310 returned: success
311 type: str
312 sample: "httpd"
313 md5sum:
314 description: md5 checksum of the file after download
315 returned: when supported
316 type: str
317 sample: "2a5aeecc61dc98c4d780b14b330e3282"
318 mode:
319 description: permissions of the target
320 returned: success
321 type: str
322 sample: "0644"
323 msg:
324 description: the HTTP message from the request
325 returned: always
326 type: str
327 sample: OK (unknown bytes)
328 owner:
329 description: owner of the file
330 returned: success
331 type: str
332 sample: httpd
333 secontext:
334 description: the SELinux security context of the file
335 returned: success
336 type: str
337 sample: unconfined_u:object_r:user_tmp_t:s0
338 size:
339 description: size of the target
340 returned: success
341 type: int
342 sample: 1220
343 src:
344 description: source file used after download
345 returned: always
346 type: str
347 sample: /tmp/tmpAdFLdV
348 state:
349 description: state of the target
350 returned: success
351 type: str
352 sample: file
353 status_code:
354 description: the HTTP status code from the request
355 returned: always
356 type: int
357 sample: 200
358 uid:
359 description: owner id of the file, after execution
360 returned: success
361 type: int
362 sample: 100
363 url:
364 description: the actual URL used for the request
365 returned: always
366 type: str
367 sample: https://www.ansible.com/
368 """
369
370 import email.message
371 import os
372 import re
373 import shutil
374 import tempfile
375
376 from datetime import datetime, timezone
377 from urllib.parse import urlsplit
378
379 from ansible.module_utils.basic import AnsibleModule
380 from ansible.module_utils.common.text.converters import to_native
381 from ansible.module_utils.urls import fetch_url, is_fetch_success, mask_url, url_argument_spec
382
383 # ==============================================================
384 # url handling
385
386
387 def url_filename(url):
388 fn = os.path.basename(urlsplit(url)[2])
389 if fn == '':
390 return 'index.html'
391 return fn
392
393
394 def url_get(module, url, dest, use_proxy, last_mod_time, force, timeout=10, headers=None, tmp_dest='', method='GET', unredirected_headers=None,
395 decompress=True, ciphers=None, use_netrc=True):
396 """
397 Download data from the url and store in a temporary file.
398
399 Return (tempfile, info about the request)
400 """
401
402 start = datetime.now(timezone.utc)
403 rsp, info = fetch_url(module, url, use_proxy=use_proxy, force=force, last_mod_time=last_mod_time, timeout=timeout, headers=headers, method=method,
404 unredirected_headers=unredirected_headers, decompress=decompress, ciphers=ciphers, use_netrc=use_netrc)
405 elapsed = (datetime.now(timezone.utc) - start).seconds
406
407 if info['status'] == 304:
408 module.exit_json(url=mask_url(url), dest=dest, changed=False, msg=info.get('msg', ''), status_code=info['status'], elapsed=elapsed)
409
410 if not is_fetch_success(info) and not url.startswith('file:/'):
411 module.fail_json(msg=f"Request failed with msg {info['msg']}", status_code=info['status'], response=info['msg'], url=mask_url(url),
412 dest=dest, elapsed=elapsed)
413
414 # create a temporary file and copy content to do checksum-based replacement
415 if tmp_dest:
416 # tmp_dest should be an existing dir
417 tmp_dest_is_dir = os.path.isdir(tmp_dest)
418 if not tmp_dest_is_dir:
419 if os.path.exists(tmp_dest):
420 module.fail_json(msg="%s is a file but should be a directory." % tmp_dest, elapsed=elapsed)
421 else:
422 module.fail_json(msg="%s directory does not exist." % tmp_dest, elapsed=elapsed)
423 else:
424 tmp_dest = module.tmpdir
425
426 fd, tempname = tempfile.mkstemp(dir=tmp_dest)
427
428 f = os.fdopen(fd, 'wb')
429 try:
430 shutil.copyfileobj(rsp, f)
431 except Exception as e:
432 os.remove(tempname)
433 module.fail_json(msg="failed to create temporary content file: %s" % to_native(e), elapsed=elapsed)
434 f.close()
435 rsp.close()
436
437 # Since shutil.copyfileobj() will read from HTTPResponse in chunks, HTTPResponse.read() will not recognize
438 # if the entire content-length of data was not read. We need to do that validation here, unless a 'chunked'
439 # transfer-encoding was used, in which case we will not know content-length because it will not be returned.
440 # But in that case, HTTPResponse will behave correctly and recognize an IncompleteRead.
441
442 is_gzip = info.get('content-encoding') == 'gzip'
443
444 if not module.check_mode and 'content-length' in info:
445 # If data is decompressed, then content-length won't match the amount of data we've read, so skip.
446 if not is_gzip or (is_gzip and not decompress):
447 st = os.stat(tempname)
448 cl = int(info['content-length'])
449 if st.st_size != cl:
450 diff = cl - st.st_size
451 module.fail_json(msg=f'Incomplete read, ({rsp.length=}, {cl=}, {st.st_size=}) failed to read remaining {diff} bytes')
452
453 return tempname, info
454
455
456 def extract_filename_from_headers(headers):
457 """Extracts a filename from the given dict of HTTP headers.
458
459 Returns the filename if successful, else None.
460 """
461 msg = email.message.Message()
462 msg['content-disposition'] = headers.get('content-disposition', '')
463 if filename := msg.get_param('filename', header='content-disposition'):
464 # Avoid directory traversal
465 filename = os.path.basename(filename)
466 return filename
467
468
469 def is_url(checksum):
470 """
471 Returns True if checksum value has supported URL scheme, else False."""
472 supported_schemes = ('http', 'https', 'ftp', 'file')
473
474 return urlsplit(checksum).scheme in supported_schemes
475
476
477 def parse_digest_lines(filename: str, lines: list[str]) -> list[tuple[str, str]]:
478 """Returns a list of tuple containing the filename and digest depending upon
479 the lines provided
480 """
481 checksum_map = []
482 BSD_DIGEST_LINE = re.compile(r'^(\w+) ?\((?P<path>.+)\) ?= (?P<digest>[\w.]+)$')
483 GNU_DIGEST_LINE = re.compile(r'^(?P<digest>[\w.]+)\s+(\*|\.\/|\.)?(?P<path>.+)$')
484
485 if len(lines) == 1 and len(lines[0].split()) == 1:
486 # Only a single line with a single string
487 # treat it as a checksum only file
488 checksum_map.append((lines[0], filename))
489 return checksum_map
490 # The assumption here is the file is in the format of
491 # checksum filename
492 for line in lines:
493 match = BSD_DIGEST_LINE.match(line)
494 if match:
495 checksum_map.append((match.group('digest'), match.group('path')))
496 else:
497 match = GNU_DIGEST_LINE.match(line)
498 if match:
499 checksum_map.append((match.group('digest'), match.group('path').lstrip("./")))
500
501 return checksum_map
502
503
504 # ==============================================================
505 # main
506
507 def main():
508 argument_spec = url_argument_spec()
509
510 # setup aliases
511 argument_spec['url_username']['aliases'] = ['username']
512 argument_spec['url_password']['aliases'] = ['password']
513
514 argument_spec.update(
515 url=dict(type='str', required=True),
516 dest=dict(type='path', required=True),
517 backup=dict(type='bool', default=False),
518 checksum=dict(type='str', default=''),
519 timeout=dict(type='int', default=10),
520 headers=dict(type='dict'),
521 tmp_dest=dict(type='path'),
522 unredirected_headers=dict(type='list', elements='str', default=[]),
523 decompress=dict(type='bool', default=True),
524 ciphers=dict(type='list', elements='str'),
525 use_netrc=dict(type='bool', default=True),
526 )
527
528 module = AnsibleModule(
529 # not checking because of daisy chain to file module
530 argument_spec=argument_spec,
531 add_file_common_args=True,
532 supports_check_mode=True,
533 )
534
535 url = module.params['url']
536 dest = module.params['dest']
537 backup = module.params['backup']
538 force = module.params['force']
539 checksum = module.params['checksum']
540 use_proxy = module.params['use_proxy']
541 timeout = module.params['timeout']
542 headers = module.params['headers']
543 tmp_dest = module.params['tmp_dest']
544 unredirected_headers = module.params['unredirected_headers']
545 decompress = module.params['decompress']
546 ciphers = module.params['ciphers']
547 use_netrc = module.params['use_netrc']
548
549 result = dict(
550 changed=False,
551 checksum_dest=None,
552 checksum_src=None,
553 dest=dest,
554 elapsed=0,
555 url=mask_url(url),
556 )
557
558 dest_is_dir = os.path.isdir(dest)
559 last_mod_time = None
560
561 # checksum specified, parse for algorithm and checksum
562 if checksum:
563 try:
564 algorithm, checksum = checksum.split(':', 1)
565 except ValueError:
566 module.fail_json(msg="The checksum parameter has to be in format <algorithm>:<checksum>", **result)
567
568 if is_url(checksum):
569 checksum_url = checksum
570 # download checksum file to checksum_tmpsrc
571 checksum_tmpsrc, _dummy = url_get(module, checksum_url, dest, use_proxy, last_mod_time, force, timeout, headers, tmp_dest,
572 unredirected_headers=unredirected_headers, ciphers=ciphers, use_netrc=use_netrc)
573 with open(checksum_tmpsrc) as f:
574 lines = [line.rstrip('\n') for line in f]
575 os.remove(checksum_tmpsrc)
576 filename = url_filename(url)
577 checksum_map = parse_digest_lines(filename=filename, lines=lines)
578 # Look through each line in the checksum file for a hash corresponding to
579 # the filename in the url, returning the first hash that is found.
580 for cksum in (s for (s, f) in checksum_map if f == filename):
581 checksum = cksum
582 break
583 else:
584 checksum = None
585
586 if checksum is None:
587 module.fail_json(msg="Unable to find a checksum for file '%s' in '%s'" % (filename, mask_url(checksum_url)))
588 # Remove any non-alphanumeric characters, including the infamous
589 # Unicode zero-width space
590 checksum = re.sub(r'\W+', '', checksum).lower()
591 # Ensure the checksum portion is a hexdigest
592 try:
593 int(checksum, 16)
594 except ValueError:
595 module.fail_json(msg='The checksum format is invalid', **result)
596
597 if not dest_is_dir and os.path.exists(dest):
598 checksum_mismatch = False
599
600 # If the download is not forced and there is a checksum, allow
601 # checksum match to skip the download.
602 if not force and checksum != '':
603 destination_checksum = module.digest_from_file(dest, algorithm)
604
605 if checksum != destination_checksum:
606 checksum_mismatch = True
607
608 # Not forcing redownload, unless checksum does not match
609 if not force and checksum and not checksum_mismatch:
610 # Not forcing redownload, unless checksum does not match
611 # allow file attribute changes
612 file_args = module.load_file_common_arguments(module.params, path=dest)
613 result['changed'] = module.set_fs_attributes_if_different(file_args, False)
614 if result['changed']:
615 module.exit_json(msg="file already exists but file attributes changed", **result)
616 module.exit_json(msg="file already exists", **result)
617
618 # If the file already exists, prepare the last modified time for the
619 # request.
620 mtime = os.path.getmtime(dest)
621 last_mod_time = datetime.fromtimestamp(mtime, timezone.utc)
622
623 # If the checksum does not match we have to force the download
624 # because last_mod_time may be newer than on remote
625 if checksum_mismatch:
626 force = True
627
628 # download to tmpsrc
629 start = datetime.now(timezone.utc)
630 method = 'HEAD' if module.check_mode else 'GET'
631 tmpsrc, info = url_get(module, url, dest, use_proxy, last_mod_time, force, timeout, headers, tmp_dest, method,
632 unredirected_headers=unredirected_headers, decompress=decompress, ciphers=ciphers, use_netrc=use_netrc)
633 result['elapsed'] = (datetime.now(timezone.utc) - start).seconds
634 result['src'] = tmpsrc
635
636 # Now the request has completed, we can finally generate the final
637 # destination file name from the info dict.
638
639 if dest_is_dir:
640 filename = extract_filename_from_headers(info)
641 if not filename:
642 # Fall back to extracting the filename from the URL.
643 # Pluck the URL from the info, since a redirect could have changed
644 # it.
645 filename = url_filename(info['url'])
646 dest = os.path.join(dest, filename)
647 result['dest'] = dest
648
649 # raise an error if there is no tmpsrc file
650 if not os.path.exists(tmpsrc):
651 os.remove(tmpsrc)
652 module.fail_json(msg="Request failed", status_code=info['status'], response=info['msg'], **result)
653 if not os.access(tmpsrc, os.R_OK):
654 os.remove(tmpsrc)
655 module.fail_json(msg="Source %s is not readable" % (tmpsrc), **result)
656 result['checksum_src'] = module.sha1(tmpsrc)
657
658 # check if there is no dest file
659 if os.path.exists(dest):
660 # raise an error if copy has no permission on dest
661 if not os.access(dest, os.W_OK):
662 os.remove(tmpsrc)
663 module.fail_json(msg="Destination %s is not writable" % (dest), **result)
664 if not os.access(dest, os.R_OK):
665 os.remove(tmpsrc)
666 module.fail_json(msg="Destination %s is not readable" % (dest), **result)
667 result['checksum_dest'] = module.sha1(dest)
668 else:
669 if not os.path.exists(os.path.dirname(dest)):
670 os.remove(tmpsrc)
671 module.fail_json(msg="Destination %s does not exist" % (os.path.dirname(dest)), **result)
672 if not os.access(os.path.dirname(dest), os.W_OK):
673 os.remove(tmpsrc)
674 module.fail_json(msg="Destination %s is not writable" % (os.path.dirname(dest)), **result)
675
676 if module.check_mode:
677 if os.path.exists(tmpsrc):
678 os.remove(tmpsrc)
679 result['changed'] = ('checksum_dest' not in result or
680 result['checksum_src'] != result['checksum_dest'])
681 module.exit_json(msg=info.get('msg', ''), **result)
682
683 # If a checksum was provided, ensure that the temporary file matches this checksum
684 # before moving it to the destination.
685 if checksum != '':
686 tmpsrc_checksum = module.digest_from_file(tmpsrc, algorithm)
687
688 if checksum != tmpsrc_checksum:
689 os.remove(tmpsrc)
690 module.fail_json(msg=f"The checksum for {tmpsrc} did not match {checksum}; it was {tmpsrc_checksum}.", **result)
691
692 # Copy temporary file to destination if necessary
693 backup_file = None
694 if result['checksum_src'] != result['checksum_dest']:
695 try:
696 if backup:
697 if os.path.exists(dest):
698 backup_file = module.backup_local(dest)
699 module.atomic_move(tmpsrc, dest, unsafe_writes=module.params['unsafe_writes'])
700 except Exception as e:
701 if os.path.exists(tmpsrc):
702 os.remove(tmpsrc)
703 module.fail_json(msg="failed to copy %s to %s: %s" % (tmpsrc, dest, to_native(e)), **result)
704 result['changed'] = True
705 else:
706 result['changed'] = False
707 if os.path.exists(tmpsrc):
708 os.remove(tmpsrc)
709
710 # allow file attribute changes
711 file_args = module.load_file_common_arguments(module.params, path=dest)
712 result['changed'] = module.set_fs_attributes_if_different(file_args, result['changed'])
713
714 # Backwards compat only. We'll return None on FIPS enabled systems
715 try:
716 result['md5sum'] = module.md5(dest)
717 except ValueError:
718 result['md5sum'] = None
719
720 if backup_file:
721 result['backup_file'] = backup_file
722
723 # Mission complete
724 module.exit_json(msg=info.get('msg', ''), status_code=info.get('status', ''), **result)
725
726
727 if __name__ == '__main__':
728 main()