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