ln: clarify usage of -L, -n, -T
[coreutils.git] / src / cp.c
blob15f3aa9a6e40649b24e7477cb00811b2c81b32c0
1 /* cp.c -- file copying (main routines)
2 Copyright (C) 1989-1991, 1995-2011 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_HELP_OPTION_DECL},
145 {GETOPT_VERSION_OPTION_DECL},
146 {NULL, 0, NULL, 0}
149 void
150 usage (int status)
152 if (status != EXIT_SUCCESS)
153 fprintf (stderr, _("Try `%s --help' for more information.\n"),
154 program_name);
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\
166 "), stdout);
167 fputs (_("\
168 Mandatory arguments to long options are mandatory for short options too.\n\
169 "), stdout);
170 fputs (_("\
171 -a, --archive same as -dR --preserve=all\n\
172 --attributes-only don't copy the file data, just the attributes\n\
173 --backup[=CONTROL] make a backup of each existing destination file\
175 -b like --backup but does not accept an argument\n\
176 --copy-contents copy contents of special files when recursive\n\
177 -d same as --no-dereference --preserve=links\n\
178 "), stdout);
179 fputs (_("\
180 -f, --force if an existing destination file cannot be\n\
181 opened, remove it and try again (redundant if\
183 the -n option is used)\n\
184 -i, --interactive prompt before overwrite (overrides a previous -n\
186 option)\n\
187 -H follow command-line symbolic links in SOURCE\n\
188 "), stdout);
189 fputs (_("\
190 -l, --link hard link files instead of copying\n\
191 -L, --dereference always follow symbolic links in SOURCE\n\
192 "), stdout);
193 fputs (_("\
194 -n, --no-clobber do not overwrite an existing file (overrides\n\
195 a previous -i option)\n\
196 -P, --no-dereference never follow symbolic links in SOURCE\n\
197 "), stdout);
198 fputs (_("\
199 -p same as --preserve=mode,ownership,timestamps\n\
200 --preserve[=ATTR_LIST] preserve the specified attributes (default:\n\
201 mode,ownership,timestamps), if possible\n\
202 additional attributes: context, links, xattr,\
204 all\n\
205 "), stdout);
206 fputs (_("\
207 --no-preserve=ATTR_LIST don't preserve the specified attributes\n\
208 --parents use full source file name under DIRECTORY\n\
209 "), stdout);
210 fputs (_("\
211 -R, -r, --recursive copy directories recursively\n\
212 --reflink[=WHEN] control clone/CoW copies. See below\n\
213 --remove-destination remove each existing destination file before\n\
214 attempting to open it (contrast with --force)\
215 \n"), stdout);
216 fputs (_("\
217 --sparse=WHEN control creation of sparse files. See below\n\
218 --strip-trailing-slashes remove any trailing slashes from each SOURCE\n\
219 argument\n\
220 "), stdout);
221 fputs (_("\
222 -s, --symbolic-link make symbolic links instead of copying\n\
223 -S, --suffix=SUFFIX override the usual backup suffix\n\
224 -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY\n\
225 -T, --no-target-directory treat DEST as a normal file\n\
226 "), stdout);
227 fputs (_("\
228 -u, --update copy only when the SOURCE file is newer\n\
229 than the destination file or when the\n\
230 destination file is missing\n\
231 -v, --verbose explain what is being done\n\
232 -x, --one-file-system stay on this file system\n\
233 "), stdout);
234 fputs (HELP_OPTION_DESCRIPTION, stdout);
235 fputs (VERSION_OPTION_DESCRIPTION, stdout);
236 fputs (_("\
238 By default, sparse SOURCE files are detected by a crude heuristic and the\n\
239 corresponding DEST file is made sparse as well. That is the behavior\n\
240 selected by --sparse=auto. Specify --sparse=always to create a sparse DEST\n\
241 file whenever the SOURCE file contains a long enough sequence of zero bytes.\n\
242 Use --sparse=never to inhibit creation of sparse files.\n\
244 When --reflink[=always] is specified, perform a lightweight copy, where the\n\
245 data blocks are copied only when modified. If this is not possible the copy\n\
246 fails, or if --reflink=auto is specified, fall back to a standard copy.\n\
247 "), stdout);
248 fputs (_("\
250 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
251 The version control method may be selected via the --backup option or through\n\
252 the VERSION_CONTROL environment variable. Here are the values:\n\
254 "), stdout);
255 fputs (_("\
256 none, off never make backups (even if --backup is given)\n\
257 numbered, t make numbered backups\n\
258 existing, nil numbered if numbered backups exist, simple otherwise\n\
259 simple, never always make simple backups\n\
260 "), stdout);
261 fputs (_("\
263 As a special case, cp makes a backup of SOURCE when the force and backup\n\
264 options are given and SOURCE and DEST are the same name for an existing,\n\
265 regular file.\n\
266 "), stdout);
267 emit_ancillary_info ();
269 exit (status);
272 /* Ensure that the parent directories of CONST_DST_NAME have the
273 correct protections, for the --parents option. This is done
274 after all copying has been completed, to allow permissions
275 that don't include user write/execute.
277 SRC_OFFSET is the index in CONST_DST_NAME of the beginning of the
278 source directory name.
280 ATTR_LIST is a null-terminated linked list of structures that
281 indicates the end of the filename of each intermediate directory
282 in CONST_DST_NAME that may need to have its attributes changed.
283 The command `cp --parents --preserve a/b/c d/e_dir' changes the
284 attributes of the directories d/e_dir/a and d/e_dir/a/b to match
285 the corresponding source directories regardless of whether they
286 existed before the `cp' command was given.
288 Return true if the parent of CONST_DST_NAME and any intermediate
289 directories specified by ATTR_LIST have the proper permissions
290 when done. */
292 static bool
293 re_protect (char const *const_dst_name, size_t src_offset,
294 struct dir_attr *attr_list, const struct cp_options *x)
296 struct dir_attr *p;
297 char *dst_name; /* A copy of CONST_DST_NAME we can change. */
298 char *src_name; /* The source name in `dst_name'. */
300 ASSIGN_STRDUPA (dst_name, const_dst_name);
301 src_name = dst_name + src_offset;
303 for (p = attr_list; p; p = p->next)
305 dst_name[p->slash_offset] = '\0';
307 /* Adjust the times (and if possible, ownership) for the copy.
308 chown turns off set[ug]id bits for non-root,
309 so do the chmod last. */
311 if (x->preserve_timestamps)
313 struct timespec timespec[2];
315 timespec[0] = get_stat_atime (&p->st);
316 timespec[1] = get_stat_mtime (&p->st);
318 if (utimens (dst_name, timespec))
320 error (0, errno, _("failed to preserve times for %s"),
321 quote (dst_name));
322 return false;
326 if (x->preserve_ownership)
328 if (lchown (dst_name, p->st.st_uid, p->st.st_gid) != 0)
330 if (! chown_failure_ok (x))
332 error (0, errno, _("failed to preserve ownership for %s"),
333 quote (dst_name));
334 return false;
336 /* Failing to preserve ownership is OK. Still, try to preserve
337 the group, but ignore the possible error. */
338 ignore_value (lchown (dst_name, -1, p->st.st_gid));
342 if (x->preserve_mode)
344 if (copy_acl (src_name, -1, dst_name, -1, p->st.st_mode) != 0)
345 return false;
347 else if (p->restore_mode)
349 if (lchmod (dst_name, p->st.st_mode) != 0)
351 error (0, errno, _("failed to preserve permissions for %s"),
352 quote (dst_name));
353 return false;
357 dst_name[p->slash_offset] = '/';
359 return true;
362 /* Ensure that the parent directory of CONST_DIR exists, for
363 the --parents option.
365 SRC_OFFSET is the index in CONST_DIR (which is a destination
366 directory) of the beginning of the source directory name.
367 Create any leading directories that don't already exist.
368 If VERBOSE_FMT_STRING is nonzero, use it as a printf format
369 string for printing a message after successfully making a directory.
370 The format should take two string arguments: the names of the
371 source and destination directories.
372 Creates a linked list of attributes of intermediate directories,
373 *ATTR_LIST, for re_protect to use after calling copy.
374 Sets *NEW_DST if this function creates parent of CONST_DIR.
376 Return true if parent of CONST_DIR exists as a directory with the proper
377 permissions when done. */
379 /* FIXME: Synch this function with the one in ../lib/mkdir-p.c. */
381 static bool
382 make_dir_parents_private (char const *const_dir, size_t src_offset,
383 char const *verbose_fmt_string,
384 struct dir_attr **attr_list, bool *new_dst,
385 const struct cp_options *x)
387 struct stat stats;
388 char *dir; /* A copy of CONST_DIR we can change. */
389 char *src; /* Source name in DIR. */
390 char *dst_dir; /* Leading directory of DIR. */
391 size_t dirlen; /* Length of DIR. */
393 ASSIGN_STRDUPA (dir, const_dir);
395 src = dir + src_offset;
397 dirlen = dir_len (dir);
398 dst_dir = alloca (dirlen + 1);
399 memcpy (dst_dir, dir, dirlen);
400 dst_dir[dirlen] = '\0';
402 *attr_list = NULL;
404 if (stat (dst_dir, &stats) != 0)
406 /* A parent of CONST_DIR does not exist.
407 Make all missing intermediate directories. */
408 char *slash;
410 slash = src;
411 while (*slash == '/')
412 slash++;
413 while ((slash = strchr (slash, '/')))
415 struct dir_attr *new IF_LINT ( = NULL);
416 bool missing_dir;
418 *slash = '\0';
419 missing_dir = (stat (dir, &stats) != 0);
421 if (missing_dir || x->preserve_ownership || x->preserve_mode
422 || x->preserve_timestamps)
424 /* Add this directory to the list of directories whose
425 modes might need fixing later. */
426 struct stat src_st;
427 int src_errno = (stat (src, &src_st) != 0
428 ? errno
429 : S_ISDIR (src_st.st_mode)
431 : ENOTDIR);
432 if (src_errno)
434 error (0, src_errno, _("failed to get attributes of %s"),
435 quote (src));
436 return false;
439 new = xmalloc (sizeof *new);
440 new->st = src_st;
441 new->slash_offset = slash - dir;
442 new->restore_mode = false;
443 new->next = *attr_list;
444 *attr_list = new;
447 if (missing_dir)
449 mode_t src_mode;
450 mode_t omitted_permissions;
451 mode_t mkdir_mode;
453 /* This component does not exist. We must set
454 *new_dst and new->st.st_mode inside this loop because,
455 for example, in the command `cp --parents ../a/../b/c e_dir',
456 make_dir_parents_private creates only e_dir/../a if
457 ./b already exists. */
458 *new_dst = true;
459 src_mode = new->st.st_mode;
461 /* If the ownership or special mode bits might change,
462 omit some permissions at first, so unauthorized users
463 cannot nip in before the file is ready. */
464 omitted_permissions = (src_mode
465 & (x->preserve_ownership
466 ? S_IRWXG | S_IRWXO
467 : x->preserve_mode
468 ? S_IWGRP | S_IWOTH
469 : 0));
471 /* POSIX says mkdir's behavior is implementation-defined when
472 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
473 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
474 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
475 mkdir_mode = src_mode & CHMOD_MODE_BITS & ~omitted_permissions;
476 if (mkdir (dir, mkdir_mode) != 0)
478 error (0, errno, _("cannot make directory %s"),
479 quote (dir));
480 return false;
482 else
484 if (verbose_fmt_string != NULL)
485 printf (verbose_fmt_string, src, dir);
488 /* We need search and write permissions to the new directory
489 for writing the directory's contents. Check if these
490 permissions are there. */
492 if (lstat (dir, &stats))
494 error (0, errno, _("failed to get attributes of %s"),
495 quote (dir));
496 return false;
500 if (! x->preserve_mode)
502 if (omitted_permissions & ~stats.st_mode)
503 omitted_permissions &= ~ cached_umask ();
504 if (omitted_permissions & ~stats.st_mode
505 || (stats.st_mode & S_IRWXU) != S_IRWXU)
507 new->st.st_mode = stats.st_mode | omitted_permissions;
508 new->restore_mode = true;
512 if ((stats.st_mode & S_IRWXU) != S_IRWXU)
514 /* Make the new directory searchable and writable.
515 The original permissions will be restored later. */
517 if (lchmod (dir, stats.st_mode | S_IRWXU) != 0)
519 error (0, errno, _("setting permissions for %s"),
520 quote (dir));
521 return false;
525 else if (!S_ISDIR (stats.st_mode))
527 error (0, 0, _("%s exists but is not a directory"),
528 quote (dir));
529 return false;
531 else
532 *new_dst = false;
533 *slash++ = '/';
535 /* Avoid unnecessary calls to `stat' when given
536 file names containing multiple adjacent slashes. */
537 while (*slash == '/')
538 slash++;
542 /* We get here if the parent of DIR already exists. */
544 else if (!S_ISDIR (stats.st_mode))
546 error (0, 0, _("%s exists but is not a directory"), quote (dst_dir));
547 return false;
549 else
551 *new_dst = false;
553 return true;
556 /* FILE is the last operand of this command.
557 Return true if FILE is a directory.
558 But report an error and exit if there is a problem accessing FILE,
559 or if FILE does not exist but would have to refer to an existing
560 directory if it referred to anything at all.
562 If the file exists, store the file's status into *ST.
563 Otherwise, set *NEW_DST. */
565 static bool
566 target_directory_operand (char const *file, struct stat *st, bool *new_dst)
568 int err = (stat (file, st) == 0 ? 0 : errno);
569 bool is_a_dir = !err && S_ISDIR (st->st_mode);
570 if (err)
572 if (err != ENOENT)
573 error (EXIT_FAILURE, err, _("accessing %s"), quote (file));
574 *new_dst = true;
576 return is_a_dir;
579 /* Scan the arguments, and copy each by calling copy.
580 Return true if successful. */
582 static bool
583 do_copy (int n_files, char **file, const char *target_directory,
584 bool no_target_directory, struct cp_options *x)
586 struct stat sb;
587 bool new_dst = false;
588 bool ok = true;
590 if (n_files <= !target_directory)
592 if (n_files <= 0)
593 error (0, 0, _("missing file operand"));
594 else
595 error (0, 0, _("missing destination file operand after %s"),
596 quote (file[0]));
597 usage (EXIT_FAILURE);
600 if (no_target_directory)
602 if (target_directory)
603 error (EXIT_FAILURE, 0,
604 _("cannot combine --target-directory (-t) "
605 "and --no-target-directory (-T)"));
606 if (2 < n_files)
608 error (0, 0, _("extra operand %s"), quote (file[2]));
609 usage (EXIT_FAILURE);
611 /* Update NEW_DST and SB, which may be checked below. */
612 ignore_value (target_directory_operand (file[n_files -1], &sb, &new_dst));
614 else if (!target_directory)
616 if (2 <= n_files
617 && target_directory_operand (file[n_files - 1], &sb, &new_dst))
618 target_directory = file[--n_files];
619 else if (2 < n_files)
620 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
621 quote (file[n_files - 1]));
624 if (target_directory)
626 /* cp file1...filen edir
627 Copy the files `file1' through `filen'
628 to the existing directory `edir'. */
629 int i;
631 /* Initialize these hash tables only if we'll need them.
632 The problems they're used to detect can arise only if
633 there are two or more files to copy. */
634 if (2 <= n_files)
636 dest_info_init (x);
637 src_info_init (x);
640 for (i = 0; i < n_files; i++)
642 char *dst_name;
643 bool parent_exists = true; /* True if dir_name (dst_name) exists. */
644 struct dir_attr *attr_list;
645 char *arg_in_concat = NULL;
646 char *arg = file[i];
648 /* Trailing slashes are meaningful (i.e., maybe worth preserving)
649 only in the source file names. */
650 if (remove_trailing_slashes)
651 strip_trailing_slashes (arg);
653 if (parents_option)
655 char *arg_no_trailing_slash;
657 /* Use `arg' without trailing slashes in constructing destination
658 file names. Otherwise, we can end up trying to create a
659 directory via `mkdir ("dst/foo/"...', which is not portable.
660 It fails, due to the trailing slash, on at least
661 NetBSD 1.[34] systems. */
662 ASSIGN_STRDUPA (arg_no_trailing_slash, arg);
663 strip_trailing_slashes (arg_no_trailing_slash);
665 /* Append all of `arg' (minus any trailing slash) to `dest'. */
666 dst_name = file_name_concat (target_directory,
667 arg_no_trailing_slash,
668 &arg_in_concat);
670 /* For --parents, we have to make sure that the directory
671 dir_name (dst_name) exists. We may have to create a few
672 leading directories. */
673 parent_exists =
674 (make_dir_parents_private
675 (dst_name, arg_in_concat - dst_name,
676 (x->verbose ? "%s -> %s\n" : NULL),
677 &attr_list, &new_dst, x));
679 else
681 char *arg_base;
682 /* Append the last component of `arg' to `target_directory'. */
684 ASSIGN_BASENAME_STRDUPA (arg_base, arg);
685 /* For `cp -R source/.. dest', don't copy into `dest/..'. */
686 dst_name = (STREQ (arg_base, "..")
687 ? xstrdup (target_directory)
688 : file_name_concat (target_directory, arg_base,
689 NULL));
692 if (!parent_exists)
694 /* make_dir_parents_private failed, so don't even
695 attempt the copy. */
696 ok = false;
698 else
700 bool copy_into_self;
701 ok &= copy (arg, dst_name, new_dst, x, &copy_into_self, NULL);
703 if (parents_option)
704 ok &= re_protect (dst_name, arg_in_concat - dst_name,
705 attr_list, x);
708 if (parents_option)
710 while (attr_list)
712 struct dir_attr *p = attr_list;
713 attr_list = attr_list->next;
714 free (p);
718 free (dst_name);
721 else /* !target_directory */
723 char const *new_dest;
724 char const *source = file[0];
725 char const *dest = file[1];
726 bool unused;
728 if (parents_option)
730 error (0, 0,
731 _("with --parents, the destination must be a directory"));
732 usage (EXIT_FAILURE);
735 /* When the force and backup options have been specified and
736 the source and destination are the same name for an existing
737 regular file, convert the user's command, e.g.,
738 `cp --force --backup foo foo' to `cp --force foo fooSUFFIX'
739 where SUFFIX is determined by any version control options used. */
741 if (x->unlink_dest_after_failed_open
742 && x->backup_type != no_backups
743 && STREQ (source, dest)
744 && !new_dst && S_ISREG (sb.st_mode))
746 static struct cp_options x_tmp;
748 new_dest = find_backup_file_name (dest, x->backup_type);
749 /* Set x->backup_type to `no_backups' so that the normal backup
750 mechanism is not used when performing the actual copy.
751 backup_type must be set to `no_backups' only *after* the above
752 call to find_backup_file_name -- that function uses
753 backup_type to determine the suffix it applies. */
754 x_tmp = *x;
755 x_tmp.backup_type = no_backups;
756 x = &x_tmp;
758 else
760 new_dest = dest;
763 ok = copy (source, new_dest, 0, x, &unused, NULL);
766 return ok;
769 static void
770 cp_option_init (struct cp_options *x)
772 cp_options_default (x);
773 x->copy_as_regular = true;
774 x->dereference = DEREF_UNDEFINED;
775 x->unlink_dest_before_opening = false;
776 x->unlink_dest_after_failed_open = false;
777 x->hard_link = false;
778 x->interactive = I_UNSPECIFIED;
779 x->move_mode = false;
780 x->one_file_system = false;
781 x->reflink_mode = REFLINK_NEVER;
783 x->preserve_ownership = false;
784 x->preserve_links = false;
785 x->preserve_mode = false;
786 x->preserve_timestamps = false;
787 x->preserve_security_context = false;
788 x->require_preserve_context = false;
789 x->preserve_xattr = false;
790 x->reduce_diagnostics = false;
791 x->require_preserve_xattr = false;
793 x->data_copy_required = true;
794 x->require_preserve = false;
795 x->recursive = false;
796 x->sparse_mode = SPARSE_AUTO;
797 x->symbolic_link = false;
798 x->set_mode = false;
799 x->mode = 0;
801 /* Not used. */
802 x->stdin_tty = false;
804 x->update = false;
805 x->verbose = false;
807 /* By default, refuse to open a dangling destination symlink, because
808 in general one cannot do that safely, give the current semantics of
809 open's O_EXCL flag, (which POSIX doesn't even allow cp to use, btw).
810 But POSIX requires it. */
811 x->open_dangling_dest_symlink = getenv ("POSIXLY_CORRECT") != NULL;
813 x->dest_info = NULL;
814 x->src_info = NULL;
817 /* Given a string, ARG, containing a comma-separated list of arguments
818 to the --preserve option, set the appropriate fields of X to ON_OFF. */
819 static void
820 decode_preserve_arg (char const *arg, struct cp_options *x, bool on_off)
822 enum File_attribute
824 PRESERVE_MODE,
825 PRESERVE_TIMESTAMPS,
826 PRESERVE_OWNERSHIP,
827 PRESERVE_LINK,
828 PRESERVE_CONTEXT,
829 PRESERVE_XATTR,
830 PRESERVE_ALL
832 static enum File_attribute const preserve_vals[] =
834 PRESERVE_MODE, PRESERVE_TIMESTAMPS,
835 PRESERVE_OWNERSHIP, PRESERVE_LINK, PRESERVE_CONTEXT, PRESERVE_XATTR,
836 PRESERVE_ALL
838 /* Valid arguments to the `--preserve' option. */
839 static char const* const preserve_args[] =
841 "mode", "timestamps",
842 "ownership", "links", "context", "xattr", "all", NULL
844 ARGMATCH_VERIFY (preserve_args, preserve_vals);
846 char *arg_writable = xstrdup (arg);
847 char *s = arg_writable;
850 /* find next comma */
851 char *comma = strchr (s, ',');
852 enum File_attribute val;
854 /* If we found a comma, put a NUL in its place and advance. */
855 if (comma)
856 *comma++ = 0;
858 /* process S. */
859 val = XARGMATCH ("--preserve", s, preserve_args, preserve_vals);
860 switch (val)
862 case PRESERVE_MODE:
863 x->preserve_mode = on_off;
864 break;
866 case PRESERVE_TIMESTAMPS:
867 x->preserve_timestamps = on_off;
868 break;
870 case PRESERVE_OWNERSHIP:
871 x->preserve_ownership = on_off;
872 break;
874 case PRESERVE_LINK:
875 x->preserve_links = on_off;
876 break;
878 case PRESERVE_CONTEXT:
879 x->preserve_security_context = on_off;
880 x->require_preserve_context = on_off;
881 break;
883 case PRESERVE_XATTR:
884 x->preserve_xattr = on_off;
885 x->require_preserve_xattr = on_off;
886 break;
888 case PRESERVE_ALL:
889 x->preserve_mode = on_off;
890 x->preserve_timestamps = on_off;
891 x->preserve_ownership = on_off;
892 x->preserve_links = on_off;
893 if (selinux_enabled)
894 x->preserve_security_context = on_off;
895 x->preserve_xattr = on_off;
896 break;
898 default:
899 abort ();
901 s = comma;
903 while (s);
905 free (arg_writable);
909 main (int argc, char **argv)
911 int c;
912 bool ok;
913 bool make_backups = false;
914 char *backup_suffix_string;
915 char *version_control_string = NULL;
916 struct cp_options x;
917 bool copy_contents = false;
918 char *target_directory = NULL;
919 bool no_target_directory = false;
921 initialize_main (&argc, &argv);
922 set_program_name (argv[0]);
923 setlocale (LC_ALL, "");
924 bindtextdomain (PACKAGE, LOCALEDIR);
925 textdomain (PACKAGE);
927 atexit (close_stdin);
929 selinux_enabled = (0 < is_selinux_enabled ());
930 cp_option_init (&x);
932 /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
933 we'll actually use backup_suffix_string. */
934 backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
936 while ((c = getopt_long (argc, argv, "abdfHilLnprst:uvxPRS:T",
937 long_opts, NULL))
938 != -1)
940 switch (c)
942 case SPARSE_OPTION:
943 x.sparse_mode = XARGMATCH ("--sparse", optarg,
944 sparse_type_string, sparse_type);
945 break;
947 case REFLINK_OPTION:
948 if (optarg == NULL)
949 x.reflink_mode = REFLINK_ALWAYS;
950 else
951 x.reflink_mode = XARGMATCH ("--reflink", optarg,
952 reflink_type_string, reflink_type);
953 break;
955 case 'a':
956 /* Like -dR --preserve=all with reduced failure diagnostics. */
957 x.dereference = DEREF_NEVER;
958 x.preserve_links = true;
959 x.preserve_ownership = true;
960 x.preserve_mode = true;
961 x.preserve_timestamps = true;
962 x.require_preserve = true;
963 if (selinux_enabled)
964 x.preserve_security_context = true;
965 x.preserve_xattr = true;
966 x.reduce_diagnostics = true;
967 x.recursive = true;
968 break;
970 case 'b':
971 make_backups = true;
972 if (optarg)
973 version_control_string = optarg;
974 break;
976 case ATTRIBUTES_ONLY_OPTION:
977 x.data_copy_required = false;
978 break;
980 case COPY_CONTENTS_OPTION:
981 copy_contents = true;
982 break;
984 case 'd':
985 x.preserve_links = true;
986 x.dereference = DEREF_NEVER;
987 break;
989 case 'f':
990 x.unlink_dest_after_failed_open = true;
991 break;
993 case 'H':
994 x.dereference = DEREF_COMMAND_LINE_ARGUMENTS;
995 break;
997 case 'i':
998 x.interactive = I_ASK_USER;
999 break;
1001 case 'l':
1002 x.hard_link = true;
1003 break;
1005 case 'L':
1006 x.dereference = DEREF_ALWAYS;
1007 break;
1009 case 'n':
1010 x.interactive = I_ALWAYS_NO;
1011 break;
1013 case 'P':
1014 x.dereference = DEREF_NEVER;
1015 break;
1017 case NO_PRESERVE_ATTRIBUTES_OPTION:
1018 decode_preserve_arg (optarg, &x, false);
1019 break;
1021 case PRESERVE_ATTRIBUTES_OPTION:
1022 if (optarg == NULL)
1024 /* Fall through to the case for `p' below. */
1026 else
1028 decode_preserve_arg (optarg, &x, true);
1029 x.require_preserve = true;
1030 break;
1033 case 'p':
1034 x.preserve_ownership = true;
1035 x.preserve_mode = true;
1036 x.preserve_timestamps = true;
1037 x.require_preserve = true;
1038 break;
1040 case PARENTS_OPTION:
1041 parents_option = true;
1042 break;
1044 case 'r':
1045 case 'R':
1046 x.recursive = true;
1047 break;
1049 case UNLINK_DEST_BEFORE_OPENING:
1050 x.unlink_dest_before_opening = true;
1051 break;
1053 case STRIP_TRAILING_SLASHES_OPTION:
1054 remove_trailing_slashes = true;
1055 break;
1057 case 's':
1058 x.symbolic_link = true;
1059 break;
1061 case 't':
1062 if (target_directory)
1063 error (EXIT_FAILURE, 0,
1064 _("multiple target directories specified"));
1065 else
1067 struct stat st;
1068 if (stat (optarg, &st) != 0)
1069 error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg));
1070 if (! S_ISDIR (st.st_mode))
1071 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
1072 quote (optarg));
1074 target_directory = optarg;
1075 break;
1077 case 'T':
1078 no_target_directory = true;
1079 break;
1081 case 'u':
1082 x.update = true;
1083 break;
1085 case 'v':
1086 x.verbose = true;
1087 break;
1089 case 'x':
1090 x.one_file_system = true;
1091 break;
1093 case 'S':
1094 make_backups = true;
1095 backup_suffix_string = optarg;
1096 break;
1098 case_GETOPT_HELP_CHAR;
1100 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1102 default:
1103 usage (EXIT_FAILURE);
1107 if (x.hard_link && x.symbolic_link)
1109 error (0, 0, _("cannot make both hard and symbolic links"));
1110 usage (EXIT_FAILURE);
1113 if (make_backups && x.interactive == I_ALWAYS_NO)
1115 error (0, 0,
1116 _("options --backup and --no-clobber are mutually exclusive"));
1117 usage (EXIT_FAILURE);
1120 if (x.reflink_mode == REFLINK_ALWAYS && x.sparse_mode != SPARSE_AUTO)
1122 error (0, 0, _("--reflink can be used only with --sparse=auto"));
1123 usage (EXIT_FAILURE);
1126 if (backup_suffix_string)
1127 simple_backup_suffix = xstrdup (backup_suffix_string);
1129 x.backup_type = (make_backups
1130 ? xget_version (_("backup type"),
1131 version_control_string)
1132 : no_backups);
1134 if (x.dereference == DEREF_UNDEFINED)
1136 if (x.recursive)
1137 /* This is compatible with FreeBSD. */
1138 x.dereference = DEREF_NEVER;
1139 else
1140 x.dereference = DEREF_ALWAYS;
1143 if (x.recursive)
1144 x.copy_as_regular = copy_contents;
1146 /* If --force (-f) was specified and we're in link-creation mode,
1147 first remove any existing destination file. */
1148 if (x.unlink_dest_after_failed_open && (x.hard_link || x.symbolic_link))
1149 x.unlink_dest_before_opening = true;
1151 if (x.preserve_security_context)
1153 if (!selinux_enabled)
1154 error (EXIT_FAILURE, 0,
1155 _("cannot preserve security context "
1156 "without an SELinux-enabled kernel"));
1159 #if !USE_XATTR
1160 if (x.require_preserve_xattr)
1161 error (EXIT_FAILURE, 0, _("cannot preserve extended attributes, cp is "
1162 "built without xattr support"));
1163 #endif
1165 /* Allocate space for remembering copied and created files. */
1167 hash_init ();
1169 ok = do_copy (argc - optind, argv + optind,
1170 target_directory, no_target_directory, &x);
1172 forget_all ();
1174 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);