1 /* vi: set sw=4 ts=4: */
3 * Mini copy_file implementation for busybox
5 * Copyright (C) 2001 by Matt Kraai <kraai@alumni.carnegiemellon.edu>
6 * SELinux support by Yuichi Nakamura <ynakam@hitachisoft.jp>
8 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
12 // FEATURE_NON_POSIX_CP:
14 // POSIX: if exists and -i, ask (w/o -i assume yes).
15 // Then open w/o EXCL (yes, not unlink!).
16 // If open still fails and -f, try unlink, then try open again.
18 // If dest is a (sym)link, we overwrite link destination!
19 // (or fail, if it points to dir/nonexistent location/etc).
20 // This is strange, but POSIX-correct.
21 // coreutils cp has --remove-destination to override this...
23 /* Called if open of destination, link creation etc fails.
24 * errno must be set to relevant value ("why we cannot create dest?")
25 * to give reasonable error message */
26 static int ask_and_unlink(const char *dest, int flags)
30 #if !ENABLE_FEATURE_NON_POSIX_CP
31 if (!(flags & (FILEUTILS_FORCE|FILEUTILS_INTERACTIVE))) {
32 /* Either it exists, or the *path* doesnt exist */
33 bb_perror_msg("can't create '%s'", dest);
37 // else: act as if -f is always in effect.
38 // We don't want "can't create" msg, we want unlink to be done
39 // (silently unless -i). Why? POSIX cp usually succeeds with
40 // O_TRUNC open of existing file, and user is left ignorantly happy.
41 // With above block unconditionally enabled, non-POSIX cp
42 // will complain a lot more than POSIX one.
44 /* TODO: maybe we should do it only if ctty is present? */
45 if (flags & FILEUTILS_INTERACTIVE) {
46 // We would not do POSIX insanity. -i asks,
47 // then _unlinks_ the offender. Presto.
48 // (No "opening without O_EXCL", no "unlink only if -f")
49 // Or else we will end up having 3 open()s!
50 fprintf(stderr, "%s: overwrite '%s'? ", applet_name, dest);
51 if (!bb_ask_y_confirmation())
52 return 0; /* not allowed to overwrite */
54 if (unlink(dest) < 0) {
55 #if ENABLE_FEATURE_VERBOSE_CP_MESSAGE
56 if (e == errno && e == ENOENT) {
57 /* e == ENOTDIR is similar: path has non-dir component,
58 * but in this case we don't even reach copy_file() */
59 bb_error_msg("can't create '%s': Path does not exist", dest);
60 return -1; /* error */
63 errno = e; /* do not use errno from unlink */
64 bb_perror_msg("can't create '%s'", dest);
65 return -1; /* error */
67 #if ENABLE_FEATURE_CP_LONG_OPTIONS
68 if (flags & FILEUTILS_RMDEST)
69 if (flags & FILEUTILS_VERBOSE)
70 printf("removed '%s'\n", dest);
72 return 1; /* ok (to try again) */
76 * -1 error, copy not made
77 * 0 copy is made or user answered "no" in interactive mode
78 * (failures to preserve mode/owner/times are not reported in exit code)
80 int FAST_FUNC copy_file(const char *source, const char *dest, int flags)
82 /* This is a recursive function, try to minimize stack usage */
83 /* NB: each struct stat is ~100 bytes */
84 struct stat source_stat;
85 struct stat dest_stat;
87 smallint dest_exists = 0;
90 /* Inverse of cp -d ("cp without -d") */
91 #define FLAGS_DEREF (flags & (FILEUTILS_DEREFERENCE + FILEUTILS_DEREFERENCE_L0))
93 if ((FLAGS_DEREF ? stat : lstat)(source, &source_stat) < 0) {
94 /* This may be a dangling symlink.
95 * Making [sym]links to dangling symlinks works, so... */
96 if (flags & (FILEUTILS_MAKE_SOFTLINK|FILEUTILS_MAKE_HARDLINK))
98 bb_perror_msg("can't stat '%s'", source);
102 if (lstat(dest, &dest_stat) < 0) {
103 if (errno != ENOENT) {
104 bb_perror_msg("can't stat '%s'", dest);
108 if (source_stat.st_dev == dest_stat.st_dev
109 && source_stat.st_ino == dest_stat.st_ino
111 bb_error_msg("'%s' and '%s' are the same file", source, dest);
118 if ((flags & FILEUTILS_PRESERVE_SECURITY_CONTEXT) && is_selinux_enabled() > 0) {
119 security_context_t con;
120 if (lgetfilecon(source, &con) >= 0) {
121 if (setfscreatecon(con) < 0) {
122 bb_perror_msg("can't set setfscreatecon %s", con);
126 } else if (errno == ENOTSUP || errno == ENODATA) {
127 setfscreatecon_or_die(NULL);
129 bb_perror_msg("can't lgetfilecon %s", source);
135 if (S_ISDIR(source_stat.st_mode)) {
139 mode_t saved_umask = 0;
141 if (!(flags & FILEUTILS_RECUR)) {
142 bb_error_msg("omitting directory '%s'", source);
146 /* Did we ever create source ourself before? */
147 tp = is_in_ino_dev_hashtable(&source_stat);
149 /* We did! it's a recursion! man the lifeboats... */
150 bb_error_msg("recursion detected, omitting directory '%s'",
156 if (!S_ISDIR(dest_stat.st_mode)) {
157 bb_error_msg("target '%s' is not a directory", dest);
160 /* race here: user can substitute a symlink between
161 * this check and actual creation of files inside dest */
165 saved_umask = umask(0);
167 mode = source_stat.st_mode;
168 if (!(flags & FILEUTILS_PRESERVE_STATUS))
169 mode = source_stat.st_mode & ~saved_umask;
170 /* Allow owner to access new dir (at least for now) */
172 if (mkdir(dest, mode) < 0) {
174 bb_perror_msg("can't create directory '%s'", dest);
178 /* need stat info for add_to_ino_dev_hashtable */
179 if (lstat(dest, &dest_stat) < 0) {
180 bb_perror_msg("can't stat '%s'", dest);
184 /* remember (dev,inode) of each created dir.
185 * NULL: name is not remembered */
186 add_to_ino_dev_hashtable(&dest_stat, NULL);
188 /* Recursively copy files in SOURCE */
189 dp = opendir(source);
192 goto preserve_mode_ugid_time;
195 while ((d = readdir(dp)) != NULL) {
196 char *new_source, *new_dest;
198 new_source = concat_subpath_file(source, d->d_name);
199 if (new_source == NULL)
201 new_dest = concat_path_file(dest, d->d_name);
202 if (copy_file(new_source, new_dest, flags & ~FILEUTILS_DEREFERENCE_L0) < 0)
210 && chmod(dest, source_stat.st_mode & ~saved_umask) < 0
212 bb_perror_msg("can't preserve %s of '%s'", "permissions", dest);
213 /* retval = -1; - WRONG! copy *WAS* made */
215 goto preserve_mode_ugid_time;
219 if (flags & FILEUTILS_UPDATE) {
220 if (source_stat.st_mtime <= dest_stat.st_mtime) {
221 return 0; /* source file must be newer */
224 #if ENABLE_FEATURE_CP_LONG_OPTIONS
225 if (flags & FILEUTILS_RMDEST) {
226 ovr = ask_and_unlink(dest, flags);
234 if (flags & (FILEUTILS_MAKE_SOFTLINK|FILEUTILS_MAKE_HARDLINK)) {
235 int (*lf)(const char *oldpath, const char *newpath);
238 * if (DEREF && MAKE_SOFTLINK) source = realpath(source) ?
239 * (but realpath returns NULL on dangling symlinks...) */
240 lf = (flags & FILEUTILS_MAKE_SOFTLINK) ? symlink : link;
241 if (lf(source, dest) < 0) {
242 ovr = ask_and_unlink(dest, flags);
245 if (lf(source, dest) < 0) {
246 bb_perror_msg("can't create link '%s'", dest);
250 /* _Not_ jumping to preserve_mode_ugid_time:
251 * (sym)links don't have those */
255 if (/* "cp thing1 thing2" without -R: just open and read() from thing1 */
256 !(flags & FILEUTILS_RECUR)
257 /* "cp [-opts] regular_file thing2" */
258 || S_ISREG(source_stat.st_mode)
259 /* DEREF uses stat, which never returns S_ISLNK() == true.
260 * So the below is never true: */
261 /* || (FLAGS_DEREF && S_ISLNK(source_stat.st_mode)) */
267 if (!FLAGS_DEREF && S_ISLNK(source_stat.st_mode)) {
268 /* "cp -d symlink dst": create a link */
272 if (ENABLE_FEATURE_PRESERVE_HARDLINKS && !FLAGS_DEREF) {
273 const char *link_target;
274 link_target = is_in_ino_dev_hashtable(&source_stat);
276 if (link(link_target, dest) < 0) {
277 ovr = ask_and_unlink(dest, flags);
280 if (link(link_target, dest) < 0) {
281 bb_perror_msg("can't create link '%s'", dest);
287 add_to_ino_dev_hashtable(&source_stat, dest);
290 src_fd = open_or_warn(source, O_RDONLY);
294 /* Do not try to open with weird mode fields */
295 new_mode = source_stat.st_mode;
296 if (!S_ISREG(source_stat.st_mode))
299 if (ENABLE_FEATURE_NON_POSIX_CP || (flags & FILEUTILS_INTERACTIVE)) {
301 * O_CREAT|O_EXCL: require that file did not exist before creation
303 dst_fd = open(dest, O_WRONLY|O_CREAT|O_EXCL, new_mode);
304 } else { /* POSIX, and not "cp -i" */
306 * O_CREAT|O_TRUNC: create, or truncate (security problem versus (sym)link attacks)
308 dst_fd = open(dest, O_WRONLY|O_CREAT|O_TRUNC, new_mode);
311 ovr = ask_and_unlink(dest, flags);
316 /* It shouldn't exist. If it exists, do not open (symlink attack?) */
317 dst_fd = open3_or_warn(dest, O_WRONLY|O_CREAT|O_EXCL, new_mode);
325 if ((flags & (FILEUTILS_PRESERVE_SECURITY_CONTEXT|FILEUTILS_SET_SECURITY_CONTEXT))
326 && is_selinux_enabled() > 0
328 security_context_t con;
329 if (getfscreatecon(&con) == -1) {
330 bb_perror_msg("getfscreatecon");
334 if (setfilecon(dest, con) == -1) {
335 bb_perror_msg("setfilecon:%s,%s", dest, con);
343 #if ENABLE_FEATURE_CP_REFLINK
344 # undef BTRFS_IOCTL_MAGIC
345 # define BTRFS_IOCTL_MAGIC 0x94
346 # undef BTRFS_IOC_CLONE
347 # define BTRFS_IOC_CLONE _IOW (BTRFS_IOCTL_MAGIC, 9, int)
348 if (flags & FILEUTILS_REFLINK) {
349 retval = ioctl(dst_fd, BTRFS_IOC_CLONE, src_fd);
352 /* reflink did not work */
353 if (flags & FILEUTILS_REFLINK_ALWAYS) {
354 bb_perror_msg("failed to clone '%s' from '%s'", dest, source);
357 /* fall through to standard copy */
361 if (bb_copyfd_eof(src_fd, dst_fd) == -1)
363 IF_FEATURE_CP_REFLINK(do_close:)
364 /* Careful with writing... */
365 if (close(dst_fd) < 0) {
366 bb_perror_msg("error writing to '%s'", dest);
369 /* ...but read size is already checked by bb_copyfd_eof */
371 /* "cp /dev/something new_file" should not
372 * copy mode of /dev/something */
373 if (!S_ISREG(source_stat.st_mode))
375 goto preserve_mode_ugid_time;
379 /* Source is a symlink or a special file */
380 /* We are lazy here, a bit lax with races... */
383 ovr = ask_and_unlink(dest, flags);
387 if (S_ISLNK(source_stat.st_mode)) {
388 char *lpath = xmalloc_readlink_or_warn(source);
390 int r = symlink(lpath, dest);
394 bb_perror_msg("can't create %slink '%s' to '%s'",
399 if (flags & FILEUTILS_PRESERVE_STATUS)
400 if (lchown(dest, source_stat.st_uid, source_stat.st_gid) < 0)
401 bb_perror_msg("can't preserve %s of '%s'", "ownership", dest);
403 /* _Not_ jumping to preserve_mode_ugid_time:
404 * symlinks don't have those */
407 if (S_ISBLK(source_stat.st_mode) || S_ISCHR(source_stat.st_mode)
408 || S_ISSOCK(source_stat.st_mode) || S_ISFIFO(source_stat.st_mode)
410 if (mknod(dest, source_stat.st_mode, source_stat.st_rdev) < 0) {
411 bb_perror_msg("can't create '%s'", dest);
415 bb_error_msg("unrecognized file '%s' with mode %x", source, source_stat.st_mode);
419 preserve_mode_ugid_time:
421 if (flags & FILEUTILS_PRESERVE_STATUS
423 /* && !(flags & (FILEUTILS_MAKE_SOFTLINK|FILEUTILS_MAKE_HARDLINK)) */
425 struct timeval times[2];
427 times[1].tv_sec = times[0].tv_sec = source_stat.st_mtime;
428 times[1].tv_usec = times[0].tv_usec = 0;
429 /* BTW, utimes sets usec-precision time - just FYI */
430 if (utimes(dest, times) < 0)
431 bb_perror_msg("can't preserve %s of '%s'", "times", dest);
432 if (chown(dest, source_stat.st_uid, source_stat.st_gid) < 0) {
433 source_stat.st_mode &= ~(S_ISUID | S_ISGID);
434 bb_perror_msg("can't preserve %s of '%s'", "ownership", dest);
436 if (chmod(dest, source_stat.st_mode) < 0)
437 bb_perror_msg("can't preserve %s of '%s'", "permissions", dest);
441 if (flags & FILEUTILS_VERBOSE) {
442 printf("'%s' -> '%s'\n", source, dest);