cp.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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. // options shared between mv/cp must be in same order (right to left)
  15. // for FLAG macros to work out right in shared infrastructure.
  16. USE_CP(NEWTOY(cp, "<1(preserve):;D(parents)RHLPprudaslvnF(remove-destination)fit:T[-HLPd][-niu][+Rr]", TOYFLAG_BIN))
  17. USE_MV(NEWTOY(mv, "<1vnF(remove-destination)fit:T[-ni]", TOYFLAG_BIN))
  18. USE_INSTALL(NEWTOY(install, "<1cdDpsvt:m:o:g:", TOYFLAG_USR|TOYFLAG_BIN))
  19. config CP
  20. bool "cp"
  21. default y
  22. help
  23. usage: cp [-adfHiLlnPpRrsTv] [--preserve=motcxa] [-t TARGET] SOURCE... [DEST]
  24. Copy files from SOURCE to DEST. If more than one SOURCE, DEST must
  25. be a directory.
  26. -a Same as -dpr
  27. -D Create leading dirs under DEST (--parents)
  28. -d Don't dereference symlinks
  29. -F Delete any existing destination file first (--remove-destination)
  30. -f Delete destination files we can't write to
  31. -H Follow symlinks listed on command line
  32. -i Interactive, prompt before overwriting existing DEST
  33. -L Follow all symlinks
  34. -l Hard link instead of copy
  35. -n No clobber (don't overwrite DEST)
  36. -u Update (keep newest mtime)
  37. -P Do not follow symlinks
  38. -p Preserve timestamps, ownership, and mode
  39. -R Recurse into subdirectories (DEST must be a directory)
  40. -r Synonym for -R
  41. -s Symlink instead of copy
  42. -t Copy to TARGET dir (no DEST)
  43. -T DEST always treated as file, max 2 arguments
  44. -v Verbose
  45. Arguments to --preserve are the first letter(s) of:
  46. mode - permissions (ignore umask for rwx, copy suid and sticky bit)
  47. ownership - user and group
  48. timestamps - file creation, modification, and access times.
  49. context - security context
  50. xattr - extended attributes
  51. all - all of the above
  52. config MV
  53. bool "mv"
  54. default y
  55. help
  56. usage: mv [-finTv] [-t TARGET] SOURCE... [DEST]
  57. -f Force copy by deleting destination file
  58. -i Interactive, prompt before overwriting existing DEST
  59. -n No clobber (don't overwrite DEST)
  60. -t Move to TARGET dir (no DEST)
  61. -T DEST always treated as file, max 2 arguments
  62. -v Verbose
  63. config INSTALL
  64. bool "install"
  65. default y
  66. help
  67. usage: install [-dDpsv] [-o USER] [-g GROUP] [-m MODE] [-t TARGET] [SOURCE...] [DEST]
  68. Copy files and set attributes.
  69. -d Act like mkdir -p
  70. -D Create leading directories for DEST
  71. -g Make copy belong to GROUP
  72. -m Set permissions to MODE
  73. -o Make copy belong to USER
  74. -p Preserve timestamps
  75. -s Call "strip -p"
  76. -t Copy files to TARGET dir (no DEST)
  77. -v Verbose
  78. */
  79. #define FORCE_FLAGS
  80. #define FOR_cp
  81. #include "toys.h"
  82. GLOBALS(
  83. union {
  84. // install's options
  85. struct {
  86. char *g, *o, *m, *t;
  87. } i;
  88. // cp's options
  89. struct {
  90. char *t, *preserve;
  91. } c;
  92. };
  93. char *destname;
  94. struct stat top;
  95. int (*callback)(struct dirtree *try);
  96. uid_t uid;
  97. gid_t gid;
  98. int pflags;
  99. )
  100. struct cp_preserve {
  101. char *name;
  102. } static const cp_preserve[] = TAGGED_ARRAY(CP,
  103. {"mode"}, {"ownership"}, {"timestamps"}, {"context"}, {"xattr"},
  104. );
  105. // Callback from dirtree_read() for each file/directory under a source dir.
  106. static int cp_node(struct dirtree *try)
  107. {
  108. int fdout = -1, cfd = try->parent ? try->parent->extra : AT_FDCWD,
  109. save = DIRTREE_SAVE*(CFG_MV && toys.which->name[0] == 'm'), rc = 0,
  110. tfd = dirtree_parentfd(try);
  111. unsigned flags = toys.optflags;
  112. char *s = 0, *catch = try->parent ? try->name : TT.destname, *err = "%s";
  113. struct stat cst;
  114. if (!dirtree_notdotdot(try)) return 0;
  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. // If mv child had a problem, free data and don't try to delete parent dir.
  120. if (try->child) {
  121. save = 0;
  122. llist_traverse(try->child, free);
  123. }
  124. } else {
  125. // -d is only the same as -r for symlinks, not for directories
  126. if (S_ISLNK(try->st.st_mode) && (flags & FLAG_d)) flags |= FLAG_r;
  127. // Detect recursive copies via repeated top node (cp -R .. .) or
  128. // identical source/target (fun with hardlinks).
  129. if ((TT.top.st_dev == try->st.st_dev && TT.top.st_ino == try->st.st_ino
  130. && (catch = TT.destname))
  131. || (!fstatat(cfd, catch, &cst, 0) && cst.st_dev == try->st.st_dev
  132. && cst.st_ino == try->st.st_ino))
  133. {
  134. error_msg("'%s' is '%s'", catch, err = dirtree_path(try, 0));
  135. free(err);
  136. return save;
  137. }
  138. // Handle -inuvF
  139. if (!faccessat(cfd, catch, F_OK, 0) && !S_ISDIR(cst.st_mode)) {
  140. if (S_ISDIR(try->st.st_mode))
  141. error_msg("dir at '%s'", s = dirtree_path(try, 0));
  142. else if ((flags & FLAG_F) && unlinkat(cfd, catch, 0))
  143. error_msg("unlink '%s'", catch);
  144. else if (flags & FLAG_i) {
  145. fprintf(stderr, "%s: overwrite '%s'", toys.which->name,
  146. s = dirtree_path(try, 0));
  147. if (yesno(0)) rc++;
  148. } else if (!((flags&FLAG_u) && nanodiff(&try->st.st_mtim, &cst.st_mtim)>0)
  149. && !(flags & FLAG_n)) rc++;
  150. free(s);
  151. if (!rc) return save;
  152. }
  153. if (flags & FLAG_v) {
  154. printf("%s '%s'\n", toys.which->name, s = dirtree_path(try, 0));
  155. free(s);
  156. }
  157. // Loop for -f retry after unlink
  158. do {
  159. // directory, hardlink, symlink, mknod (char, block, fifo, socket), file
  160. // Copy directory
  161. if (S_ISDIR(try->st.st_mode)) {
  162. struct stat st2;
  163. if (!(flags & (FLAG_a|FLAG_r))) {
  164. err = "Skipped dir '%s'";
  165. catch = try->name;
  166. break;
  167. }
  168. // Always make directory writeable to us, so we can create files in it.
  169. //
  170. // Yes, there's a race window between mkdir() and open() so it's
  171. // possible that -p can be made to chown a directory other than the one
  172. // we created. The closest we can do to closing this is make sure
  173. // that what we open _is_ a directory rather than something else.
  174. if (!mkdirat(cfd, catch, try->st.st_mode | 0200) || errno == EEXIST)
  175. if (-1 != (try->extra = openat(cfd, catch, O_NOFOLLOW)))
  176. if (!fstat(try->extra, &st2) && S_ISDIR(st2.st_mode))
  177. return DIRTREE_COMEAGAIN | (DIRTREE_SYMFOLLOW*!!FLAG(L));
  178. // Hardlink
  179. } else if (flags & FLAG_l) {
  180. if (!linkat(tfd, try->name, cfd, catch, 0)) err = 0;
  181. // Copy tree as symlinks. For non-absolute paths this involves
  182. // appending the right number of .. entries as you go down the tree.
  183. } else if (flags & FLAG_s) {
  184. char *s;
  185. struct dirtree *or;
  186. int dotdots = 0;
  187. s = dirtree_path(try, 0);
  188. for (or = try; or->parent; or = or->parent) dotdots++;
  189. if (*or->name == '/') dotdots = 0;
  190. if (dotdots) {
  191. char *s2 = xmprintf("%*c%s", 3*dotdots, ' ', s);
  192. free(s);
  193. s = s2;
  194. while(dotdots--) {
  195. memcpy(s2, "../", 3);
  196. s2 += 3;
  197. }
  198. }
  199. if (!symlinkat(s, cfd, catch)) {
  200. err = 0;
  201. fdout = AT_FDCWD;
  202. }
  203. free(s);
  204. // Do something _other_ than copy contents of a file?
  205. } else if (!S_ISREG(try->st.st_mode)
  206. && (try->parent || (flags & (FLAG_a|FLAG_P|FLAG_r))))
  207. {
  208. // make symlink, or make block/char/fifo/socket
  209. if (S_ISLNK(try->st.st_mode)
  210. ? readlinkat0(tfd, try->name, toybuf, sizeof(toybuf)) &&
  211. (!unlinkat(cfd, catch, 0) || ENOENT == errno) &&
  212. !symlinkat(toybuf, cfd, catch)
  213. : !mknodat(cfd, catch, try->st.st_mode, try->st.st_rdev))
  214. {
  215. err = 0;
  216. fdout = AT_FDCWD;
  217. }
  218. // Copy contents of file.
  219. } else {
  220. int fdin, ii;
  221. fdin = openat(tfd, try->name, O_RDONLY);
  222. if (fdin < 0) {
  223. catch = try->name;
  224. break;
  225. }
  226. // When copying contents use symlink target's attributes
  227. if (S_ISLNK(try->st.st_mode)) fstat(fdin, &try->st);
  228. fdout = openat(cfd, catch, O_RDWR|O_CREAT|O_TRUNC, try->st.st_mode);
  229. if (fdout >= 0) {
  230. xsendfile(fdin, fdout);
  231. err = 0;
  232. }
  233. // We only copy xattrs for files because there's no flistxattrat()
  234. if (TT.pflags&(_CP_xattr|_CP_context)) {
  235. ssize_t listlen = xattr_flist(fdin, 0, 0), len;
  236. char *name, *value, *list;
  237. if (listlen>0) {
  238. list = xmalloc(listlen);
  239. xattr_flist(fdin, list, listlen);
  240. list[listlen-1] = 0; // I do not trust this API.
  241. for (name = list; name-list < listlen; name += strlen(name)+1) {
  242. // context copies security, xattr copies everything else
  243. ii = strncmp(name, "security.", 9) ? _CP_xattr : _CP_context;
  244. if (!(TT.pflags&ii)) continue;
  245. if ((len = xattr_fget(fdin, name, 0, 0))>0) {
  246. value = xmalloc(len);
  247. if (len == xattr_fget(fdin, name, value, len))
  248. if (xattr_fset(fdout, name, value, len, 0))
  249. perror_msg("%s setxattr(%s=%s)", catch, name, value);
  250. free(value);
  251. }
  252. }
  253. free(list);
  254. }
  255. }
  256. close(fdin);
  257. }
  258. } while (err && (flags & (FLAG_f|FLAG_n)) && !unlinkat(cfd, catch, 0));
  259. }
  260. // Did we make a thing?
  261. if (fdout != -1) {
  262. // Inability to set --preserve isn't fatal, some require root access.
  263. // ownership
  264. if (TT.pflags & _CP_ownership) {
  265. // permission bits already correct for mknod and don't apply to symlink
  266. // If we can't get a filehandle to the actual object, use racy functions
  267. if (fdout == AT_FDCWD)
  268. rc = fchownat(cfd, catch, try->st.st_uid, try->st.st_gid,
  269. AT_SYMLINK_NOFOLLOW);
  270. else rc = fchown(fdout, try->st.st_uid, try->st.st_gid);
  271. if (rc && !geteuid()) {
  272. char *pp;
  273. perror_msg("chown '%s'", pp = dirtree_path(try, 0));
  274. free(pp);
  275. }
  276. }
  277. // timestamp
  278. if (TT.pflags & _CP_timestamps) {
  279. struct timespec times[] = {try->st.st_atim, try->st.st_mtim};
  280. if (fdout == AT_FDCWD) utimensat(cfd, catch, times, AT_SYMLINK_NOFOLLOW);
  281. else futimens(fdout, times);
  282. }
  283. // mode comes last because other syscalls can strip suid bit
  284. if (fdout != AT_FDCWD) {
  285. if (TT.pflags & _CP_mode) fchmod(fdout, try->st.st_mode);
  286. xclose(fdout);
  287. }
  288. if (save)
  289. if (unlinkat(tfd, try->name, S_ISDIR(try->st.st_mode) ? AT_REMOVEDIR :0))
  290. err = "%s";
  291. }
  292. if (err) {
  293. if (catch == try->name) {
  294. s = dirtree_path(try, 0);
  295. while (try->parent) try = try->parent;
  296. catch = xmprintf("%s%s", TT.destname, s+strlen(try->name));
  297. free(s);
  298. s = catch;
  299. } else s = 0;
  300. perror_msg(err, catch);
  301. free(s);
  302. }
  303. return 0;
  304. }
  305. void cp_main(void)
  306. {
  307. char *tt = *toys.which->name == 'i' ? TT.i.t : TT.c.t,
  308. *destname = tt ? : toys.optargs[--toys.optc];
  309. int i, destdir = !stat(destname, &TT.top);
  310. if (!toys.optc) error_exit("Needs 2 arguments");
  311. if (!destdir && errno==ENOENT && FLAG(D)) {
  312. if (tt && mkpathat(AT_FDCWD, tt, 0777, MKPATHAT_MAKE|MKPATHAT_MKLAST))
  313. perror_exit("-t '%s'", tt);
  314. destdir = 1;
  315. } else {
  316. destdir = destdir && S_ISDIR(TT.top.st_mode);
  317. if (!destdir && (toys.optc>1 || FLAG(D) || tt))
  318. error_exit("'%s' not directory", destname);
  319. }
  320. if (FLAG(T)) {
  321. if (toys.optc>1) help_exit("Max 2 arguments");
  322. if (destdir) error_exit("'%s' is a directory", destname);
  323. }
  324. if (FLAG(a)||FLAG(p)) TT.pflags = _CP_mode|_CP_ownership|_CP_timestamps;
  325. // Not using comma_args() (yet?) because interpeting as letters.
  326. if (FLAG(preserve)) {
  327. char *pre = xstrdup(TT.c.preserve ? TT.c.preserve : "mot"), *s;
  328. if (comma_remove(pre, "all")) TT.pflags = ~0;
  329. for (i=0; i<ARRAY_LEN(cp_preserve); i++)
  330. while (comma_remove(pre, cp_preserve[i].name)) TT.pflags |= 1<<i;
  331. if (*pre) {
  332. // Try to interpret as letters, commas won't set anything this doesn't.
  333. for (s = pre; *s; s++) {
  334. for (i=0; i<ARRAY_LEN(cp_preserve); i++)
  335. if (*s == *cp_preserve[i].name) break;
  336. if (i == ARRAY_LEN(cp_preserve)) {
  337. if (*s == 'a') TT.pflags = ~0;
  338. else break;
  339. } else TT.pflags |= 1<<i;
  340. }
  341. if (*s) error_exit("bad --preserve=%s", pre);
  342. }
  343. free(pre);
  344. }
  345. if (TT.pflags & _CP_mode) umask(0);
  346. if (!TT.callback) TT.callback = cp_node;
  347. // Loop through sources
  348. for (i=0; i<toys.optc; i++) {
  349. char *src = toys.optargs[i], *trail;
  350. int send = 1;
  351. if (!(trail = strrchr(src, '/')) || trail[1]) trail = 0;
  352. else while (trail>src && *trail=='/') *trail-- = 0;
  353. if (destdir) {
  354. char *s = FLAG(D) ? src : getbasename(src);
  355. TT.destname = xmprintf("%s/%s", destname, s);
  356. if (FLAG(D)) {
  357. if (!(s = fileunderdir(TT.destname, destname))) {
  358. error_msg("%s not under %s", TT.destname, destname);
  359. continue;
  360. }
  361. // TODO: .. follows abspath, not links...
  362. free(s);
  363. mkpath(TT.destname);
  364. }
  365. } else TT.destname = destname;
  366. // "mv across devices" triggers cp fallback path, so set that as default
  367. errno = EXDEV;
  368. if (CFG_MV && toys.which->name[0] == 'm') {
  369. int force = FLAG(f), no_clobber = FLAG(n);
  370. if (!force || no_clobber) {
  371. struct stat st;
  372. int exists = !stat(TT.destname, &st);
  373. // Prompt if -i or file isn't writable. Technically "is writable" is
  374. // more complicated (022 is not writeable by the owner, just everybody
  375. // _else_) but I don't care.
  376. if (exists && (FLAG(i) || (!(st.st_mode & 0222) && isatty(0)))) {
  377. fprintf(stderr, "%s: overwrite '%s'", toys.which->name, TT.destname);
  378. if (!yesno(0)) send = 0;
  379. else unlink(TT.destname);
  380. }
  381. // if -n and dest exists, don't try to rename() or copy
  382. if (exists && no_clobber) send = 0;
  383. }
  384. if (send) send = rename(src, TT.destname);
  385. if (trail) trail[1] = '/';
  386. }
  387. // Copy if we didn't mv or hit an error, skipping nonexistent sources
  388. if (send) {
  389. if (errno!=EXDEV || dirtree_flagread(src, DIRTREE_SHUTUP+
  390. DIRTREE_SYMFOLLOW*!!(FLAG(H)||FLAG(L)), TT.callback))
  391. perror_msg("bad '%s'", src);
  392. }
  393. if (destdir) free(TT.destname);
  394. }
  395. }
  396. void mv_main(void)
  397. {
  398. toys.optflags |= FLAG_d|FLAG_p|FLAG_r;
  399. cp_main();
  400. }
  401. // Export cp flags into install's flag context.
  402. static inline int cp_flag_F(void) { return FLAG_F; };
  403. static inline int cp_flag_p(void) { return FLAG_p; };
  404. static inline int cp_flag_v(void) { return FLAG_v; };
  405. // Switch to install's flag context
  406. #define FOR_install
  407. #include <generated/flags.h>
  408. static int install_node(struct dirtree *try)
  409. {
  410. try->st.st_mode = TT.i.m ? string_to_mode(TT.i.m, try->st.st_mode) : 0755;
  411. if (TT.i.g) try->st.st_gid = TT.gid;
  412. if (TT.i.o) try->st.st_uid = TT.uid;
  413. // Always returns 0 because no -r
  414. cp_node(try);
  415. // No -r so always one level deep, so destname as set by cp_node() is correct
  416. if (FLAG(s) && xrun((char *[]){"strip", "-p", TT.destname, 0}))
  417. toys.exitval = 1;
  418. return 0;
  419. }
  420. void install_main(void)
  421. {
  422. char **ss;
  423. TT.uid = TT.i.o ? xgetuid(TT.i.o) : -1;
  424. TT.gid = TT.i.g ? xgetgid(TT.i.g) : -1;
  425. if (FLAG(d)) {
  426. for (ss = toys.optargs; *ss; ss++) {
  427. if (FLAG(v)) printf("%s\n", *ss);
  428. if (mkpathat(AT_FDCWD, *ss, 0777, MKPATHAT_MKLAST | MKPATHAT_MAKE))
  429. perror_msg_raw(*ss);
  430. if (FLAG(g)||FLAG(o))
  431. if (lchown(*ss, TT.uid, TT.gid)) perror_msg("chown '%s'", *ss);
  432. }
  433. return;
  434. }
  435. if (FLAG(D)) {
  436. char *destname = FLAG(t) ? TT.i.t : (TT.destname = toys.optargs[toys.optc-1]);
  437. if (mkpathat(AT_FDCWD, destname, 0777, MKPATHAT_MAKE | (FLAG(t) ? MKPATHAT_MKLAST : 0)))
  438. perror_exit("-D '%s'", destname);
  439. if (toys.optc == !FLAG(t)) return;
  440. }
  441. // Translate flags from install to cp
  442. toys.optflags = cp_flag_F() + cp_flag_v()*!!FLAG(v)
  443. + cp_flag_p()*!!(FLAG(p)|FLAG(o)|FLAG(g));
  444. TT.callback = install_node;
  445. cp_main();
  446. }