cp: detect and prevent infinite recursion
[platform/upstream/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 *existing_name;
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                 existing_name = is_in_ino_dev_hashtable(&source_stat);
128                 if (existing_name) {
129                         /* We did! it's a recursion! man the lifeboats... */
130                         bb_error_msg("recursion detected, omitting directory '%s'",
131                                         existing_name);
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                         char *link_target;
226
227                         link_target = is_in_ino_dev_hashtable(&source_stat);
228                         if (link_target) {
229                                 if (link(link_target, dest) < 0) {
230                                         ovr = ask_and_unlink(dest, flags);
231                                         if (ovr <= 0)
232                                                 return ovr;
233                                         if (link(link_target, dest) < 0) {
234                                                 bb_perror_msg("cannot create link '%s'", dest);
235                                                 return -1;
236                                         }
237                                 }
238                                 return 0;
239                         }
240                         add_to_ino_dev_hashtable(&source_stat, dest);
241                 }
242
243                 src_fd = open_or_warn(source, O_RDONLY);
244                 if (src_fd < 0)
245                         return -1;
246
247 #if DO_POSIX_CP  /* POSIX way (a security problem versus symlink attacks!): */
248                 dst_fd = open(dest, (flags & FILEUTILS_INTERACTIVE)
249                                 ? O_WRONLY|O_CREAT|O_EXCL
250                                 : O_WRONLY|O_CREAT|O_TRUNC, source_stat.st_mode);
251 #else  /* safe way: */
252                 dst_fd = open(dest, O_WRONLY|O_CREAT|O_EXCL, source_stat.st_mode);
253 #endif
254                 if (dst_fd == -1) {
255                         ovr = ask_and_unlink(dest, flags);
256                         if (ovr <= 0) {
257                                 close(src_fd);
258                                 return ovr;
259                         }
260                         /* It shouldn't exist. If it exists, do not open (symlink attack?) */
261                         dst_fd = open3_or_warn(dest, O_WRONLY|O_CREAT|O_EXCL, source_stat.st_mode);
262                         if (dst_fd < 0) {
263                                 close(src_fd);
264                                 return -1;
265                         }
266                 }
267
268 #if ENABLE_SELINUX
269                 if (((flags & FILEUTILS_PRESERVE_SECURITY_CONTEXT)
270                     || (flags & FILEUTILS_SET_SECURITY_CONTEXT))
271                  && is_selinux_enabled() > 0
272                 ) {
273                         security_context_t con;
274                         if (getfscreatecon(&con) == -1) {
275                                 bb_perror_msg("getfscreatecon");
276                                 return -1;
277                         }
278                         if (con) {
279                                 if (setfilecon(dest, con) == -1) {
280                                         bb_perror_msg("setfilecon:%s,%s", dest, con);
281                                         freecon(con);
282                                         return -1;
283                                 }
284                                 freecon(con);
285                         }
286                 }
287 #endif
288                 if (bb_copyfd_eof(src_fd, dst_fd) == -1)
289                         retval = -1;
290                 /* Ok, writing side I can understand... */
291                 if (close(dst_fd) < 0) {
292                         bb_perror_msg("cannot close '%s'", dest);
293                         retval = -1;
294                 }
295                 /* ...but read size is already checked by bb_copyfd_eof */
296                 close(src_fd);
297                 goto preserve_mode_ugid_time;
298         }
299
300         /* Source is a symlink or a special file */
301         /* We are lazy here, a bit lax with races... */
302         if (dest_exists) {
303                 errno = EEXIST;
304                 ovr = ask_and_unlink(dest, flags);
305                 if (ovr <= 0)
306                         return ovr;
307         }
308         if (S_ISLNK(source_stat.st_mode)) {
309                 char *lpath = xmalloc_readlink_or_warn(source);
310                 if (lpath) {
311                         int r = symlink(lpath, dest);
312                         free(lpath);
313                         if (r < 0) {
314                                 bb_perror_msg("cannot create symlink '%s'", dest);
315                                 return -1;
316                         }
317                         if (flags & FILEUTILS_PRESERVE_STATUS)
318                                 if (lchown(dest, source_stat.st_uid, source_stat.st_gid) < 0)
319                                         bb_perror_msg("cannot preserve %s of '%s'", "ownership", dest);
320                 }
321                 /* _Not_ jumping to preserve_mode_ugid_time:
322                  * symlinks don't have those */
323                 return 0;
324         }
325         if (S_ISBLK(source_stat.st_mode) || S_ISCHR(source_stat.st_mode)
326          || S_ISSOCK(source_stat.st_mode) || S_ISFIFO(source_stat.st_mode)
327         ) {
328                 if (mknod(dest, source_stat.st_mode, source_stat.st_rdev) < 0) {
329                         bb_perror_msg("cannot create '%s'", dest);
330                         return -1;
331                 }
332         } else {
333                 bb_error_msg("unrecognized file '%s' with mode %x", source, source_stat.st_mode);
334                 return -1;
335         }
336
337  preserve_mode_ugid_time:
338
339         if (flags & FILEUTILS_PRESERVE_STATUS
340         /* Cannot happen: */
341         /* && !(flags & (FILEUTILS_MAKE_SOFTLINK|FILEUTILS_MAKE_HARDLINK)) */
342         ) {
343                 struct utimbuf times;
344
345                 times.actime = source_stat.st_atime;
346                 times.modtime = source_stat.st_mtime;
347                 /* BTW, utimes sets usec-precision time - just FYI */
348                 if (utime(dest, &times) < 0)
349                         bb_perror_msg("cannot preserve %s of '%s'", "times", dest);
350                 if (chown(dest, source_stat.st_uid, source_stat.st_gid) < 0) {
351                         source_stat.st_mode &= ~(S_ISUID | S_ISGID);
352                         bb_perror_msg("cannot preserve %s of '%s'", "ownership", dest);
353                 }
354                 if (chmod(dest, source_stat.st_mode) < 0)
355                         bb_perror_msg("cannot preserve %s of '%s'", "permissions", dest);
356         }
357
358         return retval;
359 }