Debian Codegraph @

file_subs.c

raw symbols SCIP
1 /* $OpenBSD: file_subs.c,v 1.53 2017/01/21 08:17:06 krw Exp $ */
2 /* $NetBSD: file_subs.c,v 1.4 1995/03/21 09:07:18 cgd Exp $ */
3
4 /*-
5 * Copyright (c) 2007, 2008, 2009, 2012, 2014, 2016, 2018, 2019, 2024
6 * mirabilos <[email protected]>
7 * Copyright (c) 2018
8 * Jonathan de Boyne Pollard <[email protected]>
9 * mirabilos <[email protected]>
10 * Copyright (c) 2011
11 * Svante Signell <[email protected]>
12 * Copyright (c) 1992 Keith Muller.
13 * Copyright (c) 1992, 1993
14 * The Regents of the University of California. All rights reserved.
15 *
16 * This code is derived from software contributed to Berkeley by
17 * Keith Muller of the University of California, San Diego.
18 *
19 * Redistribution and use in source and binary forms, with or without
20 * modification, are permitted provided that the following conditions
21 * are met:
22 * 1. Redistributions of source code must retain the above copyright
23 * notice, this list of conditions and the following disclaimer.
24 * 2. Redistributions in binary form must reproduce the above copyright
25 * notice, this list of conditions and the following disclaimer in the
26 * documentation and/or other materials provided with the distribution.
27 * 3. Neither the name of the University nor the names of its contributors
28 * may be used to endorse or promote products derived from this software
29 * without specific prior written permission.
30 *
31 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
32 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
33 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
34 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
35 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
36 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
37 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
38 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
39 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
40 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
41 * SUCH DAMAGE.
42 */
43
44 #include <sys/stat.h>
45 #if HAVE_BOTH_TIME_H
46 #include <sys/time.h>
47 #include <time.h>
48 #elif HAVE_SYS_TIME_H
49 #include <sys/time.h>
50 #elif HAVE_TIME_H
51 #include <time.h>
52 #endif
53 #include <err.h>
54 #include <errno.h>
55 #include <fcntl.h>
56 #include <limits.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #if HAVE_STRINGS_H
61 #include <strings.h>
62 #endif
63 #include <unistd.h>
64 #if HAVE_UTIME_H
65 #include <utime.h>
66 #endif
67
68 #include "pax.h"
69 #define EXTERN
70 #include "ftimes.h"
71 #undef EXTERN
72 #include "extern.h"
73
74 __RCSID("$MirOS: src/bin/pax/file_subs.c,v 1.33 2024/08/17 23:33:51 tg Exp $");
75
76 /*
77 * routines that deal with file operations such as: creating, removing;
78 * and setting access modes, uid/gid and times of files
79 */
80
81 #if HAVE_FUTIMENS || HAVE_FUTIMES
82 #define PAX_FSET_FTIME
83 #endif
84
85 static int mk_link(char *, struct stat *, char *, int);
86 #ifdef PAX_FSET_FTIME
87 static void fset_ftime(const char *, int, const struct stat *, int);
88 #endif
89
90 /*
91 * file_creat()
92 * Create and open a file.
93 * Return:
94 * file descriptor or -1 for failure
95 */
96
97 int
98 file_creat(ARCHD *arcn)
99 {
100 int fd = -1;
101 mode_t file_mode;
102 int oerrno;
103
104 /*
105 * Assume file doesn't exist, so just try to create it, most times this
106 * works. We have to take special handling when the file does exist. To
107 * detect this, we use O_EXCL. For example when trying to create a
108 * file and a character device or FIFO exists with the same name, we
109 * can accidently open the device by mistake (or block waiting to open).
110 * If we find that the open has failed, then spend the effort to
111 * figure out why. This strategy was found to have better average
112 * performance in common use than checking the file (and the path)
113 * first with lstat.
114 */
115 file_mode = arcn->sb.st_mode & FILEBITS;
116 if ((fd = binopen3(0, arcn->name, O_WRONLY | O_CREAT | O_EXCL,
117 file_mode)) >= 0)
118 return (fd);
119
120 /*
121 * the file seems to exist. First we try to get rid of it (found to be
122 * the second most common failure when traced). If this fails, only
123 * then we go to the expense to check and create the path to the file
124 */
125 if (unlnk_exist(arcn->name, arcn->type) != 0)
126 return(-1);
127
128 for (;;) {
129 /*
130 * try to open it again, if this fails, check all the nodes in
131 * the path and give it a final try. if chk_path() finds that
132 * it cannot fix anything, we will skip the last attempt
133 */
134 if ((fd = binopen3(0, arcn->name, O_WRONLY | O_CREAT | O_TRUNC,
135 file_mode)) >= 0)
136 break;
137 oerrno = errno;
138 if (nodirs || chk_path(arcn->name,arcn->sb.st_uid,arcn->sb.st_gid) < 0) {
139 syswarn(1, oerrno, "Unable to create %s", arcn->name);
140 return(-1);
141 }
142 }
143 return(fd);
144 }
145
146 /*
147 * file_close()
148 * Close file descriptor to a file just created by pax. Sets modes,
149 * ownership and times as required.
150 * Return:
151 * 0 for success, -1 for failure
152 */
153
154 void
155 file_close(ARCHD *arcn, int fd)
156 {
157 int res = 0;
158
159 if (fd < 0)
160 return;
161
162 /*
163 * set owner/groups first as this may strip off mode bits we want
164 * then set file permission modes. Then set file access and
165 * modification times.
166 */
167 if (pids)
168 res = fset_ids(arcn->name, fd, arcn->sb.st_uid,
169 arcn->sb.st_gid);
170
171 /*
172 * IMPORTANT SECURITY NOTE:
173 * if not preserving mode or we cannot set uid/gid, then PROHIBIT
174 * set uid/gid bits
175 */
176 if (!pmode || res)
177 arcn->sb.st_mode &= ~(SETBITS);
178 if (pmode)
179 fset_pmode(arcn->name, fd, arcn->sb.st_mode);
180 #ifdef PAX_FSET_FTIME
181 if (patime || pmtime)
182 fset_ftime(arcn->name, fd, &arcn->sb, 0);
183 #endif
184 if (close(fd) < 0)
185 syswarn(0, errno, "Unable to close file descriptor on %s",
186 arcn->name);
187 }
188
189 /*
190 * lnk_creat()
191 * Create a hard link to arcn->ln_name from arcn->name. arcn->ln_name
192 * must exist;
193 * Return:
194 * fd+2 if data should be extracted,
195 * 0 if ok, 1 if we could not make the link, -1 otherwise
196 */
197
198 int
199 lnk_creat(ARCHD *arcn, int *fdp)
200 {
201 struct stat sb;
202 int res;
203
204 /*
205 * we may be running as root, so we have to be sure that link target
206 * is not a directory, so we lstat and check
207 */
208 if (lstat(arcn->ln_name, &sb) < 0) {
209 syswarn(1, errno, "Unable to link to %s from %s",
210 arcn->ln_name, arcn->name);
211 return (-1);
212 }
213
214 if (S_ISDIR(sb.st_mode)) {
215 paxwarn(1, "A hard link to the directory %s is not allowed",
216 arcn->ln_name);
217 return(-1);
218 }
219
220 res = mk_link(arcn->ln_name, &sb, arcn->name, 0);
221 if (res == 0) {
222 /* check for a hardlink to a placeholder symlink */
223 res = sltab_add_link(arcn->name, &sb);
224
225 if (res < 0) {
226 /* arrgh, it failed, clean up */
227 unlink(arcn->name);
228 }
229 }
230
231 if (fdp != NULL && res == 0 && sb.st_size == 0 && arcn->skip > 0) {
232 /* request to write out file data late (broken archive) */
233 if (pmode)
234 set_pmode(arcn->name, 0600, /*XXX I think */ 0);
235 if ((*fdp = binopen2(0, arcn->name, O_WRONLY | O_TRUNC)) == -1) {
236 res = errno;
237 syswarn(1, res, "Unable to re-open %s", arcn->name);
238 if (pmode)
239 set_pmode(arcn->name, sb.st_mode, 0);
240 }
241 res = 0;
242 } else if (fdp != NULL)
243 *fdp = -1;
244 return (res);
245 }
246
247 /*
248 * cross_lnk()
249 * Create a hard link to arcn->org_name from arcn->name. Only used in copy
250 * with the -l flag. No warning or error if this does not succeed (we will
251 * then just create the file)
252 * Return:
253 * 1 if copy() should try to create this file node
254 * 0 if cross_lnk() ok, -1 for fatal flaw (like linking to self).
255 */
256
257 int
258 cross_lnk(ARCHD *arcn)
259 {
260 /*
261 * try to make a link to original file (-l flag in copy mode). make
262 * sure we do not try to link to directories in case we are running as
263 * root (and it might succeed).
264 */
265 if (arcn->type == PAX_DIR)
266 return(1);
267 return(mk_link(arcn->org_name, &(arcn->sb), arcn->name, 1));
268 }
269
270 /*
271 * chk_same()
272 * In copy mode if we are not trying to make hard links between the src
273 * and destinations, make sure we are not going to overwrite ourselves by
274 * accident. This slows things down a little, but we have to protect all
275 * those people who make typing errors.
276 * Return:
277 * 1 the target does not exist, go ahead and copy
278 * 0 skip it file exists (-k) or may be the same as source file
279 */
280
281 int
282 chk_same(ARCHD *arcn)
283 {
284 struct stat sb;
285
286 /*
287 * if file does not exist, return. if file exists and -k, skip it
288 * quietly
289 */
290 if (lstat(arcn->name, &sb) < 0)
291 return(1);
292 if (kflag)
293 return(0);
294
295 /*
296 * better make sure the user does not have src == dest by mistake
297 */
298 if ((arcn->sb.st_dev == sb.st_dev) && (arcn->sb.st_ino == sb.st_ino)) {
299 paxwarn(1, "Unable to copy %s, file would overwrite itself",
300 arcn->name);
301 return(0);
302 }
303 return(1);
304 }
305
306 /*
307 * helper function to copy a symbolic link
308 */
309
310 static int
311 mk_link_symlink(const char *to, const char *from)
312 {
313 int cnt;
314 char buf[PAXPATHLEN + 1];
315
316 if ((cnt = readlink(to, buf, PAXPATHLEN)) < 0)
317 return (-1);
318 /* cf. comment in ftree.c:next_file() */
319 buf[cnt] = '\0';
320 return (symlink(buf, from));
321 }
322
323 /*
324 * mk_link()
325 * try to make a hard link between two files. if ign set, we do not
326 * complain.
327 * Return:
328 * 0 if successful (or we are done with this file but no error, such as
329 * finding the from file exists and the user has set -k).
330 * 1 when ign was set to indicates we could not make the link but we
331 * should try to copy/extract the file as that might work (and is an
332 * allowed option). -1 an error occurred.
333 */
334
335 static int
336 mk_link(char *to, struct stat *to_sb, char *from, int ign)
337 {
338 struct stat sb;
339 int oerrno;
340
341 /*
342 * if from file exists, it has to be unlinked to make the link. If the
343 * file exists and -k is set, skip it quietly
344 */
345 if (lstat(from, &sb) == 0) {
346 if (kflag)
347 return(0);
348
349 /*
350 * make sure it is not the same file, protect the user
351 */
352 if ((to_sb->st_dev==sb.st_dev)&&(to_sb->st_ino == sb.st_ino)) {
353 paxwarn(1, "Unable to link file %s to itself", to);
354 return(-1);
355 }
356
357 /*
358 * try to get rid of the file, based on the type
359 */
360 if (S_ISDIR(sb.st_mode)) {
361 if (rmdir(from) < 0) {
362 syswarn(1, errno, "Unable to remove %s", from);
363 return(-1);
364 }
365 delete_dir(sb.st_dev, sb.st_ino);
366 } else if (unlink(from) < 0) {
367 if (!ign) {
368 syswarn(1, errno, "Unable to remove %s", from);
369 return(-1);
370 }
371 return(1);
372 }
373 }
374
375 /*
376 * from file is gone (or did not exist), try to make the hard link.
377 * if it fails, check the path and try it again (if chk_path() says to
378 * try again)
379 */
380 for (;;) {
381 #if HAVE_LINKAT
382 if (linkat(AT_FDCWD, to, AT_FDCWD, from, 0) == 0)
383 #else
384 if (link(to, from) == 0)
385 #endif
386 break;
387 oerrno = errno;
388 if (S_ISLNK(to_sb->st_mode)) {
389 /* just copy the symlink */
390 if (mk_link_symlink(to, from) == 0)
391 break;
392 }
393 if (!nodirs && chk_path(from, to_sb->st_uid, to_sb->st_gid) == 0)
394 continue;
395 /*-
396 * non-standard (via -M lncp) cross-device link handling:
397 * copy if hard link fails (but what if there are several
398 * links for the same file mixed between several devices?
399 * this code copies for all non-original devices, instead
400 * of tracking them and linking between them on their re-
401 * spective target device)
402 */
403 if (oerrno == EXDEV && (anonarch & ANON_LNCP)) {
404 int fdsrc, fddest;
405 ARCHD tarcn;
406
407 if ((fdsrc = binopen3(0, to, O_RDONLY, 0)) < 0) {
408 if (!ign)
409 syswarn(1, errno,
410 "Unable to open %s to read", to);
411 goto lncp_failed;
412 }
413 strlcpy(tarcn.name, from, sizeof(tarcn.name));
414 memcpy(&tarcn.sb, to_sb, sizeof(struct stat));
415 tarcn.type = PAX_REG; /* XXX */
416 tarcn.org_name = to;
417 if ((fddest = file_creat(&tarcn)) < 0) {
418 rdfile_close(&tarcn, &fdsrc);
419 goto lncp_failed;
420 }
421 cp_file(&tarcn, fdsrc, fddest);
422 file_close(&tarcn, fddest);
423 rdfile_close(&tarcn, &fdsrc);
424 /* file copied successfully, continue on */
425 break;
426 }
427 if (!ign) {
428 lncp_failed:
429 syswarn(1, oerrno, "Unable to link to %s from %s",
430 to, from);
431 return (-1);
432 }
433 return (1);
434 }
435
436 /*
437 * all right the link was made
438 */
439 return (0);
440 }
441
442 /*
443 * node_creat()
444 * create an entry in the filesystem (other than a file or hard link).
445 * If successful, sets uid/gid modes and times as required.
446 * Return:
447 * 0 if ok, -1 otherwise
448 */
449
450 int
451 node_creat(ARCHD *arcn)
452 {
453 int res;
454 int ign = 0;
455 int oerrno;
456 int pass = 0;
457 mode_t file_mode;
458 struct stat sb;
459 char *allocd = NULL;
460 char *nm = arcn->name;
461 int len, defer_pmode = 0;
462
463 /*
464 * create node based on type, if that fails try to unlink the node and
465 * try again. finally check the path and try again. As noted in the
466 * file and link creation routines, this method seems to exhibit the
467 * best performance in general use workloads.
468 */
469 file_mode = arcn->sb.st_mode & FILEBITS;
470
471 for (;;) {
472 switch (arcn->type) {
473 case PAX_DIR:
474 /*
475 * If -h (or -L) was given in tar-mode, follow the
476 * potential symlink chain before trying to create the
477 * directory.
478 */
479 if (op_mode == OP_TAR && Lflag) {
480 while (lstat(nm, &sb) == 0 &&
481 S_ISLNK(sb.st_mode)) {
482 char *target = malloc(sb.st_size + 1);
483 if (target == NULL) {
484 free(allocd);
485 oerrno = ENOMEM;
486 syswarn(1, oerrno,
487 "Out of memory");
488 return (-1);
489 }
490 len = readlink(nm, target,
491 sb.st_size + 1);
492 if (len == -1) {
493 syswarn(0, errno,
494 "cannot follow symlink %s in chain for %s",
495 nm, arcn->name);
496 res = -1;
497 goto badlink;
498 }
499 target[len] = '\0';
500 nm = target;
501 free(allocd);
502 allocd = target;
503 }
504 }
505 res = mkdir(nm, file_mode);
506
507 badlink:
508 if (ign)
509 res = 0;
510 break;
511 case PAX_CHR:
512 file_mode |= S_IFCHR;
513 res = mknod(nm, file_mode, arcn->sb.st_rdev);
514 break;
515 case PAX_BLK:
516 file_mode |= S_IFBLK;
517 res = mknod(nm, file_mode, arcn->sb.st_rdev);
518 break;
519 case PAX_FIF:
520 res = mkfifo(nm, file_mode);
521 break;
522 case PAX_SCK:
523 /*
524 * Skip sockets, operation has no meaning under BSD
525 */
526 paxwarn(0,
527 "%s skipped. Sockets cannot be copied or extracted",
528 nm);
529 free(allocd);
530 return (-1);
531 case PAX_SLK:
532 if (arcn->ln_name[0] != '/' &&
533 !has_dotdot(arcn->ln_name))
534 res = symlink(arcn->ln_name, nm);
535 else {
536 /*
537 * absolute symlinks and symlinks with ".."
538 * have to be deferred to prevent the archive
539 * from bootstrapping itself to outside the
540 * working directory.
541 */
542 res = sltab_add_sym(nm, arcn->ln_name,
543 arcn->sb.st_mode);
544 if (res == 0)
545 defer_pmode = 1;
546 }
547 break;
548 case PAX_CTG:
549 case PAX_HLK:
550 case PAX_HRG:
551 case PAX_REG:
552 default:
553 /*
554 * we should never get here
555 */
556 paxwarn(0, "%s has an unknown file type, skipping",
557 nm);
558 free(allocd);
559 return (-1);
560 }
561
562 /*
563 * if we were able to create the node break out of the loop,
564 * otherwise try to unlink the node and try again. if that
565 * fails check the full path and try a final time.
566 */
567 if (res == 0)
568 break;
569
570 /*
571 * we failed to make the node
572 */
573 oerrno = errno;
574 if ((ign = unlnk_exist(nm, arcn->type)) < 0) {
575 free(allocd);
576 return (-1);
577 }
578
579 if (++pass <= 1)
580 continue;
581
582 if (nodirs || chk_path(nm,arcn->sb.st_uid,arcn->sb.st_gid) < 0) {
583 syswarn(1, oerrno, "Unable to create %s", nm);
584 free(allocd);
585 return (-1);
586 }
587 }
588
589 /*
590 * we were able to create the node. set uid/gid, modes and times
591 */
592 if (pids)
593 res = set_ids(nm, arcn->sb.st_uid, arcn->sb.st_gid,
594 arcn->type == PAX_SLK);
595 else
596 res = 0;
597
598 /*
599 * IMPORTANT SECURITY NOTE:
600 * if not preserving mode or we cannot set uid/gid, then PROHIBIT any
601 * set uid/gid bits
602 */
603 if (!pmode || res)
604 arcn->sb.st_mode &= ~(SETBITS);
605 if (pmode && !defer_pmode)
606 set_pmode(nm, arcn->sb.st_mode, arcn->type == PAX_SLK);
607
608 if (arcn->type == PAX_DIR && op_mode != OP_CPIO) {
609 /*
610 * Dirs must be processed again at end of extract to set times
611 * and modes to agree with those stored in the archive. However
612 * to allow extract to continue, we may have to also set owner
613 * rights. This allows nodes in the archive that are children
614 * of this directory to be extracted without failure. Both time
615 * and modes will be fixed after the entire archive is read and
616 * before pax exits. To do that safely, we want the dev+ino
617 * of the directory we created.
618 */
619 if (lstat(nm, &sb) < 0) {
620 syswarn(0, errno, "Unable to stat %s", nm);
621 } else if (access(nm, R_OK | W_OK | X_OK) < 0) {
622 /*
623 * We have to add rights to the dir, so we make
624 * sure to restore the mode. The mode must be
625 * restored AS CREATED and not as stored if
626 * pmode is not set.
627 */
628 set_pmode(nm,
629 ((sb.st_mode & FILEBITS) | S_IRWXU), 0);
630 if (!pmode)
631 arcn->sb.st_mode = sb.st_mode;
632
633 /*
634 * we have to force the mode to what was set
635 * here, since we changed it from the default
636 * as created.
637 */
638 arcn->sb.st_dev = sb.st_dev;
639 arcn->sb.st_ino = sb.st_ino;
640 add_dir(nm, &(arcn->sb), 1);
641 } else if (pmode || patime || pmtime) {
642 arcn->sb.st_dev = sb.st_dev;
643 arcn->sb.st_ino = sb.st_ino;
644 add_dir(nm, &(arcn->sb), 0);
645 }
646 } else if (patime || pmtime)
647 set_ftime(nm, &arcn->sb, 0, arcn->type == PAX_SLK);
648 free(allocd);
649 return (0);
650 }
651
652 /*
653 * unlnk_exist()
654 * Remove node from filesystem with the specified name. We pass the type
655 * of the node that is going to replace it. When we try to create a
656 * directory and find that it already exists, we allow processing to
657 * continue as proper modes etc will always be set for it later on.
658 * Return:
659 * 0 is ok to proceed, no file with the specified name exists
660 * -1 we were unable to remove the node, or we should not remove it (-k)
661 * 1 we found a directory and we were going to create a directory.
662 */
663
664 int
665 unlnk_exist(char *name, int type)
666 {
667 struct stat sb;
668
669 /*
670 * the file does not exist, or -k we are done
671 */
672 if (lstat(name, &sb) < 0)
673 return(0);
674 if (kflag)
675 return(-1);
676
677 if (S_ISDIR(sb.st_mode)) {
678 /*
679 * try to remove a directory, if it fails and we were going to
680 * create a directory anyway, tell the caller (return a 1)
681 */
682 if (rmdir(name) < 0) {
683 if (type == PAX_DIR)
684 return(1);
685 syswarn(1,errno,"Unable to remove directory %s", name);
686 return(-1);
687 }
688 delete_dir(sb.st_dev, sb.st_ino);
689 return(0);
690 }
691
692 /*
693 * try to get rid of all non-directory type nodes
694 */
695 if (unlink(name) < 0) {
696 syswarn(1, errno, "Unable to remove %s", name);
697 return(-1);
698 }
699 return(0);
700 }
701
702 /*
703 * chk_path()
704 * We were trying to create some kind of node in the filesystem and it
705 * failed. chk_path() makes sure the path up to the node exists and is
706 * writeable. When we have to create a directory that is missing along the
707 * path somewhere, the directory we create will be set to the same
708 * uid/gid as the file has (when uid and gid are being preserved).
709 * NOTE: this routine is a real performance loss. It is only used as a
710 * last resort when trying to create entries in the filesystem.
711 * Return:
712 * -1 when it could find nothing it is allowed to fix.
713 * 0 otherwise
714 */
715
716 int
717 chk_path(char *name, uid_t st_uid, gid_t st_gid)
718 {
719 char *spt = name;
720 char *next;
721 struct stat sb;
722 int retval = -1;
723
724 /*
725 * watch out for paths with nodes stored directly in / (e.g. /bozo)
726 */
727 while (*spt == '/')
728 ++spt;
729
730 for (;;) {
731 /*
732 * work forward from the first / and check each part of the path
733 */
734 spt = strchr(spt, '/');
735 if (spt == NULL)
736 break;
737
738 /*
739 * skip over duplicate slashes; stop if there're only
740 * trailing slashes left
741 */
742 next = spt + 1;
743 while (*next == '/')
744 next++;
745 if (*next == '\0')
746 break;
747
748 *spt = '\0';
749
750 /*
751 * if it exists we assume it is a directory, it is not within
752 * the spec (at least it seems to read that way) to alter the
753 * filesystem for nodes NOT EXPLICITLY stored on the archive.
754 * If that assumption is changed, you would test the node here
755 * and figure out how to get rid of it (probably like some
756 * recursive unlink()) or fix up the directory permissions if
757 * required (do an access()).
758 */
759 if (lstat(name, &sb) == 0) {
760 *spt = '/';
761 spt = next;
762 continue;
763 }
764
765 /*
766 * the path fails at this point, see if we can create the
767 * needed directory and continue on
768 */
769 if (mkdir(name, S_IRWXU | S_IRWXG | S_IRWXO) < 0) {
770 *spt = '/';
771 retval = -1;
772 break;
773 }
774
775 /*
776 * we were able to create the directory. We will tell the
777 * caller that we found something to fix, and it is ok to try
778 * and create the node again.
779 */
780 retval = 0;
781 if (pids)
782 (void)set_ids(name, st_uid, st_gid, 0);
783
784 /*
785 * make sure the user doesn't have some strange umask that
786 * causes this newly created directory to be unusable. We fix
787 * the modes and restore them back to the creation default at
788 * the end of pax
789 */
790 if ((access(name, R_OK | W_OK | X_OK) < 0) &&
791 (lstat(name, &sb) == 0)) {
792 set_pmode(name, ((sb.st_mode & FILEBITS) | S_IRWXU), 0);
793 add_dir(name, &sb, 1);
794 }
795 *spt = '/';
796 spt = next;
797 continue;
798 }
799 return(retval);
800 }
801
802 /*
803 * set_ftime()
804 * Set the access time and modification time for a named file. If frc
805 * is non-zero we force these times to be set even if the user did not
806 * request access and/or modification time preservation (this is also
807 * used by -t to reset access times).
808 * When ign is zero, only those times the user has asked for are set, the
809 * other ones are left alone. We do not assume the un-documented feature
810 * of many utimes() implementations that consider a 0 time value as a do
811 * not set request.
812 */
813
814 void
815 set_ftime(const char *fnm, const struct stat *sbp, int frc,
816 int issymlink MKSH_A_UNUSED)
817 {
818 #if HAVE_UTIMENSAT
819 struct timespec ts[2];
820 #else
821 struct {
822 time_t tv_sec;
823 long tv_nsec;
824 } ts[2];
825 #if HAVE_UTIMES
826 struct timeval tv[2];
827 #else
828 struct utimbuf u;
829 #endif
830 struct stat sb;
831 #endif
832 int rv;
833
834 /* pre-initialise values to set */
835 st_timexp(a, &ts[0], sbp);
836 st_timexp(m, &ts[1], sbp);
837
838 if (!frc && (!patime || !pmtime)) {
839 /*
840 * If we are not forcing, only set those times the user
841 * wants set. We get the current values of the times if
842 * we need them (utimensat does not).
843 */
844 #if HAVE_UTIMENSAT
845 if (!patime)
846 ts[0].tv_nsec = UTIME_OMIT;
847 if (!pmtime)
848 ts[1].tv_nsec = UTIME_OMIT;
849 #else
850 if (lstat(fnm, &sb) == 0) {
851 if (!patime)
852 st_timexp(a, &ts[0], &sb);
853 if (!pmtime)
854 st_timexp(m, &ts[1], &sb);
855 } else
856 syswarn(0, errno, "Unable to stat %s", fnm);
857 #endif
858 }
859
860 /* set the times */
861 #if HAVE_UTIMENSAT
862 rv = utimensat(AT_FDCWD, fnm, ts, AT_SYMLINK_NOFOLLOW);
863 #elif HAVE_UTIMES
864 tv[0].tv_sec = ts[0].tv_sec;
865 tv[0].tv_usec = ts[0].tv_nsec / 1000;
866 tv[1].tv_sec = ts[1].tv_sec;
867 tv[1].tv_usec = ts[1].tv_nsec / 1000;
868 #if HAVE_LUTIMES
869 rv = (issymlink ? lutimes : utimes)(fnm, tv);
870 #else
871 if (issymlink)
872 /* no can do */
873 return;
874 rv = utimes(fnm, tv);
875 #endif
876 if (rv < 0 && issymlink && (errno == ENOSYS || errno == ENOTSUP))
877 /* might be glibc */
878 return;
879 #else
880 if (issymlink)
881 /* no can do */
882 return;
883 u.actime = ts[0].tv_sec;
884 u.modtime = ts[1].tv_sec;
885 rv = utime(fnm, &u);
886 #endif
887
888 if (rv < 0)
889 syswarn(1, errno, "Access/modification time set failed on: %s",
890 fnm);
891 }
892
893 #ifdef PAX_FSET_FTIME
894 static void
895 fset_ftime(const char *fnm, int fd, const struct stat *sbp, int frc)
896 {
897 #if HAVE_FUTIMENS
898 struct timespec ts[2];
899 #else
900 struct {
901 time_t tv_sec;
902 long tv_nsec;
903 } ts[2];
904 struct timeval tv[2];
905 struct stat sb;
906 #endif
907 int rv;
908
909 /* pre-initialise values to set */
910 st_timexp(a, &ts[0], sbp);
911 st_timexp(m, &ts[1], sbp);
912
913 if (!frc && (!patime || !pmtime)) {
914 /*
915 * If we are not forcing, only set those times the user
916 * wants set. We get the current values of the times if
917 * we need them (futimens does not).
918 */
919 #if HAVE_FUTIMENS
920 if (!patime)
921 ts[0].tv_nsec = UTIME_OMIT;
922 if (!pmtime)
923 ts[1].tv_nsec = UTIME_OMIT;
924 #else
925 if (fstat(fd, &sb) == 0) {
926 if (!patime)
927 st_timexp(a, &ts[0], &sb);
928 if (!pmtime)
929 st_timexp(m, &ts[1], &sb);
930 } else
931 syswarn(0, errno, "Unable to stat %s", fnm);
932 #endif
933 }
934
935 /* set the times */
936 #if HAVE_FUTIMENS
937 rv = futimens(fd, ts);
938 #else
939 tv[0].tv_sec = ts[0].tv_sec;
940 tv[0].tv_usec = ts[0].tv_nsec / 1000;
941 tv[1].tv_sec = ts[1].tv_sec;
942 tv[1].tv_usec = ts[1].tv_nsec / 1000;
943 rv = futimes(fd, tv);
944 #endif
945 if (rv < 0)
946 syswarn(1, errno, "Access/modification time set failed on: %s",
947 fnm);
948 }
949 #endif
950
951 /*
952 * set_ids()
953 * set the uid and gid of a filesystem node
954 * Return:
955 * 0 when set, -1 on failure
956 */
957
958 int
959 set_ids(char *fnm, uid_t uid, gid_t gid, int issymlink MKSH_A_UNUSED)
960 {
961 int rv;
962
963 #if HAVE_FCHOWNAT
964 rv = fchownat(AT_FDCWD, fnm, uid, gid, AT_SYMLINK_NOFOLLOW);
965 #elif HAVE_LCHOWN
966 rv = (issymlink ? lchown : chown)(fnm, uid, gid);
967 if (rv < 0 && issymlink && (errno == ENOSYS || errno == ENOTSUP))
968 /* might be glibc */
969 return (0);
970 #else
971 if (issymlink)
972 /* no can do */
973 return (0);
974 rv = chown(fnm, uid, gid);
975 #endif
976
977 if (rv < 0) {
978 /*
979 * ignore EPERM unless in verbose mode or being run by root.
980 * if running as pax, POSIX requires a warning.
981 */
982 if (/* portability, imake style though */
983 #ifndef __INTERIX
984 errno != EPERM || vflag || geteuid() == 0 ||
985 #endif
986 op_mode == OP_PAX)
987 syswarn(1, errno, "Unable to set file uid/gid of %s",
988 fnm);
989 return (-1);
990 }
991 return (0);
992 }
993
994 int
995 fset_ids(char *fnm, int fd, uid_t uid, gid_t gid)
996 {
997 if (fchown(fd, uid, gid) < 0) {
998 /*
999 * ignore EPERM unless in verbose mode or being run by root.
1000 * if running as pax, POSIX requires a warning.
1001 */
1002 if (/* portability, imake style though */
1003 #ifndef __INTERIX
1004 errno != EPERM || vflag || geteuid() == 0 ||
1005 #endif
1006 op_mode == OP_PAX)
1007 syswarn(1, errno, "Unable to set file uid/gid of %s",
1008 fnm);
1009 return (-1);
1010 }
1011 return (0);
1012 }
1013
1014 /*
1015 * set_pmode()
1016 * Set file access mode
1017 */
1018
1019 void
1020 set_pmode(char *fnm, mode_t mode, int issymlink MKSH_A_UNUSED)
1021 {
1022 int rv;
1023
1024 mode &= ABITS;
1025 #if HAVE_FCHMODAT
1026 rv = fchmodat(AT_FDCWD, fnm, mode, AT_SYMLINK_NOFOLLOW);
1027 if (rv < 0 && (errno == ENOSYS || errno == ENOTSUP)) {
1028 /* glibc sucks */
1029 if (issymlink)
1030 return;
1031 rv = chmod(fnm, mode);
1032 }
1033 #elif HAVE_LCHMOD
1034 rv = (issymlink ? lchmod : chmod)(fnm, mode);
1035 if (rv < 0 && issymlink && (errno == ENOSYS || errno == ENOTSUP))
1036 /* similarly glibc */
1037 return;
1038 #else
1039 if (issymlink)
1040 /* no can do */
1041 return;
1042 rv = chmod(fnm, mode);
1043 #endif
1044 if (rv < 0)
1045 syswarn(1, errno, "Could not set permissions on %s", fnm);
1046 }
1047
1048 void
1049 fset_pmode(char *fnm, int fd, mode_t mode)
1050 {
1051 mode &= ABITS;
1052 if (fchmod(fd, mode) < 0)
1053 syswarn(1, errno, "Could not set permissions on %s", fnm);
1054 }
1055
1056 /*
1057 * set_attr()
1058 * Given a DIRDATA, restore the mode and times as indicated, but
1059 * only after verifying that it's the directory that we wanted.
1060 */
1061 int
1062 set_attr(const struct file_times *ft, int force_times, mode_t mode,
1063 int do_mode, int in_sig)
1064 {
1065 struct stat sb;
1066 int fd, r;
1067
1068 if (!do_mode && !force_times && !patime && !pmtime)
1069 return (0);
1070
1071 /*
1072 * We could legitimately go through a symlink here,
1073 * so do *not* use O_NOFOLLOW. The dev+ino check will
1074 * protect us from evil.
1075 */
1076 fd = binopen2(BO_MAYBE_DIR, ft->ft_name, O_RDONLY);
1077 if (fd == -1) {
1078 if (!in_sig)
1079 syswarn(1, errno, "Unable to restore mode and times"
1080 " for directory %s", ft->ft_name);
1081 return (-1);
1082 }
1083
1084 if (fstat(fd, &sb) == -1) {
1085 if (!in_sig)
1086 syswarn(1, errno, "Unable to stat directory %s",
1087 ft->ft_name);
1088 r = -1;
1089 #ifndef O_DIRECTORY
1090 } else if (!S_ISDIR(sb.st_mode)) {
1091 if (!in_sig)
1092 syswarn(1, ENOTDIR, "Unable to restore mode and times"
1093 " for directory %s", ft->ft_name);
1094 r = -1;
1095 #endif
1096 } else if (ft->ft_ino != sb.st_ino || ft->ft_dev != sb.st_dev) {
1097 if (!in_sig)
1098 paxwarn(1, "Directory vanished before restoring"
1099 " mode and times: %s", ft->ft_name);
1100 r = -1;
1101 } else {
1102 /* Whew, it's a match! Is there anything to change? */
1103 if (do_mode && (mode & ABITS) != (sb.st_mode & ABITS))
1104 fset_pmode(ft->ft_name, fd, mode);
1105 #ifdef PAX_FSET_FTIME
1106 if (((force_times || patime) && st_timecmp(a, &ft->sb, &sb, !=)) ||
1107 ((force_times || pmtime) && st_timecmp(m, &ft->sb, &sb, !=)))
1108 fset_ftime(ft->ft_name, fd, &ft->sb, force_times);
1109 #endif
1110 r = 0;
1111 }
1112 close(fd);
1113
1114 return (r);
1115 }
1116
1117 /*
1118 * file_write()
1119 * Write/copy a file (during copy or archive extract). This routine knows
1120 * how to copy files with lseek holes in it. (Which are read as file
1121 * blocks containing all 0's but do not have any file blocks associated
1122 * with the data). Typical examples of these are files created by dbm
1123 * variants (.pag files). While the file size of these files are huge, the
1124 * actual storage is quite small (the files are sparse). The problem is
1125 * the holes read as all zeros so are probably stored on the archive that
1126 * way (there is no way to determine if the file block is really a hole,
1127 * we only know that a file block of all zero's can be a hole).
1128 * At this writing, no major archive format knows how to archive files
1129 * with holes. However, on extraction (or during copy, -rw) we have to
1130 * deal with these files. Without detecting the holes, the files can
1131 * consume a lot of file space if just written to disk. This replacement
1132 * for write when passed the basic allocation size of a filesystem block,
1133 * uses lseek whenever it detects the input data is all 0 within that
1134 * file block. In more detail, the strategy is as follows:
1135 * While the input is all zero keep doing an lseek. Keep track of when we
1136 * pass over file block boundaries. Only write when we hit a non zero
1137 * input. once we have written a file block, we continue to write it to
1138 * the end (we stop looking at the input). When we reach the start of the
1139 * next file block, start checking for zero blocks again. Working on file
1140 * block boundaries significantly reduces the overhead when copying files
1141 * that are NOT very sparse. This overhead (when compared to a write) is
1142 * almost below the measurement resolution on many systems. Without it,
1143 * files with holes cannot be safely copied. It does has a side effect as
1144 * it can put holes into files that did not have them before, but that is
1145 * not a problem since the file contents are unchanged (in fact it saves
1146 * file space). (Except on paging files for diskless clients. But since we
1147 * cannot determine one of those file from here, we ignore them). If this
1148 * ever ends up on a system where CTG files are supported and the holes
1149 * are not desired, just do a conditional test in those routines that
1150 * call file_write() and have it call write() instead. BEFORE CLOSING THE
1151 * FILE, make sure to call file_flush() when the last write finishes with
1152 * an empty block. A lot of filesystems will not create an lseek hole at
1153 * the end. In this case we drop a single 0 at the end to force the
1154 * trailing 0's in the file.
1155 * ---Parameters---
1156 * rem: how many bytes left in this filesystem block
1157 * isempt: have we written to the file block yet (is it empty)
1158 * sz: basic file block allocation size
1159 * cnt: number of bytes on this write
1160 * str: buffer to write
1161 * Return:
1162 * number of bytes written, -1 on write (or lseek) error.
1163 */
1164
1165 int
1166 file_write(int fd, char *str, int cnt, int *rem, int *isempt, int sz,
1167 char *name)
1168 {
1169 char *pt;
1170 char *end;
1171 int wcnt;
1172 char *st = str;
1173 char **strp;
1174
1175 /*
1176 * while we have data to process
1177 */
1178 while (cnt) {
1179 if (!*rem) {
1180 /*
1181 * We are now at the start of filesystem block again
1182 * (or what we think one is...). start looking for
1183 * empty blocks again
1184 */
1185 *isempt = 1;
1186 *rem = sz;
1187 }
1188
1189 /*
1190 * only examine up to the end of the current file block or
1191 * remaining characters to write, whatever is smaller
1192 */
1193 wcnt = MINIMUM(cnt, *rem);
1194 cnt -= wcnt;
1195 *rem -= wcnt;
1196 if (*isempt) {
1197 /*
1198 * have not written to this block yet, so we keep
1199 * looking for zero's
1200 */
1201 pt = st;
1202 end = st + wcnt;
1203
1204 /*
1205 * look for a zero filled buffer
1206 */
1207 while ((pt < end) && (*pt == '\0'))
1208 ++pt;
1209
1210 if (pt == end) {
1211 /*
1212 * skip, buf is empty so far
1213 */
1214 if (fd > -1 &&
1215 lseek(fd, wcnt, SEEK_CUR) < 0) {
1216 if (errno == ESPIPE)
1217 goto isapipe;
1218 syswarn(1, errno,
1219 "Failed seek on file %s", name);
1220 return (-1);
1221 }
1222 st = pt;
1223 continue;
1224 }
1225 isapipe:
1226 /*
1227 * drat, the buf is not zero filled
1228 */
1229 *isempt = 0;
1230 }
1231
1232 /*
1233 * have non-zero data in this filesystem block, have to write
1234 */
1235 switch (fd) {
1236 case -1:
1237 strp = &gnu_name_string;
1238 break;
1239 case -2:
1240 strp = &gnu_link_string;
1241 break;
1242 default:
1243 strp = NULL;
1244 break;
1245 }
1246 if (strp) {
1247 if (*strp)
1248 err(1, "WARNING! Major Internal Error! GNU hack Failing!");
1249 *strp = malloc(wcnt + 1);
1250 if (*strp == NULL) {
1251 paxwarn(1, "Out of memory");
1252 return(-1);
1253 }
1254 memcpy(*strp, st, wcnt);
1255 (*strp)[wcnt] = '\0';
1256 break;
1257 } else if (write(fd, st, wcnt) != wcnt) {
1258 syswarn(1, errno, "Failed write to file %s", name);
1259 return(-1);
1260 }
1261 st += wcnt;
1262 }
1263 return(st - str);
1264 }
1265
1266 /*
1267 * file_flush()
1268 * when the last file block in a file is zero, many filesystems will not
1269 * let us create a hole at the end. To get the last block with zeros, we
1270 * write the last BYTE with a zero (back up one byte and write a zero).
1271 */
1272
1273 void
1274 file_flush(int fd, char *fname, int isempt)
1275 {
1276 static char blnk[] = "\0";
1277
1278 /*
1279 * silly test, but make sure we are only called when the last block is
1280 * filled with all zeros.
1281 */
1282 if (!isempt)
1283 return;
1284
1285 /*
1286 * move back one byte and write a zero
1287 */
1288 if (lseek(fd, -1, SEEK_CUR) < 0) {
1289 syswarn(1, errno, "Failed seek on file %s", fname);
1290 return;
1291 }
1292
1293 if (write(fd, blnk, 1) < 0)
1294 syswarn(1, errno, "Failed write to file %s", fname);
1295 }
1296
1297 /*
1298 * rdfile_close()
1299 * close a file we have been reading (to copy or archive). If we have to
1300 * reset access time (tflag) do so (the times are stored in arcn).
1301 */
1302
1303 void
1304 rdfile_close(ARCHD *arcn MKSH_A_UNUSED, int *fd)
1305 {
1306 /*
1307 * make sure the file is open
1308 */
1309 if (*fd < 0)
1310 return;
1311
1312 /*
1313 * user wants last access time reset
1314 */
1315 #ifdef PAX_FSET_FTIME
1316 if (tflag)
1317 fset_ftime(arcn->org_name, *fd, &arcn->sb, 1);
1318 #endif
1319
1320 (void)close(*fd);
1321 *fd = -1;
1322 }
1323
1324 /*
1325 * set_crc()
1326 * read a file to calculate its crc. This is a real drag. Archive formats
1327 * that have this, end up reading the file twice (we have to write the
1328 * header WITH the crc before writing the file contents. Oh well...
1329 * Return:
1330 * 0 if was able to calculate the crc, -1 otherwise
1331 */
1332
1333 int
1334 set_crc(ARCHD *arcn, int fd)
1335 {
1336 int i;
1337 int res;
1338 off_t cpcnt = 0;
1339 size_t size;
1340 uint32_t crc = 0;
1341 char tbuf[FILEBLK];
1342 struct stat sb;
1343
1344 if (fd < 0) {
1345 /*
1346 * hmm, no fd, should never happen. well no crc then.
1347 */
1348 arcn->crc = 0;
1349 return(0);
1350 }
1351
1352 if ((size = arcn->sb.st_blksize) > sizeof(tbuf))
1353 size = sizeof(tbuf);
1354
1355 /*
1356 * read all the bytes we think that there are in the file. If the user
1357 * is trying to archive an active file, forget this file.
1358 */
1359 for (;;) {
1360 if ((res = read(fd, tbuf, size)) <= 0)
1361 break;
1362 cpcnt += res;
1363 for (i = 0; i < res; ++i)
1364 crc += (tbuf[i] & 0xff);
1365 }
1366
1367 /*
1368 * safety check. we want to avoid archiving files that are active as
1369 * they can create inconsistent archive copies.
1370 */
1371 if (cpcnt != (off_t)arcn->sb.st_size)
1372 paxwarn(1, "File changed size %s", arcn->org_name);
1373 else if (fstat(fd, &sb) < 0)
1374 syswarn(1, errno, "Failed stat on %s", arcn->org_name);
1375 else if (st_timecmp(m, &arcn->sb, &sb, !=))
1376 paxwarn(1, "File %s was modified during read", arcn->org_name);
1377 else if (lseek(fd, 0, SEEK_SET) < 0)
1378 syswarn(1, errno, "File rewind failed on: %s", arcn->org_name);
1379 else {
1380 arcn->crc = crc;
1381 return(0);
1382 }
1383 return(-1);
1384 }