cp: with --parents --no-preserve=mode don't copy dir perms
[coreutils.git] / src / cp.c
blob13dc1ea097c9a31c373fcfe3354dfe29c919bf7f
1 /* cp.c -- file copying (main routines)
2 Copyright (C) 1989-2016 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 <http://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 "error.h"
31 #include "filenamecat.h"
32 #include "ignore-value.h"
33 #include "quote.h"
34 #include "stat-time.h"
35 #include "utimens.h"
36 #include "acl.h"
38 #if ! HAVE_LCHOWN
39 # define lchown(name, uid, gid) chown (name, uid, gid)
40 #endif
42 #define ASSIGN_BASENAME_STRDUPA(Dest, File_name) \
43 do \
44 { \
45 char *tmp_abns_; \
46 ASSIGN_STRDUPA (tmp_abns_, (File_name)); \
47 Dest = last_component (tmp_abns_); \
48 strip_trailing_slashes (Dest); \
49 } \
50 while (0)
52 /* The official name of this program (e.g., no 'g' prefix). */
53 #define PROGRAM_NAME "cp"
55 #define AUTHORS \
56 proper_name_utf8 ("Torbjorn Granlund", "Torbj\303\266rn Granlund"), \
57 proper_name ("David MacKenzie"), \
58 proper_name ("Jim Meyering")
60 /* Used by do_copy, make_dir_parents_private, and re_protect
61 to keep a list of leading directories whose protections
62 need to be fixed after copying. */
63 struct dir_attr
65 struct stat st;
66 bool restore_mode;
67 size_t slash_offset;
68 struct dir_attr *next;
71 /* For long options that have no equivalent short option, use a
72 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
73 enum
75 ATTRIBUTES_ONLY_OPTION = CHAR_MAX + 1,
76 COPY_CONTENTS_OPTION,
77 NO_PRESERVE_ATTRIBUTES_OPTION,
78 PARENTS_OPTION,
79 PRESERVE_ATTRIBUTES_OPTION,
80 REFLINK_OPTION,
81 SPARSE_OPTION,
82 STRIP_TRAILING_SLASHES_OPTION,
83 UNLINK_DEST_BEFORE_OPENING
86 /* True if the kernel is SELinux enabled. */
87 static bool selinux_enabled;
89 /* If true, the command "cp x/e_file e_dir" uses "e_dir/x/e_file"
90 as its destination instead of the usual "e_dir/e_file." */
91 static bool parents_option = false;
93 /* Remove any trailing slashes from each SOURCE argument. */
94 static bool remove_trailing_slashes;
96 static char const *const sparse_type_string[] =
98 "never", "auto", "always", NULL
100 static enum Sparse_type const sparse_type[] =
102 SPARSE_NEVER, SPARSE_AUTO, SPARSE_ALWAYS
104 ARGMATCH_VERIFY (sparse_type_string, sparse_type);
106 static char const *const reflink_type_string[] =
108 "auto", "always", NULL
110 static enum Reflink_type const reflink_type[] =
112 REFLINK_AUTO, REFLINK_ALWAYS
114 ARGMATCH_VERIFY (reflink_type_string, reflink_type);
116 static struct option const long_opts[] =
118 {"archive", no_argument, NULL, 'a'},
119 {"attributes-only", no_argument, NULL, ATTRIBUTES_ONLY_OPTION},
120 {"backup", optional_argument, NULL, 'b'},
121 {"copy-contents", no_argument, NULL, COPY_CONTENTS_OPTION},
122 {"dereference", no_argument, NULL, 'L'},
123 {"force", no_argument, NULL, 'f'},
124 {"interactive", no_argument, NULL, 'i'},
125 {"link", no_argument, NULL, 'l'},
126 {"no-clobber", no_argument, NULL, 'n'},
127 {"no-dereference", no_argument, NULL, 'P'},
128 {"no-preserve", required_argument, NULL, NO_PRESERVE_ATTRIBUTES_OPTION},
129 {"no-target-directory", no_argument, NULL, 'T'},
130 {"one-file-system", no_argument, NULL, 'x'},
131 {"parents", no_argument, NULL, PARENTS_OPTION},
132 {"path", no_argument, NULL, PARENTS_OPTION}, /* Deprecated. */
133 {"preserve", optional_argument, NULL, PRESERVE_ATTRIBUTES_OPTION},
134 {"recursive", no_argument, NULL, 'R'},
135 {"remove-destination", no_argument, NULL, UNLINK_DEST_BEFORE_OPENING},
136 {"sparse", required_argument, NULL, SPARSE_OPTION},
137 {"reflink", optional_argument, NULL, REFLINK_OPTION},
138 {"strip-trailing-slashes", no_argument, NULL, STRIP_TRAILING_SLASHES_OPTION},
139 {"suffix", required_argument, NULL, 'S'},
140 {"symbolic-link", no_argument, NULL, 's'},
141 {"target-directory", required_argument, NULL, 't'},
142 {"update", no_argument, NULL, 'u'},
143 {"verbose", no_argument, NULL, 'v'},
144 {GETOPT_SELINUX_CONTEXT_OPTION_DECL},
145 {GETOPT_HELP_OPTION_DECL},
146 {GETOPT_VERSION_OPTION_DECL},
147 {NULL, 0, NULL, 0}
150 void
151 usage (int status)
153 if (status != EXIT_SUCCESS)
154 emit_try_help ();
155 else
157 printf (_("\
158 Usage: %s [OPTION]... [-T] SOURCE DEST\n\
159 or: %s [OPTION]... SOURCE... DIRECTORY\n\
160 or: %s [OPTION]... -t DIRECTORY SOURCE...\n\
162 program_name, program_name, program_name);
163 fputs (_("\
164 Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.\n\
165 "), stdout);
167 emit_mandatory_arg_note ();
169 fputs (_("\
170 -a, --archive same as -dR --preserve=all\n\
171 --attributes-only don't copy the file data, just the attributes\n\
172 --backup[=CONTROL] make a backup of each existing destination file\
174 -b like --backup but does not accept an argument\n\
175 --copy-contents copy contents of special files when recursive\n\
176 -d same as --no-dereference --preserve=links\n\
177 "), stdout);
178 fputs (_("\
179 -f, --force if an existing destination file cannot be\n\
180 opened, remove it and try again (this option\n\
181 is ignored when the -n option is also used)\n\
182 -i, --interactive prompt before overwrite (overrides a previous -n\
184 option)\n\
185 -H follow command-line symbolic links in SOURCE\n\
186 "), stdout);
187 fputs (_("\
188 -l, --link hard link files instead of copying\n\
189 -L, --dereference always follow symbolic links in SOURCE\n\
190 "), stdout);
191 fputs (_("\
192 -n, --no-clobber do not overwrite an existing file (overrides\n\
193 a previous -i option)\n\
194 -P, --no-dereference never follow symbolic links in SOURCE\n\
195 "), stdout);
196 fputs (_("\
197 -p same as --preserve=mode,ownership,timestamps\n\
198 --preserve[=ATTR_LIST] preserve the specified attributes (default:\n\
199 mode,ownership,timestamps), if possible\n\
200 additional attributes: context, links, xattr,\
202 all\n\
203 "), stdout);
204 fputs (_("\
205 --no-preserve=ATTR_LIST don't preserve the specified attributes\n\
206 --parents use full source file name under DIRECTORY\n\
207 "), stdout);
208 fputs (_("\
209 -R, -r, --recursive copy directories recursively\n\
210 --reflink[=WHEN] control clone/CoW copies. See below\n\
211 --remove-destination remove each existing destination file before\n\
212 attempting to open it (contrast with --force)\
213 \n"), stdout);
214 fputs (_("\
215 --sparse=WHEN control creation of sparse files. See below\n\
216 --strip-trailing-slashes remove any trailing slashes from each SOURCE\n\
217 argument\n\
218 "), stdout);
219 fputs (_("\
220 -s, --symbolic-link make symbolic links instead of copying\n\
221 -S, --suffix=SUFFIX override the usual backup suffix\n\
222 -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY\n\
223 -T, --no-target-directory treat DEST as a normal file\n\
224 "), stdout);
225 fputs (_("\
226 -u, --update copy only when the SOURCE file is newer\n\
227 than the destination file or when the\n\
228 destination file is missing\n\
229 -v, --verbose explain what is being done\n\
230 -x, --one-file-system stay on this file system\n\
231 "), stdout);
232 fputs (_("\
233 -Z set SELinux security context of destination\n\
234 file to default type\n\
235 --context[=CTX] like -Z, or if CTX is specified then set the\n\
236 SELinux or SMACK security context to CTX\n\
237 "), stdout);
238 fputs (HELP_OPTION_DESCRIPTION, stdout);
239 fputs (VERSION_OPTION_DESCRIPTION, stdout);
240 fputs (_("\
242 By default, sparse SOURCE files are detected by a crude heuristic and the\n\
243 corresponding DEST file is made sparse as well. That is the behavior\n\
244 selected by --sparse=auto. Specify --sparse=always to create a sparse DEST\n\
245 file whenever the SOURCE file contains a long enough sequence of zero bytes.\n\
246 Use --sparse=never to inhibit creation of sparse files.\n\
248 When --reflink[=always] is specified, perform a lightweight copy, where the\n\
249 data blocks are copied only when modified. If this is not possible the copy\n\
250 fails, or if --reflink=auto is specified, fall back to a standard copy.\n\
251 "), stdout);
252 fputs (_("\
254 The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
255 The version control method may be selected via the --backup option or through\n\
256 the VERSION_CONTROL environment variable. Here are the values:\n\
258 "), stdout);
259 fputs (_("\
260 none, off never make backups (even if --backup is given)\n\
261 numbered, t make numbered backups\n\
262 existing, nil numbered if numbered backups exist, simple otherwise\n\
263 simple, never always make simple backups\n\
264 "), stdout);
265 fputs (_("\
267 As a special case, cp makes a backup of SOURCE when the force and backup\n\
268 options are given and SOURCE and DEST are the same name for an existing,\n\
269 regular file.\n\
270 "), stdout);
271 emit_ancillary_info (PROGRAM_NAME);
273 exit (status);
276 /* Ensure that the parent directories of CONST_DST_NAME have the
277 correct protections, for the --parents option. This is done
278 after all copying has been completed, to allow permissions
279 that don't include user write/execute.
281 SRC_OFFSET is the index in CONST_DST_NAME of the beginning of the
282 source directory name.
284 ATTR_LIST is a null-terminated linked list of structures that
285 indicates the end of the filename of each intermediate directory
286 in CONST_DST_NAME that may need to have its attributes changed.
287 The command 'cp --parents --preserve a/b/c d/e_dir' changes the
288 attributes of the directories d/e_dir/a and d/e_dir/a/b to match
289 the corresponding source directories regardless of whether they
290 existed before the 'cp' command was given.
292 Return true if the parent of CONST_DST_NAME and any intermediate
293 directories specified by ATTR_LIST have the proper permissions
294 when done. */
296 static bool
297 re_protect (char const *const_dst_name, size_t src_offset,
298 struct dir_attr *attr_list, const struct cp_options *x)
300 struct dir_attr *p;
301 char *dst_name; /* A copy of CONST_DST_NAME we can change. */
302 char *src_name; /* The source name in 'dst_name'. */
304 ASSIGN_STRDUPA (dst_name, const_dst_name);
305 src_name = dst_name + src_offset;
307 for (p = attr_list; p; p = p->next)
309 dst_name[p->slash_offset] = '\0';
311 /* Adjust the times (and if possible, ownership) for the copy.
312 chown turns off set[ug]id bits for non-root,
313 so do the chmod last. */
315 if (x->preserve_timestamps)
317 struct timespec timespec[2];
319 timespec[0] = get_stat_atime (&p->st);
320 timespec[1] = get_stat_mtime (&p->st);
322 if (utimens (dst_name, timespec))
324 error (0, errno, _("failed to preserve times for %s"),
325 quoteaf (dst_name));
326 return false;
330 if (x->preserve_ownership)
332 if (lchown (dst_name, p->st.st_uid, p->st.st_gid) != 0)
334 if (! chown_failure_ok (x))
336 error (0, errno, _("failed to preserve ownership for %s"),
337 quoteaf (dst_name));
338 return false;
340 /* Failing to preserve ownership is OK. Still, try to preserve
341 the group, but ignore the possible error. */
342 ignore_value (lchown (dst_name, -1, p->st.st_gid));
346 if (x->preserve_mode)
348 if (copy_acl (src_name, -1, dst_name, -1, p->st.st_mode) != 0)
349 return false;
351 else if (p->restore_mode)
353 if (lchmod (dst_name, p->st.st_mode) != 0)
355 error (0, errno, _("failed to preserve permissions for %s"),
356 quoteaf (dst_name));
357 return false;
361 dst_name[p->slash_offset] = '/';
363 return true;
366 /* Ensure that the parent directory of CONST_DIR exists, for
367 the --parents option.
369 SRC_OFFSET is the index in CONST_DIR (which is a destination
370 directory) of the beginning of the source directory name.
371 Create any leading directories that don't already exist.
372 If VERBOSE_FMT_STRING is nonzero, use it as a printf format
373 string for printing a message after successfully making a directory.
374 The format should take two string arguments: the names of the
375 source and destination directories.
376 Creates a linked list of attributes of intermediate directories,
377 *ATTR_LIST, for re_protect to use after calling copy.
378 Sets *NEW_DST if this function creates parent of CONST_DIR.
380 Return true if parent of CONST_DIR exists as a directory with the proper
381 permissions when done. */
383 /* FIXME: Synch this function with the one in ../lib/mkdir-p.c. */
385 static bool
386 make_dir_parents_private (char const *const_dir, size_t src_offset,
387 char const *verbose_fmt_string,
388 struct dir_attr **attr_list, bool *new_dst,
389 const struct cp_options *x)
391 struct stat stats;
392 char *dir; /* A copy of CONST_DIR we can change. */
393 char *src; /* Source name in DIR. */
394 char *dst_dir; /* Leading directory of DIR. */
395 size_t dirlen; /* Length of DIR. */
397 ASSIGN_STRDUPA (dir, const_dir);
399 src = dir + src_offset;
401 dirlen = dir_len (dir);
402 dst_dir = alloca (dirlen + 1);
403 memcpy (dst_dir, dir, dirlen);
404 dst_dir[dirlen] = '\0';
406 *attr_list = NULL;
408 if (stat (dst_dir, &stats) != 0)
410 /* A parent of CONST_DIR does not exist.
411 Make all missing intermediate directories. */
412 char *slash;
414 slash = src;
415 while (*slash == '/')
416 slash++;
417 while ((slash = strchr (slash, '/')))
419 struct dir_attr *new IF_LINT ( = NULL);
420 bool missing_dir;
422 *slash = '\0';
423 missing_dir = (stat (dir, &stats) != 0);
425 if (missing_dir || x->preserve_ownership || x->preserve_mode
426 || x->preserve_timestamps)
428 /* Add this directory to the list of directories whose
429 modes might need fixing later. */
430 struct stat src_st;
431 int src_errno = (stat (src, &src_st) != 0
432 ? errno
433 : S_ISDIR (src_st.st_mode)
435 : ENOTDIR);
436 if (src_errno)
438 error (0, src_errno, _("failed to get attributes of %s"),
439 quoteaf (src));
440 return false;
443 new = xmalloc (sizeof *new);
444 new->st = src_st;
445 new->slash_offset = slash - dir;
446 new->restore_mode = false;
447 new->next = *attr_list;
448 *attr_list = new;
451 if (missing_dir)
453 mode_t src_mode;
454 mode_t omitted_permissions;
455 mode_t mkdir_mode;
457 /* This component does not exist. We must set
458 *new_dst and new->st.st_mode inside this loop because,
459 for example, in the command 'cp --parents ../a/../b/c e_dir',
460 make_dir_parents_private creates only e_dir/../a if
461 ./b already exists. */
462 *new_dst = true;
463 src_mode = new->st.st_mode;
465 /* If the ownership or special mode bits might change,
466 omit some permissions at first, so unauthorized users
467 cannot nip in before the file is ready. */
468 omitted_permissions = (src_mode
469 & (x->preserve_ownership
470 ? S_IRWXG | S_IRWXO
471 : x->preserve_mode
472 ? S_IWGRP | S_IWOTH
473 : 0));
475 /* POSIX says mkdir's behavior is implementation-defined when
476 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
477 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
478 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
479 mkdir_mode = x->explicit_no_preserve_mode ? S_IRWXUGO : src_mode;
480 mkdir_mode &= CHMOD_MODE_BITS & ~omitted_permissions;
481 if (mkdir (dir, mkdir_mode) != 0)
483 error (0, errno, _("cannot make directory %s"),
484 quoteaf (dir));
485 return false;
487 else
489 if (verbose_fmt_string != NULL)
490 printf (verbose_fmt_string, src, dir);
493 /* We need search and write permissions to the new directory
494 for writing the directory's contents. Check if these
495 permissions are there. */
497 if (lstat (dir, &stats))
499 error (0, errno, _("failed to get attributes of %s"),
500 quoteaf (dir));
501 return false;
505 if (! x->preserve_mode)
507 if (omitted_permissions & ~stats.st_mode)
508 omitted_permissions &= ~ cached_umask ();
509 if (omitted_permissions & ~stats.st_mode
510 || (stats.st_mode & S_IRWXU) != S_IRWXU)
512 new->st.st_mode = stats.st_mode | omitted_permissions;
513 new->restore_mode = true;
517 if ((stats.st_mode & S_IRWXU) != S_IRWXU)
519 /* Make the new directory searchable and writable.
520 The original permissions will be restored later. */
522 if (lchmod (dir, stats.st_mode | S_IRWXU) != 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;
538 *slash++ = '/';
540 /* Avoid unnecessary calls to 'stat' when given
541 file names containing multiple adjacent slashes. */
542 while (*slash == '/')
543 slash++;
547 /* We get here if the parent of DIR already exists. */
549 else if (!S_ISDIR (stats.st_mode))
551 error (0, 0, _("%s exists but is not a directory"), quoteaf (dst_dir));
552 return false;
554 else
556 *new_dst = false;
558 return true;
561 /* FILE is the last operand of this command.
562 Return true if FILE is a directory.
563 But report an error and exit if there is a problem accessing FILE,
564 or if FILE does not exist but would have to refer to an existing
565 directory if it referred to anything at all.
567 If the file exists, store the file's status into *ST.
568 Otherwise, set *NEW_DST. */
570 static bool
571 target_directory_operand (char const *file, struct stat *st, bool *new_dst)
573 int err = (stat (file, st) == 0 ? 0 : errno);
574 bool is_a_dir = !err && S_ISDIR (st->st_mode);
575 if (err)
577 if (err != ENOENT)
578 error (EXIT_FAILURE, err, _("failed to access %s"), quoteaf (file));
579 *new_dst = true;
581 return is_a_dir;
584 /* Scan the arguments, and copy each by calling copy.
585 Return true if successful. */
587 static bool
588 do_copy (int n_files, char **file, const char *target_directory,
589 bool no_target_directory, struct cp_options *x)
591 struct stat sb;
592 bool new_dst = false;
593 bool ok = true;
595 if (n_files <= !target_directory)
597 if (n_files <= 0)
598 error (0, 0, _("missing file operand"));
599 else
600 error (0, 0, _("missing destination file operand after %s"),
601 quoteaf (file[0]));
602 usage (EXIT_FAILURE);
605 if (no_target_directory)
607 if (target_directory)
608 error (EXIT_FAILURE, 0,
609 _("cannot combine --target-directory (-t) "
610 "and --no-target-directory (-T)"));
611 if (2 < n_files)
613 error (0, 0, _("extra operand %s"), quoteaf (file[2]));
614 usage (EXIT_FAILURE);
616 /* Update NEW_DST and SB, which may be checked below. */
617 ignore_value (target_directory_operand (file[n_files -1], &sb, &new_dst));
619 else if (!target_directory)
621 if (2 <= n_files
622 && target_directory_operand (file[n_files - 1], &sb, &new_dst))
623 target_directory = file[--n_files];
624 else if (2 < n_files)
625 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
626 quoteaf (file[n_files - 1]));
629 if (target_directory)
631 /* cp file1...filen edir
632 Copy the files 'file1' through 'filen'
633 to the existing directory 'edir'. */
634 int i;
636 /* Initialize these hash tables only if we'll need them.
637 The problems they're used to detect can arise only if
638 there are two or more files to copy. */
639 if (2 <= n_files)
641 dest_info_init (x);
642 src_info_init (x);
645 for (i = 0; i < n_files; i++)
647 char *dst_name;
648 bool parent_exists = true; /* True if dir_name (dst_name) exists. */
649 struct dir_attr *attr_list;
650 char *arg_in_concat = NULL;
651 char *arg = file[i];
653 /* Trailing slashes are meaningful (i.e., maybe worth preserving)
654 only in the source file names. */
655 if (remove_trailing_slashes)
656 strip_trailing_slashes (arg);
658 if (parents_option)
660 char *arg_no_trailing_slash;
662 /* Use 'arg' without trailing slashes in constructing destination
663 file names. Otherwise, we can end up trying to create a
664 directory via 'mkdir ("dst/foo/"...', which is not portable.
665 It fails, due to the trailing slash, on at least
666 NetBSD 1.[34] systems. */
667 ASSIGN_STRDUPA (arg_no_trailing_slash, arg);
668 strip_trailing_slashes (arg_no_trailing_slash);
670 /* Append all of 'arg' (minus any trailing slash) to 'dest'. */
671 dst_name = file_name_concat (target_directory,
672 arg_no_trailing_slash,
673 &arg_in_concat);
675 /* For --parents, we have to make sure that the directory
676 dir_name (dst_name) exists. We may have to create a few
677 leading directories. */
678 parent_exists =
679 (make_dir_parents_private
680 (dst_name, arg_in_concat - dst_name,
681 (x->verbose ? "%s -> %s\n" : NULL),
682 &attr_list, &new_dst, x));
684 else
686 char *arg_base;
687 /* Append the last component of 'arg' to 'target_directory'. */
689 ASSIGN_BASENAME_STRDUPA (arg_base, arg);
690 /* For 'cp -R source/.. dest', don't copy into 'dest/..'. */
691 dst_name = (STREQ (arg_base, "..")
692 ? xstrdup (target_directory)
693 : file_name_concat (target_directory, arg_base,
694 NULL));
697 if (!parent_exists)
699 /* make_dir_parents_private failed, so don't even
700 attempt the copy. */
701 ok = false;
703 else
705 bool copy_into_self;
706 ok &= copy (arg, dst_name, new_dst, x, &copy_into_self, NULL);
708 if (parents_option)
709 ok &= re_protect (dst_name, arg_in_concat - dst_name,
710 attr_list, x);
713 if (parents_option)
715 while (attr_list)
717 struct dir_attr *p = attr_list;
718 attr_list = attr_list->next;
719 free (p);
723 free (dst_name);
726 else /* !target_directory */
728 char const *new_dest;
729 char const *source = file[0];
730 char const *dest = file[1];
731 bool unused;
733 if (parents_option)
735 error (0, 0,
736 _("with --parents, the destination must be a directory"));
737 usage (EXIT_FAILURE);
740 /* When the force and backup options have been specified and
741 the source and destination are the same name for an existing
742 regular file, convert the user's command, e.g.,
743 'cp --force --backup foo foo' to 'cp --force foo fooSUFFIX'
744 where SUFFIX is determined by any version control options used. */
746 if (x->unlink_dest_after_failed_open
747 && x->backup_type != no_backups
748 && STREQ (source, dest)
749 && !new_dst && S_ISREG (sb.st_mode))
751 static struct cp_options x_tmp;
753 new_dest = find_backup_file_name (dest, x->backup_type);
754 /* Set x->backup_type to 'no_backups' so that the normal backup
755 mechanism is not used when performing the actual copy.
756 backup_type must be set to 'no_backups' only *after* the above
757 call to find_backup_file_name -- that function uses
758 backup_type to determine the suffix it applies. */
759 x_tmp = *x;
760 x_tmp.backup_type = no_backups;
761 x = &x_tmp;
763 else
765 new_dest = dest;
768 ok = copy (source, new_dest, 0, x, &unused, NULL);
771 return ok;
774 static void
775 cp_option_init (struct cp_options *x)
777 cp_options_default (x);
778 x->copy_as_regular = true;
779 x->dereference = DEREF_UNDEFINED;
780 x->unlink_dest_before_opening = false;
781 x->unlink_dest_after_failed_open = false;
782 x->hard_link = false;
783 x->interactive = I_UNSPECIFIED;
784 x->move_mode = false;
785 x->one_file_system = false;
786 x->reflink_mode = REFLINK_NEVER;
788 x->preserve_ownership = false;
789 x->preserve_links = false;
790 x->preserve_mode = false;
791 x->preserve_timestamps = false;
792 x->explicit_no_preserve_mode = false;
793 x->preserve_security_context = false; /* -a or --preserve=context. */
794 x->require_preserve_context = false; /* --preserve=context. */
795 x->set_security_context = false; /* -Z, set sys default context. */
796 x->preserve_xattr = false;
797 x->reduce_diagnostics = false;
798 x->require_preserve_xattr = false;
800 x->data_copy_required = true;
801 x->require_preserve = false;
802 x->recursive = false;
803 x->sparse_mode = SPARSE_AUTO;
804 x->symbolic_link = false;
805 x->set_mode = false;
806 x->mode = 0;
808 /* Not used. */
809 x->stdin_tty = false;
811 x->update = false;
812 x->verbose = false;
814 /* By default, refuse to open a dangling destination symlink, because
815 in general one cannot do that safely, give the current semantics of
816 open's O_EXCL flag, (which POSIX doesn't even allow cp to use, btw).
817 But POSIX requires it. */
818 x->open_dangling_dest_symlink = getenv ("POSIXLY_CORRECT") != NULL;
820 x->dest_info = NULL;
821 x->src_info = NULL;
824 /* Given a string, ARG, containing a comma-separated list of arguments
825 to the --preserve option, set the appropriate fields of X to ON_OFF. */
826 static void
827 decode_preserve_arg (char const *arg, struct cp_options *x, bool on_off)
829 enum File_attribute
831 PRESERVE_MODE,
832 PRESERVE_TIMESTAMPS,
833 PRESERVE_OWNERSHIP,
834 PRESERVE_LINK,
835 PRESERVE_CONTEXT,
836 PRESERVE_XATTR,
837 PRESERVE_ALL
839 static enum File_attribute const preserve_vals[] =
841 PRESERVE_MODE, PRESERVE_TIMESTAMPS,
842 PRESERVE_OWNERSHIP, PRESERVE_LINK, PRESERVE_CONTEXT, PRESERVE_XATTR,
843 PRESERVE_ALL
845 /* Valid arguments to the '--preserve' option. */
846 static char const* const preserve_args[] =
848 "mode", "timestamps",
849 "ownership", "links", "context", "xattr", "all", NULL
851 ARGMATCH_VERIFY (preserve_args, preserve_vals);
853 char *arg_writable = xstrdup (arg);
854 char *s = arg_writable;
857 /* find next comma */
858 char *comma = strchr (s, ',');
859 enum File_attribute val;
861 /* If we found a comma, put a NUL in its place and advance. */
862 if (comma)
863 *comma++ = 0;
865 /* process S. */
866 val = XARGMATCH (on_off ? "--preserve" : "--no-preserve",
867 s, preserve_args, preserve_vals);
868 switch (val)
870 case PRESERVE_MODE:
871 x->preserve_mode = on_off;
872 x->explicit_no_preserve_mode = !on_off;
873 break;
875 case PRESERVE_TIMESTAMPS:
876 x->preserve_timestamps = on_off;
877 break;
879 case PRESERVE_OWNERSHIP:
880 x->preserve_ownership = on_off;
881 break;
883 case PRESERVE_LINK:
884 x->preserve_links = on_off;
885 break;
887 case PRESERVE_CONTEXT:
888 x->require_preserve_context = on_off;
889 x->preserve_security_context = on_off;
890 break;
892 case PRESERVE_XATTR:
893 x->preserve_xattr = on_off;
894 x->require_preserve_xattr = on_off;
895 break;
897 case PRESERVE_ALL:
898 x->preserve_mode = on_off;
899 x->preserve_timestamps = on_off;
900 x->preserve_ownership = on_off;
901 x->preserve_links = on_off;
902 x->explicit_no_preserve_mode = !on_off;
903 if (selinux_enabled)
904 x->preserve_security_context = on_off;
905 x->preserve_xattr = on_off;
906 break;
908 default:
909 abort ();
911 s = comma;
913 while (s);
915 free (arg_writable);
919 main (int argc, char **argv)
921 int c;
922 bool ok;
923 bool make_backups = false;
924 char *backup_suffix_string;
925 char *version_control_string = NULL;
926 struct cp_options x;
927 bool copy_contents = false;
928 char *target_directory = NULL;
929 bool no_target_directory = false;
930 char const *scontext = NULL;
932 initialize_main (&argc, &argv);
933 set_program_name (argv[0]);
934 setlocale (LC_ALL, "");
935 bindtextdomain (PACKAGE, LOCALEDIR);
936 textdomain (PACKAGE);
938 atexit (close_stdin);
940 selinux_enabled = (0 < is_selinux_enabled ());
941 cp_option_init (&x);
943 /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
944 we'll actually use backup_suffix_string. */
945 backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
947 while ((c = getopt_long (argc, argv, "abdfHilLnprst:uvxPRS:TZ",
948 long_opts, NULL))
949 != -1)
951 switch (c)
953 case SPARSE_OPTION:
954 x.sparse_mode = XARGMATCH ("--sparse", optarg,
955 sparse_type_string, sparse_type);
956 break;
958 case REFLINK_OPTION:
959 if (optarg == NULL)
960 x.reflink_mode = REFLINK_ALWAYS;
961 else
962 x.reflink_mode = XARGMATCH ("--reflink", optarg,
963 reflink_type_string, reflink_type);
964 break;
966 case 'a':
967 /* Like -dR --preserve=all with reduced failure diagnostics. */
968 x.dereference = DEREF_NEVER;
969 x.preserve_links = true;
970 x.preserve_ownership = true;
971 x.preserve_mode = true;
972 x.preserve_timestamps = true;
973 x.require_preserve = true;
974 if (selinux_enabled)
975 x.preserve_security_context = true;
976 x.preserve_xattr = true;
977 x.reduce_diagnostics = true;
978 x.recursive = true;
979 break;
981 case 'b':
982 make_backups = true;
983 if (optarg)
984 version_control_string = optarg;
985 break;
987 case ATTRIBUTES_ONLY_OPTION:
988 x.data_copy_required = false;
989 break;
991 case COPY_CONTENTS_OPTION:
992 copy_contents = true;
993 break;
995 case 'd':
996 x.preserve_links = true;
997 x.dereference = DEREF_NEVER;
998 break;
1000 case 'f':
1001 x.unlink_dest_after_failed_open = true;
1002 break;
1004 case 'H':
1005 x.dereference = DEREF_COMMAND_LINE_ARGUMENTS;
1006 break;
1008 case 'i':
1009 x.interactive = I_ASK_USER;
1010 break;
1012 case 'l':
1013 x.hard_link = true;
1014 break;
1016 case 'L':
1017 x.dereference = DEREF_ALWAYS;
1018 break;
1020 case 'n':
1021 x.interactive = I_ALWAYS_NO;
1022 break;
1024 case 'P':
1025 x.dereference = DEREF_NEVER;
1026 break;
1028 case NO_PRESERVE_ATTRIBUTES_OPTION:
1029 decode_preserve_arg (optarg, &x, false);
1030 break;
1032 case PRESERVE_ATTRIBUTES_OPTION:
1033 if (optarg == NULL)
1035 /* Fall through to the case for 'p' below. */
1037 else
1039 decode_preserve_arg (optarg, &x, true);
1040 x.require_preserve = true;
1041 break;
1044 case 'p':
1045 x.preserve_ownership = true;
1046 x.preserve_mode = true;
1047 x.preserve_timestamps = true;
1048 x.require_preserve = true;
1049 break;
1051 case PARENTS_OPTION:
1052 parents_option = true;
1053 break;
1055 case 'r':
1056 case 'R':
1057 x.recursive = true;
1058 break;
1060 case UNLINK_DEST_BEFORE_OPENING:
1061 x.unlink_dest_before_opening = true;
1062 break;
1064 case STRIP_TRAILING_SLASHES_OPTION:
1065 remove_trailing_slashes = true;
1066 break;
1068 case 's':
1069 x.symbolic_link = true;
1070 break;
1072 case 't':
1073 if (target_directory)
1074 error (EXIT_FAILURE, 0,
1075 _("multiple target directories specified"));
1076 else
1078 struct stat st;
1079 if (stat (optarg, &st) != 0)
1080 error (EXIT_FAILURE, errno, _("failed to access %s"),
1081 quoteaf (optarg));
1082 if (! S_ISDIR (st.st_mode))
1083 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
1084 quoteaf (optarg));
1086 target_directory = optarg;
1087 break;
1089 case 'T':
1090 no_target_directory = true;
1091 break;
1093 case 'u':
1094 x.update = true;
1095 break;
1097 case 'v':
1098 x.verbose = true;
1099 break;
1101 case 'x':
1102 x.one_file_system = true;
1103 break;
1105 case 'Z':
1106 /* politely decline if we're not on a selinux-enabled kernel. */
1107 if (selinux_enabled)
1109 if (optarg)
1110 scontext = optarg;
1111 else
1112 x.set_security_context = true;
1114 else if (optarg)
1116 error (0, 0,
1117 _("warning: ignoring --context; "
1118 "it requires an SELinux-enabled kernel"));
1120 break;
1122 case 'S':
1123 make_backups = true;
1124 backup_suffix_string = optarg;
1125 break;
1127 case_GETOPT_HELP_CHAR;
1129 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1131 default:
1132 usage (EXIT_FAILURE);
1136 if (x.hard_link && x.symbolic_link)
1138 error (0, 0, _("cannot make both hard and symbolic links"));
1139 usage (EXIT_FAILURE);
1142 if (make_backups && x.interactive == I_ALWAYS_NO)
1144 error (0, 0,
1145 _("options --backup and --no-clobber are mutually exclusive"));
1146 usage (EXIT_FAILURE);
1149 if (x.reflink_mode == REFLINK_ALWAYS && x.sparse_mode != SPARSE_AUTO)
1151 error (0, 0, _("--reflink can be used only with --sparse=auto"));
1152 usage (EXIT_FAILURE);
1155 if (backup_suffix_string)
1156 simple_backup_suffix = xstrdup (backup_suffix_string);
1158 x.backup_type = (make_backups
1159 ? xget_version (_("backup type"),
1160 version_control_string)
1161 : no_backups);
1163 if (x.dereference == DEREF_UNDEFINED)
1165 if (x.recursive && ! x.hard_link)
1166 /* This is compatible with FreeBSD. */
1167 x.dereference = DEREF_NEVER;
1168 else
1169 x.dereference = DEREF_ALWAYS;
1172 if (x.recursive)
1173 x.copy_as_regular = copy_contents;
1175 /* If --force (-f) was specified and we're in link-creation mode,
1176 first remove any existing destination file. */
1177 if (x.unlink_dest_after_failed_open && (x.hard_link || x.symbolic_link))
1178 x.unlink_dest_before_opening = true;
1180 /* Ensure -Z overrides -a. */
1181 if ((x.set_security_context || scontext)
1182 && ! x.require_preserve_context)
1183 x.preserve_security_context = false;
1185 if (x.preserve_security_context && (x.set_security_context || scontext))
1186 error (EXIT_FAILURE, 0,
1187 _("cannot set target context and preserve it"));
1189 if (x.require_preserve_context && ! selinux_enabled)
1190 error (EXIT_FAILURE, 0,
1191 _("cannot preserve security context "
1192 "without an SELinux-enabled kernel"));
1194 /* FIXME: This handles new files. But what about existing files?
1195 I.e., if updating a tree, new files would have the specified context,
1196 but shouldn't existing files be updated for consistency like this?
1197 if (scontext)
1198 restorecon (dst_path, 0, true);
1200 if (scontext && setfscreatecon (se_const (scontext)) < 0)
1201 error (EXIT_FAILURE, errno,
1202 _("failed to set default file creation context to %s"),
1203 quote (scontext));
1205 #if !USE_XATTR
1206 if (x.require_preserve_xattr)
1207 error (EXIT_FAILURE, 0, _("cannot preserve extended attributes, cp is "
1208 "built without xattr support"));
1209 #endif
1211 /* Allocate space for remembering copied and created files. */
1213 hash_init ();
1215 ok = do_copy (argc - optind, argv + optind,
1216 target_directory, no_target_directory, &x);
1218 #ifdef lint
1219 forget_all ();
1220 #endif
1222 return ok ? EXIT_SUCCESS : EXIT_FAILURE;