1 /* cp.c -- file copying (main routines)
2 Copyright (C) 1989, 1990, 1991, 1995 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)
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
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. */
28 #include "backupfile.h"
30 #include "safe-stat.h"
31 #include "safe-lstat.h"
33 #ifndef _POSIX_VERSION
37 /* Used by do_copy, make_path_private, and re_protect
38 to keep a list of leading directories whose protections
39 need to be fixed after copying. */
44 struct dir_attr *next;
49 enum backup_type get_version ();
53 static int do_copy ();
55 static int copy_dir ();
56 static int make_path_private ();
57 static int copy_reg ();
58 static int re_protect ();
60 /* Initial number of entries in each hash table entry's table of inodes. */
61 #define INITIAL_HASH_MODULE 100
63 /* Initial number of entries in the inode hash table. */
64 #define INITIAL_ENTRY_TAB_SIZE 70
66 /* The invocation name of this program. */
69 /* A pointer to either lstat or stat, depending on
70 whether dereferencing of symlinks is done. */
71 static int (*xstat) ();
73 /* If nonzero, copy all files except (directories and, if not dereferencing
74 them, symbolic links,) as if they were regular files. */
75 static int flag_copy_as_regular = 1;
77 /* If nonzero, dereference symbolic links (copy the files they point to). */
78 static int flag_dereference = 1;
80 /* If nonzero, remove existing destination nondirectories. */
81 static int flag_force = 0;
83 /* If nonzero, create hard links instead of copying files.
84 Create destination directories as usual. */
85 static int flag_hard_link = 0;
87 /* If nonzero, query before overwriting existing destinations
88 with regular files. */
89 static int flag_interactive = 0;
91 /* If nonzero, the command "cp x/e_file e_dir" uses "e_dir/x/e_file"
92 as its destination instead of the usual "e_dir/e_file." */
93 static int flag_path = 0;
95 /* If nonzero, give the copies the original files' permissions,
96 ownership, and timestamps. */
97 static int flag_preserve = 0;
99 /* If nonzero, copy directories recursively and copy special files
100 as themselves rather than copying their contents. */
101 static int flag_recursive = 0;
103 /* If nonzero, create symbolic links instead of copying files.
104 Create destination directories as usual. */
105 static int flag_symbolic_link = 0;
107 /* If nonzero, when copying recursively, skip any subdirectories that are
108 on different filesystems from the one we started on. */
109 static int flag_one_file_system = 0;
111 /* If nonzero, do not copy a nondirectory that has an existing destination
112 with the same or newer modification time. */
113 static int flag_update = 0;
115 /* If nonzero, display the names of the files before copying them. */
116 static int flag_verbose = 0;
118 /* The error code to return to the system. */
119 static int exit_status = 0;
121 /* The bits to preserve in created files' modes. */
122 static int umask_kill;
124 /* This process's effective user ID. */
127 /* If non-zero, display usage information and exit. */
128 static int show_help;
130 /* If non-zero, print the version on standard output and exit. */
131 static int show_version;
133 static struct option const long_opts[] =
135 {"archive", no_argument, NULL, 'a'},
136 {"backup", no_argument, NULL, 'b'},
137 {"force", no_argument, NULL, 'f'},
138 {"interactive", no_argument, NULL, 'i'},
139 {"link", no_argument, NULL, 'l'},
140 {"no-dereference", no_argument, &flag_dereference, 0},
141 {"one-file-system", no_argument, &flag_one_file_system, 1},
142 {"parents", no_argument, &flag_path, 1},
143 {"path", no_argument, &flag_path, 1},
144 {"preserve", no_argument, &flag_preserve, 1},
145 {"recursive", no_argument, NULL, 'R'},
146 {"suffix", required_argument, NULL, 'S'},
147 {"symbolic-link", no_argument, NULL, 's'},
148 {"update", no_argument, &flag_update, 1},
149 {"verbose", no_argument, &flag_verbose, 1},
150 {"version-control", required_argument, NULL, 'V'},
151 {"help", no_argument, &show_help, 1},
152 {"version", no_argument, &show_version, 1},
162 int make_backups = 0;
165 program_name = argv[0];
168 version = getenv ("SIMPLE_BACKUP_SUFFIX");
170 simple_backup_suffix = version;
171 version = getenv ("VERSION_CONTROL");
173 /* Find out the current file creation mask, to knock the right bits
174 when using chmod. The creation mask is set to to be liberal, so
175 that created directories can be written, even if it would not
176 have been allowed with the mask this process was started with. */
178 umask_kill = 0777777 ^ umask (0);
180 while ((c = getopt_long (argc, argv, "abdfilprsuvxPRS:V:", long_opts,
188 case 'a': /* Like -dpR. */
189 flag_dereference = 0;
192 flag_copy_as_regular = 0;
200 flag_dereference = 0;
205 flag_interactive = 0;
210 flag_interactive = 1;
227 flag_copy_as_regular = 1;
232 flag_copy_as_regular = 0;
237 flag_symbolic_link = 1;
239 error (1, 0, "symbolic links are not supported on this system");
252 flag_one_file_system = 1;
256 simple_backup_suffix = optarg;
264 usage (2, (char *) 0);
270 printf ("%s\n", version_string);
277 if (flag_hard_link && flag_symbolic_link)
278 usage (2, "cannot make both hard and symbolic links");
281 backup_type = get_version (version);
283 if (flag_preserve == 1)
284 umask_kill = 0777777;
286 /* The key difference between -d (--no-dereference) and not is the version
287 of `stat' to call. */
289 if (flag_dereference)
294 /* Allocate space for remembering copied and created files. */
296 hash_init (INITIAL_HASH_MODULE, INITIAL_ENTRY_TAB_SIZE);
298 exit_status |= do_copy (argc, argv);
303 /* Scan the arguments, and copy each by calling copy.
304 Return 0 if successful, 1 if any errors occur. */
317 usage (2, "missing file arguments");
318 if (optind >= argc - 1)
319 usage (2, "missing file argument");
321 dest = argv[argc - 1];
323 if (safe_lstat (dest, &sb))
327 error (0, errno, "%s", dest);
337 /* If `dest' is not a symlink to a nonexistent file, use
338 the results of stat instead of lstat, so we can copy files
339 into symlinks to directories. */
340 if (safe_stat (dest, &sbx) == 0)
344 if (!new_dst && S_ISDIR (sb.st_mode))
346 /* cp file1...filen edir
347 Copy the files `file1' through `filen'
348 to the existing directory `edir'. */
355 int parent_exists = 1; /* True if dirname (dst_path) exists. */
356 struct dir_attr *attr_list;
360 strip_trailing_slashes (arg);
364 /* Append all of `arg' to `dest'. */
365 dst_path = xmalloc (strlen (dest) + strlen (arg) + 2);
366 stpcpy (stpcpy (stpcpy (dst_path, dest), "/"), arg);
368 /* For --parents, we have to make sure that the directory
369 dirname (dst_path) exists. We may have to create a few
370 leading directories. */
371 parent_exists = !make_path_private (dst_path,
372 strlen (dest) + 1, 0700,
373 flag_verbose ? "%s -> %s\n" :
375 &attr_list, &new_dst);
379 /* Append the last component of `arg' to `dest'. */
382 /* For `cp -R source/.. dest', don't copy into `dest/..'. */
383 if (!strcmp (ap, ".."))
384 dst_path = xstrdup (dest);
387 dst_path = xmalloc (strlen (dest) + strlen (ap) + 2);
388 stpcpy (stpcpy (stpcpy (dst_path, dest), "/"), ap);
394 /* make_path_private failed, so we shouldn't even attempt the copy. */
399 ret |= copy (arg, dst_path, new_dst, 0, (struct dir_list *) 0);
404 ret |= re_protect (dst_path, strlen (dest) + 1,
411 if (optind == argc - 1)
416 else if (argc - optind == 2)
420 struct stat source_stats;
423 usage (2, "when preserving paths, last argument must be a directory");
425 source = argv[optind];
427 /* When the destination is specified with a trailing slash and the
428 source exists but is not a directory, convert the user's command
429 `cp source dest/' to `cp source dest/basename(source)'. */
431 if (dest[strlen (dest) - 1] == '/'
432 && safe_lstat (source, &source_stats) == 0
433 && !S_ISDIR (source_stats.st_mode))
438 tmp_source = (char *) alloca (strlen (source) + 1);
439 strcpy (tmp_source, source);
440 strip_trailing_slashes (tmp_source);
441 source_base = basename (tmp_source);
443 new_dest = (char *) alloca (strlen (dest) + 1 +
444 strlen (source_base) + 1);
445 stpcpy (stpcpy (stpcpy (new_dest, dest), "/"), source_base);
452 return copy (source, new_dest, new_dst, 0, (struct dir_list *) 0);
456 "when copying multiple files, last argument must be a directory");
459 /* Copy the file SRC_PATH to the file DST_PATH. The files may be of
460 any type. NEW_DST should be non-zero if the file DST_PATH cannot
461 exist because its parent directory was just created; NEW_DST should
462 be zero if DST_PATH might already exist. DEVICE is the device
463 number of the parent directory, or 0 if the parent of this file is
464 not known. ANCESTORS points to a linked, null terminated list of
465 devices and inodes of parent directories of SRC_PATH.
466 Return 0 if successful, 1 if an error occurs. */
469 copy (src_path, dst_path, new_dst, device, ancestors)
474 struct dir_list *ancestors;
481 char *dst_backup = NULL;
484 if ((*xstat) (src_path, &src_sb))
486 error (0, errno, "%s", src_path);
490 /* Are we crossing a file system boundary? */
491 if (flag_one_file_system && device != 0 && device != src_sb.st_dev)
494 /* We wouldn't insert a node unless nlink > 1, except that we need to
495 find created files so as to not copy infinitely if a directory is
496 copied into itself. */
498 earlier_file = remember_copied (dst_path, src_sb.st_ino, src_sb.st_dev);
500 /* Did we just create this file? */
502 if (earlier_file == &new_file)
505 src_mode = src_sb.st_mode;
506 src_type = src_sb.st_mode;
508 if (S_ISDIR (src_type) && !flag_recursive)
510 error (0, 0, "%s: omitting directory", src_path);
516 if ((*xstat) (dst_path, &dst_sb))
520 error (0, errno, "%s", dst_path);
528 /* The file exists already. */
530 if (src_sb.st_ino == dst_sb.st_ino && src_sb.st_dev == dst_sb.st_dev)
535 error (0, 0, "`%s' and `%s' are the same file",
540 if (!S_ISDIR (src_type))
542 if (S_ISDIR (dst_sb.st_mode))
545 "%s: cannot overwrite directory with non-directory",
550 if (flag_update && src_sb.st_mtime <= dst_sb.st_mtime)
554 if (S_ISREG (src_type) && !flag_force)
556 if (flag_interactive)
558 if (eaccess_stat (&dst_sb, W_OK, dst_path) != 0)
560 "%s: overwrite `%s', overriding mode %04o? ",
561 program_name, dst_path,
562 (unsigned int) (dst_sb.st_mode & 07777));
564 fprintf (stderr, "%s: overwrite `%s'? ",
565 program_name, dst_path);
571 if (backup_type != none && !S_ISDIR (dst_sb.st_mode))
573 char *tmp_backup = find_backup_file_name (dst_path);
574 if (tmp_backup == NULL)
575 error (1, 0, "virtual memory exhausted");
576 dst_backup = (char *) alloca (strlen (tmp_backup) + 1);
577 strcpy (dst_backup, tmp_backup);
579 if (rename (dst_path, dst_backup))
583 error (0, errno, "cannot backup `%s'", dst_path);
593 if (S_ISDIR (dst_sb.st_mode))
595 /* Temporarily change mode to allow overwriting. */
596 if (eaccess_stat (&dst_sb, W_OK | X_OK) != 0)
598 if (chmod (dst_path, 0700))
600 error (0, errno, "%s", dst_path);
609 if (unlink (dst_path) && errno != ENOENT)
611 error (0, errno, "cannot remove old link to `%s'",
621 /* If the source is a directory, we don't always create the destination
622 directory. So --verbose should not announce anything until we're
623 sure we'll create a directory. */
624 if (flag_verbose && !S_ISDIR (src_type))
625 printf ("%s -> %s\n", src_path, dst_path);
627 /* Did we copy this inode somewhere else (in this command line argument)
628 and therefore this is a second hard link to the inode? */
630 if (!flag_dereference && src_sb.st_nlink > 1 && earlier_file)
632 if (link (earlier_file, dst_path))
634 error (0, errno, "%s", dst_path);
640 if (S_ISDIR (src_type))
642 struct dir_list *dir;
644 /* If this directory has been copied before during the
645 recursion, there is a symbolic link to an ancestor
646 directory of the symbolic link. It is impossible to
647 continue to copy this, unless we've got an infinite disk. */
649 if (is_ancestor (&src_sb, ancestors))
651 error (0, 0, "%s: cannot copy cyclic symbolic link", src_path);
655 /* Insert the current directory in the list of parents. */
657 dir = (struct dir_list *) alloca (sizeof (struct dir_list));
658 dir->parent = ancestors;
659 dir->ino = src_sb.st_ino;
660 dir->dev = src_sb.st_dev;
662 if (new_dst || !S_ISDIR (dst_sb.st_mode))
664 /* Create the new directory writable and searchable, so
665 we can create new entries in it. */
667 if (mkdir (dst_path, (src_mode & umask_kill) | 0700))
669 error (0, errno, "cannot create directory `%s'", dst_path);
673 /* Insert the created directory's inode and device
674 numbers into the search structure, so that we can
675 avoid copying it again. */
677 if (remember_created (dst_path))
681 printf ("%s -> %s\n", src_path, dst_path);
684 /* Copy the contents of the directory. */
686 if (copy_dir (src_path, dst_path, new_dst, &src_sb, dir))
690 else if (flag_symbolic_link)
693 || (!strncmp (dst_path, "./", 2) && strchr (dst_path + 2, '/') == 0)
694 || strchr (dst_path, '/') == 0)
696 if (symlink (src_path, dst_path))
698 error (0, errno, "%s", dst_path);
706 "%s: can only make relative symbolic links in current directory", dst_path);
711 else if (flag_hard_link)
713 if (link (src_path, dst_path))
715 error (0, errno, "cannot create link `%s'", dst_path);
720 else if (S_ISREG (src_type)
721 || (flag_copy_as_regular && !S_ISDIR (src_type)
723 && !S_ISLNK (src_type)
727 if (copy_reg (src_path, dst_path))
732 if (S_ISFIFO (src_type))
734 if (mkfifo (dst_path, src_mode & umask_kill))
736 error (0, errno, "cannot create fifo `%s'", dst_path);
742 if (S_ISBLK (src_type) || S_ISCHR (src_type)
744 || S_ISSOCK (src_type)
748 if (mknod (dst_path, src_mode & umask_kill, src_sb.st_rdev))
750 error (0, errno, "cannot create special file `%s'", dst_path);
756 if (S_ISLNK (src_type))
761 link_val = (char *) alloca (PATH_MAX + 2);
762 link_size = readlink (src_path, link_val, PATH_MAX + 1);
765 error (0, errno, "cannot read symbolic link `%s'", src_path);
768 link_val[link_size] = '\0';
770 if (symlink (link_val, dst_path))
772 error (0, errno, "cannot create symbolic link `%s'", dst_path);
780 error (0, 0, "%s: unknown file type", src_path);
784 /* Adjust the times (and if possible, ownership) for the copy.
785 chown turns off set[ug]id bits for non-root,
786 so do the chmod last. */
792 utb.actime = src_sb.st_atime;
793 utb.modtime = src_sb.st_mtime;
795 if (utime (dst_path, &utb))
797 error (0, errno, "%s", dst_path);
801 /* If non-root uses -p, it's ok if we can't preserve ownership.
802 But root probably wants to know, e.g. if NFS disallows it. */
804 (myeuid == 0 ? src_sb.st_uid : myeuid),
806 && (errno != EPERM || myeuid == 0))
808 error (0, errno, "%s", dst_path);
813 if ((flag_preserve || new_dst)
814 && (flag_copy_as_regular || S_ISREG (src_type) || S_ISDIR (src_type)))
816 if (chmod (dst_path, src_mode & umask_kill))
818 error (0, errno, "%s", dst_path);
824 /* Reset the temporarily changed mode. */
825 if (chmod (dst_path, dst_sb.st_mode))
827 error (0, errno, "%s", dst_path);
837 if (rename (dst_backup, dst_path))
838 error (0, errno, "cannot un-backup `%s'", dst_path);
843 /* Ensure that the parent directory of CONST_DIRPATH exists, for
844 the --parents option.
846 SRC_OFFSET is the index in CONST_DIRPATH (which is a destination
847 path) of the beginning of the source directory name.
848 Create any leading directories that don't already exist,
849 giving them permissions MODE.
850 If VERBOSE_FMT_STRING is nonzero, use it as a printf format
851 string for printing a message after successfully making a directory.
852 The format should take two string arguments: the names of the
853 source and destination directories.
854 Creates a linked list of attributes of intermediate directories,
855 *ATTR_LIST, for re_protect to use after calling copy.
856 Sets *NEW_DST to 1 if this function creates parent of CONST_DIRPATH.
858 Return 0 if parent of CONST_DIRPATH exists as a directory with the proper
859 permissions when done, otherwise 1. */
862 make_path_private (const_dirpath, src_offset, mode, verbose_fmt_string,
867 char *verbose_fmt_string;
868 struct dir_attr **attr_list;
872 char *dirpath; /* A copy of CONST_DIRPATH we can change. */
873 char *src; /* Source name in `dirpath'. */
874 char *tmp_dst_dirname; /* Leading path of `dirpath', malloc. */
875 char *dst_dirname; /* Leading path of `dirpath', alloca. */
877 dirpath = (char *) alloca (strlen (const_dirpath) + 1);
878 strcpy (dirpath, const_dirpath);
880 src = dirpath + src_offset;
882 tmp_dst_dirname = dirname (dirpath);
883 dst_dirname = (char *) alloca (strlen (tmp_dst_dirname) + 1);
884 strcpy (dst_dirname, tmp_dst_dirname);
885 free (tmp_dst_dirname);
889 if ((*xstat) (dst_dirname, &stats))
891 /* Parent of CONST_DIRNAME does not exist.
892 Make all missing intermediate directories. */
896 while (*slash == '/')
898 while ((slash = strchr (slash, '/')))
900 /* Add this directory to the list of directories whose modes need
902 struct dir_attr *new =
903 (struct dir_attr *) xmalloc (sizeof (struct dir_attr));
904 new->slash_offset = slash - dirpath;
905 new->next = *attr_list;
909 if ((*xstat) (dirpath, &stats))
911 /* This element of the path does not exist. We must set
912 *new_dst and new->is_new_dir inside this loop because,
913 for example, in the command `cp --parents ../a/../b/c e_dir',
914 make_path_private creates only e_dir/../a if ./b already
918 if (mkdir (dirpath, mode))
920 error (0, errno, "cannot make directory `%s'", dirpath);
925 if (verbose_fmt_string != NULL)
926 printf (verbose_fmt_string, src, dirpath);
929 else if (!S_ISDIR (stats.st_mode))
931 error (0, 0, "`%s' exists but is not a directory", dirpath);
941 /* Avoid unnecessary calls to `stat' when given
942 pathnames containing multiple adjacent slashes. */
943 while (*slash == '/')
948 /* We get here if the parent of `dirpath' already exists. */
950 else if (!S_ISDIR (stats.st_mode))
952 error (0, 0, "`%s' exists but is not a directory", dst_dirname);
962 /* Ensure that the parent directories of CONST_DST_PATH have the
963 correct protections, for the --parents option. This is done
964 after all copying has been completed, to allow permissions
965 that don't include user write/execute.
967 SRC_OFFSET is the index in CONST_DST_PATH of the beginning of the
968 source directory name.
970 ATTR_LIST is a null-terminated linked list of structures that
971 indicates the end of the filename of each intermediate directory
972 in CONST_DST_PATH that may need to have its attributes changed.
973 The command `cp --parents --preserve a/b/c d/e_dir' changes the
974 attributes of the directories d/e_dir/a and d/e_dir/a/b to match
975 the corresponding source directories regardless of whether they
976 existed before the `cp' command was given.
978 Return 0 if the parent of CONST_DST_PATH and any intermediate
979 directories specified by ATTR_LIST have the proper permissions
980 when done, otherwise 1. */
983 re_protect (const_dst_path, src_offset, attr_list)
984 char *const_dst_path;
986 struct dir_attr *attr_list;
989 char *dst_path; /* A copy of CONST_DST_PATH we can change. */
990 char *src_path; /* The source name in `dst_path'. */
992 dst_path = (char *) alloca (strlen (const_dst_path) + 1);
993 strcpy (dst_path, const_dst_path);
994 src_path = dst_path + src_offset;
996 for (p = attr_list; p; p = p->next)
1000 dst_path[p->slash_offset] = '\0';
1002 if ((*xstat) (src_path, &src_sb))
1004 error (0, errno, "%s", src_path);
1008 /* Adjust the times (and if possible, ownership) for the copy.
1009 chown turns off set[ug]id bits for non-root,
1010 so do the chmod last. */
1016 utb.actime = src_sb.st_atime;
1017 utb.modtime = src_sb.st_mtime;
1019 if (utime (dst_path, &utb))
1021 error (0, errno, "%s", dst_path);
1025 /* If non-root uses -p, it's ok if we can't preserve ownership.
1026 But root probably wants to know, e.g. if NFS disallows it. */
1027 if (chown (dst_path, src_sb.st_uid, src_sb.st_gid)
1028 && (errno != EPERM || myeuid == 0))
1030 error (0, errno, "%s", dst_path);
1035 if (flag_preserve || p->is_new_dir)
1037 if (chmod (dst_path, src_sb.st_mode & umask_kill))
1039 error (0, errno, "%s", dst_path);
1044 dst_path[p->slash_offset] = '/';
1049 /* Read the contents of the directory SRC_PATH_IN, and recursively
1050 copy the contents to DST_PATH_IN. NEW_DST is non-zero if
1051 DST_PATH_IN is a directory that was created previously in the
1052 recursion. SRC_SB and ANCESTORS describe SRC_PATH_IN.
1053 Return 0 if successful, -1 if an error occurs. */
1056 copy_dir (src_path_in, dst_path_in, new_dst, src_sb, ancestors)
1060 struct stat *src_sb;
1061 struct dir_list *ancestors;
1070 name_space = savedir (src_path_in, src_sb->st_size);
1071 if (name_space == 0)
1075 error (0, errno, "%s", src_path_in);
1079 error (1, 0, "virtual memory exhausted");
1083 while (*namep != '\0')
1085 int fn_length = strlen (namep) + 1;
1087 dst_path = xmalloc (strlen (dst_path_in) + fn_length + 1);
1088 src_path = xmalloc (strlen (src_path_in) + fn_length + 1);
1090 stpcpy (stpcpy (stpcpy (src_path, src_path_in), "/"), namep);
1091 stpcpy (stpcpy (stpcpy (dst_path, dst_path_in), "/"), namep);
1093 ret |= copy (src_path, dst_path, new_dst, src_sb->st_dev, ancestors);
1095 /* Free the memory for `src_path'. The memory for `dst_path'
1096 cannot be deallocated, since it is used to create multiple
1107 /* Copy a regular file from SRC_PATH to DST_PATH.
1108 If the source file contains holes, copies holes and blocks of zeros
1109 in the source file as holes in the destination file.
1110 (Holes are read as zeroes by the `read' system call.)
1111 Return 0 if successful, -1 if an error occurred. */
1114 copy_reg (src_path, dst_path)
1127 long n_read_total = 0;
1128 int last_write_made_hole = 0;
1131 source_desc = open (src_path, O_RDONLY);
1132 if (source_desc < 0)
1134 error (0, errno, "%s", src_path);
1138 /* Create the new regular file with small permissions initially,
1139 to not create a security hole. */
1141 dest_desc = open (dst_path, O_WRONLY | O_CREAT | O_TRUNC, 0600);
1144 error (0, errno, "cannot create regular file `%s'", dst_path);
1149 /* Find out the optimal buffer size. */
1151 if (fstat (dest_desc, &sb))
1153 error (0, errno, "%s", dst_path);
1158 buf_size = ST_BLKSIZE (sb);
1160 #ifdef HAVE_ST_BLOCKS
1161 if (S_ISREG (sb.st_mode))
1163 /* Find out whether the file contains any sparse blocks. */
1165 if (fstat (source_desc, &sb))
1167 error (0, errno, "%s", src_path);
1172 /* If the file has fewer blocks than would normally
1173 be needed for a file of its size, then
1174 at least one of the blocks in the file is a hole. */
1175 if (S_ISREG (sb.st_mode) && sb.st_size > sb.st_blocks * DEV_BSIZE)
1180 /* Make a buffer with space for a sentinel at the end. */
1182 buf = (char *) alloca (buf_size + sizeof (int));
1186 n_read = read (source_desc, buf, buf_size);
1193 error (0, errno, "%s", src_path);
1200 n_read_total += n_read;
1205 buf[n_read] = 1; /* Sentinel to stop loop. */
1207 /* Find first non-zero *word*, or the word with the sentinel. */
1213 /* Find the first non-zero *byte*, or the sentinel. */
1215 cp = (char *) (ip - 1);
1219 /* If we found the sentinel, the whole input block was zero,
1220 and we can make a hole. */
1222 if (cp > buf + n_read)
1225 if (lseek (dest_desc, (off_t) n_read, SEEK_CUR) < 0L)
1227 error (0, errno, "%s", dst_path);
1231 last_write_made_hole = 1;
1234 /* Clear to indicate that a normal write is needed. */
1239 if (full_write (dest_desc, buf, n_read) < 0)
1241 error (0, errno, "%s", dst_path);
1245 last_write_made_hole = 0;
1249 /* If the file ends with a `hole', something needs to be written at
1250 the end. Otherwise the kernel would truncate the file at the end
1251 of the last write operation. */
1253 if (last_write_made_hole)
1255 #ifdef HAVE_FTRUNCATE
1256 /* Write a null character and truncate it again. */
1257 if (full_write (dest_desc, "", 1) < 0
1258 || ftruncate (dest_desc, n_read_total) < 0)
1260 /* Seek backwards one character and write a null. */
1261 if (lseek (dest_desc, (off_t) -1, SEEK_CUR) < 0L
1262 || full_write (dest_desc, "", 1) < 0)
1265 error (0, errno, "%s", dst_path);
1271 if (close (dest_desc) < 0)
1273 error (0, errno, "%s", dst_path);
1277 if (close (source_desc) < 0)
1279 error (0, errno, "%s", src_path);