.
[coreutils.git] / src / copy.c
blob29c71723f11b8b4ce4ba6fff5f18288e5e5c8a27
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 "savedir.h"
14 #include "copy.h"
15 #include "cp-hash.h"
16 #include "path-concat.h"
18 /* On Linux (from slackware-1.2.13 to 2.0.2?) there is no lchown function.
19 To change ownership of symlinks, you must run chown with an effective
20 UID of 0. */
21 #ifdef __linux__
22 # define ROOT_CHOWN_AFFECTS_SYMLINKS
23 #endif
25 #define DO_CHOWN(Chown, File, New_uid, New_gid) \
26 (Chown ((File), (x->myeuid == 0 ? (New_uid) : x->myeuid), (New_gid)) \
27 /* If non-root uses -p, it's ok if we can't preserve ownership. \
28 But root probably wants to know, e.g. if NFS disallows it. */ \
29 && (errno != EPERM || x->myeuid == 0))
31 struct dir_list
33 struct dir_list *parent;
34 ino_t ino;
35 dev_t dev;
38 int full_write ();
39 int euidaccess ();
40 int yesno ();
42 static int copy_internal PARAMS ((const char *src_path, const char *dst_path,
43 int new_dst, dev_t device,
44 struct dir_list *ancestors,
45 const struct cp_options *x));
47 /* The invocation name of this program. */
48 extern char *program_name;
50 static int
51 is_ancestor (const struct stat *sb, const struct dir_list *ancestors)
53 while (ancestors != 0)
55 if (ancestors->ino == sb->st_ino && ancestors->dev == sb->st_dev)
56 return 1;
57 ancestors = ancestors->parent;
59 return 0;
62 /* Read the contents of the directory SRC_PATH_IN, and recursively
63 copy the contents to DST_PATH_IN. NEW_DST is nonzero if
64 DST_PATH_IN is a directory that was created previously in the
65 recursion. SRC_SB and ANCESTORS describe SRC_PATH_IN.
66 Return 0 if successful, -1 if an error occurs. */
68 static int
69 copy_dir (const char *src_path_in, const char *dst_path_in, int new_dst,
70 const struct stat *src_sb, struct dir_list *ancestors,
71 const struct cp_options *x)
73 char *name_space;
74 char *namep;
75 char *src_path;
76 char *dst_path;
77 int ret = 0;
79 errno = 0;
80 name_space = savedir (src_path_in, (unsigned int) src_sb->st_size);
81 if (name_space == 0)
83 if (errno)
85 error (0, errno, "%s", src_path_in);
86 return -1;
88 else
89 error (1, 0, _("virtual memory exhausted"));
92 namep = name_space;
93 while (*namep != '\0')
95 src_path = path_concat (src_path_in, namep, NULL);
96 dst_path = path_concat (dst_path_in, namep, NULL);
97 if (dst_path == NULL || src_path == NULL)
98 error (1, 0, _("virtual memory exhausted"));
100 ret |= copy_internal (src_path, dst_path, new_dst, src_sb->st_dev,
101 ancestors, x);
103 /* Free the memory for `src_path'. The memory for `dst_path'
104 cannot be deallocated, since it is used to create multiple
105 hard links. */
107 free (src_path);
109 namep += strlen (namep) + 1;
111 free (name_space);
112 return -ret;
115 /* Copy a regular file from SRC_PATH to DST_PATH.
116 If the source file contains holes, copies holes and blocks of zeros
117 in the source file as holes in the destination file.
118 (Holes are read as zeroes by the `read' system call.)
119 Return 0 if successful, -1 if an error occurred.
120 FIXME: describe sparse_mode. */
122 static int
123 copy_reg (const char *src_path, const char *dst_path,
124 enum Sparse_type sparse_mode)
126 char *buf;
127 int buf_size;
128 int dest_desc;
129 int source_desc;
130 int n_read;
131 struct stat sb;
132 char *cp;
133 int *ip;
134 int return_val = 0;
135 off_t n_read_total = 0;
136 int last_write_made_hole = 0;
137 int make_holes = (sparse_mode == SPARSE_ALWAYS);
139 source_desc = open (src_path, O_RDONLY);
140 if (source_desc < 0)
142 error (0, errno, "%s", src_path);
143 return -1;
146 /* Create the new regular file with small permissions initially,
147 to not create a security hole. */
149 dest_desc = open (dst_path, O_WRONLY | O_CREAT | O_TRUNC, 0600);
150 if (dest_desc < 0)
152 error (0, errno, _("cannot create regular file `%s'"), dst_path);
153 return_val = -1;
154 goto ret2;
157 /* Find out the optimal buffer size. */
159 if (fstat (dest_desc, &sb))
161 error (0, errno, "%s", dst_path);
162 return_val = -1;
163 goto ret;
166 buf_size = ST_BLKSIZE (sb);
168 #ifdef HAVE_ST_BLOCKS
169 if (sparse_mode == SPARSE_AUTO && S_ISREG (sb.st_mode))
171 /* Use a heuristic to determine whether SRC_PATH contains any
172 sparse blocks. */
174 if (fstat (source_desc, &sb))
176 error (0, errno, "%s", src_path);
177 return_val = -1;
178 goto ret;
181 /* If the file has fewer blocks than would normally
182 be needed for a file of its size, then
183 at least one of the blocks in the file is a hole. */
184 if (S_ISREG (sb.st_mode)
185 && sb.st_size / ST_NBLOCKSIZE > ST_NBLOCKS (sb))
186 make_holes = 1;
188 #endif
190 /* Make a buffer with space for a sentinel at the end. */
192 buf = (char *) alloca (buf_size + sizeof (int));
194 for (;;)
196 n_read = read (source_desc, buf, buf_size);
197 if (n_read < 0)
199 #ifdef EINTR
200 if (errno == EINTR)
201 continue;
202 #endif
203 error (0, errno, "%s", src_path);
204 return_val = -1;
205 goto ret;
207 if (n_read == 0)
208 break;
210 n_read_total += n_read;
212 ip = 0;
213 if (make_holes)
215 buf[n_read] = 1; /* Sentinel to stop loop. */
217 /* Find first nonzero *word*, or the word with the sentinel. */
219 ip = (int *) buf;
220 while (*ip++ == 0)
223 /* Find the first nonzero *byte*, or the sentinel. */
225 cp = (char *) (ip - 1);
226 while (*cp++ == 0)
229 /* If we found the sentinel, the whole input block was zero,
230 and we can make a hole. */
232 if (cp > buf + n_read)
234 /* Make a hole. */
235 if (lseek (dest_desc, (off_t) n_read, SEEK_CUR) < 0L)
237 error (0, errno, "%s", dst_path);
238 return_val = -1;
239 goto ret;
241 last_write_made_hole = 1;
243 else
244 /* Clear to indicate that a normal write is needed. */
245 ip = 0;
247 if (ip == 0)
249 if (full_write (dest_desc, buf, n_read) < 0)
251 error (0, errno, "%s", dst_path);
252 return_val = -1;
253 goto ret;
255 last_write_made_hole = 0;
259 /* If the file ends with a `hole', something needs to be written at
260 the end. Otherwise the kernel would truncate the file at the end
261 of the last write operation. */
263 if (last_write_made_hole)
265 #ifdef HAVE_FTRUNCATE
266 /* Write a null character and truncate it again. */
267 if (full_write (dest_desc, "", 1) < 0
268 || ftruncate (dest_desc, n_read_total) < 0)
269 #else
270 /* Seek backwards one character and write a null. */
271 if (lseek (dest_desc, (off_t) -1, SEEK_CUR) < 0L
272 || full_write (dest_desc, "", 1) < 0)
273 #endif
275 error (0, errno, "%s", dst_path);
276 return_val = -1;
280 ret:
281 if (close (dest_desc) < 0)
283 error (0, errno, "%s", dst_path);
284 return_val = -1;
286 ret2:
287 if (close (source_desc) < 0)
289 error (0, errno, "%s", src_path);
290 return_val = -1;
293 return return_val;
296 /* Copy the file SRC_PATH to the file DST_PATH. The files may be of
297 any type. NEW_DST should be nonzero if the file DST_PATH cannot
298 exist because its parent directory was just created; NEW_DST should
299 be zero if DST_PATH might already exist. DEVICE is the device
300 number of the parent directory, or 0 if the parent of this file is
301 not known. ANCESTORS points to a linked, null terminated list of
302 devices and inodes of parent directories of SRC_PATH.
303 Return 0 if successful, 1 if an error occurs. */
305 static int
306 copy_internal (const char *src_path, const char *dst_path,
307 int new_dst, dev_t device, struct dir_list *ancestors,
308 const struct cp_options *x)
310 struct stat src_sb;
311 struct stat dst_sb;
312 int src_mode;
313 int src_type;
314 char *earlier_file;
315 char *dst_backup = NULL;
316 int fix_mode = 0;
318 if ((*(x->xstat)) (src_path, &src_sb))
320 error (0, errno, "%s", src_path);
321 return 1;
324 /* Are we crossing a file system boundary? */
325 if (x->one_file_system && device != 0 && device != src_sb.st_dev)
326 return 0;
328 /* We wouldn't insert a node unless nlink > 1, except that we need to
329 find created files so as to not copy infinitely if a directory is
330 copied into itself. */
332 earlier_file = remember_copied (dst_path, src_sb.st_ino, src_sb.st_dev);
334 /* Did we just create this file? */
336 if (earlier_file == &new_file)
337 return 0;
339 src_mode = src_sb.st_mode;
340 src_type = src_sb.st_mode;
342 if (S_ISDIR (src_type) && !x->recursive)
344 error (0, 0, _("%s: omitting directory"), src_path);
345 return 1;
348 if (!new_dst)
350 if ((*(x->xstat)) (dst_path, &dst_sb))
352 if (errno != ENOENT)
354 error (0, errno, "%s", dst_path);
355 return 1;
357 else
358 new_dst = 1;
360 else
362 int same;
364 /* The destination file exists already. */
366 same = (src_sb.st_ino == dst_sb.st_ino
367 && src_sb.st_dev == dst_sb.st_dev);
369 #ifdef S_ISLNK
370 /* If we're preserving symlinks (--no-dereference) and the
371 destination file is a symlink, use stat (not xstat) to
372 see if it points back to the source. */
373 if (!same && !x->dereference && S_ISLNK (dst_sb.st_mode))
375 struct stat dst2_sb;
376 if (stat (dst_path, &dst2_sb) == 0
377 && (src_sb.st_ino == dst2_sb.st_ino &&
378 src_sb.st_dev == dst2_sb.st_dev))
379 same = 1;
381 #endif
383 if (same)
385 if (x->hard_link)
386 return 0;
388 error (0, 0, _("`%s' and `%s' are the same file"),
389 src_path, dst_path);
390 return 1;
393 if (!S_ISDIR (src_type))
395 if (S_ISDIR (dst_sb.st_mode))
397 error (0, 0,
398 _("%s: cannot overwrite directory with non-directory"),
399 dst_path);
400 return 1;
403 if (x->update && src_sb.st_mtime <= dst_sb.st_mtime)
404 return 0;
407 if (!S_ISDIR (src_type) && !x->force && x->interactive)
409 if (euidaccess (dst_path, W_OK) != 0)
411 fprintf (stderr,
412 _("%s: overwrite `%s', overriding mode %04o? "),
413 program_name, dst_path,
414 (unsigned int) (dst_sb.st_mode & 07777));
416 else
418 fprintf (stderr, _("%s: overwrite `%s'? "),
419 program_name, dst_path);
421 if (!yesno ())
422 return 0;
425 if (backup_type != none && !S_ISDIR (dst_sb.st_mode))
427 char *tmp_backup = find_backup_file_name (dst_path);
428 if (tmp_backup == NULL)
429 error (1, 0, _("virtual memory exhausted"));
431 /* Detect (and fail) when creating the backup file would
432 destroy the source file. Before, running the commands
433 cd /tmp; rm -f a a~; : > a; echo A > a~; cp -b -V simple a~ a
434 would leave two zero-length files: a and a~. */
435 if (STREQ (tmp_backup, src_path))
437 error (0, 0,
438 _("backing up `%s' would destroy source; `%s' not copied"),
439 dst_path, src_path);
440 return 1;
443 dst_backup = (char *) alloca (strlen (tmp_backup) + 1);
444 strcpy (dst_backup, tmp_backup);
445 free (tmp_backup);
446 if (rename (dst_path, dst_backup))
448 if (errno != ENOENT)
450 error (0, errno, _("cannot backup `%s'"), dst_path);
451 return 1;
453 else
454 dst_backup = NULL;
456 new_dst = 1;
458 else if (x->force)
460 if (S_ISDIR (dst_sb.st_mode))
462 /* Temporarily change mode to allow overwriting. */
463 if (euidaccess (dst_path, W_OK | X_OK) != 0)
465 if (chmod (dst_path, 0700))
467 error (0, errno, "%s", dst_path);
468 return 1;
470 else
471 fix_mode = 1;
474 else
476 if (unlink (dst_path) && errno != ENOENT)
478 error (0, errno, _("cannot remove old link to `%s'"),
479 dst_path);
480 return 1;
482 new_dst = 1;
488 /* If the source is a directory, we don't always create the destination
489 directory. So --verbose should not announce anything until we're
490 sure we'll create a directory. */
491 if (x->verbose && !S_ISDIR (src_type))
492 printf ("%s -> %s\n", src_path, dst_path);
494 /* Did we copy this inode somewhere else (in this command line argument)
495 and therefore this is a second hard link to the inode? */
497 if (!x->dereference && src_sb.st_nlink > 1 && earlier_file)
499 if (link (earlier_file, dst_path))
501 error (0, errno, "%s", dst_path);
502 goto un_backup;
504 return 0;
507 if (S_ISDIR (src_type))
509 struct dir_list *dir;
511 /* If this directory has been copied before during the
512 recursion, there is a symbolic link to an ancestor
513 directory of the symbolic link. It is impossible to
514 continue to copy this, unless we've got an infinite disk. */
516 if (is_ancestor (&src_sb, ancestors))
518 error (0, 0, _("%s: cannot copy cyclic symbolic link"), src_path);
519 goto un_backup;
522 /* Insert the current directory in the list of parents. */
524 dir = (struct dir_list *) alloca (sizeof (struct dir_list));
525 dir->parent = ancestors;
526 dir->ino = src_sb.st_ino;
527 dir->dev = src_sb.st_dev;
529 if (new_dst || !S_ISDIR (dst_sb.st_mode))
531 /* Create the new directory writable and searchable, so
532 we can create new entries in it. */
534 if (mkdir (dst_path, (src_mode & x->umask_kill) | 0700))
536 error (0, errno, _("cannot create directory `%s'"), dst_path);
537 goto un_backup;
540 /* Insert the created directory's inode and device
541 numbers into the search structure, so that we can
542 avoid copying it again. */
544 if (remember_created (dst_path))
545 goto un_backup;
547 if (x->verbose)
548 printf ("%s -> %s\n", src_path, dst_path);
551 /* Copy the contents of the directory. */
553 if (copy_dir (src_path, dst_path, new_dst, &src_sb, dir, x))
554 return 1;
556 #ifdef S_ISLNK
557 else if (x->symbolic_link)
559 if (*src_path == '/'
560 || (!strncmp (dst_path, "./", 2) && strchr (dst_path + 2, '/') == 0)
561 || strchr (dst_path, '/') == 0)
563 if (symlink (src_path, dst_path))
565 error (0, errno, "%s", dst_path);
566 goto un_backup;
569 return 0;
571 else
573 error (0, 0,
574 _("%s: can make relative symbolic links only in current directory"),
575 dst_path);
576 goto un_backup;
579 #endif
580 else if (x->hard_link)
582 if (link (src_path, dst_path))
584 error (0, errno, _("cannot create link `%s'"), dst_path);
585 goto un_backup;
587 return 0;
589 else if (S_ISREG (src_type)
590 || (x->copy_as_regular && !S_ISDIR (src_type)
591 #ifdef S_ISLNK
592 && !S_ISLNK (src_type)
593 #endif
596 if (copy_reg (src_path, dst_path, x->sparse_mode))
597 goto un_backup;
599 else
600 #ifdef S_ISFIFO
601 if (S_ISFIFO (src_type))
603 if (mkfifo (dst_path, src_mode & x->umask_kill))
605 error (0, errno, _("cannot create fifo `%s'"), dst_path);
606 goto un_backup;
609 else
610 #endif
611 if (S_ISBLK (src_type) || S_ISCHR (src_type)
612 #ifdef S_ISSOCK
613 || S_ISSOCK (src_type)
614 #endif
617 if (mknod (dst_path, src_mode & x->umask_kill, src_sb.st_rdev))
619 error (0, errno, _("cannot create special file `%s'"), dst_path);
620 goto un_backup;
623 else
624 #ifdef S_ISLNK
625 if (S_ISLNK (src_type))
627 char *link_val;
628 int link_size;
630 link_val = (char *) alloca (PATH_MAX + 2);
631 link_size = readlink (src_path, link_val, PATH_MAX + 1);
632 if (link_size < 0)
634 error (0, errno, _("cannot read symbolic link `%s'"), src_path);
635 goto un_backup;
637 link_val[link_size] = '\0';
639 if (symlink (link_val, dst_path))
641 error (0, errno, _("cannot create symbolic link `%s'"), dst_path);
642 goto un_backup;
645 if (x->preserve)
647 /* Preserve the owner and group of the just-`copied'
648 symbolic link, if possible. */
649 # ifdef HAVE_LCHOWN
650 if (DO_CHOWN (lchown, dst_path, src_sb.st_uid, src_sb.st_gid))
652 error (0, errno, _("preserving ownership for %s"), dst_path);
653 goto un_backup;
655 # else
656 # ifdef ROOT_CHOWN_AFFECTS_SYMLINKS
657 if (x->myeuid == 0)
659 if (DO_CHOWN (chown, dst_path, src_sb.st_uid, src_sb.st_gid))
661 error (0, errno, _("preserving ownership for %s"), dst_path);
662 goto un_backup;
665 else
667 /* FIXME: maybe give a diagnostic: you must be root
668 to preserve ownership and group of symlinks. */
670 # else
671 /* Can't preserve ownership of symlinks.
672 FIXME: maybe give a warning or even error for symlinks
673 in directories with the sticky bit set -- there, not
674 preserving owner/group is a potential security problem. */
675 # endif
676 # endif
679 return 0;
681 else
682 #endif
684 error (0, 0, _("%s: unknown file type"), src_path);
685 goto un_backup;
688 /* POSIX says that `cp -p' must restore the following:
689 - permission bits
690 - setuid, setgid bits
691 - owner and group
692 If it fails to restore any of those, we may give a warning but
693 the destination must not be removed.
694 FIXME: implement the above. */
696 /* Adjust the times (and if possible, ownership) for the copy.
697 chown turns off set[ug]id bits for non-root,
698 so do the chmod last. */
700 if (x->preserve)
702 struct utimbuf utb;
704 utb.actime = src_sb.st_atime;
705 utb.modtime = src_sb.st_mtime;
707 if (utime (dst_path, &utb))
709 error (0, errno, _("preserving times for %s"), dst_path);
710 if (x->require_preserve)
711 return 1;
714 if (DO_CHOWN (chown, dst_path, src_sb.st_uid, src_sb.st_gid))
716 error (0, errno, _("preserving ownership for %s"), dst_path);
717 if (x->require_preserve)
718 return 1;
722 if ((x->preserve || new_dst)
723 && (x->copy_as_regular || S_ISREG (src_type) || S_ISDIR (src_type)))
725 if (chmod (dst_path, src_mode & x->umask_kill))
727 error (0, errno, _("preserving permissions for %s"), dst_path);
728 if (x->require_preserve)
729 return 1;
732 else if (fix_mode)
734 /* Reset the temporarily changed mode. */
735 if (chmod (dst_path, dst_sb.st_mode))
737 error (0, errno, _("restoring permissions of %s"), dst_path);
738 return 1;
742 return 0;
744 un_backup:
745 if (dst_backup)
747 if (rename (dst_backup, dst_path))
748 error (0, errno, _("cannot un-backup `%s'"), dst_path);
750 return 1;
753 static int
754 valid_options (const struct cp_options *co)
756 assert (co != NULL);
758 /* FIXME: make sure xstat and dereference are consistent. */
759 assert (co->xstat);
761 assert (co->sparse_mode != SPARSE_UNUSED);
762 return 1;
765 /* Copy the file SRC_PATH to the file DST_PATH. The files may be of
766 any type. NONEXISTENT_DST should be nonzero if the file DST_PATH
767 is known not to exist (e.g., because its parent directory was just
768 created); NONEXISTENT_DST should be zero if DST_PATH might already
769 exist. DEVICE is the device number of the parent directory of
770 DST_PATH, or 0 if the parent of this file is not known.
771 OPTIONS is ... FIXME-describe
772 Return 0 if successful, 1 if an error occurs. */
775 copy (const char *src_path, const char *dst_path,
776 int nonexistent_dst, const struct cp_options *options)
778 assert (valid_options (options));
779 return copy_internal (src_path, dst_path, nonexistent_dst, 0, NULL, options);