copy_file.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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. return 1; /* ok (to try again) */
  64. }
  65. /* Return:
  66. * -1 error, copy not made
  67. * 0 copy is made or user answered "no" in interactive mode
  68. * (failures to preserve mode/owner/times are not reported in exit code)
  69. */
  70. int FAST_FUNC copy_file(const char *source, const char *dest, int flags)
  71. {
  72. /* This is a recursive function, try to minimize stack usage */
  73. /* NB: each struct stat is ~100 bytes */
  74. struct stat source_stat;
  75. struct stat dest_stat;
  76. smallint retval = 0;
  77. smallint dest_exists = 0;
  78. smallint ovr;
  79. /* Inverse of cp -d ("cp without -d") */
  80. #define FLAGS_DEREF (flags & (FILEUTILS_DEREFERENCE + FILEUTILS_DEREFERENCE_L0))
  81. if ((FLAGS_DEREF ? stat : lstat)(source, &source_stat) < 0) {
  82. /* This may be a dangling symlink.
  83. * Making [sym]links to dangling symlinks works, so... */
  84. if (flags & (FILEUTILS_MAKE_SOFTLINK|FILEUTILS_MAKE_HARDLINK))
  85. goto make_links;
  86. bb_perror_msg("can't stat '%s'", source);
  87. return -1;
  88. }
  89. if (lstat(dest, &dest_stat) < 0) {
  90. if (errno != ENOENT) {
  91. bb_perror_msg("can't stat '%s'", dest);
  92. return -1;
  93. }
  94. } else {
  95. if (source_stat.st_dev == dest_stat.st_dev
  96. && source_stat.st_ino == dest_stat.st_ino
  97. ) {
  98. bb_error_msg("'%s' and '%s' are the same file", source, dest);
  99. return -1;
  100. }
  101. dest_exists = 1;
  102. }
  103. #if ENABLE_SELINUX
  104. if ((flags & FILEUTILS_PRESERVE_SECURITY_CONTEXT) && is_selinux_enabled() > 0) {
  105. security_context_t con;
  106. if (lgetfilecon(source, &con) >= 0) {
  107. if (setfscreatecon(con) < 0) {
  108. bb_perror_msg("can't set setfscreatecon %s", con);
  109. freecon(con);
  110. return -1;
  111. }
  112. } else if (errno == ENOTSUP || errno == ENODATA) {
  113. setfscreatecon_or_die(NULL);
  114. } else {
  115. bb_perror_msg("can't lgetfilecon %s", source);
  116. return -1;
  117. }
  118. }
  119. #endif
  120. if (S_ISDIR(source_stat.st_mode)) {
  121. DIR *dp;
  122. const char *tp;
  123. struct dirent *d;
  124. mode_t saved_umask = 0;
  125. if (!(flags & FILEUTILS_RECUR)) {
  126. bb_error_msg("omitting directory '%s'", source);
  127. return -1;
  128. }
  129. /* Did we ever create source ourself before? */
  130. tp = is_in_ino_dev_hashtable(&source_stat);
  131. if (tp) {
  132. /* We did! it's a recursion! man the lifeboats... */
  133. bb_error_msg("recursion detected, omitting directory '%s'",
  134. source);
  135. return -1;
  136. }
  137. if (dest_exists) {
  138. if (!S_ISDIR(dest_stat.st_mode)) {
  139. bb_error_msg("target '%s' is not a directory", dest);
  140. return -1;
  141. }
  142. /* race here: user can substitute a symlink between
  143. * this check and actual creation of files inside dest */
  144. } else {
  145. /* Create DEST */
  146. mode_t mode;
  147. saved_umask = umask(0);
  148. mode = source_stat.st_mode;
  149. if (!(flags & FILEUTILS_PRESERVE_STATUS))
  150. mode = source_stat.st_mode & ~saved_umask;
  151. /* Allow owner to access new dir (at least for now) */
  152. mode |= S_IRWXU;
  153. if (mkdir(dest, mode) < 0) {
  154. umask(saved_umask);
  155. bb_perror_msg("can't create directory '%s'", dest);
  156. return -1;
  157. }
  158. umask(saved_umask);
  159. /* need stat info for add_to_ino_dev_hashtable */
  160. if (lstat(dest, &dest_stat) < 0) {
  161. bb_perror_msg("can't stat '%s'", dest);
  162. return -1;
  163. }
  164. }
  165. /* remember (dev,inode) of each created dir.
  166. * NULL: name is not remembered */
  167. add_to_ino_dev_hashtable(&dest_stat, NULL);
  168. /* Recursively copy files in SOURCE */
  169. dp = opendir(source);
  170. if (dp == NULL) {
  171. retval = -1;
  172. goto preserve_mode_ugid_time;
  173. }
  174. while ((d = readdir(dp)) != NULL) {
  175. char *new_source, *new_dest;
  176. new_source = concat_subpath_file(source, d->d_name);
  177. if (new_source == NULL)
  178. continue;
  179. new_dest = concat_path_file(dest, d->d_name);
  180. if (copy_file(new_source, new_dest, flags & ~FILEUTILS_DEREFERENCE_L0) < 0)
  181. retval = -1;
  182. free(new_source);
  183. free(new_dest);
  184. }
  185. closedir(dp);
  186. if (!dest_exists
  187. && chmod(dest, source_stat.st_mode & ~saved_umask) < 0
  188. ) {
  189. bb_perror_msg("can't preserve %s of '%s'", "permissions", dest);
  190. /* retval = -1; - WRONG! copy *WAS* made */
  191. }
  192. goto preserve_mode_ugid_time;
  193. }
  194. if (flags & (FILEUTILS_MAKE_SOFTLINK|FILEUTILS_MAKE_HARDLINK)) {
  195. int (*lf)(const char *oldpath, const char *newpath);
  196. make_links:
  197. /* Hmm... maybe
  198. * if (DEREF && MAKE_SOFTLINK) source = realpath(source) ?
  199. * (but realpath returns NULL on dangling symlinks...) */
  200. lf = (flags & FILEUTILS_MAKE_SOFTLINK) ? symlink : link;
  201. if (lf(source, dest) < 0) {
  202. ovr = ask_and_unlink(dest, flags);
  203. if (ovr <= 0)
  204. return ovr;
  205. if (lf(source, dest) < 0) {
  206. bb_perror_msg("can't create link '%s'", dest);
  207. return -1;
  208. }
  209. }
  210. /* _Not_ jumping to preserve_mode_ugid_time:
  211. * (sym)links don't have those */
  212. return 0;
  213. }
  214. if (/* "cp thing1 thing2" without -R: just open and read() from thing1 */
  215. !(flags & FILEUTILS_RECUR)
  216. /* "cp [-opts] regular_file thing2" */
  217. || S_ISREG(source_stat.st_mode)
  218. /* DEREF uses stat, which never returns S_ISLNK() == true.
  219. * So the below is never true: */
  220. /* || (FLAGS_DEREF && S_ISLNK(source_stat.st_mode)) */
  221. ) {
  222. int src_fd;
  223. int dst_fd;
  224. mode_t new_mode;
  225. if (!FLAGS_DEREF && S_ISLNK(source_stat.st_mode)) {
  226. /* "cp -d symlink dst": create a link */
  227. goto dont_cat;
  228. }
  229. if (ENABLE_FEATURE_PRESERVE_HARDLINKS && !FLAGS_DEREF) {
  230. const char *link_target;
  231. link_target = is_in_ino_dev_hashtable(&source_stat);
  232. if (link_target) {
  233. if (link(link_target, dest) < 0) {
  234. ovr = ask_and_unlink(dest, flags);
  235. if (ovr <= 0)
  236. return ovr;
  237. if (link(link_target, dest) < 0) {
  238. bb_perror_msg("can't create link '%s'", dest);
  239. return -1;
  240. }
  241. }
  242. return 0;
  243. }
  244. add_to_ino_dev_hashtable(&source_stat, dest);
  245. }
  246. src_fd = open_or_warn(source, O_RDONLY);
  247. if (src_fd < 0)
  248. return -1;
  249. /* Do not try to open with weird mode fields */
  250. new_mode = source_stat.st_mode;
  251. if (!S_ISREG(source_stat.st_mode))
  252. new_mode = 0666;
  253. // POSIX way is a security problem versus (sym)link attacks
  254. if (!ENABLE_FEATURE_NON_POSIX_CP) {
  255. dst_fd = open(dest, O_WRONLY|O_CREAT|O_TRUNC, new_mode);
  256. } else { /* safe way: */
  257. dst_fd = open(dest, O_WRONLY|O_CREAT|O_EXCL, new_mode);
  258. }
  259. if (dst_fd == -1) {
  260. ovr = ask_and_unlink(dest, flags);
  261. if (ovr <= 0) {
  262. close(src_fd);
  263. return ovr;
  264. }
  265. /* It shouldn't exist. If it exists, do not open (symlink attack?) */
  266. dst_fd = open3_or_warn(dest, O_WRONLY|O_CREAT|O_EXCL, new_mode);
  267. if (dst_fd < 0) {
  268. close(src_fd);
  269. return -1;
  270. }
  271. }
  272. #if ENABLE_SELINUX
  273. if ((flags & (FILEUTILS_PRESERVE_SECURITY_CONTEXT|FILEUTILS_SET_SECURITY_CONTEXT))
  274. && is_selinux_enabled() > 0
  275. ) {
  276. security_context_t con;
  277. if (getfscreatecon(&con) == -1) {
  278. bb_perror_msg("getfscreatecon");
  279. return -1;
  280. }
  281. if (con) {
  282. if (setfilecon(dest, con) == -1) {
  283. bb_perror_msg("setfilecon:%s,%s", dest, con);
  284. freecon(con);
  285. return -1;
  286. }
  287. freecon(con);
  288. }
  289. }
  290. #endif
  291. if (bb_copyfd_eof(src_fd, dst_fd) == -1)
  292. retval = -1;
  293. /* Careful with writing... */
  294. if (close(dst_fd) < 0) {
  295. bb_perror_msg("error writing to '%s'", dest);
  296. retval = -1;
  297. }
  298. /* ...but read size is already checked by bb_copyfd_eof */
  299. close(src_fd);
  300. /* "cp /dev/something new_file" should not
  301. * copy mode of /dev/something */
  302. if (!S_ISREG(source_stat.st_mode))
  303. return retval;
  304. goto preserve_mode_ugid_time;
  305. }
  306. dont_cat:
  307. /* Source is a symlink or a special file */
  308. /* We are lazy here, a bit lax with races... */
  309. if (dest_exists) {
  310. errno = EEXIST;
  311. ovr = ask_and_unlink(dest, flags);
  312. if (ovr <= 0)
  313. return ovr;
  314. }
  315. if (S_ISLNK(source_stat.st_mode)) {
  316. char *lpath = xmalloc_readlink_or_warn(source);
  317. if (lpath) {
  318. int r = symlink(lpath, dest);
  319. free(lpath);
  320. if (r < 0) {
  321. bb_perror_msg("can't create symlink '%s'", dest);
  322. return -1;
  323. }
  324. if (flags & FILEUTILS_PRESERVE_STATUS)
  325. if (lchown(dest, source_stat.st_uid, source_stat.st_gid) < 0)
  326. bb_perror_msg("can't preserve %s of '%s'", "ownership", dest);
  327. }
  328. /* _Not_ jumping to preserve_mode_ugid_time:
  329. * symlinks don't have those */
  330. return 0;
  331. }
  332. if (S_ISBLK(source_stat.st_mode) || S_ISCHR(source_stat.st_mode)
  333. || S_ISSOCK(source_stat.st_mode) || S_ISFIFO(source_stat.st_mode)
  334. ) {
  335. if (mknod(dest, source_stat.st_mode, source_stat.st_rdev) < 0) {
  336. bb_perror_msg("can't create '%s'", dest);
  337. return -1;
  338. }
  339. } else {
  340. bb_error_msg("unrecognized file '%s' with mode %x", source, source_stat.st_mode);
  341. return -1;
  342. }
  343. preserve_mode_ugid_time:
  344. if (flags & FILEUTILS_PRESERVE_STATUS
  345. /* Cannot happen: */
  346. /* && !(flags & (FILEUTILS_MAKE_SOFTLINK|FILEUTILS_MAKE_HARDLINK)) */
  347. ) {
  348. struct timeval times[2];
  349. times[1].tv_sec = times[0].tv_sec = source_stat.st_mtime;
  350. times[1].tv_usec = times[0].tv_usec = 0;
  351. /* BTW, utimes sets usec-precision time - just FYI */
  352. if (utimes(dest, times) < 0)
  353. bb_perror_msg("can't preserve %s of '%s'", "times", dest);
  354. if (chown(dest, source_stat.st_uid, source_stat.st_gid) < 0) {
  355. source_stat.st_mode &= ~(S_ISUID | S_ISGID);
  356. bb_perror_msg("can't preserve %s of '%s'", "ownership", dest);
  357. }
  358. if (chmod(dest, source_stat.st_mode) < 0)
  359. bb_perror_msg("can't preserve %s of '%s'", "permissions", dest);
  360. }
  361. if (flags & FILEUTILS_VERBOSE) {
  362. printf("'%s' -> '%s'\n", source, dest);
  363. }
  364. return retval;
  365. }