OSDN Git Service

Rename xmsprintf() to just xmprintf().
[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  * TODO: sHLP
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"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 -rdavsl options"
32   default y
33   depends on CP
34   help
35     usage: cp [-rdavsl]
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 // TODO: PLHlsd
70
71 GLOBALS(
72   char *destname;
73   struct stat top;
74 )
75
76 // Callback from dirtree_read() for each file/directory under a source dir.
77
78 int cp_node(struct dirtree *try)
79 {
80   int fdout = -1, cfd = try->parent ? try->parent->extra : AT_FDCWD,
81       tfd = dirtree_parentfd(try);
82   unsigned flags = toys.optflags;
83   char *catch = try->parent ? try->name : TT.destname, *err = "%s";
84   struct stat cst;
85
86   if (!dirtree_notdotdot(try)) return 0;
87
88   // If returning from COMEAGAIN, jump straight to -p logic at end.
89   if (S_ISDIR(try->st.st_mode) && try->data == -1) {
90     fdout = try->extra;
91     err = 0;
92   } else {
93
94     // -d is only the same as -r for symlinks, not for directories
95     if (S_ISLNK(try->st.st_mode) & (flags & FLAG_d)) flags |= FLAG_r;
96
97     // Detect recursive copies via repeated top node (cp -R .. .) or
98     // identical source/target (fun with hardlinks).
99     if ((TT.top.st_dev == try->st.st_dev && TT.top.st_ino == try->st.st_ino
100          && (catch = TT.destname))
101         || (!fstatat(cfd, catch, &cst, 0) && cst.st_dev == try->st.st_dev
102          && cst.st_ino == try->st.st_ino))
103     {
104       error_msg("'%s' is '%s'", catch, err = dirtree_path(try, 0));
105       free(err);
106
107       return 0;
108     }
109
110     // Handle -inv
111
112     if (!faccessat(cfd, catch, F_OK, 0) && !S_ISDIR(cst.st_mode)) {
113       char *s;
114
115       if (S_ISDIR(try->st.st_dev)) {
116         error_msg("dir at '%s'", s = dirtree_path(try, 0));
117         free(s);
118         return 0;
119       } else if (flags & FLAG_n) return 0;
120       else if (flags & FLAG_i) {
121         fprintf(stderr, "cp: overwrite '%s'", s = dirtree_path(try, 0));
122         free(s);
123         if (!yesno("", 1)) return 0;
124       }
125     }
126
127     if (flags & FLAG_v) {
128       char *s = dirtree_path(try, 0);
129       printf("cp '%s'\n", s);
130       free(s);
131     }
132
133     // Loop for -f retry after unlink
134     do {
135
136       // directory, hardlink, symlink, mknod (char, block, fifo, socket), file
137
138       // Copy directory
139
140       if (S_ISDIR(try->st.st_mode)) {
141         struct stat st2;
142
143         if (!(flags & (FLAG_a|FLAG_r|FLAG_R))) {
144           err = "Skipped dir '%s'";
145           catch = try->name;
146           break;
147         }
148
149         // Always make directory writeable to us, so we can create files in it.
150         //
151         // Yes, there's a race window between mkdir() and open() so it's
152         // possible that -p can be made to chown a directory other than the one
153         // we created. The closest we can do to closing this is make sure
154         // that what we open _is_ a directory rather than something else.
155
156         if (!mkdirat(cfd, catch, try->st.st_mode | 0200) || errno == EEXIST)
157           if (-1 != (try->extra = openat(cfd, catch, O_NOFOLLOW)))
158             if (!fstat(try->extra, &st2))
159               if (S_ISDIR(st2.st_mode)) return DIRTREE_COMEAGAIN;
160
161       // Hardlink
162
163       } else if (flags & FLAG_l) {
164         if (!linkat(tfd, try->name, cfd, catch, 0)) err = 0;
165
166       // Copy tree as symlinks. For non-absolute paths this involves
167       // appending the right number of .. entries as you go down the tree.
168
169       } else if (flags & FLAG_s) {
170         char *s;
171         struct dirtree *or;
172         int dotdots = 0;
173
174         s = dirtree_path(try, 0);
175         for (or = try; or->parent; or = or->parent) dotdots++;
176
177         if (*or->name == '/') dotdots = 0;
178         if (dotdots) {
179           char *s2 = xmprintf("% *c%s", 3*dotdots, ' ', s);
180           free(s);
181           s = s2;
182           while(dotdots--) {
183             memcpy(s2, "../", 3);
184             s2 += 3;
185           }
186         }
187         if (!symlinkat(s, cfd, catch)) {
188           err = 0;
189           fdout = AT_FDCWD;
190         }
191         free(s);
192
193       // Do something _other_ than copy contents of a file?
194       } else if (!S_ISREG(try->st.st_mode)
195                  && (try->parent || (flags & (FLAG_a|FLAG_r))))
196       {
197         int i;
198
199         // make symlink, or make block/char/fifo/socket
200         if (S_ISLNK(try->st.st_mode)
201             ? (0 < (i = readlinkat(tfd, try->name, toybuf, sizeof(toybuf))) &&
202                sizeof(toybuf) > i && !symlinkat(toybuf, cfd, catch))
203             : !mknodat(cfd, catch, try->st.st_mode, try->st.st_rdev))
204         {
205           err = 0;
206           fdout = AT_FDCWD;
207         }
208
209       // Copy contents of file.
210       } else {
211         int fdin;
212
213         fdin = openat(tfd, try->name, O_RDONLY);
214         if (fdin < 0) {
215           catch = try->name;
216           break;
217         } else {
218           fdout = openat(cfd, catch, O_RDWR|O_CREAT|O_TRUNC, try->st.st_mode);
219           if (fdout >= 0) {
220             xsendfile(fdin, fdout);
221             err = 0;
222           }
223           close(fdin);
224         }
225       }
226     } while (err && (flags & (FLAG_f|FLAG_n)) && !unlinkat(cfd, catch, 0));
227   }
228
229   if (fdout != -1) {
230     if (flags & (FLAG_a|FLAG_p)) {
231       struct timespec times[2];
232
233       // Inability to set these isn't fatal, some require root access.
234
235       times[0] = try->st.st_atim;
236       times[1] = try->st.st_mtim;
237
238       // If we can't get a filehandle to the actual object, use racy functions
239       if (fdout == AT_FDCWD) {
240         fchownat(cfd, catch, try->st.st_uid, try->st.st_gid,
241                  AT_SYMLINK_NOFOLLOW);
242         utimensat(cfd, catch, times, AT_SYMLINK_NOFOLLOW);
243         // permission bits already correct for mknod, don't apply to symlink
244       } else {
245         fchown(fdout, try->st.st_uid, try->st.st_gid);
246         futimens(fdout, times);
247         fchmod(fdout, try->st.st_mode);
248       }
249     }
250
251     if (fdout != AT_FDCWD) xclose(fdout);
252
253     if (toys.which->name[0] == 'm')
254       if (unlinkat(tfd, try->name, S_ISDIR(try->st.st_mode) ? AT_REMOVEDIR : 0))
255         err = "%s";
256   }
257
258   if (err) perror_msg(err, catch);
259   return 0;
260 }
261
262 void cp_main(void)
263 {
264   char *destname = toys.optargs[--toys.optc];
265   int i, destdir = !stat(destname, &TT.top) && S_ISDIR(TT.top.st_mode);
266
267   if (toys.optc>1 && !destdir) error_exit("'%s' not directory", destname);
268   if (toys.which->name[0] == 'm') toys.optflags |= FLAG_d|FLAG_p|FLAG_R;
269   if (toys.optflags & (FLAG_a|FLAG_p)) umask(0);
270
271   // Loop through sources
272
273   for (i=0; i<toys.optc; i++) {
274     struct dirtree *new;
275     char *src = toys.optargs[i];
276     int rc = 1;
277
278     if (destdir) TT.destname = xmprintf("%s/%s", destname, basename(src));
279     else TT.destname = destname;
280
281     errno = EXDEV;
282     if (toys.which->name[0] == 'm') rc = rename(src, TT.destname);
283
284     // Skip nonexistent sources
285     if (rc) {
286       if (errno != EXDEV ||
287         !(new = dirtree_add_node(0, src, !(toys.optflags & (FLAG_d|FLAG_a)))))
288           perror_msg("bad '%s'", src);
289       else dirtree_handle_callback(new, cp_node);
290     }
291     if (destdir) free(TT.destname);
292   }
293 }