OSDN Git Service

The xattr functions were added during the 2.5 kernel, lsm.h can #include the
[android-x86/external-toybox.git] / toys / posix / cp.c
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  * TODO: --preserve=links
10  * TODO: what's this _CP_mode system.posix_acl_ business? We chmod()?
11
12 // options shared between mv/cp must be in same order (right to left)
13 // for FLAG macros to work out right in shared infrastructure.
14
15 USE_CP(NEWTOY(cp, "<2"USE_CP_PRESERVE("(preserve):;")"RHLPp"USE_CP_MORE("rdaslvnF(remove-destination)")"fi[-HLP"USE_CP_MORE("d")"]"USE_CP_MORE("[-ni]"), TOYFLAG_BIN))
16 USE_MV(NEWTOY(mv, "<2"USE_CP_MORE("vnF")"fi"USE_CP_MORE("[-ni]"), TOYFLAG_BIN))
17 USE_INSTALL(NEWTOY(install, "<1cdDpsvm:o:g:", TOYFLAG_USR|TOYFLAG_BIN))
18
19 config CP
20   bool "cp"
21   default y
22   help
23     usage: cp [-fipRHLP] SOURCE... DEST
24
25     Copy files from SOURCE to DEST.  If more than one SOURCE, DEST must
26     be a directory.
27
28     -f  delete destination files we can't write to
29     -F  delete any existing destination file first (--remove-destination)
30     -i  interactive, prompt before overwriting existing DEST
31     -p  preserve timestamps, ownership, and mode
32     -R  recurse into subdirectories (DEST must be a directory)
33     -H  Follow symlinks listed on command line
34     -L  Follow all symlinks
35     -P  Do not follow symlinks [default]
36
37 config CP_MORE
38   bool "cp -adlnrsv options"
39   default y
40   depends on CP
41   help
42     usage: cp [-adlnrsv]
43
44     -a  same as -dpr
45     -d  don't dereference symlinks
46     -l  hard link instead of copy
47     -n  no clobber (don't overwrite DEST)
48     -r  synonym for -R
49     -s  symlink instead of copy
50     -v  verbose
51
52 config CP_PRESERVE
53   bool "cp --preserve support"
54   default y
55   depends on CP_MORE
56   help
57     usage: cp [--preserve=motcxa]
58
59     --preserve takes either a comma separated list of attributes, or the first
60     letter(s) of:
61
62             mode - permissions (ignore umask for rwx, copy suid and sticky bit)
63        ownership - user and group
64       timestamps - file creation, modification, and access times.
65          context - security context
66            xattr - extended attributes
67              all - all of the above
68
69 config MV
70   bool "mv"
71   default y
72   depends on CP
73   help
74     usage: mv [-fi] SOURCE... DEST"
75
76     -f  force copy by deleting destination file
77     -i  interactive, prompt before overwriting existing DEST
78
79 config MV_MORE
80   bool
81   default y
82   depends on MV && CP_MORE
83   help
84     usage: mv [-vn]
85
86     -v  verbose
87     -n  no clobber (don't overwrite DEST)
88
89 config INSTALL
90   bool "install"
91   default y
92   depends on CP && CP_MORE
93   help
94     usage: install [-dDpsv] [-o USER] [-g GROUP] [-m MODE] [SOURCE...] DEST
95
96     Copy files and set attributes.
97
98     -d  Act like mkdir -p
99     -D  Create leading directories for DEST
100     -g  Make copy belong to GROUP
101     -m  Set permissions to MODE
102     -o  Make copy belong to USER
103     -p  Preserve timestamps
104     -s  Call "strip -p"
105     -v  Verbose
106 */
107
108 #define FOR_cp
109 #include "toys.h"
110
111 GLOBALS(
112   union {
113     struct {
114       // install's options
115       char *group;
116       char *user;
117       char *mode;
118     } i;
119     struct {
120       char *preserve;
121     } c;
122   };
123
124   char *destname;
125   struct stat top;
126   int (*callback)(struct dirtree *try);
127   uid_t uid;
128   gid_t gid;
129   int pflags;
130 )
131
132 struct cp_preserve {
133   char *name;
134 } static const cp_preserve[] = TAGGED_ARRAY(CP,
135   {"mode"}, {"ownership"}, {"timestamps"}, {"context"}, {"xattr"},
136 );
137
138 // Callback from dirtree_read() for each file/directory under a source dir.
139
140 int cp_node(struct dirtree *try)
141 {
142   int fdout = -1, cfd = try->parent ? try->parent->extra : AT_FDCWD,
143       tfd = dirtree_parentfd(try);
144   unsigned flags = toys.optflags;
145   char *catch = try->parent ? try->name : TT.destname, *err = "%s";
146   struct stat cst;
147
148   if (!dirtree_notdotdot(try)) return 0;
149
150   // If returning from COMEAGAIN, jump straight to -p logic at end.
151   if (S_ISDIR(try->st.st_mode) && try->again) {
152     fdout = try->extra;
153     err = 0;
154   } else {
155
156     // -d is only the same as -r for symlinks, not for directories
157     if (S_ISLNK(try->st.st_mode) && (flags & FLAG_d)) flags |= FLAG_r;
158
159     // Detect recursive copies via repeated top node (cp -R .. .) or
160     // identical source/target (fun with hardlinks).
161     if ((TT.top.st_dev == try->st.st_dev && TT.top.st_ino == try->st.st_ino
162          && (catch = TT.destname))
163         || (!fstatat(cfd, catch, &cst, 0) && cst.st_dev == try->st.st_dev
164          && cst.st_ino == try->st.st_ino))
165     {
166       error_msg("'%s' is '%s'", catch, err = dirtree_path(try, 0));
167       free(err);
168
169       return 0;
170     }
171
172     // Handle -inv
173
174     if (!faccessat(cfd, catch, F_OK, 0) && !S_ISDIR(cst.st_mode)) {
175       char *s;
176
177       if (S_ISDIR(try->st.st_mode)) {
178         error_msg("dir at '%s'", s = dirtree_path(try, 0));
179         free(s);
180         return 0;
181       } else if ((flags & FLAG_F) && unlinkat(cfd, catch, 0)) {
182         error_msg("unlink '%s'", catch);
183         return 0;
184       } else if (flags & FLAG_n) return 0;
185       else if (flags & FLAG_i) {
186         fprintf(stderr, "%s: overwrite '%s'", toys.which->name,
187           s = dirtree_path(try, 0));
188         free(s);
189         if (!yesno(1)) return 0;
190       }
191     }
192
193     if (flags & FLAG_v) {
194       char *s = dirtree_path(try, 0);
195       printf("%s '%s'\n", toys.which->name, s);
196       free(s);
197     }
198
199     // Loop for -f retry after unlink
200     do {
201
202       // directory, hardlink, symlink, mknod (char, block, fifo, socket), file
203
204       // Copy directory
205
206       if (S_ISDIR(try->st.st_mode)) {
207         struct stat st2;
208
209         if (!(flags & (FLAG_a|FLAG_r|FLAG_R))) {
210           err = "Skipped dir '%s'";
211           catch = try->name;
212           break;
213         }
214
215         // Always make directory writeable to us, so we can create files in it.
216         //
217         // Yes, there's a race window between mkdir() and open() so it's
218         // possible that -p can be made to chown a directory other than the one
219         // we created. The closest we can do to closing this is make sure
220         // that what we open _is_ a directory rather than something else.
221
222         if (!mkdirat(cfd, catch, try->st.st_mode | 0200) || errno == EEXIST)
223           if (-1 != (try->extra = openat(cfd, catch, O_NOFOLLOW)))
224             if (!fstat(try->extra, &st2) && S_ISDIR(st2.st_mode))
225               return DIRTREE_COMEAGAIN
226                      | (DIRTREE_SYMFOLLOW*!!(toys.optflags&FLAG_L));
227
228       // Hardlink
229
230       } else if (flags & FLAG_l) {
231         if (!linkat(tfd, try->name, cfd, catch, 0)) err = 0;
232
233       // Copy tree as symlinks. For non-absolute paths this involves
234       // appending the right number of .. entries as you go down the tree.
235
236       } else if (flags & FLAG_s) {
237         char *s;
238         struct dirtree *or;
239         int dotdots = 0;
240
241         s = dirtree_path(try, 0);
242         for (or = try; or->parent; or = or->parent) dotdots++;
243
244         if (*or->name == '/') dotdots = 0;
245         if (dotdots) {
246           char *s2 = xmprintf("%*c%s", 3*dotdots, ' ', s);
247           free(s);
248           s = s2;
249           while(dotdots--) {
250             memcpy(s2, "../", 3);
251             s2 += 3;
252           }
253         }
254         if (!symlinkat(s, cfd, catch)) {
255           err = 0;
256           fdout = AT_FDCWD;
257         }
258         free(s);
259
260       // Do something _other_ than copy contents of a file?
261       } else if (!S_ISREG(try->st.st_mode)
262                  && (try->parent || (flags & (FLAG_a|FLAG_r))))
263       {
264         int i;
265
266         // make symlink, or make block/char/fifo/socket
267         if (S_ISLNK(try->st.st_mode)
268             ? (0 < (i = readlinkat(tfd, try->name, toybuf, sizeof(toybuf))) &&
269                sizeof(toybuf) > i && !symlinkat(toybuf, cfd, catch))
270             : !mknodat(cfd, catch, try->st.st_mode, try->st.st_rdev))
271         {
272           err = 0;
273           fdout = AT_FDCWD;
274         }
275
276       // Copy contents of file.
277       } else {
278         int fdin;
279
280         fdin = openat(tfd, try->name, O_RDONLY);
281         if (fdin < 0) {
282           catch = try->name;
283           break;
284         }
285         fdout = openat(cfd, catch, O_RDWR|O_CREAT|O_TRUNC, try->st.st_mode);
286         if (fdout >= 0) {
287           xsendfile(fdin, fdout);
288           err = 0;
289         }
290
291         // We only copy xattrs for files because there's no flistxattrat()
292         if (TT.pflags&(_CP_xattr|_CP_context)) {
293           ssize_t listlen = flistxattr(fdin, 0, 0), len;
294           char *name, *value, *list;
295
296           if (listlen>0) {
297             list = xmalloc(listlen);
298             flistxattr(fdin, list, listlen);
299             list[listlen-1] = 0; // I do not trust this API.
300             for (name = list; name-list < listlen; name += strlen(name)+1) {
301               if (!(TT.pflags&_CP_xattr) && strncmp(name, "security.", 9))
302                 continue;
303               if ((len = fgetxattr(fdin, name, 0, 0))>0) {
304                 value = xmalloc(len);
305                 if (len == fgetxattr(fdin, name, value, len))
306                   if (fsetxattr(fdout, name, value, len, 0))
307                     perror_msg("%s setxattr(%s=%s)", catch, name, value);
308                 free(value);
309               }
310             }
311             free(list);
312           }
313         }
314
315         close(fdin);
316       }
317     } while (err && (flags & (FLAG_f|FLAG_n)) && !unlinkat(cfd, catch, 0));
318   }
319
320   // Did we make a thing?
321   if (fdout != -1) {
322     int rc;
323
324     // Inability to set --preserve isn't fatal, some require root access.
325
326     // ownership
327     if (TT.pflags & _CP_ownership) {
328
329       // permission bits already correct for mknod and don't apply to symlink
330       // If we can't get a filehandle to the actual object, use racy functions
331       if (fdout == AT_FDCWD)
332         rc = fchownat(cfd, catch, try->st.st_uid, try->st.st_gid,
333                       AT_SYMLINK_NOFOLLOW);
334       else rc = fchown(fdout, try->st.st_uid, try->st.st_gid);
335       if (rc) {
336         char *pp;
337
338         perror_msg("chown '%s'", pp = dirtree_path(try, 0));
339         free(pp);
340       }
341     }
342
343     // timestamp
344     if (TT.pflags & _CP_timestamps) {
345       struct timespec times[] = {try->st.st_atim, try->st.st_mtim};
346
347       if (fdout == AT_FDCWD) utimensat(cfd, catch, times, AT_SYMLINK_NOFOLLOW);
348       else futimens(fdout, times);
349     }
350
351     // mode comes last because other syscalls can strip suid bit
352     if (fdout != AT_FDCWD) {
353       if (TT.pflags & _CP_mode) fchmod(fdout, try->st.st_mode);
354       xclose(fdout);
355     }
356
357     if (CFG_MV && toys.which->name[0] == 'm')
358       if (unlinkat(tfd, try->name, S_ISDIR(try->st.st_mode) ? AT_REMOVEDIR :0))
359         err = "%s";
360   }
361
362   if (err) perror_msg(err, catch);
363   return 0;
364 }
365
366 void cp_main(void)
367 {
368   char *destname = toys.optargs[--toys.optc];
369   int i, destdir = !stat(destname, &TT.top) && S_ISDIR(TT.top.st_mode);
370
371   if (toys.optc>1 && !destdir) error_exit("'%s' not directory", destname);
372
373   if (toys.optflags & (FLAG_a|FLAG_p)) {
374     TT.pflags = CP_mode|CP_ownership|CP_timestamps;
375     umask(0);
376   }
377   // Not using comma_args() (yet?) because interpeting as letters.
378   if (CFG_CP_PRESERVE && (toys.optflags & FLAG_preserve)) {
379     char *pre = xstrdup(TT.c.preserve), *s;
380
381     if (comma_scan(pre, "all", 1)) TT.pflags = ~0;
382     for (i=0; i<ARRAY_LEN(cp_preserve); i++)
383       if (comma_scan(pre, cp_preserve[i].name, 1)) TT.pflags |= 1<<i;
384     if (*pre) {
385
386       // Try to interpret as letters, commas won't set anything this doesn't.
387       for (s = TT.c.preserve; *s; s++) {
388         for (i=0; i<ARRAY_LEN(cp_preserve); i++)
389           if (*s == *cp_preserve[i].name) break;
390         if (i == ARRAY_LEN(cp_preserve)) {
391           if (*s == 'a') TT.pflags = ~0;
392           else break;
393         } else TT.pflags |= 1<<i;
394       }
395
396       if (*s) error_exit("bad --preserve=%s", pre);
397     }
398     free(pre);
399   }
400   if (!TT.callback) TT.callback = cp_node;
401
402   // Loop through sources
403   for (i=0; i<toys.optc; i++) {
404     char *src = toys.optargs[i];
405     int rc = 1;
406
407     if (destdir) TT.destname = xmprintf("%s/%s", destname, basename(src));
408     else TT.destname = destname;
409
410     errno = EXDEV;
411     if (CFG_MV && toys.which->name[0] == 'm') {
412       if (!(toys.optflags & FLAG_f)) {
413         struct stat st;
414
415         // Technically "is writeable" is more complicated (022 is not writeable
416         // by the owner, just everybody _else_) but I don't care.
417         if (!stat(TT.destname, &st)
418           && ((toys.optflags & FLAG_i) || !(st.st_mode & 0222)))
419         {
420           fprintf(stderr, "%s: overwrite '%s'", toys.which->name, TT.destname);
421           if (!yesno(1)) rc = 0;
422           else unlink(TT.destname);
423         }
424       }
425
426       if (rc) rc = rename(src, TT.destname);
427     }
428
429     // Copy if we didn't mv, skipping nonexistent sources
430     if (rc) {
431       if (errno!=EXDEV || dirtree_flagread(src, DIRTREE_SHUTUP+
432         DIRTREE_SYMFOLLOW*!!(toys.optflags&(FLAG_H|FLAG_L)), TT.callback))
433           perror_msg("bad '%s'", src);
434     }
435     if (destdir) free(TT.destname);
436   }
437 }
438
439 void mv_main(void)
440 {
441   toys.optflags |= FLAG_d|FLAG_p|FLAG_R;
442
443   cp_main();
444 }
445
446 // Export cp flags into install's flag context.
447
448 static inline int cp_flag_F(void) { return FLAG_F; };
449 static inline int cp_flag_p(void) { return FLAG_p; };
450 static inline int cp_flag_v(void) { return FLAG_v; };
451
452 // Switch to install's flag context
453 #define CLEANUP_cp
454 #define FOR_install
455 #include <generated/flags.h>
456
457 static int install_node(struct dirtree *try)
458 {
459   try->st.st_mode = (TT.i.mode)
460     ? string_to_mode(TT.i.mode, try->st.st_mode) : 0755;
461   if (TT.i.group) try->st.st_gid = TT.gid;
462   if (TT.i.user) try->st.st_uid = TT.uid;
463
464   // Always returns 0 because no -r
465   cp_node(try);
466
467   // No -r so always one level deep, so destname as set by cp_node() is correct
468   if (toys.optflags & FLAG_s)
469     if (xrun((char *[]){"strip", "-p", TT.destname, 0})) toys.exitval = 1;
470
471   return 0;
472 }
473
474 void install_main(void)
475 {
476   char **ss;
477   int flags = toys.optflags;
478
479   if (flags & FLAG_d) {
480     for (ss = toys.optargs; *ss; ss++) {
481       if (mkpathat(AT_FDCWD, *ss, 0777, 3)) perror_msg_raw(*ss);
482       if (flags & FLAG_v) printf("%s\n", *ss);
483     }
484
485     return;
486   }
487
488   if (toys.optflags & FLAG_D) {
489     TT.destname = toys.optargs[toys.optc-1];
490     if (mkpathat(AT_FDCWD, TT.destname, 0, 2))
491       perror_exit("-D '%s'", TT.destname);
492     if (toys.optc == 1) return;
493   }
494   if (toys.optc < 2) error_exit("needs 2 args");
495
496   // Translate flags from install to cp
497   toys.optflags = cp_flag_F();
498   if (flags & FLAG_v) toys.optflags |= cp_flag_v();
499   if (flags & (FLAG_p|FLAG_o|FLAG_g)) toys.optflags |= cp_flag_p();
500
501   if (TT.i.user) TT.uid = xgetpwnamid(TT.i.user)->pw_uid;
502   if (TT.i.group) TT.gid = xgetgrnamid(TT.i.group)->gr_gid;
503
504   TT.callback = install_node;
505   cp_main();
506 }