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