doc: remove colon from node name
[coreutils.git] / src / cp.c
blob707f3984a0846decf6b2b5720454dea391997a8a
1 /* cp.c -- file copying (main routines)
2 Copyright (C) 1989-2019 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/selinux.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 "utimens.h"
37 #include "acl.h"
39 #if ! HAVE_LCHOWN
40 # define lchown(name, uid, gid) chown (name, uid, gid)
41 #endif
43 /* The official name of this program (e.g., no 'g' prefix). */
44 #define PROGRAM_NAME "cp"
46 #define AUTHORS \
47 proper_name ("Torbjorn Granlund"), \
48 proper_name ("David MacKenzie"), \
49 proper_name ("Jim Meyering")
51 /* Used by do_copy, make_dir_parents_private, and re_protect
52 to keep a list of leading directories whose protections
53 need to be fixed after copying. */
54 struct dir_attr
56 struct stat st;
57 bool restore_mode;
58 size_t slash_offset;
59 struct dir_attr *next;
62 /* For long options that have no equivalent short option, use a
63 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
64 enum
66 ATTRIBUTES_ONLY_OPTION = CHAR_MAX + 1,
67 COPY_CONTENTS_OPTION,
68 NO_PRESERVE_ATTRIBUTES_OPTION,
69 PARENTS_OPTION,
70 PRESERVE_ATTRIBUTES_OPTION,
71 REFLINK_OPTION,
72 SPARSE_OPTION,
73 STRIP_TRAILING_SLASHES_OPTION,
74 UNLINK_DEST_BEFORE_OPENING
77 /* True if the kernel is SELinux enabled. */
78 static bool selinux_enabled;
80 /* If true, the command "cp x/e_file e_dir" uses "e_dir/x/e_file"
81 as its destination instead of the usual "e_dir/e_file." */
82 static bool parents_option = false;
84 /* Remove any trailing slashes from each SOURCE argument. */
85 static bool remove_trailing_slashes;
87 static char const *const sparse_type_string[] =
89 "never", "auto", "always", NULL
91 static enum Sparse_type const sparse_type[] =
93 SPARSE_NEVER, SPARSE_AUTO, SPARSE_ALWAYS
95 ARGMATCH_VERIFY (sparse_type_string, sparse_type);
97 static char const *const reflink_type_string[] =
99 "auto", "always", "never", NULL
101 static enum Reflink_type const reflink_type[] =
103 REFLINK_AUTO, REFLINK_ALWAYS, REFLINK_NEVER
105 ARGMATCH_VERIFY (reflink_type_string, reflink_type);
107 static struct option const long_opts[] =
109 {"archive", no_argument, NULL, 'a'},
110 {"attributes-only", no_argument, NULL, ATTRIBUTES_ONLY_OPTION},
111 {"backup", optional_argument, NULL, 'b'},
112 {"copy-contents", no_argument, NULL, COPY_CONTENTS_OPTION},
113 {"dereference", no_argument, NULL, 'L'},
114 {"force", no_argument, NULL, 'f'},
115 {"interactive", no_argument, NULL, 'i'},
116 {"link", no_argument, NULL, 'l'},
117 {"no-clobber", no_argument, NULL, 'n'},
118 {"no-dereference", no_argument, NULL, 'P'},
119 {"no-preserve", required_argument, NULL, NO_PRESERVE_ATTRIBUTES_OPTION},
120 {"no-target-directory", no_argument, NULL, 'T'},
121 {"one-file-system", no_argument, NULL, 'x'},
122 {"parents", no_argument, NULL, PARENTS_OPTION},
123 {"path", no_argument, NULL, PARENTS_OPTION}, /* Deprecated. */
124 {"preserve", optional_argument, NULL, PRESERVE_ATTRIBUTES_OPTION},
125 {"recursive", no_argument, NULL, 'R'},
126 {"remove-destination", no_argument, NULL, UNLINK_DEST_BEFORE_OPENING},
127 {"sparse", required_argument, NULL, SPARSE_OPTION},
128 {"reflink", optional_argument, NULL, REFLINK_OPTION},
129 {"strip-trailing-slashes", no_argument, NULL, STRIP_TRAILING_SLASHES_OPTION},
130 {"suffix", required_argument, NULL, 'S'},
131 {"symbolic-link", no_argument, NULL, 's'},
132 {"target-directory", required_argument, NULL, 't'},
133 {"update", no_argument, NULL, 'u'},
134 {"verbose", no_argument, NULL, 'v'},
135 {GETOPT_SELINUX_CONTEXT_OPTION_DECL},
136 {GETOPT_HELP_OPTION_DECL},
137 {GETOPT_VERSION_OPTION_DECL},
138 {NULL, 0, NULL, 0}
141 void
142 usage (int status)
144 if (status != EXIT_SUCCESS)
145 emit_try_help ();
146 else
148 printf (_("\
149 Usage: %s [OPTION]... [-T] SOURCE DEST\n\
150 or: %s [OPTION]... SOURCE... DIRECTORY\n\
151 or: %s [OPTION]... -t DIRECTORY SOURCE...\n\
153 program_name, program_name, program_name);
154 fputs (_("\
155 Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.\n\
156 "), stdout);
158 emit_mandatory_arg_note ();
160 fputs (_("\
161 -a, --archive same as -dR --preserve=all\n\
162 --attributes-only don't copy the file data, just the attributes\n\
163 --backup[=CONTROL] make a backup of each existing destination file\
165 -b like --backup but does not accept an argument\n\
166 --copy-contents copy contents of special files when recursive\n\
167 -d same as --no-dereference --preserve=links\n\
168 "), stdout);
169 fputs (_("\
170 -f, --force if an existing destination file cannot be\n\
171 opened, remove it and try again (this option\n\
172 is ignored when the -n option is also used)\n\
173 -i, --interactive prompt before overwrite (overrides a previous -n\
175 option)\n\
176 -H follow command-line symbolic links in SOURCE\n\
177 "), stdout);
178 fputs (_("\
179 -l, --link hard link files instead of copying\n\
180 -L, --dereference always follow symbolic links in SOURCE\n\
181 "), stdout);
182 fputs (_("\
183 -n, --no-clobber do not overwrite an existing file (overrides\n\
184 a previous -i option)\n\
185 -P, --no-dereference never follow symbolic links in SOURCE\n\
186 "), stdout);
187 fputs (_("\
188 -p same as --preserve=mode,ownership,timestamps\n\
189 --preserve[=ATTR_LIST] preserve the specified attributes (default:\n\
190 mode,ownership,timestamps), if possible\n\
191 additional attributes: context, links, xattr,\
193 all\n\
194 "), stdout);
195 fputs (_("\
196 --no-preserve=ATTR_LIST don't preserve the specified attributes\n\
197 --parents use full source file name under DIRECTORY\n\
198 "), stdout);
199 fputs (_("\
200 -R, -r, --recursive copy directories recursively\n\
201 --reflink[=WHEN] control clone/CoW copies. See below\n\
202 --remove-destination remove each existing destination file before\n\
203 attempting to open it (contrast with --force)\
204 \n"), stdout);
205 fputs (_("\
206 --sparse=WHEN control creation of sparse files. See below\n\
207 --strip-trailing-slashes remove any trailing slashes from each SOURCE\n\
208 argument\n\
209 "), stdout);
210 fputs (_("\
211 -s, --symbolic-link make symbolic links instead of copying\n\
212 -S, --suffix=SUFFIX override the usual backup suffix\n\
213 -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY\n\
214 -T, --no-target-directory treat DEST as a normal file\n\
215 "), stdout);
216 fputs (_("\
217 -u, --update copy only when the SOURCE file is newer\n\
218 than the destination file or when the\n\
219 destination file is missing\n\
220 -v, --verbose explain what is being done\n\
221 -x, --one-file-system stay on this file system\n\
222 "), stdout);
223 fputs (_("\
224 -Z set SELinux security context of destination\n\
225 file to default type\n\
226 --context[=CTX] like -Z, or if CTX is specified then set the\n\
227 SELinux or SMACK security context to CTX\n\
228 "), stdout);
229 fputs (HELP_OPTION_DESCRIPTION, stdout);
230 fputs (VERSION_OPTION_DESCRIPTION, stdout);
231 fputs (_("\
233 By default, sparse SOURCE files are detected by a crude heuristic and the\n\
234 corresponding DEST file is made sparse as well. That is the behavior\n\
235 selected by --sparse=auto. Specify --sparse=always to create a sparse DEST\n\
236 file whenever the SOURCE file contains a long enough sequence of zero bytes.\n\
237 Use --sparse=never to inhibit creation of sparse files.\n\
238 "), stdout);
239 fputs (_("\
241 When --reflink[=always] is specified, perform a lightweight copy, where the\n\
242 data blocks are copied only when modified. If this is not possible the copy\n\
243 fails, or if --reflink=auto is specified, fall back to a standard copy.\n\
244 Use --reflink=never to ensure a standard copy is performed.\n\
245 "), stdout);
246 emit_backup_suffix_note ();
247 fputs (_("\
249 As a special case, cp makes a backup of SOURCE when the force and backup\n\
250 options are given and SOURCE and DEST are the same name for an existing,\n\
251 regular file.\n\
252 "), stdout);
253 emit_ancillary_info (PROGRAM_NAME);
255 exit (status);
258 /* Ensure that the parent directories of CONST_DST_NAME have the
259 correct protections, for the --parents option. This is done
260 after all copying has been completed, to allow permissions
261 that don't include user write/execute.
263 SRC_OFFSET is the index in CONST_DST_NAME of the beginning of the
264 source directory name.
266 ATTR_LIST is a null-terminated linked list of structures that
267 indicates the end of the filename of each intermediate directory
268 in CONST_DST_NAME that may need to have its attributes changed.
269 The command 'cp --parents --preserve a/b/c d/e_dir' changes the
270 attributes of the directories d/e_dir/a and d/e_dir/a/b to match
271 the corresponding source directories regardless of whether they
272 existed before the 'cp' command was given.
274 Return true if the parent of CONST_DST_NAME and any intermediate
275 directories specified by ATTR_LIST have the proper permissions
276 when done. */
278 static bool
279 re_protect (char const *const_dst_name, size_t src_offset,
280 struct dir_attr *attr_list, const struct cp_options *x)
282 struct dir_attr *p;
283 char *dst_name; /* A copy of CONST_DST_NAME we can change. */
284 char *src_name; /* The source name in 'dst_name'. */
286 ASSIGN_STRDUPA (dst_name, const_dst_name);
287 src_name = dst_name + src_offset;
289 for (p = attr_list; p; p = p->next)
291 dst_name[p->slash_offset] = '\0';
293 /* Adjust the times (and if possible, ownership) for the copy.
294 chown turns off set[ug]id bits for non-root,
295 so do the chmod last. */
297 if (x->preserve_timestamps)
299 struct timespec timespec[2];
301 timespec[0] = get_stat_atime (&p->st);
302 timespec[1] = get_stat_mtime (&p->st);
304 if (utimens (dst_name, timespec))
306 error (0, errno, _("failed to preserve times for %s"),
307 quoteaf (dst_name));
308 return false;
312 if (x->preserve_ownership)
314 if (lchown (dst_name, p->st.st_uid, p->st.st_gid) != 0)
316 if (! chown_failure_ok (x))
318 error (0, errno, _("failed to preserve ownership for %s"),
319 quoteaf (dst_name));
320 return false;
322 /* Failing to preserve ownership is OK. Still, try to preserve
323 the group, but ignore the possible error. */
324 ignore_value (lchown (dst_name, -1, p->st.st_gid));
328 if (x->preserve_mode)
330 if (copy_acl (src_name, -1, dst_name, -1, p->st.st_mode) != 0)
331 return false;
333 else if (p->restore_mode)
335 if (lchmod (dst_name, p->st.st_mode) != 0)
337 error (0, errno, _("failed to preserve permissions for %s"),
338 quoteaf (dst_name));
339 return false;
343 dst_name[p->slash_offset] = '/';
345 return true;
348 /* Ensure that the parent directory of CONST_DIR exists, for
349 the --parents option.
351 SRC_OFFSET is the index in CONST_DIR (which is a destination
352 directory) of the beginning of the source directory name.
353 Create any leading directories that don't already exist.
354 If VERBOSE_FMT_STRING is nonzero, use it as a printf format
355 string for printing a message after successfully making a directory.
356 The format should take two string arguments: the names of the
357 source and destination directories.
358 Creates a linked list of attributes of intermediate directories,
359 *ATTR_LIST, for re_protect to use after calling copy.
360 Sets *NEW_DST if this function creates parent of CONST_DIR.
362 Return true if parent of CONST_DIR exists as a directory with the proper
363 permissions when done. */
365 /* FIXME: Synch this function with the one in ../lib/mkdir-p.c. */
367 static bool
368 make_dir_parents_private (char const *const_dir, size_t src_offset,
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 size_t dirlen; /* Length of DIR. */
379 ASSIGN_STRDUPA (dir, const_dir);
381 src = dir + src_offset;
383 dirlen = dir_len (dir);
384 dst_dir = alloca (dirlen + 1);
385 memcpy (dst_dir, dir, dirlen);
386 dst_dir[dirlen] = '\0';
388 *attr_list = NULL;
390 /* XXX: If all dirs are present at the destination,
391 no permissions or security contexts will be updated. */
392 if (stat (dst_dir, &stats) != 0)
394 /* A parent of CONST_DIR does not exist.
395 Make all missing intermediate directories. */
396 char *slash;
398 slash = src;
399 while (*slash == '/')
400 slash++;
401 while ((slash = strchr (slash, '/')))
403 struct dir_attr *new IF_LINT ( = NULL);
404 bool missing_dir;
406 *slash = '\0';
407 missing_dir = (stat (dir, &stats) != 0);
409 if (missing_dir || x->preserve_ownership || x->preserve_mode
410 || x->preserve_timestamps)
412 /* Add this directory to the list of directories whose
413 modes might need fixing later. */
414 struct stat src_st;
415 int src_errno = (stat (src, &src_st) != 0
416 ? errno
417 : S_ISDIR (src_st.st_mode)
419 : ENOTDIR);
420 if (src_errno)
422 error (0, src_errno, _("failed to get attributes of %s"),
423 quoteaf (src));
424 return false;
427 new = xmalloc (sizeof *new);
428 new->st = src_st;
429 new->slash_offset = slash - dir;
430 new->restore_mode = false;
431 new->next = *attr_list;
432 *attr_list = new;
435 /* If required set the default context for created dirs. */
436 if (! set_process_security_ctx (src, dir,
437 missing_dir ? new->st.st_mode : 0,
438 missing_dir, x))
439 return false;
441 if (missing_dir)
443 mode_t src_mode;
444 mode_t omitted_permissions;
445 mode_t mkdir_mode;
447 /* This component does not exist. We must set
448 *new_dst and new->st.st_mode inside this loop because,
449 for example, in the command 'cp --parents ../a/../b/c e_dir',
450 make_dir_parents_private creates only e_dir/../a if
451 ./b already exists. */
452 *new_dst = true;
453 src_mode = new->st.st_mode;
455 /* If the ownership or special mode bits might change,
456 omit some permissions at first, so unauthorized users
457 cannot nip in before the file is ready. */
458 omitted_permissions = (src_mode
459 & (x->preserve_ownership
460 ? S_IRWXG | S_IRWXO
461 : x->preserve_mode
462 ? S_IWGRP | S_IWOTH
463 : 0));
465 /* POSIX says mkdir's behavior is implementation-defined when
466 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
467 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
468 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
469 mkdir_mode = x->explicit_no_preserve_mode ? S_IRWXUGO : src_mode;
470 mkdir_mode &= CHMOD_MODE_BITS & ~omitted_permissions;
471 if (mkdir (dir, mkdir_mode) != 0)
473 error (0, errno, _("cannot make directory %s"),
474 quoteaf (dir));
475 return false;
477 else
479 if (verbose_fmt_string != NULL)
480 printf (verbose_fmt_string, src, dir);
483 /* We need search and write permissions to the new directory
484 for writing the directory's contents. Check if these
485 permissions are there. */
487 if (lstat (dir, &stats))
489 error (0, errno, _("failed to get attributes of %s"),
490 quoteaf (dir));
491 return false;
495 if (! x->preserve_mode)
497 if (omitted_permissions & ~stats.st_mode)
498 omitted_permissions &= ~ cached_umask ();
499 if (omitted_permissions & ~stats.st_mode
500 || (stats.st_mode & S_IRWXU) != S_IRWXU)
502 new->st.st_mode = stats.st_mode | omitted_permissions;
503 new->restore_mode = true;
507 if ((stats.st_mode & S_IRWXU) != S_IRWXU)
509 /* Make the new directory searchable and writable.
510 The original permissions will be restored later. */
512 if (lchmod (dir, stats.st_mode | S_IRWXU) != 0)
514 error (0, errno, _("setting permissions for %s"),
515 quoteaf (dir));
516 return false;
520 else if (!S_ISDIR (stats.st_mode))
522 error (0, 0, _("%s exists but is not a directory"),
523 quoteaf (dir));
524 return false;
526 else
527 *new_dst = false;
529 /* For existing dirs, set the security context as per that already
530 set for the process global context. */
531 if (! *new_dst
532 && (x->set_security_context || x->preserve_security_context))
534 if (! set_file_security_ctx (dir, x->preserve_security_context,
535 false, x)
536 && x->require_preserve_context)
537 return false;
540 *slash++ = '/';
542 /* Avoid unnecessary calls to 'stat' when given
543 file names containing multiple adjacent slashes. */
544 while (*slash == '/')
545 slash++;
549 /* We get here if the parent of DIR already exists. */
551 else if (!S_ISDIR (stats.st_mode))
553 error (0, 0, _("%s exists but is not a directory"), quoteaf (dst_dir));
554 return false;
556 else
558 *new_dst = false;
560 return true;
563 /* FILE is the last operand of this command.
564 Return true if FILE is a directory.
566 Without -f, report an error and exit if FILE exists
567 but can't be accessed.
569 If the file exists and is accessible store the file's status into *ST.
570 Otherwise, set *NEW_DST. */
572 static bool
573 target_directory_operand (char const *file, struct stat *st,
574 bool *new_dst, bool forcing)
576 int err = (stat (file, st) == 0 ? 0 : errno);
577 bool is_a_dir = !err && S_ISDIR (st->st_mode);
578 if (err)
580 if (err == ENOENT)
581 *new_dst = true;
582 else if (forcing)
583 st->st_mode = 0; /* clear so we don't enter --backup case below. */
584 else
585 die (EXIT_FAILURE, err, _("failed to access %s"), quoteaf (file));
587 return is_a_dir;
590 /* Scan the arguments, and copy each by calling copy.
591 Return true if successful. */
593 static bool
594 do_copy (int n_files, char **file, const char *target_directory,
595 bool no_target_directory, struct cp_options *x)
597 struct stat sb;
598 bool new_dst = false;
599 bool ok = true;
600 bool forcing = x->unlink_dest_before_opening
601 || x->unlink_dest_after_failed_open;
603 if (n_files <= !target_directory)
605 if (n_files <= 0)
606 error (0, 0, _("missing file operand"));
607 else
608 error (0, 0, _("missing destination file operand after %s"),
609 quoteaf (file[0]));
610 usage (EXIT_FAILURE);
613 if (no_target_directory)
615 if (target_directory)
616 die (EXIT_FAILURE, 0,
617 _("cannot combine --target-directory (-t) "
618 "and --no-target-directory (-T)"));
619 if (2 < n_files)
621 error (0, 0, _("extra operand %s"), quoteaf (file[2]));
622 usage (EXIT_FAILURE);
624 /* Update NEW_DST and SB, which may be checked below. */
625 ignore_value (target_directory_operand (file[n_files -1], &sb, &new_dst,
626 forcing));
628 else if (!target_directory)
630 if (2 <= n_files
631 && target_directory_operand (file[n_files - 1], &sb, &new_dst,
632 forcing))
633 target_directory = file[--n_files];
634 else if (2 < n_files)
635 die (EXIT_FAILURE, 0, _("target %s is not a directory"),
636 quoteaf (file[n_files - 1]));
639 if (target_directory)
641 /* cp file1...filen edir
642 Copy the files 'file1' through 'filen'
643 to the existing directory 'edir'. */
645 /* Initialize these hash tables only if we'll need them.
646 The problems they're used to detect can arise only if
647 there are two or more files to copy. */
648 if (2 <= n_files)
650 dest_info_init (x);
651 src_info_init (x);
654 for (int i = 0; i < n_files; i++)
656 char *dst_name;
657 bool parent_exists = true; /* True if dir_name (dst_name) exists. */
658 struct dir_attr *attr_list;
659 char *arg_in_concat = NULL;
660 char *arg = file[i];
662 /* Trailing slashes are meaningful (i.e., maybe worth preserving)
663 only in the source file names. */
664 if (remove_trailing_slashes)
665 strip_trailing_slashes (arg);
667 if (parents_option)
669 char *arg_no_trailing_slash;
671 /* Use 'arg' without trailing slashes in constructing destination
672 file names. Otherwise, we can end up trying to create a
673 directory via 'mkdir ("dst/foo/"...', which is not portable.
674 It fails, due to the trailing slash, on at least
675 NetBSD 1.[34] systems. */
676 ASSIGN_STRDUPA (arg_no_trailing_slash, arg);
677 strip_trailing_slashes (arg_no_trailing_slash);
679 /* Append all of 'arg' (minus any trailing slash) to 'dest'. */
680 dst_name = file_name_concat (target_directory,
681 arg_no_trailing_slash,
682 &arg_in_concat);
684 /* For --parents, we have to make sure that the directory
685 dir_name (dst_name) exists. We may have to create a few
686 leading directories. */
687 parent_exists =
688 (make_dir_parents_private
689 (dst_name, arg_in_concat - dst_name,
690 (x->verbose ? "%s -> %s\n" : NULL),
691 &attr_list, &new_dst, x));
693 else
695 char *arg_base;
696 /* Append the last component of 'arg' to 'target_directory'. */
697 ASSIGN_STRDUPA (arg_base, last_component (arg));
698 strip_trailing_slashes (arg_base);
699 /* For 'cp -R source/.. dest', don't copy into 'dest/..'. */
700 dst_name = (STREQ (arg_base, "..")
701 ? xstrdup (target_directory)
702 : file_name_concat (target_directory, arg_base,
703 NULL));
706 if (!parent_exists)
708 /* make_dir_parents_private failed, so don't even
709 attempt the copy. */
710 ok = false;
712 else
714 bool copy_into_self;
715 ok &= copy (arg, dst_name, new_dst, x, &copy_into_self, NULL);
717 if (parents_option)
718 ok &= re_protect (dst_name, arg_in_concat - dst_name,
719 attr_list, x);
722 if (parents_option)
724 while (attr_list)
726 struct dir_attr *p = attr_list;
727 attr_list = attr_list->next;
728 free (p);
732 free (dst_name);
735 else /* !target_directory */
737 char const *new_dest;
738 char const *source = file[0];
739 char const *dest = file[1];
740 bool unused;
742 if (parents_option)
744 error (0, 0,
745 _("with --parents, the destination must be a directory"));
746 usage (EXIT_FAILURE);
749 /* When the force and backup options have been specified and
750 the source and destination are the same name for an existing
751 regular file, convert the user's command, e.g.,
752 'cp --force --backup foo foo' to 'cp --force foo fooSUFFIX'
753 where SUFFIX is determined by any version control options used. */
755 if (x->unlink_dest_after_failed_open
756 && x->backup_type != no_backups
757 && STREQ (source, dest)
758 && !new_dst && S_ISREG (sb.st_mode))
760 static struct cp_options x_tmp;
762 new_dest = find_backup_file_name (AT_FDCWD, dest, x->backup_type);
763 /* Set x->backup_type to 'no_backups' so that the normal backup
764 mechanism is not used when performing the actual copy.
765 backup_type must be set to 'no_backups' only *after* the above
766 call to find_backup_file_name -- that function uses
767 backup_type to determine the suffix it applies. */
768 x_tmp = *x;
769 x_tmp.backup_type = no_backups;
770 x = &x_tmp;
772 else
774 new_dest = dest;
777 ok = copy (source, new_dest, 0, x, &unused, NULL);
780 return ok;
783 static void
784 cp_option_init (struct cp_options *x)
786 cp_options_default (x);
787 x->copy_as_regular = true;
788 x->dereference = DEREF_UNDEFINED;
789 x->unlink_dest_before_opening = false;
790 x->unlink_dest_after_failed_open = false;
791 x->hard_link = false;
792 x->interactive = I_UNSPECIFIED;
793 x->move_mode = false;
794 x->install_mode = false;
795 x->one_file_system = false;
796 x->reflink_mode = REFLINK_NEVER;
798 x->preserve_ownership = false;
799 x->preserve_links = false;
800 x->preserve_mode = false;
801 x->preserve_timestamps = false;
802 x->explicit_no_preserve_mode = false;
803 x->preserve_security_context = false; /* -a or --preserve=context. */
804 x->require_preserve_context = false; /* --preserve=context. */
805 x->set_security_context = false; /* -Z, set sys default context. */
806 x->preserve_xattr = false;
807 x->reduce_diagnostics = false;
808 x->require_preserve_xattr = false;
810 x->data_copy_required = true;
811 x->require_preserve = false;
812 x->recursive = false;
813 x->sparse_mode = SPARSE_AUTO;
814 x->symbolic_link = false;
815 x->set_mode = false;
816 x->mode = 0;
818 /* Not used. */
819 x->stdin_tty = false;
821 x->update = false;
822 x->verbose = false;
824 /* By default, refuse to open a dangling destination symlink, because
825 in general one cannot do that safely, give the current semantics of
826 open's O_EXCL flag, (which POSIX doesn't even allow cp to use, btw).
827 But POSIX requires it. */
828 x->open_dangling_dest_symlink = getenv ("POSIXLY_CORRECT") != NULL;
830 x->dest_info = NULL;
831 x->src_info = NULL;
834 /* Given a string, ARG, containing a comma-separated list of arguments
835 to the --preserve option, set the appropriate fields of X to ON_OFF. */
836 static void
837 decode_preserve_arg (char const *arg, struct cp_options *x, bool on_off)
839 enum File_attribute
841 PRESERVE_MODE,
842 PRESERVE_TIMESTAMPS,
843 PRESERVE_OWNERSHIP,
844 PRESERVE_LINK,
845 PRESERVE_CONTEXT,
846 PRESERVE_XATTR,
847 PRESERVE_ALL
849 static enum File_attribute const preserve_vals[] =
851 PRESERVE_MODE, PRESERVE_TIMESTAMPS,
852 PRESERVE_OWNERSHIP, PRESERVE_LINK, PRESERVE_CONTEXT, PRESERVE_XATTR,
853 PRESERVE_ALL
855 /* Valid arguments to the '--preserve' option. */
856 static char const* const preserve_args[] =
858 "mode", "timestamps",
859 "ownership", "links", "context", "xattr", "all", NULL
861 ARGMATCH_VERIFY (preserve_args, preserve_vals);
863 char *arg_writable = xstrdup (arg);
864 char *s = arg_writable;
867 /* find next comma */
868 char *comma = strchr (s, ',');
869 enum File_attribute val;
871 /* If we found a comma, put a NUL in its place and advance. */
872 if (comma)
873 *comma++ = 0;
875 /* process S. */
876 val = XARGMATCH (on_off ? "--preserve" : "--no-preserve",
877 s, preserve_args, preserve_vals);
878 switch (val)
880 case PRESERVE_MODE:
881 x->preserve_mode = on_off;
882 x->explicit_no_preserve_mode = !on_off;
883 break;
885 case PRESERVE_TIMESTAMPS:
886 x->preserve_timestamps = on_off;
887 break;
889 case PRESERVE_OWNERSHIP:
890 x->preserve_ownership = on_off;
891 break;
893 case PRESERVE_LINK:
894 x->preserve_links = on_off;
895 break;
897 case PRESERVE_CONTEXT:
898 x->require_preserve_context = on_off;
899 x->preserve_security_context = on_off;
900 break;
902 case PRESERVE_XATTR:
903 x->preserve_xattr = on_off;
904 x->require_preserve_xattr = on_off;
905 break;
907 case PRESERVE_ALL:
908 x->preserve_mode = on_off;
909 x->preserve_timestamps = on_off;
910 x->preserve_ownership = on_off;
911 x->preserve_links = on_off;
912 x->explicit_no_preserve_mode = !on_off;
913 if (selinux_enabled)
914 x->preserve_security_context = on_off;
915 x->preserve_xattr = on_off;
916 break;
918 default:
919 abort ();
921 s = comma;
923 while (s);
925 free (arg_writable);
929 main (int argc, char **argv)
931 int c;
932 bool ok;
933 bool make_backups = false;
934 char const *backup_suffix = NULL;
935 char *version_control_string = NULL;
936 struct cp_options x;
937 bool copy_contents = false;
938 char *target_directory = NULL;
939 bool no_target_directory = false;
940 char const *scontext = NULL;
942 initialize_main (&argc, &argv);
943 set_program_name (argv[0]);
944 setlocale (LC_ALL, "");
945 bindtextdomain (PACKAGE, LOCALEDIR);
946 textdomain (PACKAGE);
948 atexit (close_stdin);
950 selinux_enabled = (0 < is_selinux_enabled ());
951 cp_option_init (&x);
953 while ((c = getopt_long (argc, argv, "abdfHilLnprst:uvxPRS:TZ",
954 long_opts, NULL))
955 != -1)
957 switch (c)
959 case SPARSE_OPTION:
960 x.sparse_mode = XARGMATCH ("--sparse", optarg,
961 sparse_type_string, sparse_type);
962 break;
964 case REFLINK_OPTION:
965 if (optarg == NULL)
966 x.reflink_mode = REFLINK_ALWAYS;
967 else
968 x.reflink_mode = XARGMATCH ("--reflink", optarg,
969 reflink_type_string, reflink_type);
970 break;
972 case 'a':
973 /* Like -dR --preserve=all with reduced failure diagnostics. */
974 x.dereference = DEREF_NEVER;
975 x.preserve_links = true;
976 x.preserve_ownership = true;
977 x.preserve_mode = true;
978 x.preserve_timestamps = true;
979 x.require_preserve = true;
980 if (selinux_enabled)
981 x.preserve_security_context = true;
982 x.preserve_xattr = true;
983 x.reduce_diagnostics = true;
984 x.recursive = true;
985 break;
987 case 'b':
988 make_backups = true;
989 if (optarg)
990 version_control_string = optarg;
991 break;
993 case ATTRIBUTES_ONLY_OPTION:
994 x.data_copy_required = false;
995 break;
997 case COPY_CONTENTS_OPTION:
998 copy_contents = true;
999 break;
1001 case 'd':
1002 x.preserve_links = true;
1003 x.dereference = DEREF_NEVER;
1004 break;
1006 case 'f':
1007 x.unlink_dest_after_failed_open = true;
1008 break;
1010 case 'H':
1011 x.dereference = DEREF_COMMAND_LINE_ARGUMENTS;
1012 break;
1014 case 'i':
1015 x.interactive = I_ASK_USER;
1016 break;
1018 case 'l':
1019 x.hard_link = true;
1020 break;
1022 case 'L':
1023 x.dereference = DEREF_ALWAYS;
1024 break;
1026 case 'n':
1027 x.interactive = I_ALWAYS_NO;
1028 break;
1030 case 'P':
1031 x.dereference = DEREF_NEVER;
1032 break;
1034 case NO_PRESERVE_ATTRIBUTES_OPTION:
1035 decode_preserve_arg (optarg, &x, false);
1036 break;
1038 case PRESERVE_ATTRIBUTES_OPTION:
1039 if (optarg == NULL)
1041 /* Fall through to the case for 'p' below. */
1043 else
1045 decode_preserve_arg (optarg, &x, true);
1046 x.require_preserve = true;
1047 break;
1049 FALLTHROUGH;
1051 case 'p':
1052 x.preserve_ownership = true;
1053 x.preserve_mode = true;
1054 x.preserve_timestamps = true;
1055 x.require_preserve = true;
1056 break;
1058 case PARENTS_OPTION:
1059 parents_option = true;
1060 break;
1062 case 'r':
1063 case 'R':
1064 x.recursive = true;
1065 break;
1067 case UNLINK_DEST_BEFORE_OPENING:
1068 x.unlink_dest_before_opening = true;
1069 break;
1071 case STRIP_TRAILING_SLASHES_OPTION:
1072 remove_trailing_slashes = true;
1073 break;
1075 case 's':
1076 x.symbolic_link = true;
1077 break;
1079 case 't':
1080 if (target_directory)
1081 die (EXIT_FAILURE, 0,
1082 _("multiple target directories specified"));
1083 else
1085 struct stat st;
1086 if (stat (optarg, &st) != 0)
1087 die (EXIT_FAILURE, errno, _("failed to access %s"),
1088 quoteaf (optarg));
1089 if (! S_ISDIR (st.st_mode))
1090 die (EXIT_FAILURE, 0, _("target %s is not a directory"),
1091 quoteaf (optarg));
1093 target_directory = optarg;
1094 break;
1096 case 'T':
1097 no_target_directory = true;
1098 break;
1100 case 'u':
1101 x.update = true;
1102 break;
1104 case 'v':
1105 x.verbose = true;
1106 break;
1108 case 'x':
1109 x.one_file_system = true;
1110 break;
1112 case 'Z':
1113 /* politely decline if we're not on a selinux-enabled kernel. */
1114 if (selinux_enabled)
1116 if (optarg)
1117 scontext = optarg;
1118 else
1119 x.set_security_context = true;
1121 else if (optarg)
1123 error (0, 0,
1124 _("warning: ignoring --context; "
1125 "it requires an SELinux-enabled kernel"));
1127 break;
1129 case 'S':
1130 make_backups = true;
1131 backup_suffix = optarg;
1132 break;
1134 case_GETOPT_HELP_CHAR;
1136 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1138 default:
1139 usage (EXIT_FAILURE);
1143 if (x.hard_link && x.symbolic_link)
1145 error (0, 0, _("cannot make both hard and symbolic links"));
1146 usage (EXIT_FAILURE);
1149 if (x.interactive == I_ALWAYS_NO)
1150 x.update = false;
1152 if (make_backups && x.interactive == I_ALWAYS_NO)
1154 error (0, 0,
1155 _("options --backup and --no-clobber are mutually exclusive"));
1156 usage (EXIT_FAILURE);
1159 if (x.reflink_mode == REFLINK_ALWAYS && x.sparse_mode != SPARSE_AUTO)
1161 error (0, 0, _("--reflink can be used only with --sparse=auto"));
1162 usage (EXIT_FAILURE);
1165 x.backup_type = (make_backups
1166 ? xget_version (_("backup type"),
1167 version_control_string)
1168 : no_backups);
1169 set_simple_backup_suffix (backup_suffix);
1171 if (x.dereference == DEREF_UNDEFINED)
1173 if (x.recursive && ! x.hard_link)
1174 /* This is compatible with FreeBSD. */
1175 x.dereference = DEREF_NEVER;
1176 else
1177 x.dereference = DEREF_ALWAYS;
1180 if (x.recursive)
1181 x.copy_as_regular = copy_contents;
1183 /* Ensure -Z overrides -a. */
1184 if ((x.set_security_context || scontext)
1185 && ! x.require_preserve_context)
1186 x.preserve_security_context = false;
1188 if (x.preserve_security_context && (x.set_security_context || scontext))
1189 die (EXIT_FAILURE, 0,
1190 _("cannot set target context and preserve it"));
1192 if (x.require_preserve_context && ! selinux_enabled)
1193 die (EXIT_FAILURE, 0,
1194 _("cannot preserve security context "
1195 "without an SELinux-enabled kernel"));
1197 /* FIXME: This handles new files. But what about existing files?
1198 I.e., if updating a tree, new files would have the specified context,
1199 but shouldn't existing files be updated for consistency like this?
1200 if (scontext)
1201 restorecon (dst_path, 0, true);
1203 if (scontext && setfscreatecon (se_const (scontext)) < 0)
1204 die (EXIT_FAILURE, errno,
1205 _("failed to set default file creation context to %s"),
1206 quote (scontext));
1208 #if !USE_XATTR
1209 if (x.require_preserve_xattr)
1210 die (EXIT_FAILURE, 0, _("cannot preserve extended attributes, cp is "
1211 "built without xattr support"));
1212 #endif
1214 /* Allocate space for remembering copied and created files. */
1216 hash_init ();
1218 ok = do_copy (argc - optind, argv + optind,
1219 target_directory, no_target_directory, &x);
1221 #ifdef lint
1222 forget_all ();
1223 #endif
1225 return ok ? EXIT_SUCCESS : EXIT_FAILURE;