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