copy_file.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini copy_file implementation for busybox
  4. *
  5. * Copyright (C) 2001 by Matt Kraai <kraai@alumni.carnegiemellon.edu>
  6. * SELinux support by Yuichi Nakamura <ynakam@hitachisoft.jp>
  7. *
  8. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  9. */
  10. #include "libbb.h"
  11. // FEATURE_NON_POSIX_CP:
  12. //
  13. // POSIX: if exists and -i, ask (w/o -i assume yes).
  14. // Then open w/o EXCL (yes, not unlink!).
  15. // If open still fails and -f, try unlink, then try open again.
  16. // Result: a mess:
  17. // If dest is a (sym)link, we overwrite link destination!
  18. // (or fail, if it points to dir/nonexistent location/etc).
  19. // This is strange, but POSIX-correct.
  20. // coreutils cp has --remove-destination to override this...
  21. /* Called if open of destination, link creation etc fails.
  22. * errno must be set to relevant value ("why we cannot create dest?")
  23. * to give reasonable error message */
  24. static int ask_and_unlink(const char *dest, int flags)
  25. {
  26. int e = errno;
  27. #if !ENABLE_FEATURE_NON_POSIX_CP
  28. if (!(flags & (FILEUTILS_FORCE|FILEUTILS_INTERACTIVE))) {
  29. /* Either it exists, or the *path* doesnt exist */
  30. bb_perror_msg("can't create '%s'", dest);
  31. return -1;
  32. }
  33. #endif
  34. // else: act as if -f is always in effect.
  35. // We don't want "can't create" msg, we want unlink to be done
  36. // (silently unless -i). Why? POSIX cp usually succeeds with
  37. // O_TRUNC open of existing file, and user is left ignorantly happy.
  38. // With above block unconditionally enabled, non-POSIX cp
  39. // will complain a lot more than POSIX one.
  40. /* TODO: maybe we should do it only if ctty is present? */
  41. if (flags & FILEUTILS_INTERACTIVE) {
  42. // We would not do POSIX insanity. -i asks,
  43. // then _unlinks_ the offender. Presto.
  44. // (No "opening without O_EXCL", no "unlink only if -f")
  45. // Or else we will end up having 3 open()s!
  46. fprintf(stderr, "%s: overwrite '%s'? ", applet_name, dest);
  47. if (!bb_ask_y_confirmation())
  48. return 0; /* not allowed to overwrite */
  49. }
  50. if (unlink(dest) < 0) {
  51. #if ENABLE_FEATURE_VERBOSE_CP_MESSAGE
  52. if (e == errno && e == ENOENT) {
  53. /* e == ENOTDIR is similar: path has non-dir component,
  54. * but in this case we don't even reach copy_file() */
  55. bb_error_msg("can't create '%s': Path does not exist", dest);
  56. return -1; /* error */
  57. }
  58. #endif
  59. errno = e; /* do not use errno from unlink */
  60. bb_perror_msg("can't create '%s'", dest);
  61. return -1; /* error */
  62. }
  63. #if ENABLE_FEATURE_CP_LONG_OPTIONS
  64. if (flags & FILEUTILS_RMDEST)
  65. if (flags & FILEUTILS_VERBOSE)
  66. printf("removed '%s'\n", dest);
  67. #endif
  68. return 1; /* ok (to try again) */
  69. }
  70. /* Return:
  71. * -1 error, copy not made
  72. * 0 copy is made or user answered "no" in interactive mode
  73. * (failures to preserve mode/owner/times are not reported in exit code)
  74. */
  75. int FAST_FUNC copy_file(const char *source, const char *dest, int flags)
  76. {
  77. /* This is a recursive function, try to minimize stack usage */
  78. /* NB: each struct stat is ~100 bytes */
  79. struct stat source_stat;
  80. struct stat dest_stat;
  81. smallint retval = 0;
  82. smallint dest_exists = 0;
  83. smallint ovr;
  84. /* Inverse of cp -d ("cp without -d") */
  85. #define FLAGS_DEREF (flags & (FILEUTILS_DEREFERENCE + FILEUTILS_DEREFERENCE_L0))
  86. if ((FLAGS_DEREF ? stat : lstat)(source, &source_stat) < 0) {
  87. /* This may be a dangling symlink.
  88. * Making [sym]links to dangling symlinks works, so... */
  89. if (flags & (FILEUTILS_MAKE_SOFTLINK|FILEUTILS_MAKE_HARDLINK))
  90. goto make_links;
  91. bb_perror_msg("can't stat '%s'", source);
  92. return -1;
  93. }
  94. if (lstat(dest, &dest_stat) < 0) {
  95. if (errno != ENOENT) {
  96. bb_perror_msg("can't stat '%s'", dest);
  97. return -1;
  98. }
  99. } else {
  100. if (source_stat.st_dev == dest_stat.st_dev
  101. && source_stat.st_ino == dest_stat.st_ino
  102. ) {
  103. bb_error_msg("'%s' and '%s' are the same file", source, dest);
  104. return -1;
  105. }
  106. if (flags & FILEUTILS_NO_OVERWRITE) /* cp -n */
  107. return 0;
  108. dest_exists = 1;
  109. }
  110. #if ENABLE_SELINUX
  111. if ((flags & FILEUTILS_PRESERVE_SECURITY_CONTEXT) && is_selinux_enabled() > 0) {
  112. security_context_t con;
  113. if (lgetfilecon(source, &con) >= 0) {
  114. if (setfscreatecon(con) < 0) {
  115. bb_perror_msg("can't set setfscreatecon %s", con);
  116. freecon(con);
  117. return -1;
  118. }
  119. } else if (errno == ENOTSUP || errno == ENODATA) {
  120. setfscreatecon_or_die(NULL);
  121. } else {
  122. bb_perror_msg("can't lgetfilecon %s", source);
  123. return -1;
  124. }
  125. }
  126. #endif
  127. if (S_ISDIR(source_stat.st_mode)) {
  128. DIR *dp;
  129. const char *tp;
  130. struct dirent *d;
  131. mode_t saved_umask = 0;
  132. if (!(flags & FILEUTILS_RECUR)) {
  133. bb_error_msg("omitting directory '%s'", source);
  134. return -1;
  135. }
  136. /* Did we ever create source ourself before? */
  137. tp = is_in_ino_dev_hashtable(&source_stat);
  138. if (tp) {
  139. /* We did! it's a recursion! man the lifeboats... */
  140. bb_error_msg("recursion detected, omitting directory '%s'",
  141. source);
  142. return -1;
  143. }
  144. if (dest_exists) {
  145. if (!S_ISDIR(dest_stat.st_mode)) {
  146. bb_error_msg("target '%s' is not a directory", dest);
  147. return -1;
  148. }
  149. /* race here: user can substitute a symlink between
  150. * this check and actual creation of files inside dest */
  151. } else {
  152. /* Create DEST */
  153. mode_t mode;
  154. saved_umask = umask(0);
  155. mode = source_stat.st_mode;
  156. if (!(flags & FILEUTILS_PRESERVE_STATUS))
  157. mode = source_stat.st_mode & ~saved_umask;
  158. /* Allow owner to access new dir (at least for now) */
  159. mode |= S_IRWXU;
  160. if (mkdir(dest, mode) < 0) {
  161. umask(saved_umask);
  162. bb_perror_msg("can't create directory '%s'", dest);
  163. return -1;
  164. }
  165. umask(saved_umask);
  166. /* need stat info for add_to_ino_dev_hashtable */
  167. if (lstat(dest, &dest_stat) < 0) {
  168. bb_perror_msg("can't stat '%s'", dest);
  169. return -1;
  170. }
  171. }
  172. /* remember (dev,inode) of each created dir.
  173. * NULL: name is not remembered */
  174. add_to_ino_dev_hashtable(&dest_stat, NULL);
  175. /* Recursively copy files in SOURCE */
  176. dp = opendir(source);
  177. if (dp == NULL) {
  178. retval = -1;
  179. goto preserve_mode_ugid_time;
  180. }
  181. while ((d = readdir(dp)) != NULL) {
  182. char *new_source, *new_dest;
  183. new_source = concat_subpath_file(source, d->d_name);
  184. if (new_source == NULL)
  185. continue;
  186. new_dest = concat_path_file(dest, d->d_name);
  187. if (copy_file(new_source, new_dest, flags & ~FILEUTILS_DEREFERENCE_L0) < 0)
  188. retval = -1;
  189. free(new_source);
  190. free(new_dest);
  191. }
  192. closedir(dp);
  193. if (!dest_exists
  194. && chmod(dest, source_stat.st_mode & ~saved_umask) < 0
  195. ) {
  196. bb_perror_msg("can't preserve %s of '%s'", "permissions", dest);
  197. /* retval = -1; - WRONG! copy *WAS* made */
  198. }
  199. goto preserve_mode_ugid_time;
  200. }
  201. if (dest_exists) {
  202. if (flags & FILEUTILS_UPDATE) {
  203. if (source_stat.st_mtime <= dest_stat.st_mtime) {
  204. return 0; /* source file must be newer */
  205. }
  206. }
  207. #if ENABLE_FEATURE_CP_LONG_OPTIONS
  208. if (flags & FILEUTILS_RMDEST) {
  209. ovr = ask_and_unlink(dest, flags);
  210. if (ovr <= 0)
  211. return ovr;
  212. dest_exists = 0;
  213. }
  214. #endif
  215. }
  216. if (flags & (FILEUTILS_MAKE_SOFTLINK|FILEUTILS_MAKE_HARDLINK)) {
  217. int (*lf)(const char *oldpath, const char *newpath);
  218. make_links:
  219. /* Hmm... maybe
  220. * if (DEREF && MAKE_SOFTLINK) source = realpath(source) ?
  221. * (but realpath returns NULL on dangling symlinks...) */
  222. lf = (flags & FILEUTILS_MAKE_SOFTLINK) ? symlink : link;
  223. if (lf(source, dest) < 0) {
  224. ovr = ask_and_unlink(dest, flags);
  225. if (ovr <= 0)
  226. return ovr;
  227. if (lf(source, dest) < 0) {
  228. bb_perror_msg("can't create link '%s'", dest);
  229. return -1;
  230. }
  231. }
  232. /* _Not_ jumping to preserve_mode_ugid_time:
  233. * (sym)links don't have those */
  234. return 0;
  235. }
  236. if (/* "cp thing1 thing2" without -R: just open and read() from thing1 */
  237. !(flags & FILEUTILS_RECUR)
  238. /* "cp [-opts] regular_file thing2" */
  239. || S_ISREG(source_stat.st_mode)
  240. /* DEREF uses stat, which never returns S_ISLNK() == true.
  241. * So the below is never true: */
  242. /* || (FLAGS_DEREF && S_ISLNK(source_stat.st_mode)) */
  243. ) {
  244. int src_fd;
  245. int dst_fd;
  246. mode_t new_mode;
  247. if (!FLAGS_DEREF && S_ISLNK(source_stat.st_mode)) {
  248. /* "cp -d symlink dst": create a link */
  249. goto dont_cat;
  250. }
  251. if (ENABLE_FEATURE_PRESERVE_HARDLINKS && !FLAGS_DEREF) {
  252. const char *link_target;
  253. link_target = is_in_ino_dev_hashtable(&source_stat);
  254. if (link_target) {
  255. if (link(link_target, dest) < 0) {
  256. ovr = ask_and_unlink(dest, flags);
  257. if (ovr <= 0)
  258. return ovr;
  259. if (link(link_target, dest) < 0) {
  260. bb_perror_msg("can't create link '%s'", dest);
  261. return -1;
  262. }
  263. }
  264. return 0;
  265. }
  266. add_to_ino_dev_hashtable(&source_stat, dest);
  267. }
  268. src_fd = open_or_warn(source, O_RDONLY);
  269. if (src_fd < 0)
  270. return -1;
  271. /* Do not try to open with weird mode fields */
  272. new_mode = source_stat.st_mode;
  273. if (!S_ISREG(source_stat.st_mode))
  274. new_mode = 0666;
  275. if (ENABLE_FEATURE_NON_POSIX_CP || (flags & FILEUTILS_INTERACTIVE)) {
  276. /*
  277. * O_CREAT|O_EXCL: require that file did not exist before creation
  278. */
  279. dst_fd = open(dest, O_WRONLY|O_CREAT|O_EXCL, new_mode);
  280. } else { /* POSIX, and not "cp -i" */
  281. /*
  282. * O_CREAT|O_TRUNC: create, or truncate (security problem versus (sym)link attacks)
  283. */
  284. dst_fd = open(dest, O_WRONLY|O_CREAT|O_TRUNC, new_mode);
  285. }
  286. if (dst_fd == -1) {
  287. ovr = ask_and_unlink(dest, flags);
  288. if (ovr <= 0) {
  289. close(src_fd);
  290. return ovr;
  291. }
  292. /* It shouldn't exist. If it exists, do not open (symlink attack?) */
  293. dst_fd = open3_or_warn(dest, O_WRONLY|O_CREAT|O_EXCL, new_mode);
  294. if (dst_fd < 0) {
  295. close(src_fd);
  296. return -1;
  297. }
  298. }
  299. #if ENABLE_SELINUX
  300. if ((flags & (FILEUTILS_PRESERVE_SECURITY_CONTEXT|FILEUTILS_SET_SECURITY_CONTEXT))
  301. && is_selinux_enabled() > 0
  302. ) {
  303. security_context_t con;
  304. if (getfscreatecon(&con) == -1) {
  305. bb_simple_perror_msg("getfscreatecon");
  306. return -1;
  307. }
  308. if (con) {
  309. if (setfilecon(dest, con) == -1) {
  310. bb_perror_msg("setfilecon:%s,%s", dest, con);
  311. freecon(con);
  312. return -1;
  313. }
  314. freecon(con);
  315. }
  316. }
  317. #endif
  318. #if ENABLE_FEATURE_CP_REFLINK
  319. # undef BTRFS_IOCTL_MAGIC
  320. # define BTRFS_IOCTL_MAGIC 0x94
  321. # undef BTRFS_IOC_CLONE
  322. # define BTRFS_IOC_CLONE _IOW (BTRFS_IOCTL_MAGIC, 9, int)
  323. if (flags & FILEUTILS_REFLINK) {
  324. retval = ioctl(dst_fd, BTRFS_IOC_CLONE, src_fd);
  325. if (retval == 0)
  326. goto do_close;
  327. /* reflink did not work */
  328. if (flags & FILEUTILS_REFLINK_ALWAYS) {
  329. bb_perror_msg("failed to clone '%s' from '%s'", dest, source);
  330. goto do_close;
  331. }
  332. /* fall through to standard copy */
  333. retval = 0;
  334. }
  335. #endif
  336. if (bb_copyfd_eof(src_fd, dst_fd) == -1)
  337. retval = -1;
  338. IF_FEATURE_CP_REFLINK(do_close:)
  339. /* Careful with writing... */
  340. if (close(dst_fd) < 0) {
  341. bb_perror_msg("error writing to '%s'", dest);
  342. retval = -1;
  343. }
  344. /* ...but read size is already checked by bb_copyfd_eof */
  345. close(src_fd);
  346. /* "cp /dev/something new_file" should not
  347. * copy mode of /dev/something */
  348. if (!S_ISREG(source_stat.st_mode))
  349. return retval;
  350. goto preserve_mode_ugid_time;
  351. }
  352. dont_cat:
  353. /* Source is a symlink or a special file */
  354. /* We are lazy here, a bit lax with races... */
  355. if (dest_exists) {
  356. errno = EEXIST;
  357. ovr = ask_and_unlink(dest, flags);
  358. if (ovr <= 0)
  359. return ovr;
  360. }
  361. if (S_ISLNK(source_stat.st_mode)) {
  362. char *lpath = xmalloc_readlink_or_warn(source);
  363. if (lpath) {
  364. int r = symlink(lpath, dest);
  365. if (r < 0) {
  366. /* shared message */
  367. bb_perror_msg("can't create %slink '%s' to '%s'",
  368. "sym", dest, lpath
  369. );
  370. free(lpath);
  371. return -1;
  372. }
  373. free(lpath);
  374. if (flags & FILEUTILS_PRESERVE_STATUS)
  375. if (lchown(dest, source_stat.st_uid, source_stat.st_gid) < 0)
  376. bb_perror_msg("can't preserve %s of '%s'", "ownership", dest);
  377. }
  378. /* _Not_ jumping to preserve_mode_ugid_time:
  379. * symlinks don't have those */
  380. goto verb_and_exit;
  381. }
  382. if (S_ISBLK(source_stat.st_mode) || S_ISCHR(source_stat.st_mode)
  383. || S_ISSOCK(source_stat.st_mode) || S_ISFIFO(source_stat.st_mode)
  384. ) {
  385. if (mknod(dest, source_stat.st_mode, source_stat.st_rdev) < 0) {
  386. bb_perror_msg("can't create '%s'", dest);
  387. return -1;
  388. }
  389. } else {
  390. bb_error_msg("unrecognized file '%s' with mode %x", source, source_stat.st_mode);
  391. return -1;
  392. }
  393. preserve_mode_ugid_time:
  394. if (flags & FILEUTILS_PRESERVE_STATUS
  395. /* Cannot happen: */
  396. /* && !(flags & (FILEUTILS_MAKE_SOFTLINK|FILEUTILS_MAKE_HARDLINK)) */
  397. ) {
  398. struct timeval times[2];
  399. times[1].tv_sec = times[0].tv_sec = source_stat.st_mtime;
  400. times[1].tv_usec = times[0].tv_usec = 0;
  401. /* BTW, utimes sets usec-precision time - just FYI */
  402. if (utimes(dest, times) < 0)
  403. bb_perror_msg("can't preserve %s of '%s'", "times", dest);
  404. if (chown(dest, source_stat.st_uid, source_stat.st_gid) < 0) {
  405. source_stat.st_mode &= ~(S_ISUID | S_ISGID);
  406. bb_perror_msg("can't preserve %s of '%s'", "ownership", dest);
  407. }
  408. if (chmod(dest, source_stat.st_mode) < 0)
  409. bb_perror_msg("can't preserve %s of '%s'", "permissions", dest);
  410. }
  411. verb_and_exit:
  412. if (flags & FILEUTILS_VERBOSE) {
  413. printf("'%s' -> '%s'\n", source, dest);
  414. }
  415. return retval;
  416. }