1 /* Copyright 2008 Rob Landley <rob@landley.net>
2 *
3 * See http://opengroup.org/onlinepubs/9699919799/utilities/cp.html
4 * And http://opengroup.org/onlinepubs/9699919799/utilities/mv.html
5 * And http://refspecs.linuxfoundation.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic.html#INSTALL
6 *
7 * Posix says "cp -Rf dir file" shouldn't delete file, but our -f does.
8 *
9 * Deviations from posix: -adlnrsvF, --preserve... about half the
10 * functionality in this cp isn't in posix. Posix is stuck in the 1970's.
11 *
12 * TODO: --preserve=links
13 * TODO: what's this _CP_mode system.posix_acl_ business? We chmod()?
14
15 // options shared between mv/cp must be in same order (right to left)
16 // for FLAG macros to work out right in shared infrastructure.
17
18 USE_CP(NEWTOY(cp, "<2"USE_CP_PRESERVE("(preserve):;")"D(parents)RHLPprdaslvnF(remove-destination)fi[-HLPd][-ni]", TOYFLAG_BIN))
19 USE_MV(NEWTOY(mv, "<2vnF(remove-destination)fi[-ni]", TOYFLAG_BIN))
20 USE_INSTALL(NEWTOY(install, "<1cdDpsvm:o:g:", TOYFLAG_USR|TOYFLAG_BIN))
21
22 config CP
23 bool "cp"
24 default y
25 help
26 usage: cp file SOURCE... DEST
27
28 Copy files from SOURCE to DEST. If more than one SOURCE, DEST must
29 be a directory.
30
31
32 config CP_PRESERVE
33 bool "cp --preserve support"
34 default n
35 depends on CP
36 help
37 usage: cp [--preserve=motcxa]
38
39 --preserve takes either a comma separated list of attributes, or the first
40 letter(s) of:
41
42 mode - permissions (ignore umask for rwx, copy suid and sticky bit)
43 ownership - user and group
44 timestamps - file creation, modification, and access times.
45 context - security context
46 xattr - extended attributes
47 all - all of the above
48
49 config MV
50 bool "mv"
51 default y
52 help
53 usage: mv [-fivn] SOURCE... DEST
54
55 -f Force copy by deleting destination file
56 -i Interactive, prompt before overwriting existing DEST
57 -v Verbose
58 -n No clobber (don't overwrite DEST)
59
60 config INSTALL
61 bool "install"
62 default n
63 help
64 usage: install [-dDpsv] [-o USER] [-g GROUP] [-m MODE] [SOURCE...] DEST
65
66 Copy files and set attributes.
67
68 -d Act like mkdir -p
69 -D Create leading directories for DEST
70 -g Make copy belong to GROUP
71 -m Set permissions to MODE
72 -o Make copy belong to USER
73 -p Preserve timestamps
74 -s Call "strip -p"
75 -v Verbose
76 */
77
78 #define FORCE_FLAGS
79 #define FOR_cp
80 #include "toys.h"
81
82 GLOBALS(
83 union {
84 // install's options
85 struct {
86 char *g, *o, *m;
87 } i;
88 // cp's options
89 struct {
90 char *preserve;
91 } c;
92 };
93
94 char *destname;
95 struct stat top;
96 int (*callback)(struct dirtree *try);
97 uid_t uid;
98 gid_t gid;
99 int pflags;
100 )
101
102 struct cp_preserve {
103 char *name;
104 } static const cp_preserve[] = TAGGED_ARRAY(CP,
105 {"mode"}, {"ownership"}, {"timestamps"}, {"context"}, {"xattr"},
106 );
107
108 // Callback from dirtree_read() for each file/directory under a source dir.
109
cp_node(struct dirtree * try)110 static int cp_node(struct dirtree *try)
111 {
112 int fdout = -1, cfd = try->parent ? try->parent->extra : AT_FDCWD,
113 tfd = dirtree_parentfd(try);
114 unsigned flags = toys.optflags;
115 char *catch = try->parent ? try->name : TT.destname, *err = "%s";
116 struct stat cst;
117
118 if (!dirtree_notdotdot(try)) return 0;
119
120 // If returning from COMEAGAIN, jump straight to -p logic at end.
121 if (S_ISDIR(try->st.st_mode) && try->again) {
122 fdout = try->extra;
123 err = 0;
124 } else {
125
126 // -d is only the same as -r for symlinks, not for directories
127 if (S_ISLNK(try->st.st_mode) && (flags & FLAG_d)) flags |= FLAG_r;
128
129 // Detect recursive copies via repeated top node (cp -R .. .) or
130 // identical source/target (fun with hardlinks).
131 // Handle -invF
132
133 if (!faccessat(cfd, catch, F_OK, 0) && !S_ISDIR(cst.st_mode)) {
134 char *s;
135
136 if (S_ISDIR(try->st.st_mode)) {
137 error_msg("dir at '%s'", s = dirtree_path(try, 0));
138 free(s);
139 return 0;
140 } else if ((flags & FLAG_F) && unlinkat(cfd, catch, 0)) {
141 error_msg("unlink '%s'", catch);
142 return 0;
143 } else if (flags & FLAG_n) return 0;
144 else if (flags & FLAG_i) {
145 fprintf(stderr, "%s: overwrite '%s'", toys.which->name,
146 s = dirtree_path(try, 0));
147 free(s);
148 if (!yesno(1)) return 0;
149 }
150 }
151
152 if (flags & FLAG_v) {
153 char *s = dirtree_path(try, 0);
154 printf("%s '%s'\n", toys.which->name, s);
155 free(s);
156 }
157
158 // Loop for -f retry after unlink
159 do {
160
161 // directory, hardlink, symlink, mknod (char, block, fifo, socket), file
162
163 // Copy directory
164
165 if (S_ISDIR(try->st.st_mode)) {
166 struct stat st2;
167
168 if (!(flags & (FLAG_a|FLAG_r|FLAG_R))) {
169 err = "Skipped dir '%s'";
170 catch = try->name;
171 break;
172 }
173
174 // Always make directory writeable to us, so we can create files in it.
175 //
176 // Yes, there's a race window between mkdir() and open() so it's
177 // possible that -p can be made to chown a directory other than the one
178 // we created. The closest we can do to closing this is make sure
179 // that what we open _is_ a directory rather than something else.
180
181 if (!mkdirat(cfd, catch, try->st.st_mode | 0200) || errno == EEXIST)
182 if (-1 != (try->extra = openat(cfd, catch, O_NOFOLLOW)))
183 if (!fstat(try->extra, &st2) && S_ISDIR(st2.st_mode))
184 return DIRTREE_COMEAGAIN | (DIRTREE_SYMFOLLOW*!!FLAG(L));
185
186 // Hardlink
187
188 } else if (flags & FLAG_l) {
189 if (!linkat(tfd, try->name, cfd, catch, 0)) err = 0;
190
191 // Copy tree as symlinks. For non-absolute paths this involves
192 // appending the right number of .. entries as you go down the tree.
193
194 } else if (flags & FLAG_s) {
195 char *s;
196 struct dirtree *or;
197 int dotdots = 0;
198
199 s = dirtree_path(try, 0);
200 for (or = try; or->parent; or = or->parent) dotdots++;
201
202 if (*or->name == '/') dotdots = 0;
203 if (dotdots) {
204 char *s2 = xmprintf("%*c%s", 3*dotdots, ' ', s);
205 free(s);
206 s = s2;
207 while(dotdots--) {
208 memcpy(s2, "../", 3);
209 s2 += 3;
210 }
211 }
212 if (!symlinkat(s, cfd, catch)) {
213 err = 0;
214 fdout = AT_FDCWD;
215 }
216 free(s);
217
218 // Do something _other_ than copy contents of a file?
219 } else if (!S_ISREG(try->st.st_mode)
220 && (try->parent || (flags & (FLAG_a|FLAG_r))))
221 {
222 int i;
223
224 // make symlink, or make block/char/fifo/socket
225 if (S_ISLNK(try->st.st_mode)
226 ? ((i = readlinkat0(tfd, try->name, toybuf, sizeof(toybuf))) &&
227 ((!unlinkat(cfd, catch, 0) || ENOENT == errno) &&
228 !symlinkat(toybuf, cfd, catch)))
229 : !mknodat(cfd, catch, try->st.st_mode, try->st.st_rdev))
230 {
231 err = 0;
232 fdout = AT_FDCWD;
233 }
234
235 // Copy contents of file.
236 } else {
237 int fdin;
238
239 fdin = openat(tfd, try->name, O_RDONLY);
240 if (fdin < 0) {
241 catch = try->name;
242 break;
243 }
244 // When copying contents use symlink target's attributes
245 if (S_ISLNK(try->st.st_mode)) fstat(fdin, &try->st);
246 fdout = openat(cfd, catch, O_RDWR|O_CREAT|O_TRUNC, try->st.st_mode);
247 if (fdout >= 0) {
248 xsendfile(fdin, fdout);
249 err = 0;
250 }
251
252 // We only copy xattrs for files because there's no flistxattrat()
253 if (TT.pflags&(_CP_xattr|_CP_context)) {
254 ssize_t listlen = xattr_flist(fdin, 0, 0), len;
255 char *name, *value, *list;
256
257 if (listlen>0) {
258 list = xmalloc(listlen);
259 xattr_flist(fdin, list, listlen);
260 list[listlen-1] = 0; // I do not trust this API.
261 for (name = list; name-list < listlen; name += strlen(name)+1) {
262 if (!(TT.pflags&_CP_xattr) && strncmp(name, "security.", 9))
263 continue;
264 if ((len = xattr_fget(fdin, name, 0, 0))>0) {
265 value = xmalloc(len);
266 if (len == xattr_fget(fdin, name, value, len))
267 if (xattr_fset(fdout, name, value, len, 0))
268 perror_msg("%s setxattr(%s=%s)", catch, name, value);
269 free(value);
270 }
271 }
272 free(list);
273 }
274 }
275
276 close(fdin);
277 }
278 } while (err && (flags & (FLAG_f|FLAG_n)) && !unlinkat(cfd, catch, 0));
279 }
280
281 // Did we make a thing?
282 if (fdout != -1) {
283 int rc;
284
285 // Inability to set --preserve isn't fatal, some require root access.
286
287 // ownership
288 if (TT.pflags & _CP_ownership) {
289
290 // permission bits already correct for mknod and don't apply to symlink
291 // If we can't get a filehandle to the actual object, use racy functions
292 if (fdout == AT_FDCWD)
293 rc = fchownat(cfd, catch, try->st.st_uid, try->st.st_gid,
294 AT_SYMLINK_NOFOLLOW);
295 else rc = fchown(fdout, try->st.st_uid, try->st.st_gid);
296 if (rc && !geteuid()) {
297 char *pp;
298
299 perror_msg("chown '%s'", pp = dirtree_path(try, 0));
300 free(pp);
301 }
302 }
303
304 // timestamp
305 if (TT.pflags & _CP_timestamps) {
306 struct timespec times[] = {try->st.st_atim, try->st.st_mtim};
307
308 if (fdout == AT_FDCWD) utimensat(cfd, catch, times, AT_SYMLINK_NOFOLLOW);
309 else futimens(fdout, times);
310 }
311
312 // mode comes last because other syscalls can strip suid bit
313 if (fdout != AT_FDCWD) {
314 if (TT.pflags & _CP_mode) fchmod(fdout, try->st.st_mode);
315 xclose(fdout);
316 }
317
318 if (CFG_MV && toys.which->name[0] == 'm')
319 if (unlinkat(tfd, try->name, S_ISDIR(try->st.st_mode) ? AT_REMOVEDIR :0))
320 err = "%s";
321 }
322
323 if (err) {
324 char *f = 0;
325
326 if (catch == try->name) {
327 f = dirtree_path(try, 0);
328 while (try->parent) try = try->parent;
329 catch = xmprintf("%s%s", TT.destname, f+strlen(try->name));
330 free(f);
331 f = catch;
332 }
333 perror_msg(err, catch);
334 free(f);
335 }
336 return 0;
337 }
338
cp_main(void)339 void cp_main(void)
340 {
341 char *destname = toys.optargs[--toys.optc];
342 char *srcname = toys.optargs[0];
343 int i, destdir;
344 int ret;
345 struct stat cst;
346
347 if (!*destname)
348 error_exit("Invalid argument: empty or null dest");
349
350 destdir = !stat(destname, &TT.top) && S_ISDIR(TT.top.st_mode);
351
352 if ((toys.optc>1 || FLAG(D)) && !destdir)
353 error_exit("'%s' not directory", destname);
354
355 // cp: Detect the validity of destination address.
356 ret = stat(srcname, &cst);
357 // Does the source file exist
358 if (ret < 0 && errno == ENOENT) {
359 perror_msg("'%s'", srcname);
360 return;
361 }
362 // Copying directories is not supported.
363 if (S_ISDIR(cst.st_mode)) {
364 xprintf("cp %s error: Source file can't be a directory.\n", srcname);
365 return;
366 }
367
368 if (FLAG(a)||FLAG(p)) TT.pflags = _CP_mode|_CP_ownership|_CP_timestamps;
369
370 // Not using comma_args() (yet?) because interpeting as letters.
371 if (CFG_CP_PRESERVE && FLAG(preserve)) {
372 char *pre = xstrdup(TT.c.preserve ? TT.c.preserve : "mot"), *s;
373
374 if (comma_remove(pre, "all")) TT.pflags = ~0;
375 for (i=0; i<ARRAY_LEN(cp_preserve); i++)
376 while (comma_remove(pre, cp_preserve[i].name)) TT.pflags |= 1<<i;
377 if (*pre) {
378
379 // Try to interpret as letters, commas won't set anything this doesn't.
380 for (s = pre; *s; s++) {
381 for (i=0; i<ARRAY_LEN(cp_preserve); i++)
382 if (*s == *cp_preserve[i].name) break;
383 if (i == ARRAY_LEN(cp_preserve)) {
384 if (*s == 'a') TT.pflags = ~0;
385 else break;
386 } else TT.pflags |= 1<<i;
387 }
388
389 if (*s) error_exit("bad --preserve=%s", pre);
390 }
391 free(pre);
392 }
393 if (TT.pflags & _CP_mode) umask(0);
394 if (!TT.callback) TT.callback = cp_node;
395
396 // Loop through sources
397 for (i=0; i<toys.optc; i++) {
398 char *src = toys.optargs[i], *trail = src;
399 int rc = 1;
400
401 if (CFG_MV && toys.which->name[0] == 'm') {
402 while (*++trail);
403 if (*--trail == '/') *trail = 0;
404 }
405
406 if (destdir) {
407 char *s = FLAG(D) ? getdirname(src) : getbasename(src);
408
409 TT.destname = xmprintf("%s/%s", destname, s);
410 if (FLAG(D)) {
411 free(s);
412 if (!(s = fileunderdir(TT.destname, destname))) {
413 error_msg("%s not under %s", TT.destname, destname);
414 continue;
415 }
416 // TODO: .. follows abspath, not links...
417 free(s);
418 mkpath(TT.destname);
419 }
420 } else TT.destname = destname;
421
422 ret = fstatat(AT_FDCWD, destname, &cst, 0);
423 if (ret < 0) {
424 /* Is dest path a directory? */
425 if (destname[strlen(destname) - 1] == '/') {
426 xprintf("cp error: %s, %s.\n", destname, strerror(errno));
427 return;
428 }
429 }
430
431 errno = EXDEV;
432 if (CFG_MV && toys.which->name[0] == 'm') {
433 int force = FLAG(f), no_clobber = FLAG(n);
434
435 if (!force || no_clobber) {
436 struct stat st;
437 int exists = !stat(TT.destname, &st);
438
439 // Prompt if -i or file isn't writable. Technically "is writable" is
440 // more complicated (022 is not writeable by the owner, just everybody
441 // _else_) but I don't care.
442 if (exists && (FLAG(i) || !(st.st_mode & 0222))) {
443 fprintf(stderr, "%s: overwrite '%s'", toys.which->name, TT.destname);
444 if (!yesno(1)) rc = 0;
445 else unlink(TT.destname);
446 }
447 // if -n and dest exists, don't try to rename() or copy
448 if (exists && no_clobber) rc = 0;
449 }
450 if (rc) rc = rename(src, TT.destname);
451 if (errno && !*trail) *trail = '/';
452 }
453
454 // Copy if we didn't mv, skipping nonexistent sources
455 if (rc) {
456 if (errno!=EXDEV || dirtree_flagread(src, DIRTREE_SHUTUP+
457 DIRTREE_SYMFOLLOW*!!(FLAG(H)||FLAG(L)), TT.callback))
458 perror_msg("bad '%s'", src);
459 }
460 if (destdir) free(TT.destname);
461 }
462 }
463
mv_main(void)464 void mv_main(void)
465 {
466 toys.optflags |= FLAG_d|FLAG_p|FLAG_R;
467
468 cp_main();
469 }
470
471 // Export cp flags into install's flag context.
472
cp_flag_F(void)473 static inline int cp_flag_F(void) { return FLAG_F; };
cp_flag_p(void)474 static inline int cp_flag_p(void) { return FLAG_p; };
cp_flag_v(void)475 static inline int cp_flag_v(void) { return FLAG_v; };
476
477 // Switch to install's flag context
478 #define CLEANUP_cp
479 #define FOR_install
480 #include <generated/flags.h>
481
install_node(struct dirtree * try)482 static int install_node(struct dirtree *try)
483 {
484 try->st.st_mode = TT.i.m ? string_to_mode(TT.i.m, try->st.st_mode) : 0755;
485 if (TT.i.g) try->st.st_gid = TT.gid;
486 if (TT.i.o) try->st.st_uid = TT.uid;
487
488 // Always returns 0 because no -r
489 cp_node(try);
490
491 // No -r so always one level deep, so destname as set by cp_node() is correct
492 if (FLAG(s) && xrun((char *[]){"strip", "-p", TT.destname, 0}))
493 toys.exitval = 1;
494
495 return 0;
496 }
497
install_main(void)498 void install_main(void)
499 {
500 char **ss;
501 int flags = toys.optflags;
502
503 TT.uid = TT.i.o ? xgetuid(TT.i.o) : -1;
504 TT.gid = TT.i.g ? xgetgid(TT.i.g) : -1;
505
506 if (flags & FLAG_d) {
507 for (ss = toys.optargs; *ss; ss++) {
508 if (mkpathat(AT_FDCWD, *ss, 0777, MKPATHAT_MKLAST | MKPATHAT_MAKE)) perror_msg_raw(*ss);
509 if (flags & (FLAG_g|FLAG_o))
510 if (lchown(*ss, TT.uid, TT.gid)) perror_msg("chown '%s'", *ss);
511 if (flags & FLAG_v) printf("%s\n", *ss);
512 }
513
514 return;
515 }
516
517 if (FLAG(D)) {
518 TT.destname = toys.optargs[toys.optc-1];
519 if (mkpathat(AT_FDCWD, TT.destname, 0, MKPATHAT_MAKE))
520 perror_exit("-D '%s'", TT.destname);
521 if (toys.optc == 1) return;
522 }
523 if (toys.optc < 2) error_exit("needs 2 args");
524
525 // Translate flags from install to cp
526 toys.optflags = cp_flag_F();
527 if (flags & FLAG_v) toys.optflags |= cp_flag_v();
528 if (flags & (FLAG_p|FLAG_o|FLAG_g)) toys.optflags |= cp_flag_p();
529
530 TT.callback = install_node;
531 cp_main();
532 }
533