OSDN Git Service

Move DIRTREE_COMEAGAIN second callback up to when the filehandle is still open, and...
[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 must be in same order (right to left) as CP
8 // for FLAG_X macros to work out right.
9
10 USE_CP(NEWTOY(cp, "<2RHLPp"USE_CP_MORE("rdaslvn")"fi[-HLPd]"USE_CP_MORE("[-ni]"), TOYFLAG_BIN))
11 USE_CP_MV(OLDTOY(mv, cp, "<2"USE_CP_MORE("vn")"fi"USE_CP_MORE("[-ni]"), TOYFLAG_BIN))
12
13 config CP
14   bool "cp"
15   default y
16   help
17     usage: cp [-fipRHLP] SOURCE... DEST
18
19     Copy files from SOURCE to DEST.  If more than one SOURCE, DEST must
20     be a directory.
21
22     -f  force copy by deleting destination file
23     -i  interactive, prompt before overwriting existing DEST
24     -p  preserve timestamps, ownership, and permissions
25     -R  recurse into subdirectories (DEST must be a directory)
26     -H  Follow symlinks listed on command line
27     -L  Follow all symlinks
28     -P  Do not follow symlinks [default]
29
30 config CP_MORE
31   bool "cp -adlnrsv options"
32   default y
33   depends on CP
34   help
35     usage: cp [-adlnrsv]
36
37     -a  same as -dpr
38     -d  don't dereference symlinks
39     -l  hard link instead of copy
40     -n  no clobber (don't overwrite DEST)
41     -r  synonym for -R
42     -s  symlink instead of copy
43     -v  verbose
44
45 config CP_MV
46   bool "mv"
47   default y
48   depends on CP
49   help
50     usage: mv [-fi] SOURCE... DEST"
51
52     -f  force copy by deleting destination file
53     -i  interactive, prompt before overwriting existing DEST
54
55 config CP_MV_MORE
56   bool
57   default y
58   depends on CP_MV && CP_MORE
59   help
60     usage: mv [-vn]
61
62     -v  verbose
63     -n  no clobber (don't overwrite DEST)
64 */
65
66 #define FOR_cp
67 #include "toys.h"
68
69 GLOBALS(
70   char *destname;
71   struct stat top;
72 )
73
74 // Callback from dirtree_read() for each file/directory under a source dir.
75
76 int cp_node(struct dirtree *try)
77 {
78   int fdout = -1, cfd = try->parent ? try->parent->extra : AT_FDCWD,
79       tfd = dirtree_parentfd(try);
80   unsigned flags = toys.optflags;
81   char *catch = try->parent ? try->name : TT.destname, *err = "%s";
82   struct stat cst;
83
84   if (!dirtree_notdotdot(try)) return 0;
85
86   // If returning from COMEAGAIN, jump straight to -p logic at end.
87   if (S_ISDIR(try->st.st_mode) && try->again) {
88     fdout = try->extra;
89     err = 0;
90   } else {
91
92     // -d is only the same as -r for symlinks, not for directories
93     if (S_ISLNK(try->st.st_mode) & (flags & FLAG_d)) flags |= FLAG_r;
94
95     // Detect recursive copies via repeated top node (cp -R .. .) or
96     // identical source/target (fun with hardlinks).
97     if ((TT.top.st_dev == try->st.st_dev && TT.top.st_ino == try->st.st_ino
98          && (catch = TT.destname))
99         || (!fstatat(cfd, catch, &cst, 0) && cst.st_dev == try->st.st_dev
100          && cst.st_ino == try->st.st_ino))
101     {
102       error_msg("'%s' is '%s'", catch, err = dirtree_path(try, 0));
103       free(err);
104
105       return 0;
106     }
107
108     // Handle -inv
109
110     if (!faccessat(cfd, catch, F_OK, 0) && !S_ISDIR(cst.st_mode)) {
111       char *s;
112
113       if (S_ISDIR(try->st.st_dev)) {
114         error_msg("dir at '%s'", s = dirtree_path(try, 0));
115         free(s);
116         return 0;
117       } else if (flags & FLAG_n) return 0;
118       else if (flags & FLAG_i) {
119         fprintf(stderr, "cp: overwrite '%s'", s = dirtree_path(try, 0));
120         free(s);
121         if (!yesno("", 1)) return 0;
122       }
123     }
124
125     if (flags & FLAG_v) {
126       char *s = dirtree_path(try, 0);
127       printf("cp '%s'\n", s);
128       free(s);
129     }
130
131     // Loop for -f retry after unlink
132     do {
133
134       // directory, hardlink, symlink, mknod (char, block, fifo, socket), file
135
136       // Copy directory
137
138       if (S_ISDIR(try->st.st_mode)) {
139         struct stat st2;
140
141         if (!(flags & (FLAG_a|FLAG_r|FLAG_R))) {
142           err = "Skipped dir '%s'";
143           catch = try->name;
144           break;
145         }
146
147         // Always make directory writeable to us, so we can create files in it.
148         //
149         // Yes, there's a race window between mkdir() and open() so it's
150         // possible that -p can be made to chown a directory other than the one
151         // we created. The closest we can do to closing this is make sure
152         // that what we open _is_ a directory rather than something else.
153
154         if (!mkdirat(cfd, catch, try->st.st_mode | 0200) || errno == EEXIST)
155           if (-1 != (try->extra = openat(cfd, catch, O_NOFOLLOW)))
156             if (!fstat(try->extra, &st2) && S_ISDIR(st2.st_mode))
157               return DIRTREE_COMEAGAIN
158                      | (DIRTREE_SYMFOLLOW*!!(toys.optflags&FLAG_L));
159
160       // Hardlink
161
162       } else if (flags & FLAG_l) {
163         if (!linkat(tfd, try->name, cfd, catch, 0)) err = 0;
164
165       // Copy tree as symlinks. For non-absolute paths this involves
166       // appending the right number of .. entries as you go down the tree.
167
168       } else if (flags & FLAG_s) {
169         char *s;
170         struct dirtree *or;
171         int dotdots = 0;
172
173         s = dirtree_path(try, 0);
174         for (or = try; or->parent; or = or->parent) dotdots++;
175
176         if (*or->name == '/') dotdots = 0;
177         if (dotdots) {
178           char *s2 = xmprintf("% *c%s", 3*dotdots, ' ', s);
179           free(s);
180           s = s2;
181           while(dotdots--) {
182             memcpy(s2, "../", 3);
183             s2 += 3;
184           }
185         }
186         if (!symlinkat(s, cfd, catch)) {
187           err = 0;
188           fdout = AT_FDCWD;
189         }
190         free(s);
191
192       // Do something _other_ than copy contents of a file?
193       } else if (!S_ISREG(try->st.st_mode)
194                  && (try->parent || (flags & (FLAG_a|FLAG_r))))
195       {
196         int i;
197
198         // make symlink, or make block/char/fifo/socket
199         if (S_ISLNK(try->st.st_mode)
200             ? (0 < (i = readlinkat(tfd, try->name, toybuf, sizeof(toybuf))) &&
201                sizeof(toybuf) > i && !symlinkat(toybuf, cfd, catch))
202             : !mknodat(cfd, catch, try->st.st_mode, try->st.st_rdev))
203         {
204           err = 0;
205           fdout = AT_FDCWD;
206         }
207
208       // Copy contents of file.
209       } else {
210         int fdin;
211
212         fdin = openat(tfd, try->name, O_RDONLY);
213         if (fdin < 0) {
214           catch = try->name;
215           break;
216         } else {
217           fdout = openat(cfd, catch, O_RDWR|O_CREAT|O_TRUNC, try->st.st_mode);
218           if (fdout >= 0) {
219             xsendfile(fdin, fdout);
220             err = 0;
221           }
222           close(fdin);
223         }
224       }
225     } while (err && (flags & (FLAG_f|FLAG_n)) && !unlinkat(cfd, catch, 0));
226   }
227
228   if (fdout != -1) {
229     if (flags & (FLAG_a|FLAG_p)) {
230       struct timespec times[2];
231
232       // Inability to set these isn't fatal, some require root access.
233
234       times[0] = try->st.st_atim;
235       times[1] = try->st.st_mtim;
236
237       // If we can't get a filehandle to the actual object, use racy functions
238       if (fdout == AT_FDCWD) {
239         fchownat(cfd, catch, try->st.st_uid, try->st.st_gid,
240                  AT_SYMLINK_NOFOLLOW);
241         utimensat(cfd, catch, times, AT_SYMLINK_NOFOLLOW);
242         // permission bits already correct for mknod, don't apply to symlink
243       } else {
244         fchown(fdout, try->st.st_uid, try->st.st_gid);
245         futimens(fdout, times);
246         fchmod(fdout, try->st.st_mode);
247       }
248     }
249
250     if (fdout != AT_FDCWD) xclose(fdout);
251
252     if (toys.which->name[0] == 'm')
253       if (unlinkat(tfd, try->name, S_ISDIR(try->st.st_mode) ? AT_REMOVEDIR : 0))
254         err = "%s";
255   }
256
257   if (err) perror_msg(err, catch);
258   return 0;
259 }
260
261 void cp_main(void)
262 {
263   char *destname = toys.optargs[--toys.optc];
264   int i, destdir = !stat(destname, &TT.top) && S_ISDIR(TT.top.st_mode);
265
266   if (toys.optc>1 && !destdir) error_exit("'%s' not directory", destname);
267   if (toys.which->name[0] == 'm') toys.optflags |= FLAG_d|FLAG_p|FLAG_R;
268   if (toys.optflags & (FLAG_a|FLAG_p)) umask(0);
269
270   // Loop through sources
271
272   for (i=0; i<toys.optc; i++) {
273     struct dirtree *new;
274     char *src = toys.optargs[i];
275     int rc = 1;
276
277     if (destdir) TT.destname = xmprintf("%s/%s", destname, basename(src));
278     else TT.destname = destname;
279
280     errno = EXDEV;
281     if (toys.which->name[0] == 'm') rc = rename(src, TT.destname);
282
283     // Skip nonexistent sources
284     if (rc) {
285       int symfollow = toys.optflags & (FLAG_H|FLAG_L);
286
287       if (errno != EXDEV || !(new = dirtree_add_node(0, src, symfollow)))
288           perror_msg("bad '%s'", src);
289       else dirtree_handle_callback(new, cp_node);
290     }
291     if (destdir) free(TT.destname);
292   }
293 }