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