cp: improve --preserve usage doc
[coreutils.git] / src / cp.c
blobede00cd12b69dab94955a01e2d9772948476de12
1 /* cp.c -- file copying (main routines)
2 Copyright (C) 1989-2023 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>.
17 Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. */
19 #include <config.h>
20 #include <stdio.h>
21 #include <sys/types.h>
22 #include <getopt.h>
23 #include <selinux/label.h>
25 #include "system.h"
26 #include "argmatch.h"
27 #include "backupfile.h"
28 #include "copy.h"
29 #include "cp-hash.h"
30 #include "die.h"
31 #include "error.h"
32 #include "filenamecat.h"
33 #include "ignore-value.h"
34 #include "quote.h"
35 #include "stat-time.h"
36 #include "targetdir.h"
37 #include "utimens.h"
38 #include "acl.h"
40 /* The official name of this program (e.g., no 'g' prefix). */
41 #define PROGRAM_NAME "cp"
43 #define AUTHORS \
44 proper_name ("Torbjorn Granlund"), \
45 proper_name ("David MacKenzie"), \
46 proper_name ("Jim Meyering")
48 /* Used by do_copy, make_dir_parents_private, and re_protect
49 to keep a list of leading directories whose protections
50 need to be fixed after copying. */
51 struct dir_attr
53 struct stat st;
54 bool restore_mode;
55 size_t slash_offset;
56 struct dir_attr *next;
59 /* For long options that have no equivalent short option, use a
60 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
61 enum
63 ATTRIBUTES_ONLY_OPTION = CHAR_MAX + 1,
64 COPY_CONTENTS_OPTION,
65 NO_PRESERVE_ATTRIBUTES_OPTION,
66 PARENTS_OPTION,
67 PRESERVE_ATTRIBUTES_OPTION,
68 REFLINK_OPTION,
69 SPARSE_OPTION,
70 STRIP_TRAILING_SLASHES_OPTION,
71 UNLINK_DEST_BEFORE_OPENING
74 /* True if the kernel is SELinux enabled. */
75 static bool selinux_enabled;
77 /* If true, the command "cp x/e_file e_dir" uses "e_dir/x/e_file"
78 as its destination instead of the usual "e_dir/e_file." */
79 static bool parents_option = false;
81 /* Remove any trailing slashes from each SOURCE argument. */
82 static bool remove_trailing_slashes;
84 static char const *const sparse_type_string[] =
86 "never", "auto", "always", NULL
88 static enum Sparse_type const sparse_type[] =
90 SPARSE_NEVER, SPARSE_AUTO, SPARSE_ALWAYS
92 ARGMATCH_VERIFY (sparse_type_string, sparse_type);
94 static char const *const reflink_type_string[] =
96 "auto", "always", "never", NULL
98 static enum Reflink_type const reflink_type[] =
100 REFLINK_AUTO, REFLINK_ALWAYS, REFLINK_NEVER
102 ARGMATCH_VERIFY (reflink_type_string, reflink_type);
104 static struct option const long_opts[] =
106 {"archive", no_argument, NULL, 'a'},
107 {"attributes-only", no_argument, NULL, ATTRIBUTES_ONLY_OPTION},
108 {"backup", optional_argument, NULL, 'b'},
109 {"copy-contents", no_argument, NULL, COPY_CONTENTS_OPTION},
110 {"dereference", no_argument, NULL, 'L'},
111 {"force", no_argument, NULL, 'f'},
112 {"interactive", no_argument, NULL, 'i'},
113 {"link", no_argument, NULL, 'l'},
114 {"no-clobber", no_argument, NULL, 'n'},
115 {"no-dereference", no_argument, NULL, 'P'},
116 {"no-preserve", required_argument, NULL, NO_PRESERVE_ATTRIBUTES_OPTION},
117 {"no-target-directory", no_argument, NULL, 'T'},
118 {"one-file-system", no_argument, NULL, 'x'},
119 {"parents", no_argument, NULL, PARENTS_OPTION},
120 {"path", no_argument, NULL, PARENTS_OPTION}, /* Deprecated. */
121 {"preserve", optional_argument, NULL, PRESERVE_ATTRIBUTES_OPTION},
122 {"recursive", no_argument, NULL, 'R'},
123 {"remove-destination", no_argument, NULL, UNLINK_DEST_BEFORE_OPENING},
124 {"sparse", required_argument, NULL, SPARSE_OPTION},
125 {"reflink", optional_argument, NULL, REFLINK_OPTION},
126 {"strip-trailing-slashes", no_argument, NULL, STRIP_TRAILING_SLASHES_OPTION},
127 {"suffix", required_argument, NULL, 'S'},
128 {"symbolic-link", no_argument, NULL, 's'},
129 {"target-directory", required_argument, NULL, 't'},
130 {"update", no_argument, NULL, 'u'},
131 {"verbose", no_argument, NULL, 'v'},
132 {GETOPT_SELINUX_CONTEXT_OPTION_DECL},
133 {GETOPT_HELP_OPTION_DECL},
134 {GETOPT_VERSION_OPTION_DECL},
135 {NULL, 0, NULL, 0}
138 void
139 usage (int status)
141 if (status != EXIT_SUCCESS)
142 emit_try_help ();
143 else
145 printf (_("\
146 Usage: %s [OPTION]... [-T] SOURCE DEST\n\
147 or: %s [OPTION]... SOURCE... DIRECTORY\n\
148 or: %s [OPTION]... -t DIRECTORY SOURCE...\n\
150 program_name, program_name, program_name);
151 fputs (_("\
152 Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.\n\
153 "), stdout);
155 emit_mandatory_arg_note ();
157 fputs (_("\
158 -a, --archive same as -dR --preserve=all\n\
159 --attributes-only don't copy the file data, just the attributes\n\
160 --backup[=CONTROL] make a backup of each existing destination file\
162 -b like --backup but does not accept an argument\n\
163 --copy-contents copy contents of special files when recursive\n\
164 -d same as --no-dereference --preserve=links\n\
165 "), stdout);
166 fputs (_("\
167 -f, --force if an existing destination file cannot be\n\
168 opened, remove it and try again (this option\n\
169 is ignored when the -n option is also used)\n\
170 -i, --interactive prompt before overwrite (overrides a previous -n\
172 option)\n\
173 -H follow command-line symbolic links in SOURCE\n\
174 "), stdout);
175 fputs (_("\
176 -l, --link hard link files instead of copying\n\
177 -L, --dereference always follow symbolic links in SOURCE\n\
178 "), stdout);
179 fputs (_("\
180 -n, --no-clobber do not overwrite an existing file (overrides\n\
181 a previous -i option)\n\
182 -P, --no-dereference never follow symbolic links in SOURCE\n\
183 "), stdout);
184 fputs (_("\
185 -p same as --preserve=mode,ownership,timestamps\n\
186 --preserve[=ATTR_LIST] preserve the specified attributes\n\
187 "), stdout);
188 fputs (_("\
189 --no-preserve=ATTR_LIST don't preserve the specified attributes\n\
190 --parents use full source file name under DIRECTORY\n\
191 "), stdout);
192 fputs (_("\
193 -R, -r, --recursive copy directories recursively\n\
194 --reflink[=WHEN] control clone/CoW copies. See below\n\
195 --remove-destination remove each existing destination file before\n\
196 attempting to open it (contrast with --force)\
197 \n"), stdout);
198 fputs (_("\
199 --sparse=WHEN control creation of sparse files. See below\n\
200 --strip-trailing-slashes remove any trailing slashes from each SOURCE\n\
201 argument\n\
202 "), stdout);
203 fputs (_("\
204 -s, --symbolic-link make symbolic links instead of copying\n\
205 -S, --suffix=SUFFIX override the usual backup suffix\n\
206 -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY\n\
207 -T, --no-target-directory treat DEST as a normal file\n\
208 "), stdout);
209 fputs (_("\
210 -u, --update copy only when the SOURCE file is newer\n\
211 than the destination file or when the\n\
212 destination file is missing\n\
213 -v, --verbose explain what is being done\n\
214 -x, --one-file-system stay on this file system\n\
215 "), stdout);
216 fputs (_("\
217 -Z set SELinux security context of destination\n\
218 file to default type\n\
219 --context[=CTX] like -Z, or if CTX is specified then set the\n\
220 SELinux or SMACK security context to CTX\n\
221 "), stdout);
222 fputs (HELP_OPTION_DESCRIPTION, stdout);
223 fputs (VERSION_OPTION_DESCRIPTION, stdout);
224 fputs (_("\
226 ATTR_LIST is a comma-separated list of attributes. Attributes are 'mode' for\n\
227 permissions (including any ACL and xattr permissions), 'ownership' for user\n\
228 and group, 'timestamps' for file timestamps, 'links' for hard links, 'context'\n\
229 for security context, 'xattr' for extended attributes, and 'all' for all\n\
230 attributes.\n\
231 "), stdout);
232 fputs (_("\
234 By default, sparse SOURCE files are detected by a crude heuristic and the\n\
235 corresponding DEST file is made sparse as well. That is the behavior\n\
236 selected by --sparse=auto. Specify --sparse=always to create a sparse DEST\n\
237 file whenever the SOURCE file contains a long enough sequence of zero bytes.\n\
238 Use --sparse=never to inhibit creation of sparse files.\n\
239 "), stdout);
240 fputs (_("\
242 When --reflink[=always] is specified, perform a lightweight copy, where the\n\
243 data blocks are copied only when modified. If this is not possible the copy\n\
244 fails, or if --reflink=auto is specified, fall back to a standard copy.\n\
245 Use --reflink=never to ensure a standard copy is performed.\n\
246 "), stdout);
247 emit_backup_suffix_note ();
248 fputs (_("\
250 As a special case, cp makes a backup of SOURCE when the force and backup\n\
251 options are given and SOURCE and DEST are the same name for an existing,\n\
252 regular file.\n\
253 "), stdout);
254 emit_ancillary_info (PROGRAM_NAME);
256 exit (status);
259 /* Ensure that parents of CONST_DST_NAME aka DST_DIRFD+DST_RELNAME have the
260 correct protections, for the --parents option. This is done
261 after all copying has been completed, to allow permissions
262 that don't include user write/execute.
264 ATTR_LIST is a null-terminated linked list of structures that
265 indicates the end of the filename of each intermediate directory
266 in CONST_DST_NAME that may need to have its attributes changed.
267 The command 'cp --parents --preserve a/b/c d/e_dir' changes the
268 attributes of the directories d/e_dir/a and d/e_dir/a/b to match
269 the corresponding source directories regardless of whether they
270 existed before the 'cp' command was given.
272 Return true if the parent of CONST_DST_NAME and any intermediate
273 directories specified by ATTR_LIST have the proper permissions
274 when done. */
276 static bool
277 re_protect (char const *const_dst_name, int dst_dirfd, char const *dst_relname,
278 struct dir_attr *attr_list, const struct cp_options *x)
280 struct dir_attr *p;
281 char *dst_name; /* A copy of CONST_DST_NAME we can change. */
282 char *src_name; /* The source name in 'dst_name'. */
284 ASSIGN_STRDUPA (dst_name, const_dst_name);
285 src_name = dst_name + (dst_relname - const_dst_name);
287 for (p = attr_list; p; p = p->next)
289 dst_name[p->slash_offset] = '\0';
291 /* Adjust the times (and if possible, ownership) for the copy.
292 chown turns off set[ug]id bits for non-root,
293 so do the chmod last. */
295 if (x->preserve_timestamps)
297 struct timespec timespec[2];
299 timespec[0] = get_stat_atime (&p->st);
300 timespec[1] = get_stat_mtime (&p->st);
302 if (utimensat (dst_dirfd, src_name, timespec, 0))
304 error (0, errno, _("failed to preserve times for %s"),
305 quoteaf (dst_name));
306 return false;
310 if (x->preserve_ownership)
312 if (lchownat (dst_dirfd, src_name, p->st.st_uid, p->st.st_gid) != 0)
314 if (! chown_failure_ok (x))
316 error (0, errno, _("failed to preserve ownership for %s"),
317 quoteaf (dst_name));
318 return false;
320 /* Failing to preserve ownership is OK. Still, try to preserve
321 the group, but ignore the possible error. */
322 ignore_value (lchownat (dst_dirfd, src_name, -1, p->st.st_gid));
326 if (x->preserve_mode)
328 if (copy_acl (src_name, -1, dst_name, -1, p->st.st_mode) != 0)
329 return false;
331 else if (p->restore_mode)
333 if (lchmodat (dst_dirfd, src_name, p->st.st_mode) != 0)
335 error (0, errno, _("failed to preserve permissions for %s"),
336 quoteaf (dst_name));
337 return false;
341 dst_name[p->slash_offset] = '/';
343 return true;
346 /* Ensure that the parent directory of CONST_DIR exists, for
347 the --parents option.
349 SRC_OFFSET is the index in CONST_DIR (which is a destination
350 directory) of the beginning of the source directory name.
351 Create any leading directories that don't already exist.
352 DST_DIRFD is a file descriptor for the target directory.
353 If VERBOSE_FMT_STRING is nonzero, use it as a printf format
354 string for printing a message after successfully making a directory.
355 The format should take two string arguments: the names of the
356 source and destination directories.
357 Creates a linked list of attributes of intermediate directories,
358 *ATTR_LIST, for re_protect to use after calling copy.
359 Sets *NEW_DST if this function creates parent of CONST_DIR.
361 Return true if parent of CONST_DIR exists as a directory with the proper
362 permissions when done. */
364 /* FIXME: Synch this function with the one in ../lib/mkdir-p.c. */
366 static bool
367 make_dir_parents_private (char const *const_dir, size_t src_offset,
368 int dst_dirfd,
369 char const *verbose_fmt_string,
370 struct dir_attr **attr_list, bool *new_dst,
371 const struct cp_options *x)
373 struct stat stats;
374 char *dir; /* A copy of CONST_DIR we can change. */
375 char *src; /* Source name in DIR. */
376 char *dst_dir; /* Leading directory of DIR. */
377 idx_t dirlen = dir_len (const_dir);
379 *attr_list = NULL;
381 /* Succeed immediately if the parent of CONST_DIR must already exist,
382 as the target directory has already been checked. */
383 if (dirlen <= src_offset)
384 return true;
386 ASSIGN_STRDUPA (dir, const_dir);
388 src = dir + src_offset;
390 dst_dir = alloca (dirlen + 1);
391 memcpy (dst_dir, dir, dirlen);
392 dst_dir[dirlen] = '\0';
393 char const *dst_reldir = dst_dir + src_offset;
394 while (*dst_reldir == '/')
395 dst_reldir++;
397 /* XXX: If all dirs are present at the destination,
398 no permissions or security contexts will be updated. */
399 if (fstatat (dst_dirfd, dst_reldir, &stats, 0) != 0)
401 /* A parent of CONST_DIR does not exist.
402 Make all missing intermediate directories. */
403 char *slash;
405 slash = src;
406 while (*slash == '/')
407 slash++;
408 dst_reldir = slash;
410 while ((slash = strchr (slash, '/')))
412 struct dir_attr *new;
413 bool missing_dir;
415 *slash = '\0';
416 missing_dir = fstatat (dst_dirfd, dst_reldir, &stats, 0) != 0;
418 if (missing_dir || x->preserve_ownership || x->preserve_mode
419 || x->preserve_timestamps)
421 /* Add this directory to the list of directories whose
422 modes might need fixing later. */
423 struct stat src_st;
424 int src_errno = (stat (src, &src_st) != 0
425 ? errno
426 : S_ISDIR (src_st.st_mode)
428 : ENOTDIR);
429 if (src_errno)
431 error (0, src_errno, _("failed to get attributes of %s"),
432 quoteaf (src));
433 return false;
436 new = xmalloc (sizeof *new);
437 new->st = src_st;
438 new->slash_offset = slash - dir;
439 new->restore_mode = false;
440 new->next = *attr_list;
441 *attr_list = new;
444 /* If required set the default context for created dirs. */
445 if (! set_process_security_ctx (src, dir,
446 missing_dir ? new->st.st_mode : 0,
447 missing_dir, x))
448 return false;
450 if (missing_dir)
452 mode_t src_mode;
453 mode_t omitted_permissions;
454 mode_t mkdir_mode;
456 /* This component does not exist. We must set
457 *new_dst and new->st.st_mode inside this loop because,
458 for example, in the command 'cp --parents ../a/../b/c e_dir',
459 make_dir_parents_private creates only e_dir/../a if
460 ./b already exists. */
461 *new_dst = true;
462 src_mode = new->st.st_mode;
464 /* If the ownership or special mode bits might change,
465 omit some permissions at first, so unauthorized users
466 cannot nip in before the file is ready. */
467 omitted_permissions = (src_mode
468 & (x->preserve_ownership
469 ? S_IRWXG | S_IRWXO
470 : x->preserve_mode
471 ? S_IWGRP | S_IWOTH
472 : 0));
474 /* POSIX says mkdir's behavior is implementation-defined when
475 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
476 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
477 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
478 mkdir_mode = x->explicit_no_preserve_mode ? S_IRWXUGO : src_mode;
479 mkdir_mode &= CHMOD_MODE_BITS & ~omitted_permissions;
480 if (mkdirat (dst_dirfd, dst_reldir, mkdir_mode) != 0)
482 error (0, errno, _("cannot make directory %s"),
483 quoteaf (dir));
484 return false;
486 else
488 if (verbose_fmt_string != NULL)
489 printf (verbose_fmt_string, src, dir);
492 /* We need search and write permissions to the new directory
493 for writing the directory's contents. Check if these
494 permissions are there. */
496 if (fstatat (dst_dirfd, dst_reldir, &stats, AT_SYMLINK_NOFOLLOW))
498 error (0, errno, _("failed to get attributes of %s"),
499 quoteaf (dir));
500 return false;
504 if (! x->preserve_mode)
506 if (omitted_permissions & ~stats.st_mode)
507 omitted_permissions &= ~ cached_umask ();
508 if (omitted_permissions & ~stats.st_mode
509 || (stats.st_mode & S_IRWXU) != S_IRWXU)
511 new->st.st_mode = stats.st_mode | omitted_permissions;
512 new->restore_mode = true;
516 mode_t accessible = stats.st_mode | S_IRWXU;
517 if (stats.st_mode != accessible)
519 /* Make the new directory searchable and writable.
520 The original permissions will be restored later. */
522 if (lchmodat (dst_dirfd, dst_reldir, accessible) != 0)
524 error (0, errno, _("setting permissions for %s"),
525 quoteaf (dir));
526 return false;
530 else if (!S_ISDIR (stats.st_mode))
532 error (0, 0, _("%s exists but is not a directory"),
533 quoteaf (dir));
534 return false;
536 else
537 *new_dst = false;
539 /* For existing dirs, set the security context as per that already
540 set for the process global context. */
541 if (! *new_dst
542 && (x->set_security_context || x->preserve_security_context))
544 if (! set_file_security_ctx (dir, false, x)
545 && x->require_preserve_context)
546 return false;
549 *slash++ = '/';
551 /* Avoid unnecessary calls to 'stat' when given
552 file names containing multiple adjacent slashes. */
553 while (*slash == '/')
554 slash++;
558 /* We get here if the parent of DIR already exists. */
560 else if (!S_ISDIR (stats.st_mode))
562 error (0, 0, _("%s exists but is not a directory"), quoteaf (dst_dir));
563 return false;
565 else
567 *new_dst = false;
569 return true;
572 /* Scan the arguments, and copy each by calling copy.
573 Return true if successful. */
575 static bool
576 do_copy (int n_files, char **file, char const *target_directory,
577 bool no_target_directory, struct cp_options *x)
579 struct stat sb;
580 bool new_dst = false;
581 bool ok = true;
583 if (n_files <= !target_directory)
585 if (n_files <= 0)
586 error (0, 0, _("missing file operand"));
587 else
588 error (0, 0, _("missing destination file operand after %s"),
589 quoteaf (file[0]));
590 usage (EXIT_FAILURE);
593 sb.st_mode = 0;
594 int target_dirfd = AT_FDCWD;
595 if (no_target_directory)
597 if (target_directory)
598 die (EXIT_FAILURE, 0,
599 _("cannot combine --target-directory (-t) "
600 "and --no-target-directory (-T)"));
601 if (2 < n_files)
603 error (0, 0, _("extra operand %s"), quoteaf (file[2]));
604 usage (EXIT_FAILURE);
607 else if (target_directory)
609 target_dirfd = target_directory_operand (target_directory, &sb);
610 if (! target_dirfd_valid (target_dirfd))
611 die (EXIT_FAILURE, errno, _("target directory %s"),
612 quoteaf (target_directory));
614 else
616 char const *lastfile = file[n_files - 1];
617 int fd = target_directory_operand (lastfile, &sb);
618 if (target_dirfd_valid (fd))
620 target_dirfd = fd;
621 target_directory = lastfile;
622 n_files--;
624 else
626 int err = errno;
627 if (err == ENOENT)
628 new_dst = true;
630 /* The last operand LASTFILE cannot be opened as a directory.
631 If there are more than two operands, report an error.
633 Also, report an error if LASTFILE is known to be a directory
634 even though it could not be opened, which can happen if
635 opening failed with EACCES on a platform lacking O_PATH.
636 In this case use stat to test whether LASTFILE is a
637 directory, in case opening a non-directory with (O_SEARCH
638 | O_DIRECTORY) failed with EACCES not ENOTDIR. */
639 if (2 < n_files
640 || (O_PATHSEARCH == O_SEARCH && err == EACCES
641 && (sb.st_mode || stat (lastfile, &sb) == 0)
642 && S_ISDIR (sb.st_mode)))
643 die (EXIT_FAILURE, err, _("target %s"), quoteaf (lastfile));
647 if (target_directory)
649 /* cp file1...filen edir
650 Copy the files 'file1' through 'filen'
651 to the existing directory 'edir'. */
653 /* Initialize these hash tables only if we'll need them.
654 The problems they're used to detect can arise only if
655 there are two or more files to copy. */
656 if (2 <= n_files)
658 dest_info_init (x);
659 src_info_init (x);
662 for (int i = 0; i < n_files; i++)
664 char *dst_name;
665 bool parent_exists = true; /* True if dir_name (dst_name) exists. */
666 struct dir_attr *attr_list;
667 char *arg_in_concat = NULL;
668 char *arg = file[i];
670 /* Trailing slashes are meaningful (i.e., maybe worth preserving)
671 only in the source file names. */
672 if (remove_trailing_slashes)
673 strip_trailing_slashes (arg);
675 if (parents_option)
677 char *arg_no_trailing_slash;
679 /* Use 'arg' without trailing slashes in constructing destination
680 file names. Otherwise, we can end up trying to create a
681 directory using a name with trailing slash, which fails on
682 NetBSD 1.[34] systems. */
683 ASSIGN_STRDUPA (arg_no_trailing_slash, arg);
684 strip_trailing_slashes (arg_no_trailing_slash);
686 /* Append all of 'arg' (minus any trailing slash) to 'dest'. */
687 dst_name = file_name_concat (target_directory,
688 arg_no_trailing_slash,
689 &arg_in_concat);
691 /* For --parents, we have to make sure that the directory
692 dir_name (dst_name) exists. We may have to create a few
693 leading directories. */
694 parent_exists =
695 (make_dir_parents_private
696 (dst_name, arg_in_concat - dst_name, target_dirfd,
697 (x->verbose ? "%s -> %s\n" : NULL),
698 &attr_list, &new_dst, x));
700 while (*arg_in_concat == '/')
701 arg_in_concat++;
703 else
705 char *arg_base;
706 /* Append the last component of 'arg' to 'target_directory'. */
707 ASSIGN_STRDUPA (arg_base, last_component (arg));
708 strip_trailing_slashes (arg_base);
709 /* For 'cp -R source/.. dest', don't copy into 'dest/..'. */
710 arg_base += STREQ (arg_base, "..");
711 dst_name = file_name_concat (target_directory, arg_base,
712 &arg_in_concat);
715 if (!parent_exists)
717 /* make_dir_parents_private failed, so don't even
718 attempt the copy. */
719 ok = false;
721 else
723 bool copy_into_self;
724 ok &= copy (arg, dst_name, target_dirfd, arg_in_concat,
725 new_dst, x, &copy_into_self, NULL);
727 if (parents_option)
728 ok &= re_protect (dst_name, target_dirfd, arg_in_concat,
729 attr_list, x);
732 if (parents_option)
734 while (attr_list)
736 struct dir_attr *p = attr_list;
737 attr_list = attr_list->next;
738 free (p);
742 free (dst_name);
745 else /* !target_directory */
747 char const *source = file[0];
748 char const *dest = file[1];
749 bool unused;
751 if (parents_option)
753 error (0, 0,
754 _("with --parents, the destination must be a directory"));
755 usage (EXIT_FAILURE);
758 /* When the force and backup options have been specified and
759 the source and destination are the same name for an existing
760 regular file, convert the user's command, e.g.,
761 'cp --force --backup foo foo' to 'cp --force foo fooSUFFIX'
762 where SUFFIX is determined by any version control options used. */
764 if (x->unlink_dest_after_failed_open
765 && x->backup_type != no_backups
766 && STREQ (source, dest)
767 && !new_dst
768 && (sb.st_mode != 0 || stat (dest, &sb) == 0) && S_ISREG (sb.st_mode))
770 static struct cp_options x_tmp;
772 dest = find_backup_file_name (AT_FDCWD, dest, x->backup_type);
773 /* Set x->backup_type to 'no_backups' so that the normal backup
774 mechanism is not used when performing the actual copy.
775 backup_type must be set to 'no_backups' only *after* the above
776 call to find_backup_file_name -- that function uses
777 backup_type to determine the suffix it applies. */
778 x_tmp = *x;
779 x_tmp.backup_type = no_backups;
780 x = &x_tmp;
783 ok = copy (source, dest, AT_FDCWD, dest, -new_dst, x, &unused, NULL);
786 return ok;
789 static void
790 cp_option_init (struct cp_options *x)
792 cp_options_default (x);
793 x->copy_as_regular = true;
794 x->dereference = DEREF_UNDEFINED;
795 x->unlink_dest_before_opening = false;
796 x->unlink_dest_after_failed_open = false;
797 x->hard_link = false;
798 x->interactive = I_UNSPECIFIED;
799 x->move_mode = false;
800 x->install_mode = false;
801 x->one_file_system = false;
802 x->reflink_mode = REFLINK_AUTO;
804 x->preserve_ownership = false;
805 x->preserve_links = false;
806 x->preserve_mode = false;
807 x->preserve_timestamps = false;
808 x->explicit_no_preserve_mode = false;
809 x->preserve_security_context = false; /* -a or --preserve=context. */
810 x->require_preserve_context = false; /* --preserve=context. */
811 x->set_security_context = NULL; /* -Z, set sys default context. */
812 x->preserve_xattr = false;
813 x->reduce_diagnostics = false;
814 x->require_preserve_xattr = false;
816 x->data_copy_required = true;
817 x->require_preserve = false;
818 x->recursive = false;
819 x->sparse_mode = SPARSE_AUTO;
820 x->symbolic_link = false;
821 x->set_mode = false;
822 x->mode = 0;
824 /* Not used. */
825 x->stdin_tty = false;
827 x->update = false;
828 x->verbose = false;
830 /* By default, refuse to open a dangling destination symlink, because
831 in general one cannot do that safely, give the current semantics of
832 open's O_EXCL flag, (which POSIX doesn't even allow cp to use, btw).
833 But POSIX requires it. */
834 x->open_dangling_dest_symlink = getenv ("POSIXLY_CORRECT") != NULL;
836 x->dest_info = NULL;
837 x->src_info = NULL;
840 /* Given a string, ARG, containing a comma-separated list of arguments
841 to the --preserve option, set the appropriate fields of X to ON_OFF. */
842 static void
843 decode_preserve_arg (char const *arg, struct cp_options *x, bool on_off)
845 enum File_attribute
847 PRESERVE_MODE,
848 PRESERVE_TIMESTAMPS,
849 PRESERVE_OWNERSHIP,
850 PRESERVE_LINK,
851 PRESERVE_CONTEXT,
852 PRESERVE_XATTR,
853 PRESERVE_ALL
855 static enum File_attribute const preserve_vals[] =
857 PRESERVE_MODE, PRESERVE_TIMESTAMPS,
858 PRESERVE_OWNERSHIP, PRESERVE_LINK, PRESERVE_CONTEXT, PRESERVE_XATTR,
859 PRESERVE_ALL
861 /* Valid arguments to the '--preserve' option. */
862 static char const *const preserve_args[] =
864 "mode", "timestamps",
865 "ownership", "links", "context", "xattr", "all", NULL
867 ARGMATCH_VERIFY (preserve_args, preserve_vals);
869 char *arg_writable = xstrdup (arg);
870 char *s = arg_writable;
873 /* find next comma */
874 char *comma = strchr (s, ',');
875 enum File_attribute val;
877 /* If we found a comma, put a NUL in its place and advance. */
878 if (comma)
879 *comma++ = 0;
881 /* process S. */
882 val = XARGMATCH (on_off ? "--preserve" : "--no-preserve",
883 s, preserve_args, preserve_vals);
884 switch (val)
886 case PRESERVE_MODE:
887 x->preserve_mode = on_off;
888 x->explicit_no_preserve_mode = !on_off;
889 break;
891 case PRESERVE_TIMESTAMPS:
892 x->preserve_timestamps = on_off;
893 break;
895 case PRESERVE_OWNERSHIP:
896 x->preserve_ownership = on_off;
897 break;
899 case PRESERVE_LINK:
900 x->preserve_links = on_off;
901 break;
903 case PRESERVE_CONTEXT:
904 x->require_preserve_context = on_off;
905 x->preserve_security_context = on_off;
906 break;
908 case PRESERVE_XATTR:
909 x->preserve_xattr = on_off;
910 x->require_preserve_xattr = on_off;
911 break;
913 case PRESERVE_ALL:
914 x->preserve_mode = on_off;
915 x->preserve_timestamps = on_off;
916 x->preserve_ownership = on_off;
917 x->preserve_links = on_off;
918 x->explicit_no_preserve_mode = !on_off;
919 if (selinux_enabled)
920 x->preserve_security_context = on_off;
921 x->preserve_xattr = on_off;
922 break;
924 default:
925 abort ();
927 s = comma;
929 while (s);
931 free (arg_writable);
935 main (int argc, char **argv)
937 int c;
938 bool ok;
939 bool make_backups = false;
940 char const *backup_suffix = NULL;
941 char *version_control_string = NULL;
942 struct cp_options x;
943 bool copy_contents = false;
944 char *target_directory = NULL;
945 bool no_target_directory = false;
946 char const *scontext = NULL;
948 initialize_main (&argc, &argv);
949 set_program_name (argv[0]);
950 setlocale (LC_ALL, "");
951 bindtextdomain (PACKAGE, LOCALEDIR);
952 textdomain (PACKAGE);
954 atexit (close_stdin);
956 selinux_enabled = (0 < is_selinux_enabled ());
957 cp_option_init (&x);
959 while ((c = getopt_long (argc, argv, "abdfHilLnprst:uvxPRS:TZ",
960 long_opts, NULL))
961 != -1)
963 switch (c)
965 case SPARSE_OPTION:
966 x.sparse_mode = XARGMATCH ("--sparse", optarg,
967 sparse_type_string, sparse_type);
968 break;
970 case REFLINK_OPTION:
971 if (optarg == NULL)
972 x.reflink_mode = REFLINK_ALWAYS;
973 else
974 x.reflink_mode = XARGMATCH ("--reflink", optarg,
975 reflink_type_string, reflink_type);
976 break;
978 case 'a':
979 /* Like -dR --preserve=all with reduced failure diagnostics. */
980 x.dereference = DEREF_NEVER;
981 x.preserve_links = true;
982 x.preserve_ownership = true;
983 x.preserve_mode = true;
984 x.preserve_timestamps = true;
985 x.require_preserve = true;
986 if (selinux_enabled)
987 x.preserve_security_context = true;
988 x.preserve_xattr = true;
989 x.reduce_diagnostics = true;
990 x.recursive = true;
991 break;
993 case 'b':
994 make_backups = true;
995 if (optarg)
996 version_control_string = optarg;
997 break;
999 case ATTRIBUTES_ONLY_OPTION:
1000 x.data_copy_required = false;
1001 break;
1003 case COPY_CONTENTS_OPTION:
1004 copy_contents = true;
1005 break;
1007 case 'd':
1008 x.preserve_links = true;
1009 x.dereference = DEREF_NEVER;
1010 break;
1012 case 'f':
1013 x.unlink_dest_after_failed_open = true;
1014 break;
1016 case 'H':
1017 x.dereference = DEREF_COMMAND_LINE_ARGUMENTS;
1018 break;
1020 case 'i':
1021 x.interactive = I_ASK_USER;
1022 break;
1024 case 'l':
1025 x.hard_link = true;
1026 break;
1028 case 'L':
1029 x.dereference = DEREF_ALWAYS;
1030 break;
1032 case 'n':
1033 x.interactive = I_ALWAYS_NO;
1034 break;
1036 case 'P':
1037 x.dereference = DEREF_NEVER;
1038 break;
1040 case NO_PRESERVE_ATTRIBUTES_OPTION:
1041 decode_preserve_arg (optarg, &x, false);
1042 break;
1044 case PRESERVE_ATTRIBUTES_OPTION:
1045 if (optarg == NULL)
1047 /* Fall through to the case for 'p' below. */
1049 else
1051 decode_preserve_arg (optarg, &x, true);
1052 x.require_preserve = true;
1053 break;
1055 FALLTHROUGH;
1057 case 'p':
1058 x.preserve_ownership = true;
1059 x.preserve_mode = true;
1060 x.preserve_timestamps = true;
1061 x.require_preserve = true;
1062 break;
1064 case PARENTS_OPTION:
1065 parents_option = true;
1066 break;
1068 case 'r':
1069 case 'R':
1070 x.recursive = true;
1071 break;
1073 case UNLINK_DEST_BEFORE_OPENING:
1074 x.unlink_dest_before_opening = true;
1075 break;
1077 case STRIP_TRAILING_SLASHES_OPTION:
1078 remove_trailing_slashes = true;
1079 break;
1081 case 's':
1082 x.symbolic_link = true;
1083 break;
1085 case 't':
1086 if (target_directory)
1087 die (EXIT_FAILURE, 0,
1088 _("multiple target directories specified"));
1089 target_directory = optarg;
1090 break;
1092 case 'T':
1093 no_target_directory = true;
1094 break;
1096 case 'u':
1097 x.update = true;
1098 break;
1100 case 'v':
1101 x.verbose = true;
1102 break;
1104 case 'x':
1105 x.one_file_system = true;
1106 break;
1108 case 'Z':
1109 /* politely decline if we're not on a selinux-enabled kernel. */
1110 if (selinux_enabled)
1112 if (optarg)
1113 scontext = optarg;
1114 else
1116 x.set_security_context = selabel_open (SELABEL_CTX_FILE,
1117 NULL, 0);
1118 if (! x.set_security_context)
1119 error (0, errno, _("warning: ignoring --context"));
1122 else if (optarg)
1124 error (0, 0,
1125 _("warning: ignoring --context; "
1126 "it requires an SELinux-enabled kernel"));
1128 break;
1130 case 'S':
1131 make_backups = true;
1132 backup_suffix = optarg;
1133 break;
1135 case_GETOPT_HELP_CHAR;
1137 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1139 default:
1140 usage (EXIT_FAILURE);
1144 if (x.hard_link && x.symbolic_link)
1146 error (0, 0, _("cannot make both hard and symbolic links"));
1147 usage (EXIT_FAILURE);
1150 if (x.interactive == I_ALWAYS_NO)
1151 x.update = false;
1153 if (make_backups && x.interactive == I_ALWAYS_NO)
1155 error (0, 0,
1156 _("options --backup and --no-clobber are mutually exclusive"));
1157 usage (EXIT_FAILURE);
1160 if (x.reflink_mode == REFLINK_ALWAYS && x.sparse_mode != SPARSE_AUTO)
1162 error (0, 0, _("--reflink can be used only with --sparse=auto"));
1163 usage (EXIT_FAILURE);
1166 x.backup_type = (make_backups
1167 ? xget_version (_("backup type"),
1168 version_control_string)
1169 : no_backups);
1170 set_simple_backup_suffix (backup_suffix);
1172 if (x.dereference == DEREF_UNDEFINED)
1174 if (x.recursive && ! x.hard_link)
1175 /* This is compatible with FreeBSD. */
1176 x.dereference = DEREF_NEVER;
1177 else
1178 x.dereference = DEREF_ALWAYS;
1181 if (x.recursive)
1182 x.copy_as_regular = copy_contents;
1184 /* Ensure -Z overrides -a. */
1185 if ((x.set_security_context || scontext)
1186 && ! x.require_preserve_context)
1187 x.preserve_security_context = false;
1189 if (x.preserve_security_context && (x.set_security_context || scontext))
1190 die (EXIT_FAILURE, 0,
1191 _("cannot set target context and preserve it"));
1193 if (x.require_preserve_context && ! selinux_enabled)
1194 die (EXIT_FAILURE, 0,
1195 _("cannot preserve security context "
1196 "without an SELinux-enabled kernel"));
1198 /* FIXME: This handles new files. But what about existing files?
1199 I.e., if updating a tree, new files would have the specified context,
1200 but shouldn't existing files be updated for consistency like this?
1201 if (scontext && !restorecon (NULL, dst_path, 0))
1202 error (...);
1204 if (scontext && setfscreatecon (scontext) < 0)
1205 die (EXIT_FAILURE, errno,
1206 _("failed to set default file creation context to %s"),
1207 quote (scontext));
1209 #if !USE_XATTR
1210 if (x.require_preserve_xattr)
1211 die (EXIT_FAILURE, 0, _("cannot preserve extended attributes, cp is "
1212 "built without xattr support"));
1213 #endif
1215 /* Allocate space for remembering copied and created files. */
1217 hash_init ();
1219 ok = do_copy (argc - optind, argv + optind,
1220 target_directory, no_target_directory, &x);
1222 main_exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);