A few more symlink-related fixes. Fix a bug triggered by cp
[coreutils/ericb.git] / src / cp.c
blob9436be6fbfcfd5fdde5288fb1105efd6c083795c
1 /* cp.c -- file copying (main routines)
2 Copyright (C) 89, 90, 91, 1995-2007 Free Software Foundation.
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 2, or (at your option)
7 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, write to the Free Software Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. */
20 #include <config.h>
21 #include <stdio.h>
22 #include <sys/types.h>
23 #include <getopt.h>
24 #include <selinux/selinux.h>
26 #include "system.h"
27 #include "argmatch.h"
28 #include "backupfile.h"
29 #include "copy.h"
30 #include "cp-hash.h"
31 #include "error.h"
32 #include "filenamecat.h"
33 #include "lchmod.h"
34 #include "quote.h"
35 #include "stat-time.h"
36 #include "utimens.h"
37 #include "acl.h"
39 #if ! HAVE_LCHOWN
40 # define lchown(name, uid, gid) chown (name, uid, gid)
41 #endif
43 #define ASSIGN_BASENAME_STRDUPA(Dest, File_name) \
44 do \
45 { \
46 char *tmp_abns_; \
47 ASSIGN_STRDUPA (tmp_abns_, (File_name)); \
48 Dest = last_component (tmp_abns_); \
49 strip_trailing_slashes (Dest); \
50 } \
51 while (0)
53 /* The official name of this program (e.g., no `g' prefix). */
54 #define PROGRAM_NAME "cp"
56 #define AUTHORS "Torbjorn Granlund", "David MacKenzie", "Jim Meyering"
58 /* Used by do_copy, make_dir_parents_private, and re_protect
59 to keep a list of leading directories whose protections
60 need to be fixed after copying. */
61 struct dir_attr
63 struct stat st;
64 bool restore_mode;
65 size_t slash_offset;
66 struct dir_attr *next;
69 /* For long options that have no equivalent short option, use a
70 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
71 enum
73 COPY_CONTENTS_OPTION = CHAR_MAX + 1,
74 NO_PRESERVE_ATTRIBUTES_OPTION,
75 PARENTS_OPTION,
76 PRESERVE_ATTRIBUTES_OPTION,
77 REPLY_OPTION,
78 SPARSE_OPTION,
79 STRIP_TRAILING_SLASHES_OPTION,
80 UNLINK_DEST_BEFORE_OPENING
83 /* Initial number of entries in each hash table entry's table of inodes. */
84 #define INITIAL_HASH_MODULE 100
86 /* Initial number of entries in the inode hash table. */
87 #define INITIAL_ENTRY_TAB_SIZE 70
89 /* The invocation name of this program. */
90 char *program_name;
92 /* True if the kernel is SELinux enabled. */
93 static bool selinux_enabled;
95 /* If true, the command "cp x/e_file e_dir" uses "e_dir/x/e_file"
96 as its destination instead of the usual "e_dir/e_file." */
97 static bool parents_option = false;
99 /* Remove any trailing slashes from each SOURCE argument. */
100 static bool remove_trailing_slashes;
102 static char const *const sparse_type_string[] =
104 "never", "auto", "always", NULL
106 static enum Sparse_type const sparse_type[] =
108 SPARSE_NEVER, SPARSE_AUTO, SPARSE_ALWAYS
110 ARGMATCH_VERIFY (sparse_type_string, sparse_type);
112 /* Valid arguments to the `--reply' option. */
113 static char const* const reply_args[] =
115 "yes", "no", "query", NULL
117 /* The values that correspond to the above strings. */
118 static int const reply_vals[] =
120 I_ALWAYS_YES, I_ALWAYS_NO, I_ASK_USER
122 ARGMATCH_VERIFY (reply_args, reply_vals);
124 static struct option const long_opts[] =
126 {"archive", no_argument, NULL, 'a'},
127 {"backup", optional_argument, NULL, 'b'},
128 {"copy-contents", no_argument, NULL, COPY_CONTENTS_OPTION},
129 {"dereference", no_argument, NULL, 'L'},
130 {"force", no_argument, NULL, 'f'},
131 {"interactive", no_argument, NULL, 'i'},
132 {"link", no_argument, NULL, 'l'},
133 {"no-dereference", no_argument, NULL, 'P'},
134 {"no-preserve", required_argument, NULL, NO_PRESERVE_ATTRIBUTES_OPTION},
135 {"no-target-directory", no_argument, NULL, 'T'},
136 {"one-file-system", no_argument, NULL, 'x'},
137 {"parents", no_argument, NULL, PARENTS_OPTION},
138 {"path", no_argument, NULL, PARENTS_OPTION}, /* Deprecated. */
139 {"preserve", optional_argument, NULL, PRESERVE_ATTRIBUTES_OPTION},
140 {"recursive", no_argument, NULL, 'R'},
141 {"remove-destination", no_argument, NULL, UNLINK_DEST_BEFORE_OPENING},
142 {"reply", required_argument, NULL, REPLY_OPTION}, /* Deprecated 2005-07-03,
143 remove in 2008. */
144 {"sparse", required_argument, NULL, SPARSE_OPTION},
145 {"strip-trailing-slashes", no_argument, NULL, STRIP_TRAILING_SLASHES_OPTION},
146 {"suffix", required_argument, NULL, 'S'},
147 {"symbolic-link", no_argument, NULL, 's'},
148 {"target-directory", required_argument, NULL, 't'},
149 {"update", no_argument, NULL, 'u'},
150 {"verbose", no_argument, NULL, 'v'},
151 {GETOPT_HELP_OPTION_DECL},
152 {GETOPT_VERSION_OPTION_DECL},
153 {NULL, 0, NULL, 0}
156 void
157 usage (int status)
159 if (status != EXIT_SUCCESS)
160 fprintf (stderr, _("Try `%s --help' for more information.\n"),
161 program_name);
162 else
164 printf (_("\
165 Usage: %s [OPTION]... [-T] SOURCE DEST\n\
166 or: %s [OPTION]... SOURCE... DIRECTORY\n\
167 or: %s [OPTION]... -t DIRECTORY SOURCE...\n\
169 program_name, program_name, program_name);
170 fputs (_("\
171 Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.\n\
173 "), stdout);
174 fputs (_("\
175 Mandatory arguments to long options are mandatory for short options too.\n\
176 "), stdout);
177 fputs (_("\
178 -a, --archive same as -dpPR\n\
179 --backup[=CONTROL] make a backup of each existing destination file\n\
180 -b like --backup but does not accept an argument\n\
181 --copy-contents copy contents of special files when recursive\n\
182 -d same as --no-dereference --preserve=link\n\
183 "), stdout);
184 fputs (_("\
185 -f, --force if an existing destination file cannot be\n\
186 opened, remove it and try again\n\
187 -i, --interactive prompt before overwrite\n\
188 -H follow command-line symbolic links in SOURCE\n\
189 "), stdout);
190 fputs (_("\
191 -l, --link link files instead of copying\n\
192 -L, --dereference always follow symbolic links in SOURCE\n\
193 "), stdout);
194 fputs (_("\
195 -P, --no-dereference never follow symbolic links in SOURCE\n\
196 "), stdout);
197 fputs (_("\
198 -p same as --preserve=mode,ownership,timestamps\n\
199 --preserve[=ATTR_LIST] preserve the specified attributes (default:\n\
200 mode,ownership,timestamps), if possible\n\
201 additional attributes: context, links, all\n\
202 "), stdout);
203 fputs (_("\
204 --no-preserve=ATTR_LIST don't preserve the specified attributes\n\
205 --parents use full source file name under DIRECTORY\n\
206 "), stdout);
207 fputs (_("\
208 -R, -r, --recursive copy directories recursively\n\
209 --remove-destination remove each existing destination file before\n\
210 attempting to open it (contrast with --force)\n\
211 "), stdout);
212 fputs (_("\
213 --sparse=WHEN control creation of sparse files\n\
214 --strip-trailing-slashes remove any trailing slashes from each SOURCE\n\
215 argument\n\
216 "), stdout);
217 fputs (_("\
218 -s, --symbolic-link make symbolic links instead of copying\n\
219 -S, --suffix=SUFFIX override the usual backup suffix\n\
220 -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY\n\
221 -T, --no-target-directory treat DEST as a normal file\n\
222 "), stdout);
223 fputs (_("\
224 -u, --update copy only when the SOURCE file is newer\n\
225 than the destination file or when the\n\
226 destination file is missing\n\
227 -v, --verbose explain what is being done\n\
228 -x, --one-file-system stay on this file system\n\
229 "), stdout);
230 fputs (HELP_OPTION_DESCRIPTION, stdout);
231 fputs (VERSION_OPTION_DESCRIPTION, stdout);
232 fputs (_("\
234 By default, sparse SOURCE files are detected by a crude heuristic and the\n\
235 corresponding DEST file is made sparse as well. That is the behavior\n\
236 selected by --sparse=auto. Specify --sparse=always to create a sparse DEST\n\
237 file whenever the SOURCE file contains a long enough sequence of zero bytes.\n\
238 Use --sparse=never to inhibit creation of sparse files.\n\
240 "), stdout);
241 fputs (_("\
242 The backup suffix is `~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX.\n\
243 The version control method may be selected via the --backup option or through\n\
244 the VERSION_CONTROL environment variable. Here are the values:\n\
246 "), stdout);
247 fputs (_("\
248 none, off never make backups (even if --backup is given)\n\
249 numbered, t make numbered backups\n\
250 existing, nil numbered if numbered backups exist, simple otherwise\n\
251 simple, never always make simple backups\n\
252 "), stdout);
253 fputs (_("\
255 As a special case, cp makes a backup of SOURCE when the force and backup\n\
256 options are given and SOURCE and DEST are the same name for an existing,\n\
257 regular file.\n\
258 "), stdout);
259 emit_bug_reporting_address ();
261 exit (status);
264 /* Ensure that the parent directories of CONST_DST_NAME have the
265 correct protections, for the --parents option. This is done
266 after all copying has been completed, to allow permissions
267 that don't include user write/execute.
269 SRC_OFFSET is the index in CONST_DST_NAME of the beginning of the
270 source directory name.
272 ATTR_LIST is a null-terminated linked list of structures that
273 indicates the end of the filename of each intermediate directory
274 in CONST_DST_NAME that may need to have its attributes changed.
275 The command `cp --parents --preserve a/b/c d/e_dir' changes the
276 attributes of the directories d/e_dir/a and d/e_dir/a/b to match
277 the corresponding source directories regardless of whether they
278 existed before the `cp' command was given.
280 Return true if the parent of CONST_DST_NAME and any intermediate
281 directories specified by ATTR_LIST have the proper permissions
282 when done. */
284 static bool
285 re_protect (char const *const_dst_name, size_t src_offset,
286 struct dir_attr *attr_list, const struct cp_options *x)
288 struct dir_attr *p;
289 char *dst_name; /* A copy of CONST_DST_NAME we can change. */
290 char *src_name; /* The source name in `dst_name'. */
292 ASSIGN_STRDUPA (dst_name, const_dst_name);
293 src_name = dst_name + src_offset;
295 for (p = attr_list; p; p = p->next)
297 dst_name[p->slash_offset] = '\0';
299 /* Adjust the times (and if possible, ownership) for the copy.
300 chown turns off set[ug]id bits for non-root,
301 so do the chmod last. */
303 if (x->preserve_timestamps)
305 struct timespec timespec[2];
307 timespec[0] = get_stat_atime (&p->st);
308 timespec[1] = get_stat_mtime (&p->st);
310 if (utimens (dst_name, timespec))
312 error (0, errno, _("failed to preserve times for %s"),
313 quote (dst_name));
314 return false;
318 if (x->preserve_ownership)
320 if (lchown (dst_name, p->st.st_uid, p->st.st_gid) != 0
321 && ! chown_failure_ok (x))
323 error (0, errno, _("failed to preserve ownership for %s"),
324 quote (dst_name));
325 return false;
329 if (x->preserve_mode)
331 if (copy_acl (src_name, -1, dst_name, -1, p->st.st_mode) != 0)
332 return false;
334 else if (p->restore_mode)
336 if (lchmod (dst_name, p->st.st_mode) != 0)
338 error (0, errno, _("failed to preserve permissions for %s"),
339 quote (dst_name));
340 return false;
344 dst_name[p->slash_offset] = '/';
346 return true;
349 /* Ensure that the parent directory of CONST_DIR exists, for
350 the --parents option.
352 SRC_OFFSET is the index in CONST_DIR (which is a destination
353 directory) of the beginning of the source directory name.
354 Create any leading directories that don't already exist.
355 If VERBOSE_FMT_STRING is nonzero, use it as a printf format
356 string for printing a message after successfully making a directory.
357 The format should take two string arguments: the names of the
358 source and destination directories.
359 Creates a linked list of attributes of intermediate directories,
360 *ATTR_LIST, for re_protect to use after calling copy.
361 Sets *NEW_DST if this function creates parent of CONST_DIR.
363 Return true if parent of CONST_DIR exists as a directory with the proper
364 permissions when done. */
366 /* FIXME: Synch this function with the one in ../lib/mkdir-p.c. */
368 static bool
369 make_dir_parents_private (char const *const_dir, size_t src_offset,
370 char const *verbose_fmt_string,
371 struct dir_attr **attr_list, bool *new_dst,
372 const struct cp_options *x)
374 struct stat stats;
375 char *dir; /* A copy of CONST_DIR we can change. */
376 char *src; /* Source name in DIR. */
377 char *dst_dir; /* Leading directory of DIR. */
378 size_t dirlen; /* Length of DIR. */
380 ASSIGN_STRDUPA (dir, const_dir);
382 src = dir + src_offset;
384 dirlen = dir_len (dir);
385 dst_dir = alloca (dirlen + 1);
386 memcpy (dst_dir, dir, dirlen);
387 dst_dir[dirlen] = '\0';
389 *attr_list = NULL;
391 if (stat (dst_dir, &stats) != 0)
393 /* A parent of CONST_DIR does not exist.
394 Make all missing intermediate directories. */
395 char *slash;
397 slash = src;
398 while (*slash == '/')
399 slash++;
400 while ((slash = strchr (slash, '/')))
402 /* Add this directory to the list of directories whose modes need
403 fixing later. */
404 struct dir_attr *new = xmalloc (sizeof *new);
405 new->slash_offset = slash - dir;
406 new->restore_mode = false;
407 new->next = *attr_list;
408 *attr_list = new;
410 *slash = '\0';
411 if (stat (dir, &stats) != 0)
413 mode_t src_mode;
414 mode_t omitted_permissions;
415 mode_t mkdir_mode;
416 int src_errno;
418 /* This component does not exist. We must set
419 *new_dst and new->st.st_mode inside this loop because,
420 for example, in the command `cp --parents ../a/../b/c e_dir',
421 make_dir_parents_private creates only e_dir/../a if
422 ./b already exists. */
423 *new_dst = true;
424 src_errno = (stat (src, &new->st) != 0
425 ? errno
426 : S_ISDIR (new->st.st_mode)
428 : ENOTDIR);
429 if (src_errno)
431 error (0, src_errno, _("failed to get attributes of %s"),
432 quote (src));
433 return false;
435 src_mode = new->st.st_mode;
437 /* If the ownership or special mode bits might change,
438 omit some permissions at first, so unauthorized users
439 cannot nip in before the file is ready. */
440 omitted_permissions = (src_mode
441 & (x->preserve_ownership
442 ? S_IRWXG | S_IRWXO
443 : x->preserve_mode
444 ? S_IWGRP | S_IWOTH
445 : 0));
447 /* POSIX says mkdir's behavior is implementation-defined when
448 (src_mode & ~S_IRWXUGO) != 0. However, common practice is
449 to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir
450 decide what to do with S_ISUID | S_ISGID | S_ISVTX. */
451 mkdir_mode = src_mode & CHMOD_MODE_BITS & ~omitted_permissions;
452 if (mkdir (dir, mkdir_mode) != 0)
454 error (0, errno, _("cannot make directory %s"),
455 quote (dir));
456 return false;
458 else
460 if (verbose_fmt_string != NULL)
461 printf (verbose_fmt_string, src, dir);
464 /* We need search and write permissions to the new directory
465 for writing the directory's contents. Check if these
466 permissions are there. */
468 if (lstat (dir, &stats))
470 error (0, errno, _("failed to get attributes of %s"),
471 quote (dir));
472 return false;
476 if (! x->preserve_mode)
478 if (omitted_permissions & ~stats.st_mode)
479 omitted_permissions &= ~ cached_umask ();
480 if (omitted_permissions & ~stats.st_mode
481 || (stats.st_mode & S_IRWXU) != S_IRWXU)
483 new->st.st_mode = stats.st_mode | omitted_permissions;
484 new->restore_mode = true;
488 if ((stats.st_mode & S_IRWXU) != S_IRWXU)
490 /* Make the new directory searchable and writable.
491 The original permissions will be restored later. */
493 if (lchmod (dir, stats.st_mode | S_IRWXU) != 0)
495 error (0, errno, _("setting permissions for %s"),
496 quote (dir));
497 return false;
501 else if (!S_ISDIR (stats.st_mode))
503 error (0, 0, _("%s exists but is not a directory"),
504 quote (dir));
505 return false;
507 else
508 *new_dst = false;
509 *slash++ = '/';
511 /* Avoid unnecessary calls to `stat' when given
512 file names containing multiple adjacent slashes. */
513 while (*slash == '/')
514 slash++;
518 /* We get here if the parent of DIR already exists. */
520 else if (!S_ISDIR (stats.st_mode))
522 error (0, 0, _("%s exists but is not a directory"), quote (dst_dir));
523 return false;
525 else
527 *new_dst = false;
529 return true;
532 /* FILE is the last operand of this command.
533 Return true if FILE is a directory.
534 But report an error and exit if there is a problem accessing FILE,
535 or if FILE does not exist but would have to refer to an existing
536 directory if it referred to anything at all.
538 If the file exists, store the file's status into *ST.
539 Otherwise, set *NEW_DST. */
541 static bool
542 target_directory_operand (char const *file, struct stat *st, bool *new_dst)
544 int err = (stat (file, st) == 0 ? 0 : errno);
545 bool is_a_dir = !err && S_ISDIR (st->st_mode);
546 if (err)
548 if (err != ENOENT)
549 error (EXIT_FAILURE, err, _("accessing %s"), quote (file));
550 *new_dst = true;
552 return is_a_dir;
555 /* Scan the arguments, and copy each by calling copy.
556 Return true if successful. */
558 static bool
559 do_copy (int n_files, char **file, const char *target_directory,
560 bool no_target_directory, struct cp_options *x)
562 struct stat sb;
563 bool new_dst = false;
564 bool ok = true;
566 if (n_files <= !target_directory)
568 if (n_files <= 0)
569 error (0, 0, _("missing file operand"));
570 else
571 error (0, 0, _("missing destination file operand after %s"),
572 quote (file[0]));
573 usage (EXIT_FAILURE);
576 if (no_target_directory)
578 if (target_directory)
579 error (EXIT_FAILURE, 0,
580 _("Cannot combine --target-directory (-t) "
581 "and --no-target-directory (-T)"));
582 if (2 < n_files)
584 error (0, 0, _("extra operand %s"), quote (file[2]));
585 usage (EXIT_FAILURE);
588 else if (!target_directory)
590 if (2 <= n_files
591 && target_directory_operand (file[n_files - 1], &sb, &new_dst))
592 target_directory = file[--n_files];
593 else if (2 < n_files)
594 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
595 quote (file[n_files - 1]));
598 if (target_directory)
600 /* cp file1...filen edir
601 Copy the files `file1' through `filen'
602 to the existing directory `edir'. */
603 int i;
605 /* Initialize these hash tables only if we'll need them.
606 The problems they're used to detect can arise only if
607 there are two or more files to copy. */
608 if (2 <= n_files)
610 dest_info_init (x);
611 src_info_init (x);
614 for (i = 0; i < n_files; i++)
616 char *dst_name;
617 bool parent_exists = true; /* True if dir_name (dst_name) exists. */
618 struct dir_attr *attr_list;
619 char *arg_in_concat = NULL;
620 char *arg = file[i];
622 /* Trailing slashes are meaningful (i.e., maybe worth preserving)
623 only in the source file names. */
624 if (remove_trailing_slashes)
625 strip_trailing_slashes (arg);
627 if (parents_option)
629 char *arg_no_trailing_slash;
631 /* Use `arg' without trailing slashes in constructing destination
632 file names. Otherwise, we can end up trying to create a
633 directory via `mkdir ("dst/foo/"...', which is not portable.
634 It fails, due to the trailing slash, on at least
635 NetBSD 1.[34] systems. */
636 ASSIGN_STRDUPA (arg_no_trailing_slash, arg);
637 strip_trailing_slashes (arg_no_trailing_slash);
639 /* Append all of `arg' (minus any trailing slash) to `dest'. */
640 dst_name = file_name_concat (target_directory,
641 arg_no_trailing_slash,
642 &arg_in_concat);
644 /* For --parents, we have to make sure that the directory
645 dir_name (dst_name) exists. We may have to create a few
646 leading directories. */
647 parent_exists =
648 (make_dir_parents_private
649 (dst_name, arg_in_concat - dst_name,
650 (x->verbose ? "%s -> %s\n" : NULL),
651 &attr_list, &new_dst, x));
653 else
655 char *arg_base;
656 /* Append the last component of `arg' to `target_directory'. */
658 ASSIGN_BASENAME_STRDUPA (arg_base, arg);
659 /* For `cp -R source/.. dest', don't copy into `dest/..'. */
660 dst_name = (STREQ (arg_base, "..")
661 ? xstrdup (target_directory)
662 : file_name_concat (target_directory, arg_base,
663 NULL));
666 if (!parent_exists)
668 /* make_dir_parents_private failed, so don't even
669 attempt the copy. */
670 ok = false;
672 else
674 bool copy_into_self;
675 ok &= copy (arg, dst_name, new_dst, x, &copy_into_self, NULL);
677 if (parents_option)
678 ok &= re_protect (dst_name, arg_in_concat - dst_name,
679 attr_list, x);
682 free (dst_name);
685 else /* !target_directory */
687 char const *new_dest;
688 char const *source = file[0];
689 char const *dest = file[1];
690 bool unused;
692 if (parents_option)
694 error (0, 0,
695 _("with --parents, the destination must be a directory"));
696 usage (EXIT_FAILURE);
699 /* When the force and backup options have been specified and
700 the source and destination are the same name for an existing
701 regular file, convert the user's command, e.g.,
702 `cp --force --backup foo foo' to `cp --force foo fooSUFFIX'
703 where SUFFIX is determined by any version control options used. */
705 if (x->unlink_dest_after_failed_open
706 && x->backup_type != no_backups
707 && STREQ (source, dest)
708 && !new_dst && S_ISREG (sb.st_mode))
710 static struct cp_options x_tmp;
712 new_dest = find_backup_file_name (dest, x->backup_type);
713 /* Set x->backup_type to `no_backups' so that the normal backup
714 mechanism is not used when performing the actual copy.
715 backup_type must be set to `no_backups' only *after* the above
716 call to find_backup_file_name -- that function uses
717 backup_type to determine the suffix it applies. */
718 x_tmp = *x;
719 x_tmp.backup_type = no_backups;
720 x = &x_tmp;
722 else
724 new_dest = dest;
727 ok = copy (source, new_dest, 0, x, &unused, NULL);
730 return ok;
733 static void
734 cp_option_init (struct cp_options *x)
736 x->copy_as_regular = true;
737 x->dereference = DEREF_UNDEFINED;
738 x->unlink_dest_before_opening = false;
739 x->unlink_dest_after_failed_open = false;
740 x->hard_link = false;
741 x->interactive = I_UNSPECIFIED;
742 x->chown_privileges = chown_privileges ();
743 x->move_mode = false;
744 x->one_file_system = false;
746 x->preserve_ownership = false;
747 x->preserve_links = false;
748 x->preserve_mode = false;
749 x->preserve_timestamps = false;
750 x->preserve_security_context = false;
751 x->require_preserve_context = false;
753 x->require_preserve = false;
754 x->recursive = false;
755 x->sparse_mode = SPARSE_AUTO;
756 x->symbolic_link = false;
757 x->set_mode = false;
758 x->mode = 0;
760 /* Not used. */
761 x->stdin_tty = false;
763 x->update = false;
764 x->verbose = false;
765 x->dest_info = NULL;
766 x->src_info = NULL;
769 /* Given a string, ARG, containing a comma-separated list of arguments
770 to the --preserve option, set the appropriate fields of X to ON_OFF. */
771 static void
772 decode_preserve_arg (char const *arg, struct cp_options *x, bool on_off)
774 enum File_attribute
776 PRESERVE_MODE,
777 PRESERVE_TIMESTAMPS,
778 PRESERVE_OWNERSHIP,
779 PRESERVE_LINK,
780 PRESERVE_CONTEXT,
781 PRESERVE_ALL
783 static enum File_attribute const preserve_vals[] =
785 PRESERVE_MODE, PRESERVE_TIMESTAMPS,
786 PRESERVE_OWNERSHIP, PRESERVE_LINK, PRESERVE_CONTEXT, PRESERVE_ALL
788 /* Valid arguments to the `--preserve' option. */
789 static char const* const preserve_args[] =
791 "mode", "timestamps",
792 "ownership", "links", "context", "all", NULL
794 ARGMATCH_VERIFY (preserve_args, preserve_vals);
796 char *arg_writable = xstrdup (arg);
797 char *s = arg_writable;
800 /* find next comma */
801 char *comma = strchr (s, ',');
802 enum File_attribute val;
804 /* If we found a comma, put a NUL in its place and advance. */
805 if (comma)
806 *comma++ = 0;
808 /* process S. */
809 val = XARGMATCH ("--preserve", s, preserve_args, preserve_vals);
810 switch (val)
812 case PRESERVE_MODE:
813 x->preserve_mode = on_off;
814 break;
816 case PRESERVE_TIMESTAMPS:
817 x->preserve_timestamps = on_off;
818 break;
820 case PRESERVE_OWNERSHIP:
821 x->preserve_ownership = on_off;
822 break;
824 case PRESERVE_LINK:
825 x->preserve_links = on_off;
826 break;
828 case PRESERVE_CONTEXT:
829 x->preserve_security_context = on_off;
830 x->require_preserve_context = on_off;
831 break;
833 case PRESERVE_ALL:
834 x->preserve_mode = on_off;
835 x->preserve_timestamps = on_off;
836 x->preserve_ownership = on_off;
837 x->preserve_links = on_off;
838 if (selinux_enabled)
839 x->preserve_security_context = on_off;
840 break;
842 default:
843 abort ();
845 s = comma;
847 while (s);
849 free (arg_writable);
853 main (int argc, char **argv)
855 int c;
856 bool ok;
857 bool make_backups = false;
858 char *backup_suffix_string;
859 char *version_control_string = NULL;
860 struct cp_options x;
861 bool copy_contents = false;
862 char *target_directory = NULL;
863 bool no_target_directory = false;
865 initialize_main (&argc, &argv);
866 program_name = argv[0];
867 setlocale (LC_ALL, "");
868 bindtextdomain (PACKAGE, LOCALEDIR);
869 textdomain (PACKAGE);
871 atexit (close_stdout);
873 selinux_enabled = (0 < is_selinux_enabled ());
874 cp_option_init (&x);
876 /* FIXME: consider not calling getenv for SIMPLE_BACKUP_SUFFIX unless
877 we'll actually use backup_suffix_string. */
878 backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX");
880 while ((c = getopt_long (argc, argv, "abdfHilLprst:uvxPRS:T",
881 long_opts, NULL))
882 != -1)
884 switch (c)
886 case SPARSE_OPTION:
887 x.sparse_mode = XARGMATCH ("--sparse", optarg,
888 sparse_type_string, sparse_type);
889 break;
891 case 'a': /* Like -dpPR. */
892 x.dereference = DEREF_NEVER;
893 x.preserve_links = true;
894 x.preserve_ownership = true;
895 x.preserve_mode = true;
896 x.preserve_timestamps = true;
897 x.require_preserve = true;
898 x.recursive = true;
899 break;
901 case 'b':
902 make_backups = true;
903 if (optarg)
904 version_control_string = optarg;
905 break;
907 case COPY_CONTENTS_OPTION:
908 copy_contents = true;
909 break;
911 case 'd':
912 x.preserve_links = true;
913 x.dereference = DEREF_NEVER;
914 break;
916 case 'f':
917 x.unlink_dest_after_failed_open = true;
918 break;
920 case 'H':
921 x.dereference = DEREF_COMMAND_LINE_ARGUMENTS;
922 break;
924 case 'i':
925 x.interactive = I_ASK_USER;
926 break;
928 case 'l':
929 x.hard_link = true;
930 break;
932 case 'L':
933 x.dereference = DEREF_ALWAYS;
934 break;
936 case 'P':
937 x.dereference = DEREF_NEVER;
938 break;
940 case NO_PRESERVE_ATTRIBUTES_OPTION:
941 decode_preserve_arg (optarg, &x, false);
942 break;
944 case PRESERVE_ATTRIBUTES_OPTION:
945 if (optarg == NULL)
947 /* Fall through to the case for `p' below. */
949 else
951 decode_preserve_arg (optarg, &x, true);
952 x.require_preserve = true;
953 break;
956 case 'p':
957 x.preserve_ownership = true;
958 x.preserve_mode = true;
959 x.preserve_timestamps = true;
960 x.require_preserve = true;
961 break;
963 case PARENTS_OPTION:
964 parents_option = true;
965 break;
967 case 'r':
968 case 'R':
969 x.recursive = true;
970 break;
972 case REPLY_OPTION: /* Deprecated */
973 x.interactive = XARGMATCH ("--reply", optarg,
974 reply_args, reply_vals);
975 error (0, 0,
976 _("the --reply option is deprecated; use -i or -f instead"));
977 break;
979 case UNLINK_DEST_BEFORE_OPENING:
980 x.unlink_dest_before_opening = true;
981 break;
983 case STRIP_TRAILING_SLASHES_OPTION:
984 remove_trailing_slashes = true;
985 break;
987 case 's':
988 x.symbolic_link = true;
989 break;
991 case 't':
992 if (target_directory)
993 error (EXIT_FAILURE, 0,
994 _("multiple target directories specified"));
995 else
997 struct stat st;
998 if (stat (optarg, &st) != 0)
999 error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg));
1000 if (! S_ISDIR (st.st_mode))
1001 error (EXIT_FAILURE, 0, _("target %s is not a directory"),
1002 quote (optarg));
1004 target_directory = optarg;
1005 break;
1007 case 'T':
1008 no_target_directory = true;
1009 break;
1011 case 'u':
1012 x.update = true;
1013 break;
1015 case 'v':
1016 x.verbose = true;
1017 break;
1019 case 'x':
1020 x.one_file_system = true;
1021 break;
1023 case 'S':
1024 make_backups = true;
1025 backup_suffix_string = optarg;
1026 break;
1028 case_GETOPT_HELP_CHAR;
1030 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1032 default:
1033 usage (EXIT_FAILURE);
1037 if (x.hard_link & x.symbolic_link)
1039 error (0, 0, _("cannot make both hard and symbolic links"));
1040 usage (EXIT_FAILURE);
1043 if (backup_suffix_string)
1044 simple_backup_suffix = xstrdup (backup_suffix_string);
1046 x.backup_type = (make_backups
1047 ? xget_version (_("backup type"),
1048 version_control_string)
1049 : no_backups);
1051 if (x.dereference == DEREF_UNDEFINED)
1053 if (x.recursive)
1054 /* This is compatible with FreeBSD. */
1055 x.dereference = DEREF_NEVER;
1056 else
1057 x.dereference = DEREF_ALWAYS;
1060 if (x.recursive)
1061 x.copy_as_regular = copy_contents;
1063 /* If --force (-f) was specified and we're in link-creation mode,
1064 first remove any existing destination file. */
1065 if (x.unlink_dest_after_failed_open & (x.hard_link | x.symbolic_link))
1066 x.unlink_dest_before_opening = true;
1068 if (x.preserve_security_context)
1070 if (!selinux_enabled)
1071 error (EXIT_FAILURE, 0,
1072 _("cannot preserve security context "
1073 "without an SELinux-enabled kernel"));
1076 /* Allocate space for remembering copied and created files. */
1078 hash_init ();
1080 ok = do_copy (argc - optind, argv + optind,
1081 target_directory, no_target_directory, &x);
1083 forget_all ();
1085 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);