3
0

copy_file.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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. dest_exists = 1;
  107. }
  108. #if ENABLE_SELINUX
  109. if ((flags & FILEUTILS_PRESERVE_SECURITY_CONTEXT) && is_selinux_enabled() > 0) {
  110. security_context_t con;
  111. if (lgetfilecon(source, &con) >= 0) {
  112. if (setfscreatecon(con) < 0) {
  113. bb_perror_msg("can't set setfscreatecon %s", con);
  114. freecon(con);
  115. return -1;
  116. }
  117. } else if (errno == ENOTSUP || errno == ENODATA) {
  118. setfscreatecon_or_die(NULL);
  119. } else {
  120. bb_perror_msg("can't lgetfilecon %s", source);
  121. return -1;
  122. }
  123. }
  124. #endif
  125. if (S_ISDIR(source_stat.st_mode)) {
  126. DIR *dp;
  127. const char *tp;
  128. struct dirent *d;
  129. mode_t saved_umask = 0;
  130. if (!(flags & FILEUTILS_RECUR)) {
  131. bb_error_msg("omitting directory '%s'", source);
  132. return -1;
  133. }
  134. /* Did we ever create source ourself before? */
  135. tp = is_in_ino_dev_hashtable(&source_stat);
  136. if (tp) {
  137. /* We did! it's a recursion! man the lifeboats... */
  138. bb_error_msg("recursion detected, omitting directory '%s'",
  139. source);
  140. return -1;
  141. }
  142. if (dest_exists) {
  143. if (!S_ISDIR(dest_stat.st_mode)) {
  144. bb_error_msg("target '%s' is not a directory", dest);
  145. return -1;
  146. }
  147. /* race here: user can substitute a symlink between
  148. * this check and actual creation of files inside dest */
  149. } else {
  150. /* Create DEST */
  151. mode_t mode;
  152. saved_umask = umask(0);
  153. mode = source_stat.st_mode;
  154. if (!(flags & FILEUTILS_PRESERVE_STATUS))
  155. mode = source_stat.st_mode & ~saved_umask;
  156. /* Allow owner to access new dir (at least for now) */
  157. mode |= S_IRWXU;
  158. if (mkdir(dest, mode) < 0) {
  159. umask(saved_umask);
  160. bb_perror_msg("can't create directory '%s'", dest);
  161. return -1;
  162. }
  163. umask(saved_umask);
  164. /* need stat info for add_to_ino_dev_hashtable */
  165. if (lstat(dest, &dest_stat) < 0) {
  166. bb_perror_msg("can't stat '%s'", dest);
  167. return -1;
  168. }
  169. }
  170. /* remember (dev,inode) of each created dir.
  171. * NULL: name is not remembered */
  172. add_to_ino_dev_hashtable(&dest_stat, NULL);
  173. /* Recursively copy files in SOURCE */
  174. dp = opendir(source);
  175. if (dp == NULL) {
  176. retval = -1;
  177. goto preserve_mode_ugid_time;
  178. }
  179. while ((d = readdir(dp)) != NULL) {
  180. char *new_source, *new_dest;
  181. new_source = concat_subpath_file(source, d->d_name);
  182. if (new_source == NULL)
  183. continue;
  184. new_dest = concat_path_file(dest, d->d_name);
  185. if (copy_file(new_source, new_dest, flags & ~FILEUTILS_DEREFERENCE_L0) < 0)
  186. retval = -1;
  187. free(new_source);
  188. free(new_dest);
  189. }
  190. closedir(dp);
  191. if (!dest_exists
  192. && chmod(dest, source_stat.st_mode & ~saved_umask) < 0
  193. ) {
  194. bb_perror_msg("can't preserve %s of '%s'", "permissions", dest);
  195. /* retval = -1; - WRONG! copy *WAS* made */
  196. }
  197. goto preserve_mode_ugid_time;
  198. }
  199. if (dest_exists) {
  200. if (flags & FILEUTILS_UPDATE) {
  201. if (source_stat.st_mtime <= dest_stat.st_mtime) {
  202. return 0; /* source file must be newer */
  203. }
  204. }
  205. #if ENABLE_FEATURE_CP_LONG_OPTIONS
  206. if (flags & FILEUTILS_RMDEST) {
  207. ovr = ask_and_unlink(dest, flags);
  208. if (ovr <= 0)
  209. return ovr;
  210. dest_exists = 0;
  211. }
  212. #endif
  213. }
  214. if (flags & (FILEUTILS_MAKE_SOFTLINK|FILEUTILS_MAKE_HARDLINK)) {
  215. int (*lf)(const char *oldpath, const char *newpath);
  216. make_links:
  217. /* Hmm... maybe
  218. * if (DEREF && MAKE_SOFTLINK) source = realpath(source) ?
  219. * (but realpath returns NULL on dangling symlinks...) */
  220. lf = (flags & FILEUTILS_MAKE_SOFTLINK) ? symlink : link;
  221. if (lf(source, dest) < 0) {
  222. ovr = ask_and_unlink(dest, flags);
  223. if (ovr <= 0)
  224. return ovr;
  225. if (lf(source, dest) < 0) {
  226. bb_perror_msg("can't create link '%s'", dest);
  227. return -1;
  228. }
  229. }
  230. /* _Not_ jumping to preserve_mode_ugid_time:
  231. * (sym)links don't have those */
  232. return 0;
  233. }
  234. if (/* "cp thing1 thing2" without -R: just open and read() from thing1 */
  235. !(flags & FILEUTILS_RECUR)
  236. /* "cp [-opts] regular_file thing2" */
  237. || S_ISREG(source_stat.st_mode)
  238. /* DEREF uses stat, which never returns S_ISLNK() == true.
  239. * So the below is never true: */
  240. /* || (FLAGS_DEREF && S_ISLNK(source_stat.st_mode)) */
  241. ) {
  242. int src_fd;
  243. int dst_fd;
  244. mode_t new_mode;
  245. if (!FLAGS_DEREF && S_ISLNK(source_stat.st_mode)) {
  246. /* "cp -d symlink dst": create a link */
  247. goto dont_cat;
  248. }
  249. if (ENABLE_FEATURE_PRESERVE_HARDLINKS && !FLAGS_DEREF) {
  250. const char *link_target;
  251. link_target = is_in_ino_dev_hashtable(&source_stat);
  252. if (link_target) {
  253. if (link(link_target, dest) < 0) {
  254. ovr = ask_and_unlink(dest, flags);
  255. if (ovr <= 0)
  256. return ovr;
  257. if (link(link_target, dest) < 0) {
  258. bb_perror_msg("can't create link '%s'", dest);
  259. return -1;
  260. }
  261. }
  262. return 0;
  263. }
  264. add_to_ino_dev_hashtable(&source_stat, dest);
  265. }
  266. src_fd = open_or_warn(source, O_RDONLY);
  267. if (src_fd < 0)
  268. return -1;
  269. /* Do not try to open with weird mode fields */
  270. new_mode = source_stat.st_mode;
  271. if (!S_ISREG(source_stat.st_mode))
  272. new_mode = 0666;
  273. if (ENABLE_FEATURE_NON_POSIX_CP || (flags & FILEUTILS_INTERACTIVE)) {
  274. /*
  275. * O_CREAT|O_EXCL: require that file did not exist before creation
  276. */
  277. dst_fd = open(dest, O_WRONLY|O_CREAT|O_EXCL, new_mode);
  278. } else { /* POSIX, and not "cp -i" */
  279. /*
  280. * O_CREAT|O_TRUNC: create, or truncate (security problem versus (sym)link attacks)
  281. */
  282. dst_fd = open(dest, O_WRONLY|O_CREAT|O_TRUNC, new_mode);
  283. }
  284. if (dst_fd == -1) {
  285. ovr = ask_and_unlink(dest, flags);
  286. if (ovr <= 0) {
  287. close(src_fd);
  288. return ovr;
  289. }
  290. /* It shouldn't exist. If it exists, do not open (symlink attack?) */
  291. dst_fd = open3_or_warn(dest, O_WRONLY|O_CREAT|O_EXCL, new_mode);
  292. if (dst_fd < 0) {
  293. close(src_fd);
  294. return -1;
  295. }
  296. }
  297. #if ENABLE_SELINUX
  298. if ((flags & (FILEUTILS_PRESERVE_SECURITY_CONTEXT|FILEUTILS_SET_SECURITY_CONTEXT))
  299. && is_selinux_enabled() > 0
  300. ) {
  301. security_context_t con;
  302. if (getfscreatecon(&con) == -1) {
  303. bb_perror_msg("getfscreatecon");
  304. return -1;
  305. }
  306. if (con) {
  307. if (setfilecon(dest, con) == -1) {
  308. bb_perror_msg("setfilecon:%s,%s", dest, con);
  309. freecon(con);
  310. return -1;
  311. }
  312. freecon(con);
  313. }
  314. }
  315. #endif
  316. #if ENABLE_FEATURE_CP_REFLINK
  317. # undef BTRFS_IOCTL_MAGIC
  318. # define BTRFS_IOCTL_MAGIC 0x94
  319. # undef BTRFS_IOC_CLONE
  320. # define BTRFS_IOC_CLONE _IOW (BTRFS_IOCTL_MAGIC, 9, int)
  321. if (flags & FILEUTILS_REFLINK) {
  322. retval = ioctl(dst_fd, BTRFS_IOC_CLONE, src_fd);
  323. if (retval == 0)
  324. goto do_close;
  325. /* reflink did not work */
  326. if (flags & FILEUTILS_REFLINK_ALWAYS) {
  327. bb_perror_msg("failed to clone '%s' from '%s'", dest, source);
  328. goto do_close;
  329. }
  330. /* fall through to standard copy */
  331. retval = 0;
  332. }
  333. #endif
  334. if (bb_copyfd_eof(src_fd, dst_fd) == -1)
  335. retval = -1;
  336. IF_FEATURE_CP_REFLINK(do_close:)
  337. /* Careful with writing... */
  338. if (close(dst_fd) < 0) {
  339. bb_perror_msg("error writing to '%s'", dest);
  340. retval = -1;
  341. }
  342. /* ...but read size is already checked by bb_copyfd_eof */
  343. close(src_fd);
  344. /* "cp /dev/something new_file" should not
  345. * copy mode of /dev/something */
  346. if (!S_ISREG(source_stat.st_mode))
  347. return retval;
  348. goto preserve_mode_ugid_time;
  349. }
  350. dont_cat:
  351. /* Source is a symlink or a special file */
  352. /* We are lazy here, a bit lax with races... */
  353. if (dest_exists) {
  354. errno = EEXIST;
  355. ovr = ask_and_unlink(dest, flags);
  356. if (ovr <= 0)
  357. return ovr;
  358. }
  359. if (S_ISLNK(source_stat.st_mode)) {
  360. char *lpath = xmalloc_readlink_or_warn(source);
  361. if (lpath) {
  362. int r = symlink(lpath, dest);
  363. if (r < 0) {
  364. /* shared message */
  365. bb_perror_msg("can't create %slink '%s' to '%s'",
  366. "sym", dest, lpath
  367. );
  368. free(lpath);
  369. return -1;
  370. }
  371. free(lpath);
  372. if (flags & FILEUTILS_PRESERVE_STATUS)
  373. if (lchown(dest, source_stat.st_uid, source_stat.st_gid) < 0)
  374. bb_perror_msg("can't preserve %s of '%s'", "ownership", dest);
  375. }
  376. /* _Not_ jumping to preserve_mode_ugid_time:
  377. * symlinks don't have those */
  378. goto verb_and_exit;
  379. }
  380. if (S_ISBLK(source_stat.st_mode) || S_ISCHR(source_stat.st_mode)
  381. || S_ISSOCK(source_stat.st_mode) || S_ISFIFO(source_stat.st_mode)
  382. ) {
  383. if (mknod(dest, source_stat.st_mode, source_stat.st_rdev) < 0) {
  384. bb_perror_msg("can't create '%s'", dest);
  385. return -1;
  386. }
  387. } else {
  388. bb_error_msg("unrecognized file '%s' with mode %x", source, source_stat.st_mode);
  389. return -1;
  390. }
  391. preserve_mode_ugid_time:
  392. if (flags & FILEUTILS_PRESERVE_STATUS
  393. /* Cannot happen: */
  394. /* && !(flags & (FILEUTILS_MAKE_SOFTLINK|FILEUTILS_MAKE_HARDLINK)) */
  395. ) {
  396. struct timeval times[2];
  397. times[1].tv_sec = times[0].tv_sec = source_stat.st_mtime;
  398. times[1].tv_usec = times[0].tv_usec = 0;
  399. /* BTW, utimes sets usec-precision time - just FYI */
  400. if (utimes(dest, times) < 0)
  401. bb_perror_msg("can't preserve %s of '%s'", "times", dest);
  402. if (chown(dest, source_stat.st_uid, source_stat.st_gid) < 0) {
  403. source_stat.st_mode &= ~(S_ISUID | S_ISGID);
  404. bb_perror_msg("can't preserve %s of '%s'", "ownership", dest);
  405. }
  406. if (chmod(dest, source_stat.st_mode) < 0)
  407. bb_perror_msg("can't preserve %s of '%s'", "permissions", dest);
  408. }
  409. verb_and_exit:
  410. if (flags & FILEUTILS_VERBOSE) {
  411. printf("'%s' -> '%s'\n", source, dest);
  412. }
  413. return retval;
  414. }