OSDN Git Service

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