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