copy_file: handle "cp /dev/foo file" (almost) compatibly to coreutils.
[oweals/busybox.git] / libbb / copy_file.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini copy_file implementation for busybox
4  *
5  * Copyright (C) 2001 by Matt Kraai <kraai@alumni.carnegiemellon.edu>
6  * SELinux support by Yuichi Nakamura <ynakam@hitachisoft.jp>
7  *
8  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
9  *
10  */
11
12 #include "libbb.h"
13
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.
17 // Result: a mess:
18 // If dest is a softlink, we overwrite softlink's 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...
22 //
23 // NB: we have special code which still allows for "cp file /dev/node"
24 // to work POSIX-ly (the only realistic case where it makes sense)
25
26 #define DO_POSIX_CP 0  /* 1 - POSIX behavior, 0 - safe behavior */
27
28 // errno must be set to relevant value ("why we cannot create dest?")
29 // for POSIX mode to give reasonable error message
30 static int ask_and_unlink(const char *dest, int flags)
31 {
32         int e = errno;
33 #if DO_POSIX_CP
34         if (!(flags & (FILEUTILS_FORCE|FILEUTILS_INTERACTIVE))) {
35                 // Either it exists, or the *path* doesnt exist
36                 bb_perror_msg("cannot create '%s'", dest);
37                 return -1;
38         }
39 #endif
40         // If !DO_POSIX_CP, act as if -f is always in effect - we don't want
41         // "cannot create" msg, we want unlink to be done (silently unless -i).
42
43         // TODO: maybe we should do it only if ctty is present?
44         if (flags & FILEUTILS_INTERACTIVE) {
45                 // We would not do POSIX insanity. -i asks,
46                 // then _unlinks_ the offender. Presto.
47                 // (No "opening without O_EXCL", no "unlink only if -f")
48                 // Or else we will end up having 3 open()s!
49                 fprintf(stderr, "%s: overwrite '%s'? ", applet_name, dest);
50                 if (!bb_ask_confirmation())
51                         return 0; // not allowed to overwrite
52         }
53         if (unlink(dest) < 0) {
54 #if ENABLE_FEATURE_VERBOSE_CP_MESSAGE
55                 if (e == errno && e == ENOENT) {
56                         /* e == ENOTDIR is similar: path has non-dir component,
57                          * but in this case we don't even reach copy_file() */
58                         bb_error_msg("cannot create '%s': Path does not exist", dest);
59                         return -1; // error
60                 }
61 #endif
62                 errno = e;
63                 bb_perror_msg("cannot create '%s'", dest);
64                 return -1; // error
65         }
66         return 1; // ok (to try again)
67 }
68
69 /* Return:
70  * -1 error, copy not made
71  *  0 copy is made or user answered "no" in interactive mode
72  *    (failures to preserve mode/owner/times are not reported in exit code)
73  */
74 int copy_file(const char *source, const char *dest, int flags)
75 {
76         /* This is a recursive function, try to minimize stack usage */
77         /* NB: each struct stat is ~100 bytes */
78         struct stat source_stat;
79         struct stat dest_stat;
80         signed char retval = 0;
81         signed char dest_exists = 0;
82         signed char ovr;
83
84 /* Inverse of cp -d ("cp without -d") */
85 #define FLAGS_DEREF (flags & FILEUTILS_DEREFERENCE)
86
87         if ((FLAGS_DEREF ? stat : lstat)(source, &source_stat) < 0) {
88                 // This may be a dangling symlink.
89                 // Making [sym]links to dangling symlinks works, so...
90                 if (flags & (FILEUTILS_MAKE_SOFTLINK|FILEUTILS_MAKE_HARDLINK))
91                         goto make_links;
92                 bb_perror_msg("cannot stat '%s'", source);
93                 return -1;
94         }
95
96         if (lstat(dest, &dest_stat) < 0) {
97                 if (errno != ENOENT) {
98                         bb_perror_msg("cannot stat '%s'", dest);
99                         return -1;
100                 }
101         } else {
102                 if (source_stat.st_dev == dest_stat.st_dev
103                  && source_stat.st_ino == dest_stat.st_ino
104                 ) {
105                         bb_error_msg("'%s' and '%s' are the same file", source, dest);
106                         return -1;
107                 }
108                 dest_exists = 1;
109         }
110
111 #if ENABLE_SELINUX
112         if ((flags & FILEUTILS_PRESERVE_SECURITY_CONTEXT) && is_selinux_enabled() > 0) {
113                 security_context_t con;
114                 if (lgetfilecon(source, &con) >= 0) {
115                         if (setfscreatecon(con) < 0) {
116                                 bb_perror_msg("cannot set setfscreatecon %s", con);
117                                 freecon(con);
118                                 return -1;
119                         }
120                 } else if (errno == ENOTSUP || errno == ENODATA) {
121                         setfscreatecon_or_die(NULL);
122                 } else {
123                         bb_perror_msg("cannot lgetfilecon %s", source);
124                         return -1;
125                 }
126         }
127 #endif
128
129         if (S_ISDIR(source_stat.st_mode)) {
130                 DIR *dp;
131                 const char *tp;
132                 struct dirent *d;
133                 mode_t saved_umask = 0;
134
135                 if (!(flags & FILEUTILS_RECUR)) {
136                         bb_error_msg("omitting directory '%s'", source);
137                         return -1;
138                 }
139
140                 /* Did we ever create source ourself before? */
141                 tp = is_in_ino_dev_hashtable(&source_stat);
142                 if (tp) {
143                         /* We did! it's a recursion! man the lifeboats... */
144                         bb_error_msg("recursion detected, omitting directory '%s'",
145                                         source);
146                         return -1;
147                 }
148
149                 /* Create DEST */
150                 if (dest_exists) {
151                         if (!S_ISDIR(dest_stat.st_mode)) {
152                                 bb_error_msg("target '%s' is not a directory", dest);
153                                 return -1;
154                         }
155                         /* race here: user can substitute a symlink between
156                          * this check and actual creation of files inside dest */
157                 } else {
158                         mode_t mode;
159                         saved_umask = umask(0);
160
161                         mode = source_stat.st_mode;
162                         if (!(flags & FILEUTILS_PRESERVE_STATUS))
163                                 mode = source_stat.st_mode & ~saved_umask;
164                         /* Allow owner to access new dir (at least for now) */
165                         mode |= S_IRWXU;
166                         if (mkdir(dest, mode) < 0) {
167                                 umask(saved_umask);
168                                 bb_perror_msg("cannot create directory '%s'", dest);
169                                 return -1;
170                         }
171                         umask(saved_umask);
172                         /* need stat info for add_to_ino_dev_hashtable */
173                         if (lstat(dest, &dest_stat) < 0) {
174                                 bb_perror_msg("cannot stat '%s'", dest);
175                                 return -1;
176                         }
177                 }
178                 /* remember (dev,inode) of each created dir.
179                  * NULL: name is not remembered */
180                 add_to_ino_dev_hashtable(&dest_stat, NULL);
181
182                 /* Recursively copy files in SOURCE */
183                 dp = opendir(source);
184                 if (dp == NULL) {
185                         retval = -1;
186                         goto preserve_mode_ugid_time;
187                 }
188
189                 while ((d = readdir(dp)) != NULL) {
190                         char *new_source, *new_dest;
191
192                         new_source = concat_subpath_file(source, d->d_name);
193                         if (new_source == NULL)
194                                 continue;
195                         new_dest = concat_path_file(dest, d->d_name);
196                         if (copy_file(new_source, new_dest, flags) < 0)
197                                 retval = -1;
198                         free(new_source);
199                         free(new_dest);
200                 }
201                 closedir(dp);
202
203                 if (!dest_exists
204                  && chmod(dest, source_stat.st_mode & ~saved_umask) < 0
205                 ) {
206                         bb_perror_msg("cannot preserve %s of '%s'", "permissions", dest);
207                         /* retval = -1; - WRONG! copy *WAS* made */
208                 }
209                 goto preserve_mode_ugid_time;
210         }
211
212         if (flags & (FILEUTILS_MAKE_SOFTLINK|FILEUTILS_MAKE_HARDLINK)) {
213                 int (*lf)(const char *oldpath, const char *newpath);
214  make_links:
215                 // Hmm... maybe
216                 // if (DEREF && MAKE_SOFTLINK) source = realpath(source) ?
217                 // (but realpath returns NULL on dangling symlinks...)
218                 lf = (flags & FILEUTILS_MAKE_SOFTLINK) ? symlink : link;
219                 if (lf(source, dest) < 0) {
220                         ovr = ask_and_unlink(dest, flags);
221                         if (ovr <= 0)
222                                 return ovr;
223                         if (lf(source, dest) < 0) {
224                                 bb_perror_msg("cannot create link '%s'", dest);
225                                 return -1;
226                         }
227                 }
228                 /* _Not_ jumping to preserve_mode_ugid_time:
229                  * hard/softlinks don't have those */
230                 return 0;
231         }
232
233         if (/* "cp thing1 thing2" without -R: just open and read() from thing1 */
234             !(flags & FILEUTILS_RECUR)
235             /* "cp [-opts] regular_file thing2" */
236          || S_ISREG(source_stat.st_mode)
237          /* DEREF uses stat, which never returns S_ISLNK() == true.
238           * So the below is never true: */
239          /* || (FLAGS_DEREF && S_ISLNK(source_stat.st_mode)) */
240         ) {
241                 int src_fd;
242                 int dst_fd;
243                 mode_t new_mode;
244
245                 if (!FLAGS_DEREF && S_ISLNK(source_stat.st_mode)) {
246                         /* "cp -d symlink dst": create a link */
247                         goto dont_cat;
248                 }
249
250                 if (ENABLE_FEATURE_PRESERVE_HARDLINKS && !FLAGS_DEREF) {
251                         const char *link_target;
252                         link_target = is_in_ino_dev_hashtable(&source_stat);
253                         if (link_target) {
254                                 if (link(link_target, dest) < 0) {
255                                         ovr = ask_and_unlink(dest, flags);
256                                         if (ovr <= 0)
257                                                 return ovr;
258                                         if (link(link_target, dest) < 0) {
259                                                 bb_perror_msg("cannot create link '%s'", dest);
260                                                 return -1;
261                                         }
262                                 }
263                                 return 0;
264                         }
265                         add_to_ino_dev_hashtable(&source_stat, dest);
266                 }
267
268                 src_fd = open_or_warn(source, O_RDONLY);
269                 if (src_fd < 0)
270                         return -1;
271
272                 /* Do not try to open with weird mode fields */
273                 new_mode = source_stat.st_mode;
274                 if (!S_ISREG(source_stat.st_mode))
275                         new_mode = 0666;
276
277                 /* POSIX way is a security problem versus symlink attacks,
278                  * we do it only for non-symlinks, and only for non-recursive,
279                  * non-interactive cp. NB: it is still racy
280                  * for "cp file /home/bad_user/file" case
281                  * (user can rm file and create a link to /etc/passwd) */
282                 if (DO_POSIX_CP
283                  || (dest_exists
284                      && !(flags & (FILEUTILS_RECUR|FILEUTILS_INTERACTIVE))
285                      && !S_ISLNK(dest_stat.st_mode))
286                 ) {
287                         dst_fd = open(dest, O_WRONLY|O_CREAT|O_TRUNC, new_mode);
288                 } else  /* safe way: */
289                         dst_fd = open(dest, O_WRONLY|O_CREAT|O_EXCL, new_mode);
290                 if (dst_fd == -1) {
291                         ovr = ask_and_unlink(dest, flags);
292                         if (ovr <= 0) {
293                                 close(src_fd);
294                                 return ovr;
295                         }
296                         /* It shouldn't exist. If it exists, do not open (symlink attack?) */
297                         dst_fd = open3_or_warn(dest, O_WRONLY|O_CREAT|O_EXCL, new_mode);
298                         if (dst_fd < 0) {
299                                 close(src_fd);
300                                 return -1;
301                         }
302                 }
303
304 #if ENABLE_SELINUX
305                 if ((flags & (FILEUTILS_PRESERVE_SECURITY_CONTEXT|FILEUTILS_SET_SECURITY_CONTEXT))
306                  && is_selinux_enabled() > 0
307                 ) {
308                         security_context_t con;
309                         if (getfscreatecon(&con) == -1) {
310                                 bb_perror_msg("getfscreatecon");
311                                 return -1;
312                         }
313                         if (con) {
314                                 if (setfilecon(dest, con) == -1) {
315                                         bb_perror_msg("setfilecon:%s,%s", dest, con);
316                                         freecon(con);
317                                         return -1;
318                                 }
319                                 freecon(con);
320                         }
321                 }
322 #endif
323                 if (bb_copyfd_eof(src_fd, dst_fd) == -1)
324                         retval = -1;
325                 /* Ok, writing side I can understand... */
326                 if (close(dst_fd) < 0) {
327                         bb_perror_msg("cannot close '%s'", dest);
328                         retval = -1;
329                 }
330                 /* ...but read size is already checked by bb_copyfd_eof */
331                 close(src_fd);
332                 /* "cp /dev/something new_file" should not
333                  * copy mode of /dev/something */
334                 if (!S_ISREG(source_stat.st_mode))
335                         return retval;
336                 goto preserve_mode_ugid_time;
337         }
338  dont_cat:
339
340         /* Source is a symlink or a special file */
341         /* We are lazy here, a bit lax with races... */
342         if (dest_exists) {
343                 errno = EEXIST;
344                 ovr = ask_and_unlink(dest, flags);
345                 if (ovr <= 0)
346                         return ovr;
347         }
348         if (S_ISLNK(source_stat.st_mode)) {
349                 char *lpath = xmalloc_readlink_or_warn(source);
350                 if (lpath) {
351                         int r = symlink(lpath, dest);
352                         free(lpath);
353                         if (r < 0) {
354                                 bb_perror_msg("cannot create symlink '%s'", dest);
355                                 return -1;
356                         }
357                         if (flags & FILEUTILS_PRESERVE_STATUS)
358                                 if (lchown(dest, source_stat.st_uid, source_stat.st_gid) < 0)
359                                         bb_perror_msg("cannot preserve %s of '%s'", "ownership", dest);
360                 }
361                 /* _Not_ jumping to preserve_mode_ugid_time:
362                  * symlinks don't have those */
363                 return 0;
364         }
365         if (S_ISBLK(source_stat.st_mode) || S_ISCHR(source_stat.st_mode)
366          || S_ISSOCK(source_stat.st_mode) || S_ISFIFO(source_stat.st_mode)
367         ) {
368                 if (mknod(dest, source_stat.st_mode, source_stat.st_rdev) < 0) {
369                         bb_perror_msg("cannot create '%s'", dest);
370                         return -1;
371                 }
372         } else {
373                 bb_error_msg("unrecognized file '%s' with mode %x", source, source_stat.st_mode);
374                 return -1;
375         }
376
377  preserve_mode_ugid_time:
378
379         if (flags & FILEUTILS_PRESERVE_STATUS
380         /* Cannot happen: */
381         /* && !(flags & (FILEUTILS_MAKE_SOFTLINK|FILEUTILS_MAKE_HARDLINK)) */
382         ) {
383                 struct utimbuf times;
384
385                 times.actime = source_stat.st_atime;
386                 times.modtime = source_stat.st_mtime;
387                 /* BTW, utimes sets usec-precision time - just FYI */
388                 if (utime(dest, &times) < 0)
389                         bb_perror_msg("cannot preserve %s of '%s'", "times", dest);
390                 if (chown(dest, source_stat.st_uid, source_stat.st_gid) < 0) {
391                         source_stat.st_mode &= ~(S_ISUID | S_ISGID);
392                         bb_perror_msg("cannot preserve %s of '%s'", "ownership", dest);
393                 }
394                 if (chmod(dest, source_stat.st_mode) < 0)
395                         bb_perror_msg("cannot preserve %s of '%s'", "permissions", dest);
396         }
397
398         return retval;
399 }