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