*** empty log message ***
[coreutils.git] / src / copy.c
blobbf860c7039743b0cbe3b37e9191cccf4de0d2f79
1 #ifdef _AIX
2 #pragma alloca
3 #endif
5 #include <config.h>
6 #include <stdio.h>
7 #include <assert.h>
8 #include <sys/types.h>
10 #include "system.h"
11 #include "error.h"
12 #include "backupfile.h"
13 #include "copy.h"
14 #include "cp-hash.h"
16 /* On Linux (from slackware-1.2.13 to 2.0.2?) there is no lchown function.
17 To change ownership of symlinks, you must run chown with an effective
18 UID of 0. */
19 #ifdef __linux__
20 # define ROOT_CHOWN_AFFECTS_SYMLINKS
21 #endif
23 #define DO_CHOWN(Chown, File, New_uid, New_gid) \
24 (Chown ((File), (x->myeuid == 0 ? (New_uid) : x->myeuid), (New_gid)) \
25 /* If non-root uses -p, it's ok if we can't preserve ownership. \
26 But root probably wants to know, e.g. if NFS disallows it. */ \
27 && (errno != EPERM || x->myeuid == 0))
29 struct dir_list
31 struct dir_list *parent;
32 ino_t ino;
33 dev_t dev;
36 int full_write ();
37 int euidaccess ();
38 char *savedir ();
39 char *stpcpy ();
40 char *xmalloc ();
41 int yesno ();
43 static int copy_internal __P ((const char *src_path, const char *dst_path,
44 int new_dst, dev_t device,
45 struct dir_list *ancestors,
46 const struct cp_options *x));
48 /* The invocation name of this program. */
49 extern char *program_name;
51 static int
52 is_ancestor (const struct stat *sb, const struct dir_list *ancestors)
54 while (ancestors != 0)
56 if (ancestors->ino == sb->st_ino && ancestors->dev == sb->st_dev)
57 return 1;
58 ancestors = ancestors->parent;
60 return 0;
63 /* Read the contents of the directory SRC_PATH_IN, and recursively
64 copy the contents to DST_PATH_IN. NEW_DST is nonzero if
65 DST_PATH_IN is a directory that was created previously in the
66 recursion. SRC_SB and ANCESTORS describe SRC_PATH_IN.
67 Return 0 if successful, -1 if an error occurs. */
69 static int
70 copy_dir (const char *src_path_in, const char *dst_path_in, int new_dst,
71 const struct stat *src_sb, struct dir_list *ancestors,
72 const struct cp_options *x)
74 char *name_space;
75 char *namep;
76 char *src_path;
77 char *dst_path;
78 int ret = 0;
80 errno = 0;
81 name_space = savedir (src_path_in, src_sb->st_size);
82 if (name_space == 0)
84 if (errno)
86 error (0, errno, "%s", src_path_in);
87 return -1;
89 else
90 error (1, 0, _("virtual memory exhausted"));
93 namep = name_space;
94 while (*namep != '\0')
96 int fn_length = strlen (namep) + 1;
98 dst_path = xmalloc (strlen (dst_path_in) + fn_length + 1);
99 src_path = xmalloc (strlen (src_path_in) + fn_length + 1);
101 stpcpy (stpcpy (stpcpy (src_path, src_path_in), "/"), namep);
102 stpcpy (stpcpy (stpcpy (dst_path, dst_path_in), "/"), namep);
104 ret |= copy_internal (src_path, dst_path, new_dst, src_sb->st_dev,
105 ancestors, x);
107 /* Free the memory for `src_path'. The memory for `dst_path'
108 cannot be deallocated, since it is used to create multiple
109 hard links. */
111 free (src_path);
113 namep += fn_length;
115 free (name_space);
116 return -ret;
119 /* Copy a regular file from SRC_PATH to DST_PATH.
120 If the source file contains holes, copies holes and blocks of zeros
121 in the source file as holes in the destination file.
122 (Holes are read as zeroes by the `read' system call.)
123 Return 0 if successful, -1 if an error occurred.
124 FIXME: describe sparse_mode. */
126 static int
127 copy_reg (const char *src_path, const char *dst_path,
128 enum Sparse_type sparse_mode)
130 char *buf;
131 int buf_size;
132 int dest_desc;
133 int source_desc;
134 int n_read;
135 struct stat sb;
136 char *cp;
137 int *ip;
138 int return_val = 0;
139 long n_read_total = 0;
140 int last_write_made_hole = 0;
141 int make_holes = (sparse_mode == SPARSE_ALWAYS);
143 source_desc = open (src_path, O_RDONLY);
144 if (source_desc < 0)
146 error (0, errno, "%s", src_path);
147 return -1;
150 /* Create the new regular file with small permissions initially,
151 to not create a security hole. */
153 dest_desc = open (dst_path, O_WRONLY | O_CREAT | O_TRUNC, 0600);
154 if (dest_desc < 0)
156 error (0, errno, _("cannot create regular file `%s'"), dst_path);
157 return_val = -1;
158 goto ret2;
161 /* Find out the optimal buffer size. */
163 if (fstat (dest_desc, &sb))
165 error (0, errno, "%s", dst_path);
166 return_val = -1;
167 goto ret;
170 buf_size = ST_BLKSIZE (sb);
172 #ifdef HAVE_ST_BLOCKS
173 if (sparse_mode == SPARSE_AUTO && S_ISREG (sb.st_mode))
175 /* Use a heuristic to determine whether SRC_PATH contains any
176 sparse blocks. */
178 if (fstat (source_desc, &sb))
180 error (0, errno, "%s", src_path);
181 return_val = -1;
182 goto ret;
185 /* If the file has fewer blocks than would normally
186 be needed for a file of its size, then
187 at least one of the blocks in the file is a hole. */
188 if (S_ISREG (sb.st_mode)
189 && (size_t) (sb.st_size / 512) > (size_t) ST_NBLOCKS (sb))
190 make_holes = 1;
192 #endif
194 /* Make a buffer with space for a sentinel at the end. */
196 buf = (char *) alloca (buf_size + sizeof (int));
198 for (;;)
200 n_read = read (source_desc, buf, buf_size);
201 if (n_read < 0)
203 #ifdef EINTR
204 if (errno == EINTR)
205 continue;
206 #endif
207 error (0, errno, "%s", src_path);
208 return_val = -1;
209 goto ret;
211 if (n_read == 0)
212 break;
214 n_read_total += n_read;
216 ip = 0;
217 if (make_holes)
219 buf[n_read] = 1; /* Sentinel to stop loop. */
221 /* Find first nonzero *word*, or the word with the sentinel. */
223 ip = (int *) buf;
224 while (*ip++ == 0)
227 /* Find the first nonzero *byte*, or the sentinel. */
229 cp = (char *) (ip - 1);
230 while (*cp++ == 0)
233 /* If we found the sentinel, the whole input block was zero,
234 and we can make a hole. */
236 if (cp > buf + n_read)
238 /* Make a hole. */
239 if (lseek (dest_desc, (off_t) n_read, SEEK_CUR) < 0L)
241 error (0, errno, "%s", dst_path);
242 return_val = -1;
243 goto ret;
245 last_write_made_hole = 1;
247 else
248 /* Clear to indicate that a normal write is needed. */
249 ip = 0;
251 if (ip == 0)
253 if (full_write (dest_desc, buf, n_read) < 0)
255 error (0, errno, "%s", dst_path);
256 return_val = -1;
257 goto ret;
259 last_write_made_hole = 0;
263 /* If the file ends with a `hole', something needs to be written at
264 the end. Otherwise the kernel would truncate the file at the end
265 of the last write operation. */
267 if (last_write_made_hole)
269 #ifdef HAVE_FTRUNCATE
270 /* Write a null character and truncate it again. */
271 if (full_write (dest_desc, "", 1) < 0
272 || ftruncate (dest_desc, n_read_total) < 0)
273 #else
274 /* Seek backwards one character and write a null. */
275 if (lseek (dest_desc, (off_t) -1, SEEK_CUR) < 0L
276 || full_write (dest_desc, "", 1) < 0)
277 #endif
279 error (0, errno, "%s", dst_path);
280 return_val = -1;
284 ret:
285 if (close (dest_desc) < 0)
287 error (0, errno, "%s", dst_path);
288 return_val = -1;
290 ret2:
291 if (close (source_desc) < 0)
293 error (0, errno, "%s", src_path);
294 return_val = -1;
297 return return_val;
300 /* Copy the file SRC_PATH to the file DST_PATH. The files may be of
301 any type. NEW_DST should be nonzero if the file DST_PATH cannot
302 exist because its parent directory was just created; NEW_DST should
303 be zero if DST_PATH might already exist. DEVICE is the device
304 number of the parent directory, or 0 if the parent of this file is
305 not known. ANCESTORS points to a linked, null terminated list of
306 devices and inodes of parent directories of SRC_PATH.
307 Return 0 if successful, 1 if an error occurs. */
309 static int
310 copy_internal (const char *src_path, const char *dst_path,
311 int new_dst, dev_t device, struct dir_list *ancestors,
312 const struct cp_options *x)
314 struct stat src_sb;
315 struct stat dst_sb;
316 int src_mode;
317 int src_type;
318 char *earlier_file;
319 char *dst_backup = NULL;
320 int fix_mode = 0;
322 if ((*(x->xstat)) (src_path, &src_sb))
324 error (0, errno, "%s", src_path);
325 return 1;
328 /* Are we crossing a file system boundary? */
329 if (x->one_file_system && device != 0 && device != src_sb.st_dev)
330 return 0;
332 /* We wouldn't insert a node unless nlink > 1, except that we need to
333 find created files so as to not copy infinitely if a directory is
334 copied into itself. */
336 earlier_file = remember_copied (dst_path, src_sb.st_ino, src_sb.st_dev);
338 /* Did we just create this file? */
340 if (earlier_file == &new_file)
341 return 0;
343 src_mode = src_sb.st_mode;
344 src_type = src_sb.st_mode;
346 if (S_ISDIR (src_type) && !x->recursive)
348 error (0, 0, _("%s: omitting directory"), src_path);
349 return 1;
352 if (!new_dst)
354 if ((*(x->xstat)) (dst_path, &dst_sb))
356 if (errno != ENOENT)
358 error (0, errno, "%s", dst_path);
359 return 1;
361 else
362 new_dst = 1;
364 else
366 int same;
368 /* The destination file exists already. */
370 same = (src_sb.st_ino == dst_sb.st_ino
371 && src_sb.st_dev == dst_sb.st_dev);
373 /* If we're preserving symlinks (--no-dereference) and the
374 destination file is a symlink, use stat (not xstat) to
375 see if it points back to the source. */
376 if (!same && !x->dereference && S_ISLNK (dst_sb.st_mode))
378 struct stat dst2_sb;
379 if (stat (dst_path, &dst2_sb) == 0
380 && (src_sb.st_ino == dst2_sb.st_ino &&
381 src_sb.st_dev == dst2_sb.st_dev))
382 same = 1;
385 if (same)
387 if (x->hard_link)
388 return 0;
390 error (0, 0, _("`%s' and `%s' are the same file"),
391 src_path, dst_path);
392 return 1;
395 if (!S_ISDIR (src_type))
397 if (S_ISDIR (dst_sb.st_mode))
399 error (0, 0,
400 _("%s: cannot overwrite directory with non-directory"),
401 dst_path);
402 return 1;
405 if (x->update && src_sb.st_mtime <= dst_sb.st_mtime)
406 return 0;
409 if (!S_ISDIR (src_type) && !x->force && x->interactive)
411 if (euidaccess (dst_path, W_OK) != 0)
413 fprintf (stderr,
414 _("%s: overwrite `%s', overriding mode %04o? "),
415 program_name, dst_path,
416 (unsigned int) (dst_sb.st_mode & 07777));
418 else
420 fprintf (stderr, _("%s: overwrite `%s'? "),
421 program_name, dst_path);
423 if (!yesno ())
424 return 0;
427 if (backup_type != none && !S_ISDIR (dst_sb.st_mode))
429 char *tmp_backup = find_backup_file_name (dst_path);
430 if (tmp_backup == NULL)
431 error (1, 0, _("virtual memory exhausted"));
433 /* Detect (and fail) when creating the backup file would
434 destroy the source file. Before, running the commands
435 cd /tmp; rm -f a a~; : > a; echo A > a~; cp -b -V simple a~ a
436 would leave two zero-length files: a and a~. */
437 if (STREQ (tmp_backup, src_path))
439 error (0, 0,
440 _("backing up `%s' would destroy source; `%s' not copied"),
441 dst_path, src_path);
442 return 1;
445 dst_backup = (char *) alloca (strlen (tmp_backup) + 1);
446 strcpy (dst_backup, tmp_backup);
447 free (tmp_backup);
448 if (rename (dst_path, dst_backup))
450 if (errno != ENOENT)
452 error (0, errno, _("cannot backup `%s'"), dst_path);
453 return 1;
455 else
456 dst_backup = NULL;
458 new_dst = 1;
460 else if (x->force)
462 if (S_ISDIR (dst_sb.st_mode))
464 /* Temporarily change mode to allow overwriting. */
465 if (euidaccess (dst_path, W_OK | X_OK) != 0)
467 if (chmod (dst_path, 0700))
469 error (0, errno, "%s", dst_path);
470 return 1;
472 else
473 fix_mode = 1;
476 else
478 if (unlink (dst_path) && errno != ENOENT)
480 error (0, errno, _("cannot remove old link to `%s'"),
481 dst_path);
482 return 1;
484 new_dst = 1;
490 /* If the source is a directory, we don't always create the destination
491 directory. So --verbose should not announce anything until we're
492 sure we'll create a directory. */
493 if (x->verbose && !S_ISDIR (src_type))
494 printf ("%s -> %s\n", src_path, dst_path);
496 /* Did we copy this inode somewhere else (in this command line argument)
497 and therefore this is a second hard link to the inode? */
499 if (!x->dereference && src_sb.st_nlink > 1 && earlier_file)
501 if (link (earlier_file, dst_path))
503 error (0, errno, "%s", dst_path);
504 goto un_backup;
506 return 0;
509 if (S_ISDIR (src_type))
511 struct dir_list *dir;
513 /* If this directory has been copied before during the
514 recursion, there is a symbolic link to an ancestor
515 directory of the symbolic link. It is impossible to
516 continue to copy this, unless we've got an infinite disk. */
518 if (is_ancestor (&src_sb, ancestors))
520 error (0, 0, _("%s: cannot copy cyclic symbolic link"), src_path);
521 goto un_backup;
524 /* Insert the current directory in the list of parents. */
526 dir = (struct dir_list *) alloca (sizeof (struct dir_list));
527 dir->parent = ancestors;
528 dir->ino = src_sb.st_ino;
529 dir->dev = src_sb.st_dev;
531 if (new_dst || !S_ISDIR (dst_sb.st_mode))
533 /* Create the new directory writable and searchable, so
534 we can create new entries in it. */
536 if (mkdir (dst_path, (src_mode & x->umask_kill) | 0700))
538 error (0, errno, _("cannot create directory `%s'"), dst_path);
539 goto un_backup;
542 /* Insert the created directory's inode and device
543 numbers into the search structure, so that we can
544 avoid copying it again. */
546 if (remember_created (dst_path))
547 goto un_backup;
549 if (x->verbose)
550 printf ("%s -> %s\n", src_path, dst_path);
553 /* Copy the contents of the directory. */
555 if (copy_dir (src_path, dst_path, new_dst, &src_sb, dir, x))
556 return 1;
558 #ifdef S_ISLNK
559 else if (x->symbolic_link)
561 if (*src_path == '/'
562 || (!strncmp (dst_path, "./", 2) && strchr (dst_path + 2, '/') == 0)
563 || strchr (dst_path, '/') == 0)
565 if (symlink (src_path, dst_path))
567 error (0, errno, "%s", dst_path);
568 goto un_backup;
571 return 0;
573 else
575 error (0, 0,
576 _("%s: can make relative symbolic links only in current directory"),
577 dst_path);
578 goto un_backup;
581 #endif
582 else if (x->hard_link)
584 if (link (src_path, dst_path))
586 error (0, errno, _("cannot create link `%s'"), dst_path);
587 goto un_backup;
589 return 0;
591 else if (S_ISREG (src_type)
592 || (x->copy_as_regular && !S_ISDIR (src_type)
593 #ifdef S_ISLNK
594 && !S_ISLNK (src_type)
595 #endif
598 if (copy_reg (src_path, dst_path, x->sparse_mode))
599 goto un_backup;
601 else
602 #ifdef S_ISFIFO
603 if (S_ISFIFO (src_type))
605 if (mkfifo (dst_path, src_mode & x->umask_kill))
607 error (0, errno, _("cannot create fifo `%s'"), dst_path);
608 goto un_backup;
611 else
612 #endif
613 if (S_ISBLK (src_type) || S_ISCHR (src_type)
614 #ifdef S_ISSOCK
615 || S_ISSOCK (src_type)
616 #endif
619 if (mknod (dst_path, src_mode & x->umask_kill, src_sb.st_rdev))
621 error (0, errno, _("cannot create special file `%s'"), dst_path);
622 goto un_backup;
625 else
626 #ifdef S_ISLNK
627 if (S_ISLNK (src_type))
629 char *link_val;
630 int link_size;
632 link_val = (char *) alloca (PATH_MAX + 2);
633 link_size = readlink (src_path, link_val, PATH_MAX + 1);
634 if (link_size < 0)
636 error (0, errno, _("cannot read symbolic link `%s'"), src_path);
637 goto un_backup;
639 link_val[link_size] = '\0';
641 if (symlink (link_val, dst_path))
643 error (0, errno, _("cannot create symbolic link `%s'"), dst_path);
644 goto un_backup;
647 if (x->preserve)
649 /* Preserve the owner and group of the just-`copied'
650 symbolic link, if possible. */
651 # ifdef HAVE_LCHOWN
652 if (DO_CHOWN (lchown, dst_path, src_sb.st_uid, src_sb.st_gid))
654 error (0, errno, _("preserving ownership for %s"), dst_path);
655 goto un_backup;
657 # else
658 # ifdef ROOT_CHOWN_AFFECTS_SYMLINKS
659 if (x->myeuid == 0)
661 if (DO_CHOWN (chown, dst_path, src_sb.st_uid, src_sb.st_gid))
663 error (0, errno, _("preserving ownership for %s"), dst_path);
664 goto un_backup;
667 else
669 /* FIXME: maybe give a diagnostic: you must be root
670 to preserve ownership and group of symlinks. */
672 # else
673 /* Can't preserve ownership of symlinks.
674 FIXME: maybe give a warning or even error for symlinks
675 in directories with the sticky bit set -- there, not
676 preserving owner/group is a potential security problem. */
677 # endif
678 # endif
681 return 0;
683 else
684 #endif
686 error (0, 0, _("%s: unknown file type"), src_path);
687 goto un_backup;
690 /* Adjust the times (and if possible, ownership) for the copy.
691 chown turns off set[ug]id bits for non-root,
692 so do the chmod last. */
694 if (x->preserve)
696 struct utimbuf utb;
698 utb.actime = src_sb.st_atime;
699 utb.modtime = src_sb.st_mtime;
701 if (utime (dst_path, &utb))
703 error (0, errno, _("preserving times for %s"), dst_path);
704 return 1;
707 if (DO_CHOWN (chown, dst_path, src_sb.st_uid, src_sb.st_gid))
709 error (0, errno, _("preserving ownership for %s"), dst_path);
710 return 1;
714 if ((x->preserve || new_dst)
715 && (x->copy_as_regular || S_ISREG (src_type) || S_ISDIR (src_type)))
717 if (chmod (dst_path, src_mode & x->umask_kill))
719 error (0, errno, _("preserving permissions for %s"), dst_path);
720 return 1;
723 else if (fix_mode)
725 /* Reset the temporarily changed mode. */
726 if (chmod (dst_path, dst_sb.st_mode))
728 error (0, errno, _("restoring permissions of %s"), dst_path);
729 return 1;
733 return 0;
735 un_backup:
736 if (dst_backup)
738 if (rename (dst_backup, dst_path))
739 error (0, errno, _("cannot un-backup `%s'"), dst_path);
741 return 1;
744 static int
745 valid_options (const struct cp_options *co)
747 assert (co != NULL);
749 /* FIXME: make sure xstat and dereference are consistent. */
750 assert (co->xstat);
752 assert (co->sparse_mode != SPARSE_UNUSED);
753 return 1;
756 /* Copy the file SRC_PATH to the file DST_PATH. The files may be of
757 any type. NONEXISTENT_DST should be nonzero if the file DST_PATH
758 is known not to exist (e.g., because its parent directory was just
759 created); NONEXISTENT_DST should be zero if DST_PATH might already
760 exist. DEVICE is the device number of the parent directory of
761 DST_PATH, or 0 if the parent of this file is not known.
762 OPTIONS is ... FIXME-describe
763 Return 0 if successful, 1 if an error occurs. */
766 copy (const char *src_path, const char *dst_path,
767 int nonexistent_dst, const struct cp_options *options)
769 assert (valid_options (options));
770 return copy_internal (src_path, dst_path, nonexistent_dst, 0, NULL, options);