xref: /aosp_15_r20/external/toybox/toys/posix/cp.c (revision cf5a6c84e2b8763fc1a7db14496fd4742913b199)
1 /* Copyright 2008 Rob Landley <[email protected]>
2  *
3  * See http://opengroup.org/onlinepubs/9699919799/utilities/cp.html
4  * And http://opengroup.org/onlinepubs/9699919799/utilities/mv.html
5  * And http://refspecs.linuxfoundation.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic.html#INSTALL
6  *
7  * Posix says "cp -Rf dir file" shouldn't delete file, but our -f does.
8  *
9  * Deviations from posix: -adlnrsvF, --preserve... about half the
10  * functionality in this cp isn't in posix. Posix is stuck in the 1970's.
11  *
12  * TODO: --preserve=links
13  * TODO: what's this _CP_mode system.posix_acl_ business? We chmod()?
14 
15 // options shared between mv/cp must be in same order (right to left)
16 // for FLAG macros to work out right in shared infrastructure.
17 
18 USE_CP(NEWTOY(cp, "<1(preserve):;D(parents)RHLPprudaslv(verbose)nF(remove-destination)fit:T[-HLPd][-niu][+Rr]", TOYFLAG_BIN))
19 USE_MV(NEWTOY(mv, "<1x(swap)v(verbose)nF(remove-destination)fit:T[-ni]", TOYFLAG_BIN))
20 USE_INSTALL(NEWTOY(install, "<1cdDp(preserve-timestamps)svt:m:o:g:", TOYFLAG_USR|TOYFLAG_BIN))
21 
22 config CP
23   bool "cp"
24   default y
25   help
26     usage: cp [-aDdFfHiLlnPpRrsTuv] [--preserve=motcxa] [-t TARGET] SOURCE... [DEST]
27 
28     Copy files from SOURCE to DEST.  If more than one SOURCE, DEST must
29     be a directory.
30 
31     -a	Same as -dpr
32     -D	Create leading dirs under DEST (--parents)
33     -d	Don't dereference symlinks
34     -F	Delete any existing DEST first (--remove-destination)
35     -f	Delete destination files we can't write to
36     -H	Follow symlinks listed on command line
37     -i	Interactive, prompt before overwriting existing DEST
38     -L	Follow all symlinks
39     -l	Hard link instead of copy
40     -n	No clobber (don't overwrite DEST)
41     -P	Do not follow symlinks
42     -p	Preserve timestamps, ownership, and mode
43     -R	Recurse into subdirectories (DEST must be a directory)
44     -r	Synonym for -R
45     -s	Symlink instead of copy
46     -T	DEST always treated as file, max 2 arguments
47     -t	Copy to TARGET dir (no DEST)
48     -u	Update (keep newest mtime)
49     -v	Verbose
50 
51     Arguments to --preserve are the first letter(s) of:
52 
53             mode - permissions (ignore umask for rwx, copy suid and sticky bit)
54        ownership - user and group
55       timestamps - file creation, modification, and access times.
56          context - security context
57            xattr - extended attributes
58              all - all of the above
59 
60 config MV
61   bool "mv"
62   default y
63   help
64     usage: mv [-FfinTvx] [-t TARGET] SOURCE... [DEST]
65 
66     -F	Delete any existing DEST first (--remove-destination)
67     -f	Force copy by deleting destination file
68     -i	Interactive, prompt before overwriting existing DEST
69     -n	No clobber (don't overwrite DEST)
70     -t	Move to TARGET dir (no DEST)
71     -T	DEST always treated as file, max 2 arguments
72     -v	Verbose
73     -x	Atomically exchange source/dest (--swap)
74 
75 config INSTALL
76   bool "install"
77   default y
78   help
79     usage: install [-dDpsv] [-o USER] [-g GROUP] [-m MODE] [-t TARGET] [SOURCE...] [DEST]
80 
81     Copy files and set attributes.
82 
83     -d	Act like mkdir -p
84     -D	Create leading directories for DEST
85     -g	Make copy belong to GROUP
86     -m	Set permissions to MODE
87     -o	Make copy belong to USER
88     -p	Preserve timestamps
89     -s	Call "strip -p"
90     -t	Copy files to TARGET dir (no DEST)
91     -v	Verbose
92 */
93 
94 #define FORCE_FLAGS
95 #define FOR_cp
96 #include "toys.h"
97 
98 GLOBALS(
99   union {
100     // install's options
101     struct {
102       char *g, *o, *m, *t;
103     } i;
104     // cp's options
105     struct {
106       char *t, *preserve;
107     } c;
108   };
109 
110   char *destname;
111   struct stat top;
112   int (*callback)(struct dirtree *try);
113   uid_t uid;
114   gid_t gid;
115   int pflags;
116 )
117 
118 struct cp_preserve {
119   char *name;
120 } static const cp_preserve[] = TAGGED_ARRAY(CP,
121   {"mode"}, {"ownership"}, {"timestamps"}, {"context"}, {"xattr"},
122 );
123 
cp_xattr(int fdin,int fdout,char * file)124 void cp_xattr(int fdin, int fdout, char *file)
125 {
126   ssize_t listlen, len;
127   char *name, *value, *list;
128 
129   if (!(TT.pflags&(_CP_xattr|_CP_context))) return;
130   if ((listlen = xattr_flist(fdin, 0, 0))<1) return;
131 
132   list = xmalloc(listlen);
133   xattr_flist(fdin, list, listlen);
134   for (name = list; name-list < listlen; name += strlen(name)+1) {
135     // context copies security, xattr copies everything else
136     len = strncmp(name, "security.", 9) ? _CP_xattr : _CP_context;
137     if (!(TT.pflags&len)) continue;
138     if ((len = xattr_fget(fdin, name, 0, 0))>0) {
139       value = xmalloc(len);
140       if (len == xattr_fget(fdin, name, value, len))
141         if (xattr_fset(fdout, name, value, len, 0))
142           perror_msg("%s setxattr(%s=%s)", file, name, value);
143       free(value);
144     }
145   }
146   free(list);
147 }
148 
149 // Callback from dirtree_read() for each file/directory under a source dir.
150 
151 // traverses two directories in parallel: try->dirfd is source dir,
152 // try->extra is dest dir. TODO: filehandle exhaustion?
153 
cp_node(struct dirtree * try)154 static int cp_node(struct dirtree *try)
155 {
156   int fdout = -1, cfd = try->parent ? try->parent->extra : AT_FDCWD,
157       save = DIRTREE_SAVE*(CFG_MV && *toys.which->name == 'm'), rc = 0, rr = 0,
158       tfd = dirtree_parentfd(try);
159   char *s = 0, *catch = try->parent ? try->name : TT.destname, *err = "%s";
160   struct stat cst;
161 
162   if (!dirtree_notdotdot(try)) return 0;
163 
164   // If returning from COMEAGAIN, jump straight to -p logic at end.
165   if (S_ISDIR(try->st.st_mode) && (try->again&DIRTREE_COMEAGAIN)) {
166     fdout = try->extra;
167     err = 0;
168 
169     // If mv child had a problem, free data and don't try to delete parent dir.
170     if (try->child) {
171       save = 0;
172       llist_traverse(try->child, free);
173     }
174 
175     cp_xattr(try->dirfd, try->extra, catch);
176   } else {
177     // -d is only the same as -r for symlinks, not for directories
178     if (S_ISLNK(try->st.st_mode) && FLAG(d)) rr++;
179 
180     // Detect recursive copies via repeated top node (cp -R .. .) or
181     // identical source/target (fun with hardlinks).
182     if ((same_file(&TT.top, &try->st) && (catch = TT.destname))
183         || (!fstatat(cfd, catch, &cst, 0) && same_file(&cst, &try->st)))
184     {
185       error_msg("'%s' is '%s'", catch, err = dirtree_path(try, 0));
186       free(err);
187 
188       return save;
189     }
190 
191     // Handle -inuvF
192     if (!faccessat(cfd, catch, F_OK, 0) && !S_ISDIR(cst.st_mode)) {
193       if (S_ISDIR(try->st.st_mode))
194         error_msg("dir at '%s'", s = dirtree_path(try, 0));
195       else if (FLAG(F) && unlinkat(cfd, catch, 0))
196         error_msg("unlink '%s'", catch);
197       else if (FLAG(i)) {
198         fprintf(stderr, "%s: overwrite '%s'", toys.which->name, catch);
199         if (yesno(0)) rc++;
200       } else if (!(FLAG(u) && nanodiff(&try->st.st_mtim, &cst.st_mtim)>0)
201                  && !FLAG(n)) rc++;
202       free(s);
203       if (!rc) return save;
204     }
205 
206     if (FLAG(v)) {
207       printf("%s '%s' -> '%s'\n", toys.which->name, s = dirtree_path(try, 0),
208              catch);
209       free(s);
210     }
211 
212     // Loop for -f retry after unlink
213     do {
214       int ii, fdin = -1;
215 
216       // directory, hardlink, symlink, mknod (char, block, fifo, socket), file
217 
218       // Copy directory
219 
220       if (S_ISDIR(try->st.st_mode)) {
221         struct stat st2;
222 
223         if (!FLAG(a) && !FLAG(r) && !rr) {
224           err = "Skipped dir '%s'";
225           catch = try->name;
226           break;
227         }
228 
229         // Always make directory writeable to us, so we can create files in it.
230         //
231         // Yes, there's a race window between mkdir() and open() so it's
232         // possible that -p can be made to chown a directory other than the one
233         // we created. The closest we can do to closing this is make sure
234         // that what we open _is_ a directory rather than something else.
235 
236         if (!mkdirat(cfd, catch, try->st.st_mode | 0200) || errno == EEXIST)
237           if (-1 != (try->extra = openat(cfd, catch, O_NOFOLLOW)))
238             if (!fstat(try->extra, &st2) && S_ISDIR(st2.st_mode))
239               return DIRTREE_COMEAGAIN | DIRTREE_SYMFOLLOW*FLAG(L);
240 
241       // Hardlink
242 
243       } else if (FLAG(l)) {
244         if (!linkat(tfd, try->name, cfd, catch, 0)) err = 0;
245 
246       // Copy tree as symlinks. For non-absolute paths this involves
247       // appending the right number of .. entries as you go down the tree.
248 
249       } else if (FLAG(s)) {
250         char *s, *s2;
251         struct dirtree *or;
252 
253         s = dirtree_path(try, 0);
254         for (ii = 0, or = try; or->parent; or = or->parent) ii++;
255         if (*or->name == '/') ii = 0;
256         if (ii) {
257           s2 = xmprintf("%*c%s", 3*ii, ' ', s);
258           free(s);
259           s = s2;
260           while(ii--) {
261             memcpy(s2, "../", 3);
262             s2 += 3;
263           }
264         }
265         if (!symlinkat(s, cfd, catch)) {
266           err = 0;
267           fdout = AT_FDCWD;
268         }
269         free(s);
270 
271       // Do something _other_ than copy contents of a file?
272       } else if (!S_ISREG(try->st.st_mode)
273                  && (try->parent||FLAG(a)||FLAG(P)||FLAG(r)||rr))
274       {
275         // make symlink, or make block/char/fifo/socket
276         if (S_ISLNK(try->st.st_mode)
277             ? readlinkat0(tfd, try->name, toybuf, sizeof(toybuf)) &&
278               (!unlinkat(cfd, catch, 0) || ENOENT == errno) &&
279               !symlinkat(toybuf, cfd, catch)
280             : !mknodat(cfd, catch, try->st.st_mode, try->st.st_rdev))
281         {
282           err = 0;
283           fdout = AT_FDCWD;
284         }
285 
286       // Copy contents of file.
287       } else {
288         fdin = openat(tfd, try->name, O_RDONLY);
289         if (fdin < 0) {
290           catch = try->name;
291           break;
292         }
293 
294         // When copying contents use symlink target's attributes
295         if (S_ISLNK(try->st.st_mode)) fstat(fdin, &try->st);
296         fdout = openat(cfd, catch, O_RDWR|O_CREAT|O_TRUNC, try->st.st_mode);
297         if (fdout >= 0) {
298           xsendfile(fdin, fdout);
299           err = 0;
300         }
301 
302         cp_xattr(fdin, fdout, catch);
303       }
304       if (fdin != -1) close(fdin);
305     } while (err && (FLAG(f)||FLAG(n)) && !unlinkat(cfd, catch, 0));
306   }
307 
308   // Did we make a thing?
309   if (fdout != -1) {
310     // Inability to set --preserve isn't fatal, some require root access.
311 
312     // ownership
313     if (TT.pflags & _CP_ownership) {
314 
315       // permission bits already correct for mknod and don't apply to symlink
316       // If we can't get a filehandle to the actual object, use racy functions
317       if (fdout == AT_FDCWD)
318         rc = fchownat(cfd, catch, try->st.st_uid, try->st.st_gid,
319                       AT_SYMLINK_NOFOLLOW);
320       else rc = fchown(fdout, try->st.st_uid, try->st.st_gid);
321       if (rc && !geteuid()) {
322         char *pp;
323 
324         perror_msg("chown '%s'", pp = dirtree_path(try, 0));
325         free(pp);
326       }
327     }
328 
329     // timestamp
330     if (TT.pflags & _CP_timestamps) {
331       struct timespec times[] = {try->st.st_atim, try->st.st_mtim};
332 
333       if (fdout == AT_FDCWD) utimensat(cfd, catch, times, AT_SYMLINK_NOFOLLOW);
334       else futimens(fdout, times);
335     }
336 
337     // mode comes last because other syscalls can strip suid bit
338     if (fdout != AT_FDCWD) {
339       if (TT.pflags & _CP_mode) fchmod(fdout, try->st.st_mode);
340       xclose(fdout);
341     }
342 
343     if (save)
344       if (unlinkat(tfd, try->name, S_ISDIR(try->st.st_mode) ? AT_REMOVEDIR :0))
345         err = "%s";
346   }
347 
348   if (err) {
349     if (catch == try->name) {
350       s = dirtree_path(try, 0);
351       while (try->parent) try = try->parent;
352       catch = xmprintf("%s%s", TT.destname, s+strlen(try->name));
353       free(s);
354       s = catch;
355     } else s = 0;
356     perror_msg(err, catch);
357     free(s);
358   }
359 
360   return 0;
361 }
362 
cp_main(void)363 void cp_main(void)
364 {
365   char *tt = *toys.which->name == 'i' ? TT.i.t : TT.c.t,
366     *destname = tt ? : toys.optargs[--toys.optc];
367   int i, destdir = !stat(destname, &TT.top);
368 
369   if (!toys.optc) error_exit("Needs 2 arguments");
370   if (!destdir && errno==ENOENT && FLAG(D)) {
371     if (tt && mkpathat(AT_FDCWD, tt, 0777, MKPATHAT_MAKE|MKPATHAT_MKLAST))
372       perror_exit("-t '%s'", tt);
373     destdir = 1;
374   } else {
375     destdir = destdir && S_ISDIR(TT.top.st_mode);
376     if (!destdir && (toys.optc>1 || FLAG(D) || tt))
377       error_exit("'%s' not directory", destname);
378   }
379 
380   if (FLAG(T)) {
381     if (toys.optc>1) help_exit("Max 2 arguments");
382     if (destdir) error_exit("'%s' is a directory", destname);
383   }
384 
385   if (FLAG(a)||FLAG(p)) TT.pflags = _CP_mode|_CP_ownership|_CP_timestamps;
386 
387   // Not using comma_args() (yet?) because interpeting as letters.
388   if (FLAG(preserve)) {
389     char *pre = xstrdup(TT.c.preserve ? TT.c.preserve : "mot"), *s;
390 
391     if (comma_remove(pre, "all")) TT.pflags = ~0;
392     for (i=0; i<ARRAY_LEN(cp_preserve); i++)
393       while (comma_remove(pre, cp_preserve[i].name)) TT.pflags |= 1<<i;
394     if (*pre) {
395 
396       // Try to interpret as letters, commas won't set anything this doesn't.
397       for (s = pre; *s; s++) {
398         for (i=0; i<ARRAY_LEN(cp_preserve); i++)
399           if (*s == *cp_preserve[i].name) break;
400         if (i == ARRAY_LEN(cp_preserve)) {
401           if (*s == 'a') TT.pflags = ~0;
402           else break;
403         } else TT.pflags |= 1<<i;
404       }
405 
406       if (*s) error_exit("bad --preserve=%s", pre);
407     }
408     free(pre);
409   }
410   if (TT.pflags & _CP_mode) umask(0);
411   if (!TT.callback) TT.callback = cp_node;
412 
413   // Loop through sources
414   for (i=0; i<toys.optc; i++) {
415     char *src = toys.optargs[i], *trail;
416     int send = 1;
417 
418     if (!(trail = strrchr(src, '/')) || trail[1]) trail = 0;
419     else while (trail>src && *trail=='/') *trail-- = 0;
420 
421     if (destdir) {
422       char *s = FLAG(D) ? src : getbasename(src);
423 
424       TT.destname = xmprintf("%s/%s", destname, s);
425       if (FLAG(D)) {
426         if (!(s = fileunderdir(TT.destname, destname))) {
427           error_msg("%s not under %s", TT.destname, destname);
428           continue;
429         }
430         // TODO: .. follows abspath, not links...
431         free(s);
432         mkpath(TT.destname);
433       }
434     } else TT.destname = destname;
435 
436     // "mv across devices" triggers cp fallback path, so set that as default
437     errno = EXDEV;
438     if (CFG_MV && *toys.which->name == 'm') {
439       if (!FLAG(f) || FLAG(n)) {
440         struct stat st;
441         int exists = !stat(TT.destname, &st);
442 
443         // Prompt if -i or file isn't writable.  Technically "is writable" is
444         // more complicated (022 is not writeable by the owner, just everybody
445         // _else_) but I don't care.
446         if (exists && (FLAG(i) || (!(st.st_mode & 0222) && isatty(0)))) {
447           fprintf(stderr, "%s: overwrite '%s'", toys.which->name, TT.destname);
448           if (!yesno(0)) send = 0;
449           else unlink(TT.destname);
450         }
451         // if -n and dest exists, don't try to rename() or copy
452         if (exists && FLAG(n)) send = 0;
453       }
454       if (send) send = rename(src, TT.destname);
455       if (trail) trail[1] = '/';
456     }
457 
458     // Copy if we didn't mv or hit an error, skipping nonexistent sources
459     if (send) {
460       if (errno!=EXDEV || dirtree_flagread(src, DIRTREE_SHUTUP+
461         DIRTREE_SYMFOLLOW*(FLAG(H)|FLAG(L)), TT.callback))
462           perror_msg("bad '%s'", src);
463     }
464     if (destdir) free(TT.destname);
465   }
466 }
467 
468 // Export cp's flags into mv and install flag context.
469 
cp_flag_F(void)470 static inline int cp_flag_F(void) { return FLAG_F; }
cp_flag_p(void)471 static inline int cp_flag_p(void) { return FLAG_p; }
cp_flag_v(void)472 static inline int cp_flag_v(void) { return FLAG_v; }
cp_flag_dpr(void)473 static inline int cp_flag_dpr(void) { return FLAG_d|FLAG_p|FLAG_r; }
474 
475 #define FOR_mv
476 #include <generated/flags.h>
477 
mv_main(void)478 void mv_main(void)
479 {
480   toys.optflags |= cp_flag_dpr();
481   TT.pflags =~0;
482 
483   if (FLAG(x)) {
484     if (toys.optc != 2) error_exit("-x needs 2 args");
485     if (rename_exchange(toys.optargs[0], toys.optargs[1]))
486       perror_exit("-x %s %s", toys.optargs[0], toys.optargs[1]);
487   } else cp_main();
488 }
489 
490 #define FOR_install
491 #include <generated/flags.h>
492 
install_node(struct dirtree * try)493 static int install_node(struct dirtree *try)
494 {
495   try->st.st_mode = TT.i.m ? string_to_mode(TT.i.m, try->st.st_mode) : 0755;
496   if (TT.i.g) try->st.st_gid = TT.gid;
497   if (TT.i.o) try->st.st_uid = TT.uid;
498 
499   // Always returns 0 because no -r
500   cp_node(try);
501 
502   // No -r so always one level deep, so destname as set by cp_node() is correct
503   if (FLAG(s) && xrun((char *[]){"strip", "-p", TT.destname, 0}))
504     toys.exitval = 1;
505 
506   return 0;
507 }
508 
install_main(void)509 void install_main(void)
510 {
511   char **ss;
512 
513   TT.uid = TT.i.o ? xgetuid(TT.i.o) : -1;
514   TT.gid = TT.i.g ? xgetgid(TT.i.g) : -1;
515 
516   if (FLAG(d)) {
517     int mode = TT.i.m ? string_to_mode(TT.i.m, 0) : 0755;
518 
519     for (ss = toys.optargs; *ss; ss++) {
520       if (FLAG(v)) printf("%s\n", *ss);
521       if (mkpathat(AT_FDCWD, *ss, mode, MKPATHAT_MKLAST | MKPATHAT_MAKE))
522         perror_msg_raw(*ss);
523       if (FLAG(g)||FLAG(o))
524         if (lchown(*ss, TT.uid, TT.gid)) perror_msg("chown '%s'", *ss);
525       if ((mode&~01777) && chmod(*ss, mode)) perror_msg("chmod '%s'", *ss);
526     }
527 
528     return;
529   }
530 
531   if (FLAG(D)) {
532     char *destname = TT.i.t ? : (TT.destname = toys.optargs[toys.optc-1]);
533     if (mkpathat(AT_FDCWD, destname, 0777, MKPATHAT_MAKE|MKPATHAT_MKLAST*FLAG(t)))
534       perror_exit("-D '%s'", destname);
535     if (toys.optc == !FLAG(t)) return;
536   }
537 
538   // Translate flags from install to cp
539   toys.optflags = cp_flag_F() + cp_flag_v()*FLAG(v)
540     + cp_flag_p()*(FLAG(p)|FLAG(o)|FLAG(g));
541 
542   TT.callback = install_node;
543   cp_main();
544 }
545