• 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, "<2"USE_CP_PRESERVE("(preserve):;")"D(parents)RHLPprdaslvnF(remove-destination)fiT[-HLPd][-ni]", TOYFLAG_BIN))
19 USE_MV(NEWTOY(mv, "<2vnF(remove-destination)fiT[-ni]", TOYFLAG_BIN))
20 USE_INSTALL(NEWTOY(install, "<1cdDpsvm:o:g:", TOYFLAG_USR|TOYFLAG_BIN))
21 
22 config CP
23   bool "cp"
24   default y
25   help
26     usage: cp [-adfHiLlnPpRrsTv] 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     -P	Do not follow symlinks [default]
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     -v	Verbose
48 
49 config CP_PRESERVE
50   bool "cp --preserve support"
51   default y
52   depends on CP
53   help
54     usage: cp [--preserve=motcxa]
55 
56     --preserve takes either a comma separated list of attributes, or the first
57     letter(s) of:
58 
59             mode - permissions (ignore umask for rwx, copy suid and sticky bit)
60        ownership - user and group
61       timestamps - file creation, modification, and access times.
62          context - security context
63            xattr - extended attributes
64              all - all of the above
65 
66 config MV
67   bool "mv"
68   default y
69   help
70     usage: mv [-finTv] SOURCE... DEST
71 
72     -f	Force copy by deleting destination file
73     -i	Interactive, prompt before overwriting existing DEST
74     -n	No clobber (don't overwrite DEST)
75     -T	DEST always treated as file, max 2 arguments
76     -v	Verbose
77 
78 config INSTALL
79   bool "install"
80   default y
81   help
82     usage: install [-dDpsv] [-o USER] [-g GROUP] [-m MODE] [SOURCE...] DEST
83 
84     Copy files and set attributes.
85 
86     -d	Act like mkdir -p
87     -D	Create leading directories for DEST
88     -g	Make copy belong to GROUP
89     -m	Set permissions to MODE
90     -o	Make copy belong to USER
91     -p	Preserve timestamps
92     -s	Call "strip -p"
93     -v	Verbose
94 */
95 
96 #define FORCE_FLAGS
97 #define FOR_cp
98 #include "toys.h"
99 
100 GLOBALS(
101   union {
102     // install's options
103     struct {
104       char *g, *o, *m;
105     } i;
106     // cp's options
107     struct {
108       char *preserve;
109     } c;
110   };
111 
112   char *destname;
113   struct stat top;
114   int (*callback)(struct dirtree *try);
115   uid_t uid;
116   gid_t gid;
117   int pflags;
118 )
119 
120 struct cp_preserve {
121   char *name;
122 } static const cp_preserve[] = TAGGED_ARRAY(CP,
123   {"mode"}, {"ownership"}, {"timestamps"}, {"context"}, {"xattr"},
124 );
125 
126 // Callback from dirtree_read() for each file/directory under a source dir.
127 
cp_node(struct dirtree * try)128 static int cp_node(struct dirtree *try)
129 {
130   int fdout = -1, cfd = try->parent ? try->parent->extra : AT_FDCWD,
131       tfd = dirtree_parentfd(try);
132   unsigned flags = toys.optflags;
133   char *catch = try->parent ? try->name : TT.destname, *err = "%s";
134   struct stat cst;
135 
136   if (!dirtree_notdotdot(try)) return 0;
137 
138   // If returning from COMEAGAIN, jump straight to -p logic at end.
139   if (S_ISDIR(try->st.st_mode) && try->again) {
140     fdout = try->extra;
141     err = 0;
142   } else {
143 
144     // -d is only the same as -r for symlinks, not for directories
145     if (S_ISLNK(try->st.st_mode) && (flags & FLAG_d)) flags |= FLAG_r;
146 
147     // Detect recursive copies via repeated top node (cp -R .. .) or
148     // identical source/target (fun with hardlinks).
149     if ((TT.top.st_dev == try->st.st_dev && TT.top.st_ino == try->st.st_ino
150          && (catch = TT.destname))
151         || (!fstatat(cfd, catch, &cst, 0) && cst.st_dev == try->st.st_dev
152          && cst.st_ino == try->st.st_ino))
153     {
154       error_msg("'%s' is '%s'", catch, err = dirtree_path(try, 0));
155       free(err);
156 
157       return 0;
158     }
159 
160     // Handle -invF
161 
162     if (!faccessat(cfd, catch, F_OK, 0) && !S_ISDIR(cst.st_mode)) {
163       char *s;
164 
165       if (S_ISDIR(try->st.st_mode)) {
166         error_msg("dir at '%s'", s = dirtree_path(try, 0));
167         free(s);
168         return 0;
169       } else if ((flags & FLAG_F) && unlinkat(cfd, catch, 0)) {
170         error_msg("unlink '%s'", catch);
171         return 0;
172       } else if (flags & FLAG_n) return 0;
173       else if (flags & FLAG_i) {
174         fprintf(stderr, "%s: overwrite '%s'", toys.which->name,
175           s = dirtree_path(try, 0));
176         free(s);
177         if (!yesno(1)) return 0;
178       }
179     }
180 
181     if (flags & FLAG_v) {
182       char *s = dirtree_path(try, 0);
183       printf("%s '%s'\n", toys.which->name, s);
184       free(s);
185     }
186 
187     // Loop for -f retry after unlink
188     do {
189 
190       // directory, hardlink, symlink, mknod (char, block, fifo, socket), file
191 
192       // Copy directory
193 
194       if (S_ISDIR(try->st.st_mode)) {
195         struct stat st2;
196 
197         if (!(flags & (FLAG_a|FLAG_r|FLAG_R))) {
198           err = "Skipped dir '%s'";
199           catch = try->name;
200           break;
201         }
202 
203         // Always make directory writeable to us, so we can create files in it.
204         //
205         // Yes, there's a race window between mkdir() and open() so it's
206         // possible that -p can be made to chown a directory other than the one
207         // we created. The closest we can do to closing this is make sure
208         // that what we open _is_ a directory rather than something else.
209 
210         if (!mkdirat(cfd, catch, try->st.st_mode | 0200) || errno == EEXIST)
211           if (-1 != (try->extra = openat(cfd, catch, O_NOFOLLOW)))
212             if (!fstat(try->extra, &st2) && S_ISDIR(st2.st_mode))
213               return DIRTREE_COMEAGAIN | (DIRTREE_SYMFOLLOW*!!FLAG(L));
214 
215       // Hardlink
216 
217       } else if (flags & FLAG_l) {
218         if (!linkat(tfd, try->name, cfd, catch, 0)) err = 0;
219 
220       // Copy tree as symlinks. For non-absolute paths this involves
221       // appending the right number of .. entries as you go down the tree.
222 
223       } else if (flags & FLAG_s) {
224         char *s;
225         struct dirtree *or;
226         int dotdots = 0;
227 
228         s = dirtree_path(try, 0);
229         for (or = try; or->parent; or = or->parent) dotdots++;
230 
231         if (*or->name == '/') dotdots = 0;
232         if (dotdots) {
233           char *s2 = xmprintf("%*c%s", 3*dotdots, ' ', s);
234           free(s);
235           s = s2;
236           while(dotdots--) {
237             memcpy(s2, "../", 3);
238             s2 += 3;
239           }
240         }
241         if (!symlinkat(s, cfd, catch)) {
242           err = 0;
243           fdout = AT_FDCWD;
244         }
245         free(s);
246 
247       // Do something _other_ than copy contents of a file?
248       } else if (!S_ISREG(try->st.st_mode)
249                  && (try->parent || (flags & (FLAG_a|FLAG_r))))
250       {
251         int i;
252 
253         // make symlink, or make block/char/fifo/socket
254         if (S_ISLNK(try->st.st_mode)
255             ? ((i = readlinkat0(tfd, try->name, toybuf, sizeof(toybuf))) &&
256                ((!unlinkat(cfd, catch, 0) || ENOENT == errno) &&
257                 !symlinkat(toybuf, cfd, catch)))
258             : !mknodat(cfd, catch, try->st.st_mode, try->st.st_rdev))
259         {
260           err = 0;
261           fdout = AT_FDCWD;
262         }
263 
264       // Copy contents of file.
265       } else {
266         int fdin;
267 
268         fdin = openat(tfd, try->name, O_RDONLY);
269         if (fdin < 0) {
270           catch = try->name;
271           break;
272         }
273         // When copying contents use symlink target's attributes
274         if (S_ISLNK(try->st.st_mode)) fstat(fdin, &try->st);
275         fdout = openat(cfd, catch, O_RDWR|O_CREAT|O_TRUNC, try->st.st_mode);
276         if (fdout >= 0) {
277           xsendfile(fdin, fdout);
278           err = 0;
279         }
280 
281         // We only copy xattrs for files because there's no flistxattrat()
282         if (TT.pflags&(_CP_xattr|_CP_context)) {
283           ssize_t listlen = xattr_flist(fdin, 0, 0), len;
284           char *name, *value, *list;
285 
286           if (listlen>0) {
287             list = xmalloc(listlen);
288             xattr_flist(fdin, list, listlen);
289             list[listlen-1] = 0; // I do not trust this API.
290             for (name = list; name-list < listlen; name += strlen(name)+1) {
291               if (!(TT.pflags&_CP_xattr) && strncmp(name, "security.", 9))
292                 continue;
293               if ((len = xattr_fget(fdin, name, 0, 0))>0) {
294                 value = xmalloc(len);
295                 if (len == xattr_fget(fdin, name, value, len))
296                   if (xattr_fset(fdout, name, value, len, 0))
297                     perror_msg("%s setxattr(%s=%s)", catch, name, value);
298                 free(value);
299               }
300             }
301             free(list);
302           }
303         }
304 
305         close(fdin);
306       }
307     } while (err && (flags & (FLAG_f|FLAG_n)) && !unlinkat(cfd, catch, 0));
308   }
309 
310   // Did we make a thing?
311   if (fdout != -1) {
312     int rc;
313 
314     // Inability to set --preserve isn't fatal, some require root access.
315 
316     // ownership
317     if (TT.pflags & _CP_ownership) {
318 
319       // permission bits already correct for mknod and don't apply to symlink
320       // If we can't get a filehandle to the actual object, use racy functions
321       if (fdout == AT_FDCWD)
322         rc = fchownat(cfd, catch, try->st.st_uid, try->st.st_gid,
323                       AT_SYMLINK_NOFOLLOW);
324       else rc = fchown(fdout, try->st.st_uid, try->st.st_gid);
325       if (rc && !geteuid()) {
326         char *pp;
327 
328         perror_msg("chown '%s'", pp = dirtree_path(try, 0));
329         free(pp);
330       }
331     }
332 
333     // timestamp
334     if (TT.pflags & _CP_timestamps) {
335       struct timespec times[] = {try->st.st_atim, try->st.st_mtim};
336 
337       if (fdout == AT_FDCWD) utimensat(cfd, catch, times, AT_SYMLINK_NOFOLLOW);
338       else futimens(fdout, times);
339     }
340 
341     // mode comes last because other syscalls can strip suid bit
342     if (fdout != AT_FDCWD) {
343       if (TT.pflags & _CP_mode) fchmod(fdout, try->st.st_mode);
344       xclose(fdout);
345     }
346 
347     if (CFG_MV && toys.which->name[0] == 'm')
348       if (unlinkat(tfd, try->name, S_ISDIR(try->st.st_mode) ? AT_REMOVEDIR :0))
349         err = "%s";
350   }
351 
352   if (err) {
353     char *f = 0;
354 
355     if (catch == try->name) {
356       f = dirtree_path(try, 0);
357       while (try->parent) try = try->parent;
358       catch = xmprintf("%s%s", TT.destname, f+strlen(try->name));
359       free(f);
360       f = catch;
361     }
362     perror_msg(err, catch);
363     free(f);
364   }
365   return 0;
366 }
367 
cp_main(void)368 void cp_main(void)
369 {
370   char *destname = toys.optargs[--toys.optc];
371   int i, destdir = !stat(destname, &TT.top) && S_ISDIR(TT.top.st_mode);
372 
373   if (FLAG(T)) {
374     if (toys.optc>1) help_exit("Max 2 arguments");
375     if (destdir) error_exit("'%s' is a directory", destname);
376   }
377 
378   if ((toys.optc>1 || FLAG(D)) && !destdir)
379     error_exit("'%s' not directory", destname);
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 (CFG_CP_PRESERVE && 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 = src;
412     int rc = 1;
413 
414     while (*++trail);
415     if (*--trail == '/') *trail = 0;
416 
417     if (destdir) {
418       char *s = FLAG(D) ? dirname(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     errno = EXDEV;
433     if (CFG_MV && toys.which->name[0] == 'm') {
434       int force = FLAG(f), no_clobber = FLAG(n);
435 
436       if (!force || no_clobber) {
437         struct stat st;
438         int exists = !stat(TT.destname, &st);
439 
440         // Prompt if -i or file isn't writable.  Technically "is writable" is
441         // more complicated (022 is not writeable by the owner, just everybody
442         // _else_) but I don't care.
443         if (exists && (FLAG(i) || !(st.st_mode & 0222))) {
444           fprintf(stderr, "%s: overwrite '%s'", toys.which->name, TT.destname);
445           if (!yesno(1)) rc = 0;
446           else unlink(TT.destname);
447         }
448         // if -n and dest exists, don't try to rename() or copy
449         if (exists && no_clobber) rc = 0;
450       }
451       if (rc) rc = rename(src, TT.destname);
452       if (errno && !*trail) *trail = '/';
453     }
454 
455     // Copy if we didn't mv, skipping nonexistent sources
456     if (rc) {
457       if (errno!=EXDEV || dirtree_flagread(src, DIRTREE_SHUTUP+
458         DIRTREE_SYMFOLLOW*!!(FLAG(H)||FLAG(L)), TT.callback))
459           perror_msg("bad '%s'", src);
460     }
461     if (destdir) free(TT.destname);
462   }
463 }
464 
mv_main(void)465 void mv_main(void)
466 {
467   toys.optflags |= FLAG_d|FLAG_p|FLAG_R;
468 
469   cp_main();
470 }
471 
472 // Export cp flags into install's flag context.
473 
cp_flag_F(void)474 static inline int cp_flag_F(void) { return FLAG_F; };
cp_flag_p(void)475 static inline int cp_flag_p(void) { return FLAG_p; };
cp_flag_v(void)476 static inline int cp_flag_v(void) { return FLAG_v; };
477 
478 // Switch to install's flag context
479 #define CLEANUP_cp
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     TT.destname = toys.optargs[toys.optc-1];
520     if (mkpathat(AT_FDCWD, TT.destname, 0, MKPATHAT_MAKE))
521       perror_exit("-D '%s'", TT.destname);
522     if (toys.optc == 1) return;
523   }
524   if (toys.optc < 2) error_exit("needs 2 args");
525 
526   // Translate flags from install to cp
527   toys.optflags = cp_flag_F() + cp_flag_v()*!!FLAG(v)
528     + cp_flag_p()*!!(FLAG(p)|FLAG(o)|FLAG(g));
529 
530   TT.callback = install_node;
531   cp_main();
532 }
533