Debian Codegraph @

lib/ansible/modules/unarchive.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright: (c) 2012, Michael DeHaan <[email protected]>
4 # Copyright: (c) 2013, Dylan Martin <[email protected]>
5 # Copyright: (c) 2015, Toshio Kuratomi <[email protected]>
6 # Copyright: (c) 2016, Dag Wieers <[email protected]>
7 # Copyright: (c) 2017, Ansible Project
8 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
9
10 from __future__ import annotations
11
12
13 DOCUMENTATION = r"""
14 ---
15 module: unarchive
16 version_added: '1.4'
17 short_description: Unpacks an archive after (optionally) copying it from the local machine
18 description:
19 - The M(ansible.builtin.unarchive) module unpacks an archive. It will not unpack a compressed file that does not contain an archive.
20 - By default, it will copy the source file from the local system to the target before unpacking.
21 - Set O(remote_src=yes) to unpack an archive which already exists on the target.
22 - If checksum validation is desired, use M(ansible.builtin.get_url) or M(ansible.builtin.uri) instead to fetch the file and set O(remote_src=yes).
23 - For Windows targets, use the M(community.windows.win_unzip) module instead.
24 options:
25 src:
26 description:
27 - If O(remote_src=no) (default), local path to archive file to copy to the target server; can be absolute or relative. If O(remote_src=yes), path on the
28 target server to existing archive file to unpack.
29 - If O(remote_src=yes) and O(src) contains V(://), the remote machine will download the file from the URL first. (version_added 2.0). This is only for
30 simple cases, for full download support use the M(ansible.builtin.get_url) module.
31 type: path
32 required: true
33 dest:
34 description:
35 - Remote absolute path where the archive should be unpacked.
36 - The given path must exist. Base directory is not created by this module.
37 type: path
38 required: true
39 copy:
40 description:
41 - If true, the file is copied from local controller to the managed (remote) node, otherwise, the plugin will look for src archive on the managed machine.
42 - This option has been deprecated in favor of O(remote_src).
43 - This option is mutually exclusive with O(remote_src).
44 type: bool
45 default: yes
46 creates:
47 description:
48 - If the specified absolute path (file or directory) already exists, this step will B(not) be run.
49 - The specified absolute path (file or directory) must be below the base path given with O(dest).
50 type: path
51 version_added: "1.6"
52 io_buffer_size:
53 description:
54 - Size of the volatile memory buffer that is used for extracting files from the archive in bytes.
55 type: int
56 default: 65536
57 version_added: "2.12"
58 list_files:
59 description:
60 - If set to True, return the list of files that are contained in the tarball.
61 type: bool
62 default: no
63 version_added: "2.0"
64 exclude:
65 description:
66 - List the directory and file entries that you would like to exclude from the unarchive action.
67 - Mutually exclusive with O(include).
68 type: list
69 default: []
70 elements: str
71 version_added: "2.1"
72 include:
73 description:
74 - List of directory and file entries that you would like to extract from the archive. If O(include)
75 is not empty, only files listed here will be extracted.
76 - Mutually exclusive with O(exclude).
77 type: list
78 default: []
79 elements: str
80 version_added: "2.11"
81 keep_newer:
82 description:
83 - Do not replace existing files that are newer than files from the archive.
84 type: bool
85 default: no
86 version_added: "2.1"
87 extra_opts:
88 description:
89 - Specify additional options by passing in an array.
90 - Each space-separated command-line option should be a new element of the array. See examples.
91 - Command-line options with multiple elements must use multiple lines in the array, one for each element.
92 type: list
93 elements: str
94 default: []
95 version_added: "2.1"
96 remote_src:
97 description:
98 - Set to V(true) to indicate the archived file is already on the remote system and not local to the Ansible controller.
99 - This option is mutually exclusive with O(copy).
100 type: bool
101 default: no
102 version_added: "2.2"
103 validate_certs:
104 description:
105 - This only applies if using a https URL as the source of the file.
106 - This should only set to V(false) used on personally controlled sites using self-signed certificate.
107 - Prior to 2.2 the code worked as if this was set to V(true).
108 type: bool
109 default: yes
110 version_added: "2.2"
111 extends_documentation_fragment:
112 - action_common_attributes
113 - action_common_attributes.flow
114 - action_common_attributes.files
115 - decrypt
116 - files
117 attributes:
118 action:
119 support: full
120 async:
121 support: none
122 bypass_host_loop:
123 support: none
124 check_mode:
125 support: partial
126 details: Not supported for gzipped tar files.
127 diff_mode:
128 support: partial
129 details: Uses gtar's C(--diff) arg to calculate if changed or not. If this C(arg) is not supported, it will always unpack the archive.
130 platform:
131 platforms: posix
132 safe_file_operations:
133 support: none
134 vault:
135 support: full
136 todo:
137 - Re-implement tar support using native tarfile module.
138 - Re-implement zip support using native zipfile module.
139 notes:
140 - Requires C(zipinfo) and C(gtar)/C(unzip) command on target host.
141 - Requires C(zstd) command on target host to expand I(.tar.zst) files.
142 - Can handle I(.zip) files using C(unzip) as well as I(.tar), I(.tar.gz), I(.tar.bz2), I(.tar.xz), and I(.tar.zst) files using C(gtar).
143 - Does not handle I(.gz) files, I(.bz2) files, I(.xz), or I(.zst) files that do not contain a I(.tar) archive.
144 - Existing files/directories in the destination which are not in the archive
145 are not touched. This is the same behavior as a normal archive extraction.
146 - Existing files/directories in the destination which are not in the archive
147 are ignored for purposes of deciding if the archive should be unpacked or not.
148 seealso:
149 - module: community.general.archive
150 - module: community.general.iso_extract
151 - module: community.windows.win_unzip
152 author: Michael DeHaan
153 """
154
155 EXAMPLES = r"""
156 - name: Extract foo.tgz into /var/lib/foo
157 ansible.builtin.unarchive:
158 src: foo.tgz
159 dest: /var/lib/foo
160
161 - name: Unarchive a file that is already on the remote machine
162 ansible.builtin.unarchive:
163 src: /tmp/foo.zip
164 dest: /usr/local/bin
165 remote_src: yes
166
167 - name: Unarchive a file that needs to be downloaded (added in 2.0)
168 ansible.builtin.unarchive:
169 src: https://example.com/example.zip
170 dest: /usr/local/bin
171 remote_src: yes
172
173 - name: Unarchive a file with extra options
174 ansible.builtin.unarchive:
175 src: /tmp/foo.zip
176 dest: /usr/local/bin
177 extra_opts:
178 - --transform
179 - s/^xxx/yyy/
180 """
181
182 RETURN = r"""
183 dest:
184 description: Path to the destination directory.
185 returned: always
186 type: str
187 sample: /opt/software
188 files:
189 description: List of all the files in the archive.
190 returned: When O(list_files) is V(True)
191 type: list
192 sample: '["file1", "file2"]'
193 gid:
194 description: Numerical ID of the group that owns the destination directory.
195 returned: always
196 type: int
197 sample: 1000
198 group:
199 description: Name of the group that owns the destination directory.
200 returned: always
201 type: str
202 sample: "librarians"
203 handler:
204 description: Archive software handler used to extract and decompress the archive.
205 returned: always
206 type: str
207 sample: "TgzArchive"
208 mode:
209 description: String that represents the octal permissions of the destination directory.
210 returned: always
211 type: str
212 sample: "0755"
213 owner:
214 description: Name of the user that owns the destination directory.
215 returned: always
216 type: str
217 sample: "paul"
218 size:
219 description: The size of destination directory in bytes. Does not include the size of files or subdirectories contained within.
220 returned: always
221 type: int
222 sample: 36
223 src:
224 description:
225 - The source archive's path.
226 - If O(src) was a remote web URL, or from the local ansible controller, this shows the temporary location where the download was stored.
227 returned: always
228 type: str
229 sample: "/home/paul/test.tar.gz"
230 state:
231 description: State of the destination. Effectively always "directory".
232 returned: always
233 type: str
234 sample: "directory"
235 uid:
236 description: Numerical ID of the user that owns the destination directory.
237 returned: always
238 type: int
239 sample: 1000
240 """
241
242 import binascii
243 import codecs
244 import ctypes
245 import fnmatch
246 import grp
247 import os
248 import platform
249 import pwd
250 import re
251 import stat
252 import time
253 from functools import partial
254 from zipfile import ZipFile
255
256 from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
257 from ansible.module_utils.basic import AnsibleModule
258 from ansible.module_utils.common.process import get_bin_path
259 from ansible.module_utils.common.locale import get_best_parsable_locale
260 from ansible.module_utils.urls import fetch_file
261
262 from shlex import quote
263 from zipfile import BadZipFile
264
265 try:
266 from functools import cache
267 except ImportError:
268 # Python < 3.9
269 from functools import lru_cache
270 cache = lru_cache(maxsize=None)
271
272 # String from tar that shows the tar contents are different from the
273 # filesystem
274 OWNER_DIFF_RE = re.compile(r': Uid differs$')
275 GROUP_DIFF_RE = re.compile(r': Gid differs$')
276 MODE_DIFF_RE = re.compile(r': Mode differs$')
277 MOD_TIME_DIFF_RE = re.compile(r': Mod time differs$')
278 # NEWER_DIFF_RE = re.compile(r' is newer or same age.$')
279 EMPTY_FILE_RE = re.compile(r': : Warning: Cannot stat: No such file or directory$')
280 MISSING_FILE_RE = re.compile(r': Warning: Cannot stat: No such file or directory$')
281 ZIP_FILE_MODE_RE = re.compile(r'([r-][w-][SsTtx-]){3}')
282 INVALID_OWNER_RE = re.compile(r': Invalid owner')
283 INVALID_GROUP_RE = re.compile(r': Invalid group')
284 SYMLINK_DIFF_RE = re.compile(r': Symlink differs$')
285 CONTENT_DIFF_RE = re.compile(r': Contents differ$')
286 SIZE_DIFF_RE = re.compile(r': Size differs$')
287
288
289 @cache
290 def _y2038_impacted():
291 """Determine if the system has 64-bit time_t."""
292 if hasattr(ctypes, "c_time_t"): # Python >= 3.12
293 return ctypes.sizeof(ctypes.c_time_t) < 8
294 try:
295 time.gmtime(2**31)
296 except OverflowError:
297 return True
298 return False
299
300
301 def crc32(path, buffer_size):
302 """ Return a CRC32 checksum of a file """
303
304 crc = binascii.crc32(b'')
305 with open(path, 'rb') as f:
306 for b_block in iter(partial(f.read, buffer_size), b''):
307 crc = binascii.crc32(b_block, crc)
308 return crc & 0xffffffff
309
310
311 def shell_escape(string):
312 """ Quote meta-characters in the args for the unix shell """
313 return re.sub(r'([^A-Za-z0-9_])', r'\\\1', string)
314
315
316 class UnarchiveError(Exception):
317 pass
318
319
320 class ZipArchive(object):
321
322 def __init__(self, src, b_dest, file_args, module):
323 self.src = src
324 self.b_dest = b_dest
325 self.file_args = file_args
326 self.opts = module.params['extra_opts']
327 self.module = module
328 self.io_buffer_size = module.params["io_buffer_size"]
329 self.excludes = module.params['exclude']
330 self.includes = []
331 self.include_files = self.module.params['include']
332 self.cmd_path = None
333 self.zipinfo_cmd_path = None
334 self._files_in_archive = []
335 self._infodict = dict()
336 self.zipinfoflag = ''
337 self.binaries = (
338 ('unzip', 'cmd_path'),
339 ('zipinfo', 'zipinfo_cmd_path'),
340 )
341
342 def _permstr_to_octal(self, modestr, umask):
343 """ Convert a Unix permission string (rw-r--r--) into a mode (0644) """
344 revstr = modestr[::-1]
345 mode = 0
346 for j in range(0, 3):
347 for i in range(0, 3):
348 if revstr[i + 3 * j] in ['r', 'w', 'x', 's', 't']:
349 mode += 2 ** (i + 3 * j)
350 # The unzip utility does not support setting the stST bits
351 # if revstr[i + 3 * j] in ['s', 't', 'S', 'T' ]:
352 # mode += 2 ** (9 + j)
353 return (mode & ~umask)
354
355 def _legacy_file_list(self):
356 rc, out, err = self.module.run_command([self.cmd_path, '-v', self.src])
357 if rc:
358 self.module.debug(err)
359 raise UnarchiveError('Neither python zipfile nor unzip can read %s' % self.src)
360
361 for line in out.splitlines()[3:-2]:
362 fields = line.split(None, 7)
363 self._files_in_archive.append(fields[7])
364 self._infodict[fields[7]] = int(fields[6])
365
366 def _crc32(self, path):
367 if self._infodict:
368 return self._infodict[path]
369
370 try:
371 archive = ZipFile(self.src)
372 except BadZipFile as e:
373 if e.args[0].lower().startswith('bad magic number'):
374 # Python2.4 can't handle zipfiles with > 64K files. Try using
375 # /usr/bin/unzip instead
376 self._legacy_file_list()
377 else:
378 raise
379 else:
380 try:
381 for item in archive.infolist():
382 self._infodict[item.filename] = int(item.CRC)
383 except Exception:
384 archive.close()
385 raise UnarchiveError('Unable to list files in the archive')
386
387 return self._infodict[path]
388
389 @property
390 def files_in_archive(self):
391 if self._files_in_archive:
392 return self._files_in_archive
393
394 self._files_in_archive = []
395 try:
396 archive = ZipFile(self.src)
397 except BadZipFile as e:
398 if e.args[0].lower().startswith('bad magic number'):
399 # Python2.4 can't handle zipfiles with > 64K files. Try using
400 # /usr/bin/unzip instead
401 self._legacy_file_list()
402 else:
403 raise
404 else:
405 try:
406 for member in archive.namelist():
407 if self.include_files:
408 for include in self.include_files:
409 if fnmatch.fnmatch(member, include):
410 self._files_in_archive.append(to_native(member))
411 else:
412 exclude_flag = False
413 if self.excludes:
414 for exclude in self.excludes:
415 if fnmatch.fnmatch(member, exclude):
416 exclude_flag = True
417 break
418 if not exclude_flag:
419 self._files_in_archive.append(to_native(member))
420 except Exception as e:
421 archive.close()
422 raise UnarchiveError('Unable to list files in the archive: %s' % to_native(e))
423
424 archive.close()
425 return self._files_in_archive
426
427 def _valid_time_stamp(self, timestamp_str):
428 """ Return a valid time object from the given time string """
429 DT_RE = re.compile(r'^(\d{4})(\d{2})(\d{2})\.(\d{2})(\d{2})(\d{2})$')
430 match = DT_RE.match(timestamp_str)
431 epoch_date_time = (1980, 1, 1, 0, 0, 0, 0, 0, -1)
432 if match:
433 try:
434 if int(match.groups()[0]) < 1980:
435 date_time = epoch_date_time
436 elif int(match.groups()[0]) >= 2038 and _y2038_impacted():
437 date_time = (2038, 1, 1, 0, 0, 0, 0, 0, -1)
438 elif int(match.groups()[0]) > 2107:
439 date_time = (2107, 12, 31, 23, 59, 59, 0, 0, -1)
440 else:
441 date_time = (int(m) for m in match.groups() + (0, 0, -1))
442 except ValueError:
443 date_time = epoch_date_time
444 else:
445 # Assume epoch date
446 date_time = epoch_date_time
447
448 return time.mktime(time.struct_time(date_time))
449
450 def is_unarchived(self):
451 # BSD unzip doesn't support zipinfo listings with timestamp.
452 if self.zipinfoflag:
453 cmd = [self.zipinfo_cmd_path, self.zipinfoflag, '-T', '-s', self.src]
454 else:
455 cmd = [self.zipinfo_cmd_path, '-T', '-s', self.src]
456
457 if self.excludes:
458 cmd.extend(['-x', ] + self.excludes)
459 if self.include_files:
460 cmd.extend(self.include_files)
461 rc, out, err = self.module.run_command(cmd)
462 self.module.debug(err)
463
464 old_out = out
465 diff = ''
466 out = ''
467 if rc == 0:
468 unarchived = True
469 else:
470 unarchived = False
471
472 # Get some information related to user/group ownership
473 umask = os.umask(0)
474 os.umask(umask)
475 systemtype = platform.system()
476
477 # Get current user and group information
478 groups = os.getgroups()
479 run_uid = os.getuid()
480 run_gid = os.getgid()
481 try:
482 run_owner = pwd.getpwuid(run_uid).pw_name
483 except (TypeError, KeyError):
484 run_owner = run_uid
485 try:
486 run_group = grp.getgrgid(run_gid).gr_name
487 except (KeyError, ValueError, OverflowError):
488 run_group = run_gid
489
490 # Get future user ownership
491 fut_owner = fut_uid = None
492 if self.file_args['owner']:
493 try:
494 tpw = pwd.getpwnam(self.file_args['owner'])
495 except KeyError:
496 try:
497 tpw = pwd.getpwuid(int(self.file_args['owner']))
498 except (TypeError, KeyError, ValueError):
499 tpw = pwd.getpwuid(run_uid)
500 fut_owner = tpw.pw_name
501 fut_uid = tpw.pw_uid
502 else:
503 try:
504 fut_owner = run_owner
505 except Exception:
506 pass
507 fut_uid = run_uid
508
509 # Get future group ownership
510 fut_group = fut_gid = None
511 if self.file_args['group']:
512 try:
513 tgr = grp.getgrnam(self.file_args['group'])
514 except (ValueError, KeyError):
515 try:
516 # no need to check isdigit() explicitly here, if we fail to
517 # parse, the ValueError will be caught.
518 tgr = grp.getgrgid(int(self.file_args['group']))
519 except (KeyError, ValueError, OverflowError):
520 tgr = grp.getgrgid(run_gid)
521 fut_group = tgr.gr_name
522 fut_gid = tgr.gr_gid
523 else:
524 try:
525 fut_group = run_group
526 except Exception:
527 pass
528 fut_gid = run_gid
529
530 for line in old_out.splitlines():
531 change = False
532
533 pcs = line.split(None, 7)
534 if len(pcs) != 8:
535 # Too few fields... probably a piece of the header or footer
536 continue
537
538 # Check first and seventh field in order to skip header/footer
539 # 7 or 8 are FAT, 10 is normal unix perms
540 if len(pcs[0]) not in (7, 8, 10):
541 continue
542 if len(pcs[6]) != 15:
543 continue
544
545 # Possible entries:
546 # -rw-rws--- 1.9 unx 2802 t- defX 11-Aug-91 13:48 perms.2660
547 # -rw-a-- 1.0 hpf 5358 Tl i4:3 4-Dec-91 11:33 longfilename.hpfs
548 # -r--ahs 1.1 fat 4096 b- i4:2 14-Jul-91 12:58 EA DATA. SF
549 # --w------- 1.0 mac 17357 bx i8:2 4-May-92 04:02 unzip.macr
550 if pcs[0][0] not in 'dl-?' or not frozenset(pcs[0][1:]).issubset('rwxstah-'):
551 continue
552
553 ztype = pcs[0][0]
554 permstr = pcs[0][1:]
555 version = pcs[1]
556 ostype = pcs[2]
557 size = int(pcs[3])
558 path = to_text(pcs[7], errors='surrogate_or_strict')
559
560 # Skip excluded files
561 if path in self.excludes:
562 out += 'Path %s is excluded on request\n' % path
563 continue
564
565 # Itemized change requires L for symlink
566 if path[-1] == '/':
567 if ztype != 'd':
568 err += 'Path %s incorrectly tagged as "%s", but is a directory.\n' % (path, ztype)
569 ftype = 'd'
570 elif ztype == 'l':
571 ftype = 'L'
572 elif ztype == '-':
573 ftype = 'f'
574 elif ztype == '?':
575 ftype = 'f'
576
577 # Some files may be storing FAT permissions, not Unix permissions
578 # For FAT permissions, we will use a base permissions set of 777 if the item is a directory or has the execute bit set. Otherwise, 666.
579 # This permission will then be modified by the system UMask.
580 # BSD always applies the Umask, even to Unix permissions.
581 # For Unix style permissions on Linux or Mac, we want to use them directly.
582 # So we set the UMask for this file to zero. That permission set will then be unchanged when calling _permstr_to_octal
583
584 if len(permstr) == 6:
585 if path[-1] == '/':
586 permstr = 'rwxrwxrwx'
587 elif permstr == 'rwx---':
588 permstr = 'rwxrwxrwx'
589 else:
590 permstr = 'rw-rw-rw-'
591 file_umask = umask
592 elif len(permstr) == 7:
593 if permstr == 'rwxa---':
594 permstr = 'rwxrwxrwx'
595 else:
596 permstr = 'rw-rw-rw-'
597 file_umask = umask
598 elif 'bsd' in systemtype.lower():
599 file_umask = umask
600 else:
601 file_umask = 0
602
603 # Test string conformity
604 if len(permstr) != 9 or not ZIP_FILE_MODE_RE.match(permstr):
605 raise UnarchiveError('ZIP info perm format incorrect, %s' % permstr)
606
607 # DEBUG
608 # err += "%s%s %10d %s\n" % (ztype, permstr, size, path)
609
610 b_dest = os.path.join(self.b_dest, to_bytes(path, errors='surrogate_or_strict'))
611 try:
612 st = os.lstat(b_dest)
613 except Exception:
614 change = True
615 self.includes.append(path)
616 err += 'Path %s is missing\n' % path
617 diff += '>%s++++++.?? %s\n' % (ftype, path)
618 continue
619
620 # Compare file types
621 if ftype == 'd' and not stat.S_ISDIR(st.st_mode):
622 change = True
623 self.includes.append(path)
624 err += 'File %s already exists, but not as a directory\n' % path
625 diff += 'c%s++++++.?? %s\n' % (ftype, path)
626 continue
627
628 if ftype == 'f' and not stat.S_ISREG(st.st_mode):
629 change = True
630 unarchived = False
631 self.includes.append(path)
632 err += 'Directory %s already exists, but not as a regular file\n' % path
633 diff += 'c%s++++++.?? %s\n' % (ftype, path)
634 continue
635
636 if ftype == 'L' and not stat.S_ISLNK(st.st_mode):
637 change = True
638 self.includes.append(path)
639 err += 'Directory %s already exists, but not as a symlink\n' % path
640 diff += 'c%s++++++.?? %s\n' % (ftype, path)
641 continue
642
643 itemized = list('.%s.......??' % ftype)
644
645 # Note: this timestamp calculation has a rounding error
646 # somewhere... unzip and this timestamp can be one second off
647 # When that happens, we report a change and re-unzip the file
648 timestamp = self._valid_time_stamp(pcs[6])
649
650 # Compare file timestamps
651 if stat.S_ISREG(st.st_mode):
652 if self.module.params['keep_newer']:
653 if timestamp > st.st_mtime:
654 change = True
655 self.includes.append(path)
656 err += 'File %s is older, replacing file\n' % path
657 itemized[4] = 't'
658 elif stat.S_ISREG(st.st_mode) and timestamp < st.st_mtime:
659 # Add to excluded files, ignore other changes
660 out += 'File %s is newer, excluding file\n' % path
661 self.excludes.append(path)
662 continue
663 else:
664 if timestamp != st.st_mtime:
665 change = True
666 self.includes.append(path)
667 err += 'File %s differs in mtime (%f vs %f)\n' % (path, timestamp, st.st_mtime)
668 itemized[4] = 't'
669
670 # Compare file sizes
671 if stat.S_ISREG(st.st_mode) and size != st.st_size:
672 change = True
673 err += 'File %s differs in size (%d vs %d)\n' % (path, size, st.st_size)
674 itemized[3] = 's'
675
676 # Compare file checksums
677 if stat.S_ISREG(st.st_mode):
678 crc = crc32(b_dest, self.io_buffer_size)
679 if crc != self._crc32(path):
680 change = True
681 err += 'File %s differs in CRC32 checksum (0x%08x vs 0x%08x)\n' % (path, self._crc32(path), crc)
682 itemized[2] = 'c'
683
684 # Compare file permissions
685
686 # Do not handle permissions of symlinks
687 if ftype != 'L':
688
689 # Use the new mode provided with the action, if there is one
690 if self.file_args['mode']:
691 if isinstance(self.file_args['mode'], int):
692 mode = self.file_args['mode']
693 else:
694 try:
695 mode = int(self.file_args['mode'], 8)
696 except Exception as e:
697 try:
698 mode = AnsibleModule._symbolic_mode_to_octal(st, self.file_args['mode'])
699 except ValueError as e:
700 self.module.fail_json(path=path, msg="%s" % to_native(e))
701 # Only special files require no umask-handling
702 elif ztype == '?':
703 mode = self._permstr_to_octal(permstr, 0)
704 else:
705 mode = self._permstr_to_octal(permstr, file_umask)
706
707 if mode != stat.S_IMODE(st.st_mode):
708 change = True
709 itemized[5] = 'p'
710 err += 'Path %s differs in permissions (%o vs %o)\n' % (path, mode, stat.S_IMODE(st.st_mode))
711
712 # Compare file user ownership
713 owner = uid = None
714 try:
715 owner = pwd.getpwuid(st.st_uid).pw_name
716 except (TypeError, KeyError):
717 uid = st.st_uid
718
719 # If we are not root and requested owner is not our user, fail
720 if run_uid != 0 and (fut_owner != run_owner or fut_uid != run_uid):
721 raise UnarchiveError('Cannot change ownership of %s to %s, as user %s' % (path, fut_owner, run_owner))
722
723 if owner and owner != fut_owner:
724 change = True
725 err += 'Path %s is owned by user %s, not by user %s as expected\n' % (path, owner, fut_owner)
726 itemized[6] = 'o'
727 elif uid and uid != fut_uid:
728 change = True
729 err += 'Path %s is owned by uid %s, not by uid %s as expected\n' % (path, uid, fut_uid)
730 itemized[6] = 'o'
731
732 # Compare file group ownership
733 group = gid = None
734 try:
735 group = grp.getgrgid(st.st_gid).gr_name
736 except (KeyError, ValueError, OverflowError):
737 gid = st.st_gid
738
739 if run_uid != 0 and (fut_group != run_group or fut_gid != run_gid) and fut_gid not in groups:
740 raise UnarchiveError('Cannot change group ownership of %s to %s, as user %s' % (path, fut_group, run_owner))
741
742 if group and group != fut_group:
743 change = True
744 err += 'Path %s is owned by group %s, not by group %s as expected\n' % (path, group, fut_group)
745 itemized[6] = 'g'
746 elif gid and gid != fut_gid:
747 change = True
748 err += 'Path %s is owned by gid %s, not by gid %s as expected\n' % (path, gid, fut_gid)
749 itemized[6] = 'g'
750
751 # Register changed files and finalize diff output
752 if change:
753 if path not in self.includes:
754 self.includes.append(path)
755 diff += '%s %s\n' % (''.join(itemized), path)
756
757 if self.includes:
758 unarchived = False
759
760 # DEBUG
761 # out = old_out + out
762
763 return dict(unarchived=unarchived, rc=rc, out=out, err=err, cmd=cmd, diff=diff)
764
765 def unarchive(self):
766 cmd = [self.cmd_path, '-o']
767 if self.opts:
768 cmd.extend(self.opts)
769 cmd.append(self.src)
770 # NOTE: Including (changed) files as arguments is problematic (limits on command line/arguments)
771 # if self.includes:
772 # NOTE: Command unzip has this strange behaviour where it expects quoted filenames to also be escaped
773 # cmd.extend(map(shell_escape, self.includes))
774 if self.excludes:
775 cmd.extend(['-x'] + self.excludes)
776 if self.include_files:
777 cmd.extend(self.include_files)
778 cmd.extend(['-d', self.b_dest])
779 rc, out, err = self.module.run_command(cmd)
780 return dict(cmd=cmd, rc=rc, out=out, err=err)
781
782 def can_handle_archive(self):
783 missing = []
784 for b in self.binaries:
785 try:
786 setattr(self, b[1], get_bin_path(b[0]))
787 except ValueError:
788 missing.append(b[0])
789
790 if missing:
791 return False, "Unable to find required '{missing}' binary in the path.".format(missing="' or '".join(missing))
792
793 cmd = [self.cmd_path, '-l', self.src]
794 rc, out, err = self.module.run_command(cmd)
795 if rc == 0:
796 return True, None
797
798 self.module.debug(err)
799
800 return False, 'Command "%s" could not handle archive: %s' % (self.cmd_path, err)
801
802
803 class TgzArchive(object):
804
805 def __init__(self, src, b_dest, file_args, module):
806 self.src = src
807 self.b_dest = b_dest
808 self.file_args = file_args
809 self.opts = module.params['extra_opts']
810 self.module = module
811 if self.module.check_mode:
812 self.module.exit_json(
813 skipped=True, # deprecated: description='remove this skipped return', core_version='2.25'
814 msg="remote module (%s) does not support check mode when using gtar" % self.module._name,
815 )
816 self.excludes = [path.rstrip('/') for path in self.module.params['exclude']]
817 self.include_files = self.module.params['include']
818 self.cmd_path = None
819 self.tar_type = None
820 self.zipflag = '-z'
821 self._files_in_archive = []
822
823 def _get_tar_type(self):
824 cmd = [self.cmd_path, '--version']
825 (rc, out, err) = self.module.run_command(cmd)
826 tar_type = None
827 if out.startswith('bsdtar'):
828 tar_type = 'bsd'
829 elif out.startswith('tar') and 'GNU' in out:
830 tar_type = 'gnu'
831 return tar_type
832
833 @property
834 def files_in_archive(self):
835 if self._files_in_archive:
836 return self._files_in_archive
837
838 cmd = [self.cmd_path, '--list', '-C', self.b_dest]
839 if self.zipflag:
840 cmd.append(self.zipflag)
841 if self.opts:
842 cmd.extend(['--show-transformed-names'] + self.opts)
843 if self.excludes:
844 cmd.extend(['--exclude=' + f for f in self.excludes])
845 cmd.extend(['-f', self.src])
846 if self.include_files:
847 cmd.extend(self.include_files)
848
849 locale = get_best_parsable_locale(self.module)
850 rc, out, err = self.module.run_command(cmd, cwd=self.b_dest, environ_update=dict(LANG=locale, LC_ALL=locale, LC_MESSAGES=locale, LANGUAGE=locale))
851 if rc != 0:
852 self.module.debug(err)
853 raise UnarchiveError('Unable to list files in the archive: %s' % err)
854
855 for filename in out.splitlines():
856 # Compensate for locale-related problems in gtar output (octal unicode representation) #11348
857 # filename = filename.decode('string_escape')
858 filename = to_native(codecs.escape_decode(filename)[0])
859
860 # We don't allow absolute filenames. If the user wants to unarchive rooted in "/"
861 # they need to use "dest: '/'". This follows the defaults for gtar, pax, etc.
862 # Allowing absolute filenames here also causes bugs: https://github.com/ansible/ansible/issues/21397
863 if filename.startswith('/'):
864 filename = filename[1:]
865
866 exclude_flag = False
867 if self.excludes:
868 for exclude in self.excludes:
869 if fnmatch.fnmatch(filename, exclude):
870 exclude_flag = True
871 break
872
873 if not exclude_flag:
874 self._files_in_archive.append(to_native(filename))
875
876 return self._files_in_archive
877
878 def is_unarchived(self):
879 cmd = [self.cmd_path, '--diff', '-C', self.b_dest]
880 if self.zipflag:
881 cmd.append(self.zipflag)
882 if self.opts:
883 cmd.extend(['--show-transformed-names'] + self.opts)
884 if self.file_args['owner']:
885 cmd.append('--owner=' + quote(self.file_args['owner']))
886 if self.file_args['group']:
887 cmd.append('--group=' + quote(self.file_args['group']))
888 if self.module.params['keep_newer']:
889 cmd.append('--keep-newer-files')
890 if self.excludes:
891 cmd.extend(['--exclude=' + f for f in self.excludes])
892 cmd.extend(['-f', self.src])
893 if self.include_files:
894 cmd.extend(self.include_files)
895 locale = get_best_parsable_locale(self.module)
896 rc, out, err = self.module.run_command(cmd, cwd=self.b_dest, environ_update=dict(LANG=locale, LC_ALL=locale, LC_MESSAGES=locale, LANGUAGE=locale))
897
898 # Check whether the differences are in something that we're
899 # setting anyway
900
901 # What is different
902 unarchived = True
903 old_out = out
904 out = ''
905 run_uid = os.getuid()
906 # When unarchiving as a user, or when owner/group/mode is supplied --diff is insufficient
907 # Only way to be sure is to check request with what is on disk (as we do for zip)
908 # Leave this up to set_fs_attributes_if_different() instead of inducing a (false) change
909 for line in old_out.splitlines() + err.splitlines():
910 # FIXME: Remove the bogus lines from error-output as well !
911 # Ignore bogus errors on empty filenames (when using --split-component)
912 if EMPTY_FILE_RE.search(line):
913 continue
914 if run_uid == 0 and not self.file_args['owner'] and OWNER_DIFF_RE.search(line):
915 out += line + '\n'
916 if run_uid == 0 and not self.file_args['group'] and GROUP_DIFF_RE.search(line):
917 out += line + '\n'
918 if not self.file_args['mode'] and MODE_DIFF_RE.search(line):
919 out += line + '\n'
920 differ_regexes = [
921 MOD_TIME_DIFF_RE, MISSING_FILE_RE, INVALID_OWNER_RE,
922 INVALID_GROUP_RE, SYMLINK_DIFF_RE, CONTENT_DIFF_RE,
923 SIZE_DIFF_RE
924 ]
925 for regex in differ_regexes:
926 if regex.search(line):
927 out += line + '\n'
928
929 if out:
930 unarchived = False
931 return dict(unarchived=unarchived, rc=rc, out=out, err=err, cmd=cmd)
932
933 def unarchive(self):
934 cmd = [self.cmd_path, '--extract', '-C', self.b_dest]
935 if self.zipflag:
936 cmd.append(self.zipflag)
937 if self.opts:
938 cmd.extend(['--show-transformed-names'] + self.opts)
939 if self.file_args['owner']:
940 cmd.append('--owner=' + quote(self.file_args['owner']))
941 if self.file_args['group']:
942 cmd.append('--group=' + quote(self.file_args['group']))
943 if self.module.params['keep_newer']:
944 cmd.append('--keep-newer-files')
945 if self.excludes:
946 cmd.extend(['--exclude=' + f for f in self.excludes])
947 cmd.extend(['-f', self.src])
948 if self.include_files:
949 cmd.extend(self.include_files)
950 locale = get_best_parsable_locale(self.module)
951 rc, out, err = self.module.run_command(cmd, cwd=self.b_dest, environ_update=dict(LANG=locale, LC_ALL=locale, LC_MESSAGES=locale, LANGUAGE=locale))
952 return dict(cmd=cmd, rc=rc, out=out, err=err)
953
954 def can_handle_archive(self):
955 # Prefer gtar (GNU tar) as it supports the compression options -z, -j and -J
956 try:
957 self.cmd_path = get_bin_path('gtar')
958 except ValueError:
959 # Fallback to tar
960 try:
961 self.cmd_path = get_bin_path('tar')
962 except ValueError:
963 return False, "Unable to find required 'gtar' or 'tar' binary in the path"
964
965 self.tar_type = self._get_tar_type()
966
967 if self.tar_type != 'gnu':
968 return False, 'Command "%s" detected as tar type %s. GNU tar required.' % (self.cmd_path, self.tar_type)
969
970 try:
971 if self.files_in_archive:
972 return True, None
973 except UnarchiveError as e:
974 return False, 'Command "%s" could not handle archive: %s' % (self.cmd_path, to_native(e))
975 # Errors and no files in archive assume that we weren't able to
976 # properly unarchive it
977 return False, 'Command "%s" found no files in archive. Empty archive files are not supported.' % self.cmd_path
978
979
980 # Class to handle tar files that aren't compressed
981 class TarArchive(TgzArchive):
982 def __init__(self, src, b_dest, file_args, module):
983 super(TarArchive, self).__init__(src, b_dest, file_args, module)
984 # argument to tar
985 self.zipflag = ''
986
987
988 # Class to handle bzip2 compressed tar files
989 class TarBzipArchive(TgzArchive):
990 def __init__(self, src, b_dest, file_args, module):
991 super(TarBzipArchive, self).__init__(src, b_dest, file_args, module)
992 self.zipflag = '-j'
993
994
995 # Class to handle xz compressed tar files
996 class TarXzArchive(TgzArchive):
997 def __init__(self, src, b_dest, file_args, module):
998 super(TarXzArchive, self).__init__(src, b_dest, file_args, module)
999 self.zipflag = '-J'
1000
1001
1002 # Class to handle zstd compressed tar files
1003 class TarZstdArchive(TgzArchive):
1004 def __init__(self, src, b_dest, file_args, module):
1005 super(TarZstdArchive, self).__init__(src, b_dest, file_args, module)
1006 # GNU Tar supports the --use-compress-program option to
1007 # specify which executable to use for
1008 # compression/decompression.
1009 #
1010 # Note: some flavors of BSD tar support --zstd (e.g., FreeBSD
1011 # 12.2), but the TgzArchive class only supports GNU Tar.
1012 self.zipflag = '--use-compress-program=zstd'
1013
1014
1015 class ZipZArchive(ZipArchive):
1016 def __init__(self, src, b_dest, file_args, module):
1017 super(ZipZArchive, self).__init__(src, b_dest, file_args, module)
1018 # NOTE: adds 'l', which is default on most linux but not all implementations
1019 self.zipinfoflag = '-Zl'
1020 self.binaries = (
1021 ('unzip', 'cmd_path'),
1022 ('unzip', 'zipinfo_cmd_path'),
1023 )
1024
1025 def can_handle_archive(self):
1026 unzip_available, error_msg = super(ZipZArchive, self).can_handle_archive()
1027
1028 if not unzip_available:
1029 return unzip_available, error_msg
1030
1031 # Ensure unzip -Z is available before we use it in is_unarchive
1032 cmd = [self.zipinfo_cmd_path, self.zipinfoflag]
1033 rc, out, err = self.module.run_command(cmd)
1034 if 'zipinfo' in out.lower():
1035 return True, None
1036 return False, 'Command "unzip -Z" could not handle archive: %s' % err
1037
1038
1039 # try handlers in order and return the one that works or bail if none work
1040 def pick_handler(src, dest, file_args, module):
1041 handlers = [ZipArchive, ZipZArchive, TgzArchive, TarArchive, TarBzipArchive, TarXzArchive, TarZstdArchive]
1042 reasons = set()
1043 for handler in handlers:
1044 obj = handler(src, dest, file_args, module)
1045 (can_handle, reason) = obj.can_handle_archive()
1046 if can_handle:
1047 return obj
1048 reasons.add(reason)
1049 reason_msg = '\n'.join(reasons)
1050 module.fail_json(msg='Failed to find handler for "%s". Make sure the required command to extract the file is installed.\n%s' % (src, reason_msg))
1051
1052
1053 def main():
1054 module = AnsibleModule(
1055 # not checking because of daisy chain to file module
1056 argument_spec=dict(
1057 src=dict(type='path', required=True),
1058 dest=dict(type='path', required=True),
1059 remote_src=dict(type='bool', default=False),
1060 creates=dict(type='path'),
1061 list_files=dict(type='bool', default=False),
1062 keep_newer=dict(type='bool', default=False),
1063 exclude=dict(type='list', elements='str', default=[]),
1064 include=dict(type='list', elements='str', default=[]),
1065 extra_opts=dict(type='list', elements='str', default=[]),
1066 validate_certs=dict(type='bool', default=True),
1067 io_buffer_size=dict(type='int', default=64 * 1024),
1068
1069 # Options that are for the action plugin, but ignored by the module itself.
1070 # We have them here so that the sanity tests pass without ignores, which
1071 # reduces the likelihood of further bugs added.
1072 copy=dict(type='bool', default=True),
1073 decrypt=dict(type='bool', default=True),
1074 ),
1075 add_file_common_args=True,
1076 # check-mode only works for zip files, we cover that later
1077 supports_check_mode=True,
1078 mutually_exclusive=[('include', 'exclude')],
1079 )
1080
1081 src = module.params['src']
1082 dest = module.params['dest']
1083 abs_dest = os.path.abspath(dest)
1084 b_dest = to_bytes(abs_dest, errors='surrogate_or_strict')
1085
1086 if not os.path.isabs(dest):
1087 module.warn("Relative destination path '{dest}' was resolved to absolute path '{abs_dest}'.".format(dest=dest, abs_dest=abs_dest))
1088
1089 remote_src = module.params['remote_src']
1090 file_args = module.load_file_common_arguments(module.params)
1091
1092 # did tar file arrive?
1093 if not os.path.exists(src):
1094 if not remote_src:
1095 module.fail_json(msg="Source '%s' failed to transfer" % src)
1096 # If remote_src=true, and src= contains ://, try and download the file to a temp directory.
1097 elif '://' in src:
1098 src = fetch_file(module, src)
1099 else:
1100 module.fail_json(msg="Source '%s' does not exist" % src)
1101 if not os.access(src, os.R_OK):
1102 module.fail_json(msg="Source '%s' not readable" % src)
1103
1104 # ensure src is an absolute path before picking handlers
1105 src = os.path.abspath(src)
1106
1107 # skip working with 0 size archives
1108 try:
1109 if os.path.getsize(src) == 0:
1110 module.fail_json(msg="Invalid archive '%s', the file is 0 bytes" % src)
1111 except Exception as e:
1112 module.fail_json(msg="Source '%s' not readable, %s" % (src, to_native(e)))
1113
1114 # is dest OK to receive tar file?
1115 if not os.path.isdir(b_dest):
1116 module.fail_json(msg="Destination '%s' is not a directory" % dest)
1117
1118 handler = pick_handler(src, b_dest, file_args, module)
1119
1120 res_args = dict(handler=handler.__class__.__name__, dest=dest, src=src)
1121
1122 # do we need to do unpack?
1123 check_results = handler.is_unarchived()
1124
1125 # DEBUG
1126 # res_args['check_results'] = check_results
1127
1128 if module.check_mode:
1129 res_args['changed'] = not check_results['unarchived']
1130 elif check_results['unarchived']:
1131 res_args['changed'] = False
1132 else:
1133 # do the unpack
1134 try:
1135 res_args['extract_results'] = handler.unarchive()
1136 if res_args['extract_results']['rc'] != 0:
1137 module.fail_json(msg="failed to unpack %s to %s" % (src, dest), **res_args)
1138 except OSError as ex:
1139 module.fail_json(f"Failed to unpack {src!r} to {dest!r}.", exception=ex, **res_args)
1140 else:
1141 res_args['changed'] = True
1142
1143 # Get diff if required
1144 if check_results.get('diff', False):
1145 res_args['diff'] = {'prepared': check_results['diff']}
1146
1147 # Run only if we found differences (idempotence) or diff was missing
1148 if res_args.get('diff', True) and not module.check_mode:
1149 # do we need to change perms?
1150 top_folders = []
1151 for filename in handler.files_in_archive:
1152 file_args['path'] = os.path.join(b_dest, to_bytes(filename, errors='surrogate_or_strict'))
1153
1154 try:
1155 res_args['changed'] = module.set_fs_attributes_if_different(file_args, res_args['changed'], expand=False)
1156 except OSError as ex:
1157 module.fail_json("Unexpected error when accessing exploded file.", exception=ex, **res_args)
1158
1159 if '/' in filename:
1160 top_folder_path = filename.split('/')[0]
1161 if top_folder_path not in top_folders:
1162 top_folders.append(top_folder_path)
1163
1164 # make sure top folders have the right permissions
1165 # https://github.com/ansible/ansible/issues/35426
1166 if top_folders:
1167 for f in top_folders:
1168 file_args['path'] = "%s/%s" % (dest, f)
1169 try:
1170 res_args['changed'] = module.set_fs_attributes_if_different(file_args, res_args['changed'], expand=False)
1171 except OSError as ex:
1172 module.fail_json("Unexpected error when accessing exploded file.", exception=ex, **res_args)
1173
1174 if module.params['list_files']:
1175 res_args['files'] = handler.files_in_archive
1176
1177 module.exit_json(**res_args)
1178
1179
1180 if __name__ == '__main__':
1181 main()