tests: ensure touch honors trailing slash
[coreutils/ericb.git] / src / cp.c
blobf3fc1aae7a66de241d984fff0963d56e110f2577
1 /* cp.c -- file copying (main routines)
2 Copyright (C) 89, 90, 91, 1995-2009 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 COPY_CONTENTS_OPTION = CHAR_MAX + 1,
76 NO_PRESERVE_ATTRIBUTES_OPTION,
77 PARENTS_OPTION,
78 PRESERVE_ATTRIBUTES_OPTION,
79 REFLINK_OPTION,
80 SPARSE_OPTION,
81 STRIP_TRAILING_SLASHES_OPTION,
82 UNLINK_DEST_BEFORE_OPENING
85 /* True if the kernel is SELinux enabled. */
86 static bool selinux_enabled;
88 /* If true, the command "cp x/e_file e_dir" uses "e_dir/x/e_file"
89 as its destination instead of the usual "e_dir/e_file." */
90 static bool parents_option = false;
92 /* Remove any trailing slashes from each SOURCE argument. */
93 static bool remove_trailing_slashes;
95 static char const *const sparse_type_string[] =
97 "never", "auto", "always", NULL
99 static enum Sparse_type const sparse_type[] =
101 SPARSE_NEVER, SPARSE_AUTO, SPARSE_ALWAYS
103 ARGMATCH_VERIFY (sparse_type_string, sparse_type);
105 static char const *const reflink_type_string[] =
107 "auto", "always", NULL
109 static enum Reflink_type const reflink_type[] =
111 REFLINK_AUTO, REFLINK_ALWAYS
113 ARGMATCH_VERIFY (reflink_type_string, reflink_type);
115 static struct option const long_opts[] =
117 {"archive", no_argument, NULL, 'a'},
118 {"backup", optional_argument, NULL, 'b'},
119 {"copy-contents", no_argument, NULL, COPY_CONTENTS_OPTION},
120 {"dereference", no_argument, NULL, 'L'},
121 {"force", no_argument, NULL, 'f'},
122 {"interactive", no_argument, NULL, 'i'},
123 {"link", no_argument, NULL, 'l'},
124 {"no-clobber", no_argument, NULL, 'n'},
125 {"no-dereference", no_argument, NULL, 'P'},
126 {"no-preserve", required_argument, NULL, NO_PRESERVE_ATTRIBUTES_OPTION},
127 {"no-target-directory", no_argument, NULL, 'T'},
128 {"one-file-system", no_argument, NULL, 'x'},
129 {"parents", no_argument, NULL, PARENTS_OPTION},
130 {"path", no_argument, NULL, PARENTS_OPTION}, /* Deprecated. */
131 {"preserve", optional_argument, NULL, PRESERVE_ATTRIBUTES_OPTION},
132 {"recursive", no_argument, NULL, 'R'},
133 {"remove-destination", no_argument, NULL, UNLINK_DEST_BEFORE_OPENING},
134 {"sparse", required_argument, NULL, SPARSE_OPTION},
135 {"reflink", optional_argument, NULL, REFLINK_OPTION},
136 {"strip-trailing-slashes", no_argument, NULL, STRIP_TRAILING_SLASHES_OPTION},
137 {"suffix", required_argument, NULL, 'S'},
138 {"symbolic-link", no_argument, NULL, 's'},
139 {"target-directory", required_argument, NULL, 't'},
140 {"update", no_argument, NULL, 'u'},
141 {"verbose", no_argument, NULL, 'v'},
142 {GETOPT_HELP_OPTION_DECL},
143 {GETOPT_VERSION_OPTION_DECL},
144 {NULL, 0, NULL, 0}
147 void
148 usage (int status)
150 if (status != EXIT_SUCCESS)
151 fprintf (stderr, _("Try `%s --help' for more information.\n"),
152 program_name);
153 else
155 printf (_("\
156 Usage: %s [OPTION]... [-T] SOURCE DEST\n\
157 or: %s [OPTION]... SOURCE... DIRECTORY\n\
158 or: %s [OPTION]... -t DIRECTORY SOURCE...\n\
160 program_name, program_name, program_name);
161 fputs (_("\
162 Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.\n\
164 "), stdout);
165 fputs (_("\
166 Mandatory arguments to long options are mandatory for short options too.\n\
167 "), stdout);
168 fputs (_("\
169 -a, --archive same as -dR --preserve=all\n\
170 --backup[=CONTROL] make a backup of each existing destination file\n\
171 -b like --backup but does not accept an argument\n\
172 --copy-contents copy contents of special files when recursive\n\
173 -d same as --no-dereference --preserve=links\n\
174 "), stdout);
175 fputs (_("\
176 -f, --force if an existing destination file cannot be\n\
177 opened, remove it and try again (redundant if\n\
178 the -n option is used)\n\
179 -i, --interactive prompt before overwrite (overrides a previous -n\n\
180 option)\n\
181 -H follow command-line symbolic links in SOURCE\n\
182 "), stdout);
183 fputs (_("\
184 -l, --link link files instead of copying\n\
185 -L, --dereference always follow symbolic links in SOURCE\n\
186 "), stdout);
187 fputs (_("\
188 -n, --no-clobber do not overwrite an existing file (overrides\n\
189 a previous -i option)\n\
190 -P, --no-dereference never follow symbolic links in SOURCE\n\
191 "), stdout);
192 fputs (_("\
193 -p same as --preserve=mode,ownership,timestamps\n\
194 --preserve[=ATTR_LIST] preserve the specified attributes (default:\n\
195 mode,ownership,timestamps), if possible\n\
196 additional attributes: context, links, xattr,\n\
197 all\n\
198 "), stdout);
199 fputs (_("\
200 --no-preserve=ATTR_LIST don't preserve the specified attributes\n\
201 --parents use full source file name under DIRECTORY\n\
202 "), stdout);
203 fputs (_("\
204 -R, -r, --recursive copy directories recursively\n\
205 --reflink[=WHEN] control clone/CoW copies. See below.\n\
206 --remove-destination remove each existing destination file before\n\
207 attempting to open it (contrast with --force)\n\
208 "), stdout);
209 fputs (_("\
210 --sparse=WHEN control creation of sparse files. See below.\n\
211 --strip-trailing-slashes remove any trailing slashes from each SOURCE\n\
212 argument\n\
213 "), stdout);
214 fputs (_("\
215 -s, --symbolic-link make symbolic links instead of copying\n\
216 -S, --suffix=SUFFIX override the usual backup suffix\n\
217 -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY\n\
218 -T, --no-target-directory treat DEST as a normal file\n\
219 "), stdout);
220 fputs (_("\
221 -u, --update copy only when the SOURCE file is newer\n\
222 than the destination file or when the\n\
223 destination file is missing\n\
224 -v, --verbose explain what is being done\n\
225 -x, --one-file-system stay on this file system\n\
226 "), stdout);
227 fputs (HELP_OPTION_DESCRIPTION, stdout);
228 fputs (VERSION_OPTION_DESCRIPTION, stdout);
229 fputs (_("\
231 By default, sparse SOURCE files are detected by a crude heuristic and the\n\
232 corresponding DEST file is made sparse as well. That is the behavior\n\
233 selected by --sparse=auto. Specify --sparse=always to create a sparse DEST\n\
234 file whenever the SOURCE file contains a long enough sequence of zero bytes.\n\
235 Use --sparse=never to inhibit creation of sparse files.\n\
237 When --reflink[=always] is specified, perform a lightweight copy, where the\n\
238 data blocks are copied only when modified. If this is not possible the copy\n\
239 fails, or if --reflink=auto is specified, fall back to a standard copy.\n\
240 "), stdout);
241 fputs (_("\
243 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
244 The version control method may be selected via the --backup option or through\n\
245 the VERSION_CONTROL environment variable. Here are the values:\n\
247 "), stdout);
248 fputs (_("\
249 none, off never make backups (even if --backup is given)\n\
250 numbered, t make numbered backups\n\
251 existing, nil numbered if numbered backups exist, simple otherwise\n\
252 simple, never always make simple backups\n\
253 "), stdout);
254 fputs (_("\
256 As a special case, cp makes a backup of SOURCE when the force and backup\n\
257 options are given and SOURCE and DEST are the same name for an existing,\n\
258 regular file.\n\
259 "), stdout);
260 emit_ancillary_info ();
262 exit (status);
265 /* Ensure that the parent directories of CONST_DST_NAME have the
266 correct protections, for the --parents option. This is done
267 after all copying has been completed, to allow permissions
268 that don't include user write/execute.
270 SRC_OFFSET is the index in CONST_DST_NAME of the beginning of the
271 source directory name.
273 ATTR_LIST is a null-terminated linked list of structures that
274 indicates the end of the filename of each intermediate directory
275 in CONST_DST_NAME that may need to have its attributes changed.
276 The command `cp --parents --preserve a/b/c d/e_dir' changes the
277 attributes of the directories d/e_dir/a and d/e_dir/a/b to match
278 the corresponding source directories regardless of whether they
279 existed before the `cp' command was given.
281 Return true if the parent of CONST_DST_NAME and any intermediate
282 directories specified by ATTR_LIST have the proper permissions
283 when done. */
285 static bool
286 re_protect (char const *const_dst_name, size_t src_offset,
287 struct dir_attr *attr_list, const struct cp_options *x)
289 struct dir_attr *p;
290 char *dst_name; /* A copy of CONST_DST_NAME we can change. */
291 char *src_name; /* The source name in `dst_name'. */
293 ASSIGN_STRDUPA (dst_name, const_dst_name);
294 src_name = dst_name + src_offset;
296 for (p = attr_list; p; p = p->next)
298 dst_name[p->slash_offset] = '\0';
300 /* Adjust the times (and if possible, ownership) for the copy.
301 chown turns off set[ug]id bits for non-root,
302 so do the chmod last. */
304 if (x->preserve_timestamps)
306 struct timespec timespec[2];
308 timespec[0] = get_stat_atime (&p->st);
309 timespec[1] = get_stat_mtime (&p->st);
311 if (utimens (dst_name, timespec))
313 error (0, errno, _("failed to preserve times for %s"),
314 quote (dst_name));
315 return false;
319 if (x->preserve_ownership)
321 if (lchown (dst_name, p->st.st_uid, p->st.st_gid) != 0)
323 if (! chown_failure_ok (x))
325 error (0, errno, _("failed to preserve ownership for %s"),
326 quote (dst_name));
327 return false;
329 /* Failing to preserve ownership is OK. Still, try to preserve
330 the group, but ignore the possible error. */
331 ignore_value (lchown (dst_name, -1, p->st.st_gid));
335 if (x->preserve_mode)
337 if (copy_acl (src_name, -1, dst_name, -1, p->st.st_mode) != 0)
338 return false;
340 else if (p->restore_mode)
342 if (lchmod (dst_name, p->st.st_mode) != 0)
344 error (0, errno, _("failed to preserve permissions for %s"),
345 quote (dst_name));
346 return false;
350 dst_name[p->slash_offset] = '/';
352 return true;
355 /* Ensure that the parent directory of CONST_DIR exists, for
356 the --parents option.
358 SRC_OFFSET is the index in CONST_DIR (which is a destination
359 directory) of the beginning of the source directory name.
360 Create any leading directories that don't already exist.
361 If VERBOSE_FMT_STRING is nonzero, use it as a printf format
362 string for printing a message after successfully making a directory.
363 The format should take two string arguments: the names of the
364 source and destination directories.
365 Creates a linked list of attributes of intermediate directories,
366 *ATTR_LIST, for re_protect to use after calling copy.
367 Sets *NEW_DST if this function creates parent of CONST_DIR.
369 Return true if parent of CONST_DIR exists as a directory with the proper
370 permissions when done. */
372 /* FIXME: Synch this function with the one in ../lib/mkdir-p.c. */
374 static bool
375 make_dir_parents_private (char const *const_dir, size_t src_offset,
376 char const *verbose_fmt_string,
377 struct dir_attr **attr_list, bool *new_dst,
378 const struct cp_options *x)
380 struct stat stats;
381 char *dir; /* A copy of CONST_DIR we can change. */
382 char *src; /* Source name in DIR. */
383 char *dst_dir; /* Leading directory of DIR. */
384 size_t dirlen; /* Length of DIR. */
386 ASSIGN_STRDUPA (dir, const_dir);
388 src = dir + src_offset;
390 dirlen = dir_len (dir);
391 dst_dir = alloca (dirlen + 1);
392 memcpy (dst_dir, dir, dirlen);
393 dst_dir[dirlen] = '\0';
395 *attr_list = NULL;
397 if (stat (dst_dir, &stats) != 0)
399 /* A parent of CONST_DIR does not exist.
400 Make all missing intermediate directories. */
401 char *slash;
403 slash = src;
404 while (*slash == '/')
405 slash++;
406 while ((slash = strchr (slash, '/')))
408 struct dir_attr *new IF_LINT (= NULL);
409 bool missing_dir;
411 *slash = '\0';
412 missing_dir = (stat (dir, &stats) != 0);
414 if (missing_dir | x->preserve_ownership | x->preserve_mode
415 | x->preserve_timestamps)
417 /* Add this directory to the list of directories whose
418 modes might need fixing later. */
419 struct stat src_st;
420 int src_errno = (stat (src, &src_st) != 0
421 ? errno
422 : S_ISDIR (src_st.st_mode)
424 : ENOTDIR);
425 if (src_errno)
427 error (0, src_errno, _("failed to get attributes of %s"),
428 quote (src));
429 return false;
432 new = xmalloc (sizeof *new);
433 new->st = src_st;
434 new->slash_offset = slash - dir;
435 new->restore_mode = false;
436 new->next = *attr_list;
437 *attr_list = new;
440 if (missing_dir)
442 mode_t src_mode;
443 mode_t omitted_permissions;
444 mode_t mkdir_mode;
446 /* This component does not exist. We must set
447 *new_dst and new->st.st_mode inside this loop because,
448 for example, in the command `cp --parents ../a/../b/c e_dir',
449 make_dir_parents_private creates only e_dir/../a if
450 ./b already exists. */
451 *new_dst = true;
452 src_mode = new->st.st_mode;
454 /* If the ownership or special mode bits might change,
455 omit some permissions at first, so unauthorized users
456 cannot nip in before the file is ready. */
457 omitted_permissions = (src_mode
458 & (x->preserve_ownership
459 ? S_IRWXG | S_IRWXO
460 : x->preserve_mode
461 ? S_IWGRP | S_IWOTH
462 : 0));
464 /* POSIX says mkdir's behavior is implementation-defined when
465 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
466 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
467 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
468 mkdir_mode = src_mode & CHMOD_MODE_BITS & ~omitted_permissions;
469 if (mkdir (dir, mkdir_mode) != 0)
471 error (0, errno, _("cannot make directory %s"),
472 quote (dir));
473 return false;
475 else
477 if (verbose_fmt_string != NULL)
478 printf (verbose_fmt_string, src, dir);
481 /* We need search and write permissions to the new directory
482 for writing the directory's contents. Check if these
483 permissions are there. */
485 if (lstat (dir, &stats))
487 error (0, errno, _("failed to get attributes of %s"),
488 quote (dir));
489 return false;
493 if (! x->preserve_mode)
495 if (omitted_permissions & ~stats.st_mode)
496 omitted_permissions &= ~ cached_umask ();
497 if (omitted_permissions & ~stats.st_mode
498 || (stats.st_mode & S_IRWXU) != S_IRWXU)
500 new->st.st_mode = stats.st_mode | omitted_permissions;
501 new->restore_mode = true;
505 if ((stats.st_mode & S_IRWXU) != S_IRWXU)
507 /* Make the new directory searchable and writable.
508 The original permissions will be restored later. */
510 if (lchmod (dir, stats.st_mode | S_IRWXU) != 0)
512 error (0, errno, _("setting permissions for %s"),
513 quote (dir));
514 return false;
518 else if (!S_ISDIR (stats.st_mode))
520 error (0, 0, _("%s exists but is not a directory"),
521 quote (dir));
522 return false;
524 else
525 *new_dst = false;
526 *slash++ = '/';
528 /* Avoid unnecessary calls to `stat' when given
529 file names containing multiple adjacent slashes. */
530 while (*slash == '/')
531 slash++;
535 /* We get here if the parent of DIR already exists. */
537 else if (!S_ISDIR (stats.st_mode))
539 error (0, 0, _("%s exists but is not a directory"), quote (dst_dir));
540 return false;
542 else
544 *new_dst = false;
546 return true;
549 /* FILE is the last operand of this command.
550 Return true if FILE is a directory.
551 But report an error and exit if there is a problem accessing FILE,
552 or if FILE does not exist but would have to refer to an existing
553 directory if it referred to anything at all.
555 If the file exists, store the file's status into *ST.
556 Otherwise, set *NEW_DST. */
558 static bool
559 target_directory_operand (char const *file, struct stat *st, bool *new_dst)
561 int err = (stat (file, st) == 0 ? 0 : errno);
562 bool is_a_dir = !err && S_ISDIR (st->st_mode);
563 if (err)
565 if (err != ENOENT)
566 error (EXIT_FAILURE, err, _("accessing %s"), quote (file));
567 *new_dst = true;
569 return is_a_dir;
572 /* Scan the arguments, and copy each by calling copy.
573 Return true if successful. */
575 static bool
576 do_copy (int n_files, char **file, const char *target_directory,
577 bool no_target_directory, struct cp_options *x)
579 struct stat sb;
580 bool new_dst = false;
581 bool ok = true;
583 if (n_files <= !target_directory)
585 if (n_files <= 0)
586 error (0, 0, _("missing file operand"));
587 else
588 error (0, 0, _("missing destination file operand after %s"),
589 quote (file[0]));
590 usage (EXIT_FAILURE);
593 if (no_target_directory)
595 if (target_directory)
596 error (EXIT_FAILURE, 0,
597 _("cannot combine --target-directory (-t) "
598 "and --no-target-directory (-T)"));
599 if (2 < n_files)
601 error (0, 0, _("extra operand %s"), quote (file[2]));
602 usage (EXIT_FAILURE);
605 else if (!target_directory)
607 if (2 <= n_files
608 && target_directory_operand (file[n_files - 1], &sb, &new_dst))
609 target_directory = file[--n_files];
610 else if (2 < n_files)
611 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
612 quote (file[n_files - 1]));
615 if (target_directory)
617 /* cp file1...filen edir
618 Copy the files `file1' through `filen'
619 to the existing directory `edir'. */
620 int i;
622 /* Initialize these hash tables only if we'll need them.
623 The problems they're used to detect can arise only if
624 there are two or more files to copy. */
625 if (2 <= n_files)
627 dest_info_init (x);
628 src_info_init (x);
631 for (i = 0; i < n_files; i++)
633 char *dst_name;
634 bool parent_exists = true; /* True if dir_name (dst_name) exists. */
635 struct dir_attr *attr_list;
636 char *arg_in_concat = NULL;
637 char *arg = file[i];
639 /* Trailing slashes are meaningful (i.e., maybe worth preserving)
640 only in the source file names. */
641 if (remove_trailing_slashes)
642 strip_trailing_slashes (arg);
644 if (parents_option)
646 char *arg_no_trailing_slash;
648 /* Use `arg' without trailing slashes in constructing destination
649 file names. Otherwise, we can end up trying to create a
650 directory via `mkdir ("dst/foo/"...', which is not portable.
651 It fails, due to the trailing slash, on at least
652 NetBSD 1.[34] systems. */
653 ASSIGN_STRDUPA (arg_no_trailing_slash, arg);
654 strip_trailing_slashes (arg_no_trailing_slash);
656 /* Append all of `arg' (minus any trailing slash) to `dest'. */
657 dst_name = file_name_concat (target_directory,
658 arg_no_trailing_slash,
659 &arg_in_concat);
661 /* For --parents, we have to make sure that the directory
662 dir_name (dst_name) exists. We may have to create a few
663 leading directories. */
664 parent_exists =
665 (make_dir_parents_private
666 (dst_name, arg_in_concat - dst_name,
667 (x->verbose ? "%s -> %s\n" : NULL),
668 &attr_list, &new_dst, x));
670 else
672 char *arg_base;
673 /* Append the last component of `arg' to `target_directory'. */
675 ASSIGN_BASENAME_STRDUPA (arg_base, arg);
676 /* For `cp -R source/.. dest', don't copy into `dest/..'. */
677 dst_name = (STREQ (arg_base, "..")
678 ? xstrdup (target_directory)
679 : file_name_concat (target_directory, arg_base,
680 NULL));
683 if (!parent_exists)
685 /* make_dir_parents_private failed, so don't even
686 attempt the copy. */
687 ok = false;
689 else
691 bool copy_into_self;
692 ok &= copy (arg, dst_name, new_dst, x, &copy_into_self, NULL);
694 if (parents_option)
695 ok &= re_protect (dst_name, arg_in_concat - dst_name,
696 attr_list, x);
699 if (parents_option)
701 while (attr_list)
703 struct dir_attr *p = attr_list;
704 attr_list = attr_list->next;
705 free (p);
709 free (dst_name);
712 else /* !target_directory */
714 char const *new_dest;
715 char const *source = file[0];
716 char const *dest = file[1];
717 bool unused;
719 if (parents_option)
721 error (0, 0,
722 _("with --parents, the destination must be a directory"));
723 usage (EXIT_FAILURE);
726 /* When the force and backup options have been specified and
727 the source and destination are the same name for an existing
728 regular file, convert the user's command, e.g.,
729 `cp --force --backup foo foo' to `cp --force foo fooSUFFIX'
730 where SUFFIX is determined by any version control options used. */
732 if (x->unlink_dest_after_failed_open
733 && x->backup_type != no_backups
734 && STREQ (source, dest)
735 && !new_dst && S_ISREG (sb.st_mode))
737 static struct cp_options x_tmp;
739 new_dest = find_backup_file_name (dest, x->backup_type);
740 /* Set x->backup_type to `no_backups' so that the normal backup
741 mechanism is not used when performing the actual copy.
742 backup_type must be set to `no_backups' only *after* the above
743 call to find_backup_file_name -- that function uses
744 backup_type to determine the suffix it applies. */
745 x_tmp = *x;
746 x_tmp.backup_type = no_backups;
747 x = &x_tmp;
749 else
751 new_dest = dest;
754 ok = copy (source, new_dest, 0, x, &unused, NULL);
757 return ok;
760 static void
761 cp_option_init (struct cp_options *x)
763 cp_options_default (x);
764 x->copy_as_regular = true;
765 x->dereference = DEREF_UNDEFINED;
766 x->unlink_dest_before_opening = false;
767 x->unlink_dest_after_failed_open = false;
768 x->hard_link = false;
769 x->interactive = I_UNSPECIFIED;
770 x->move_mode = false;
771 x->one_file_system = false;
772 x->reflink_mode = REFLINK_NEVER;
774 x->preserve_ownership = false;
775 x->preserve_links = false;
776 x->preserve_mode = false;
777 x->preserve_timestamps = false;
778 x->preserve_security_context = false;
779 x->require_preserve_context = false;
780 x->preserve_xattr = false;
781 x->reduce_diagnostics = false;
782 x->require_preserve_xattr = false;
784 x->require_preserve = false;
785 x->recursive = false;
786 x->sparse_mode = SPARSE_AUTO;
787 x->symbolic_link = false;
788 x->set_mode = false;
789 x->mode = 0;
791 /* Not used. */
792 x->stdin_tty = false;
794 x->update = false;
795 x->verbose = false;
797 /* By default, refuse to open a dangling destination symlink, because
798 in general one cannot do that safely, give the current semantics of
799 open's O_EXCL flag, (which POSIX doesn't even allow cp to use, btw).
800 But POSIX requires it. */
801 x->open_dangling_dest_symlink = getenv ("POSIXLY_CORRECT") != NULL;
803 x->dest_info = NULL;
804 x->src_info = NULL;
807 /* Given a string, ARG, containing a comma-separated list of arguments
808 to the --preserve option, set the appropriate fields of X to ON_OFF. */
809 static void
810 decode_preserve_arg (char const *arg, struct cp_options *x, bool on_off)
812 enum File_attribute
814 PRESERVE_MODE,
815 PRESERVE_TIMESTAMPS,
816 PRESERVE_OWNERSHIP,
817 PRESERVE_LINK,
818 PRESERVE_CONTEXT,
819 PRESERVE_XATTR,
820 PRESERVE_ALL
822 static enum File_attribute const preserve_vals[] =
824 PRESERVE_MODE, PRESERVE_TIMESTAMPS,
825 PRESERVE_OWNERSHIP, PRESERVE_LINK, PRESERVE_CONTEXT, PRESERVE_XATTR,
826 PRESERVE_ALL
828 /* Valid arguments to the `--preserve' option. */
829 static char const* const preserve_args[] =
831 "mode", "timestamps",
832 "ownership", "links", "context", "xattr", "all", NULL
834 ARGMATCH_VERIFY (preserve_args, preserve_vals);
836 char *arg_writable = xstrdup (arg);
837 char *s = arg_writable;
840 /* find next comma */
841 char *comma = strchr (s, ',');
842 enum File_attribute val;
844 /* If we found a comma, put a NUL in its place and advance. */
845 if (comma)
846 *comma++ = 0;
848 /* process S. */
849 val = XARGMATCH ("--preserve", s, preserve_args, preserve_vals);
850 switch (val)
852 case PRESERVE_MODE:
853 x->preserve_mode = on_off;
854 break;
856 case PRESERVE_TIMESTAMPS:
857 x->preserve_timestamps = on_off;
858 break;
860 case PRESERVE_OWNERSHIP:
861 x->preserve_ownership = on_off;
862 break;
864 case PRESERVE_LINK:
865 x->preserve_links = on_off;
866 break;
868 case PRESERVE_CONTEXT:
869 x->preserve_security_context = on_off;
870 x->require_preserve_context = on_off;
871 break;
873 case PRESERVE_XATTR:
874 x->preserve_xattr = on_off;
875 x->require_preserve_xattr = on_off;
876 break;
878 case PRESERVE_ALL:
879 x->preserve_mode = on_off;
880 x->preserve_timestamps = on_off;
881 x->preserve_ownership = on_off;
882 x->preserve_links = on_off;
883 if (selinux_enabled)
884 x->preserve_security_context = on_off;
885 x->preserve_xattr = on_off;
886 break;
888 default:
889 abort ();
891 s = comma;
893 while (s);
895 free (arg_writable);
899 main (int argc, char **argv)
901 int c;
902 bool ok;
903 bool make_backups = false;
904 char *backup_suffix_string;
905 char *version_control_string = NULL;
906 struct cp_options x;
907 bool copy_contents = false;
908 char *target_directory = NULL;
909 bool no_target_directory = false;
911 initialize_main (&argc, &argv);
912 set_program_name (argv[0]);
913 setlocale (LC_ALL, "");
914 bindtextdomain (PACKAGE, LOCALEDIR);
915 textdomain (PACKAGE);
917 atexit (close_stdin);
919 selinux_enabled = (0 < is_selinux_enabled ());
920 cp_option_init (&x);
922 /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
923 we'll actually use backup_suffix_string. */
924 backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
926 while ((c = getopt_long (argc, argv, "abdfHilLnprst:uvxPRS:T",
927 long_opts, NULL))
928 != -1)
930 switch (c)
932 case SPARSE_OPTION:
933 x.sparse_mode = XARGMATCH ("--sparse", optarg,
934 sparse_type_string, sparse_type);
935 break;
937 case REFLINK_OPTION:
938 if (optarg == NULL)
939 x.reflink_mode = REFLINK_ALWAYS;
940 else
941 x.reflink_mode = XARGMATCH ("--reflink", optarg,
942 reflink_type_string, reflink_type);
943 break;
945 case 'a': /* Like -dR --preserve=all with reduced failure diagnostics. */
946 x.dereference = DEREF_NEVER;
947 x.preserve_links = true;
948 x.preserve_ownership = true;
949 x.preserve_mode = true;
950 x.preserve_timestamps = true;
951 x.require_preserve = true;
952 if (selinux_enabled)
953 x.preserve_security_context = true;
954 x.preserve_xattr = true;
955 x.reduce_diagnostics = true;
956 x.recursive = true;
957 break;
959 case 'b':
960 make_backups = true;
961 if (optarg)
962 version_control_string = optarg;
963 break;
965 case COPY_CONTENTS_OPTION:
966 copy_contents = true;
967 break;
969 case 'd':
970 x.preserve_links = true;
971 x.dereference = DEREF_NEVER;
972 break;
974 case 'f':
975 x.unlink_dest_after_failed_open = true;
976 break;
978 case 'H':
979 x.dereference = DEREF_COMMAND_LINE_ARGUMENTS;
980 break;
982 case 'i':
983 x.interactive = I_ASK_USER;
984 break;
986 case 'l':
987 x.hard_link = true;
988 break;
990 case 'L':
991 x.dereference = DEREF_ALWAYS;
992 break;
994 case 'n':
995 x.interactive = I_ALWAYS_NO;
996 break;
998 case 'P':
999 x.dereference = DEREF_NEVER;
1000 break;
1002 case NO_PRESERVE_ATTRIBUTES_OPTION:
1003 decode_preserve_arg (optarg, &x, false);
1004 break;
1006 case PRESERVE_ATTRIBUTES_OPTION:
1007 if (optarg == NULL)
1009 /* Fall through to the case for `p' below. */
1011 else
1013 decode_preserve_arg (optarg, &x, true);
1014 x.require_preserve = true;
1015 break;
1018 case 'p':
1019 x.preserve_ownership = true;
1020 x.preserve_mode = true;
1021 x.preserve_timestamps = true;
1022 x.require_preserve = true;
1023 break;
1025 case PARENTS_OPTION:
1026 parents_option = true;
1027 break;
1029 case 'r':
1030 case 'R':
1031 x.recursive = true;
1032 break;
1034 case UNLINK_DEST_BEFORE_OPENING:
1035 x.unlink_dest_before_opening = true;
1036 break;
1038 case STRIP_TRAILING_SLASHES_OPTION:
1039 remove_trailing_slashes = true;
1040 break;
1042 case 's':
1043 x.symbolic_link = true;
1044 break;
1046 case 't':
1047 if (target_directory)
1048 error (EXIT_FAILURE, 0,
1049 _("multiple target directories specified"));
1050 else
1052 struct stat st;
1053 if (stat (optarg, &st) != 0)
1054 error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg));
1055 if (! S_ISDIR (st.st_mode))
1056 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
1057 quote (optarg));
1059 target_directory = optarg;
1060 break;
1062 case 'T':
1063 no_target_directory = true;
1064 break;
1066 case 'u':
1067 x.update = true;
1068 break;
1070 case 'v':
1071 x.verbose = true;
1072 break;
1074 case 'x':
1075 x.one_file_system = true;
1076 break;
1078 case 'S':
1079 make_backups = true;
1080 backup_suffix_string = optarg;
1081 break;
1083 case_GETOPT_HELP_CHAR;
1085 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1087 default:
1088 usage (EXIT_FAILURE);
1092 if (x.hard_link && x.symbolic_link)
1094 error (0, 0, _("cannot make both hard and symbolic links"));
1095 usage (EXIT_FAILURE);
1098 if (make_backups && x.interactive == I_ALWAYS_NO)
1100 error (0, 0,
1101 _("options --backup and --no-clobber are mutually exclusive"));
1102 usage (EXIT_FAILURE);
1105 if (x.reflink_mode == REFLINK_ALWAYS && x.sparse_mode != SPARSE_AUTO)
1107 error (0, 0, _("--reflink can be used only with --sparse=auto"));
1108 usage (EXIT_FAILURE);
1111 if (backup_suffix_string)
1112 simple_backup_suffix = xstrdup (backup_suffix_string);
1114 x.backup_type = (make_backups
1115 ? xget_version (_("backup type"),
1116 version_control_string)
1117 : no_backups);
1119 if (x.dereference == DEREF_UNDEFINED)
1121 if (x.recursive)
1122 /* This is compatible with FreeBSD. */
1123 x.dereference = DEREF_NEVER;
1124 else
1125 x.dereference = DEREF_ALWAYS;
1128 if (x.recursive)
1129 x.copy_as_regular = copy_contents;
1131 /* If --force (-f) was specified and we're in link-creation mode,
1132 first remove any existing destination file. */
1133 if (x.unlink_dest_after_failed_open && (x.hard_link || x.symbolic_link))
1134 x.unlink_dest_before_opening = true;
1136 if (x.preserve_security_context)
1138 if (!selinux_enabled)
1139 error (EXIT_FAILURE, 0,
1140 _("cannot preserve security context "
1141 "without an SELinux-enabled kernel"));
1144 #if !USE_XATTR
1145 if (x.require_preserve_xattr)
1146 error (EXIT_FAILURE, 0, _("cannot preserve extended attributes, cp is "
1147 "built without xattr support"));
1148 #endif
1150 /* Allocate space for remembering copied and created files. */
1152 hash_init ();
1154 ok = do_copy (argc - optind, argv + optind,
1155 target_directory, no_target_directory, &x);
1157 forget_all ();
1159 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);