OSDN Git Service

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