copy_file.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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_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. // POSIX way is a security problem versus (sym)link attacks
  274. if (!ENABLE_FEATURE_NON_POSIX_CP) {
  275. dst_fd = open(dest, O_WRONLY|O_CREAT|O_TRUNC, new_mode);
  276. } else { /* safe way: */
  277. dst_fd = open(dest, O_WRONLY|O_CREAT|O_EXCL, new_mode);
  278. }
  279. if (dst_fd == -1) {
  280. ovr = ask_and_unlink(dest, flags);
  281. if (ovr <= 0) {
  282. close(src_fd);
  283. return ovr;
  284. }
  285. /* It shouldn't exist. If it exists, do not open (symlink attack?) */
  286. dst_fd = open3_or_warn(dest, O_WRONLY|O_CREAT|O_EXCL, new_mode);
  287. if (dst_fd < 0) {
  288. close(src_fd);
  289. return -1;
  290. }
  291. }
  292. #if ENABLE_SELINUX
  293. if ((flags & (FILEUTILS_PRESERVE_SECURITY_CONTEXT|FILEUTILS_SET_SECURITY_CONTEXT))
  294. && is_selinux_enabled() > 0
  295. ) {
  296. security_context_t con;
  297. if (getfscreatecon(&con) == -1) {
  298. bb_perror_msg("getfscreatecon");
  299. return -1;
  300. }
  301. if (con) {
  302. if (setfilecon(dest, con) == -1) {
  303. bb_perror_msg("setfilecon:%s,%s", dest, con);
  304. freecon(con);
  305. return -1;
  306. }
  307. freecon(con);
  308. }
  309. }
  310. #endif
  311. if (bb_copyfd_eof(src_fd, dst_fd) == -1)
  312. retval = -1;
  313. /* Careful with writing... */
  314. if (close(dst_fd) < 0) {
  315. bb_perror_msg("error writing to '%s'", dest);
  316. retval = -1;
  317. }
  318. /* ...but read size is already checked by bb_copyfd_eof */
  319. close(src_fd);
  320. /* "cp /dev/something new_file" should not
  321. * copy mode of /dev/something */
  322. if (!S_ISREG(source_stat.st_mode))
  323. return retval;
  324. goto preserve_mode_ugid_time;
  325. }
  326. dont_cat:
  327. /* Source is a symlink or a special file */
  328. /* We are lazy here, a bit lax with races... */
  329. if (dest_exists) {
  330. errno = EEXIST;
  331. ovr = ask_and_unlink(dest, flags);
  332. if (ovr <= 0)
  333. return ovr;
  334. }
  335. if (S_ISLNK(source_stat.st_mode)) {
  336. char *lpath = xmalloc_readlink_or_warn(source);
  337. if (lpath) {
  338. int r = symlink(lpath, dest);
  339. free(lpath);
  340. if (r < 0) {
  341. bb_perror_msg("can't create symlink '%s'", dest);
  342. return -1;
  343. }
  344. if (flags & FILEUTILS_PRESERVE_STATUS)
  345. if (lchown(dest, source_stat.st_uid, source_stat.st_gid) < 0)
  346. bb_perror_msg("can't preserve %s of '%s'", "ownership", dest);
  347. }
  348. /* _Not_ jumping to preserve_mode_ugid_time:
  349. * symlinks don't have those */
  350. return 0;
  351. }
  352. if (S_ISBLK(source_stat.st_mode) || S_ISCHR(source_stat.st_mode)
  353. || S_ISSOCK(source_stat.st_mode) || S_ISFIFO(source_stat.st_mode)
  354. ) {
  355. if (mknod(dest, source_stat.st_mode, source_stat.st_rdev) < 0) {
  356. bb_perror_msg("can't create '%s'", dest);
  357. return -1;
  358. }
  359. } else {
  360. bb_error_msg("unrecognized file '%s' with mode %x", source, source_stat.st_mode);
  361. return -1;
  362. }
  363. preserve_mode_ugid_time:
  364. if (flags & FILEUTILS_PRESERVE_STATUS
  365. /* Cannot happen: */
  366. /* && !(flags & (FILEUTILS_MAKE_SOFTLINK|FILEUTILS_MAKE_HARDLINK)) */
  367. ) {
  368. struct timeval times[2];
  369. times[1].tv_sec = times[0].tv_sec = source_stat.st_mtime;
  370. times[1].tv_usec = times[0].tv_usec = 0;
  371. /* BTW, utimes sets usec-precision time - just FYI */
  372. if (utimes(dest, times) < 0)
  373. bb_perror_msg("can't preserve %s of '%s'", "times", dest);
  374. if (chown(dest, source_stat.st_uid, source_stat.st_gid) < 0) {
  375. source_stat.st_mode &= ~(S_ISUID | S_ISGID);
  376. bb_perror_msg("can't preserve %s of '%s'", "ownership", dest);
  377. }
  378. if (chmod(dest, source_stat.st_mode) < 0)
  379. bb_perror_msg("can't preserve %s of '%s'", "permissions", dest);
  380. }
  381. if (flags & FILEUTILS_VERBOSE) {
  382. printf("'%s' -> '%s'\n", source, dest);
  383. }
  384. return retval;
  385. }