file_subs.c revision 1557
1195333Simp/*-
2195333Simp * Copyright (c) 1992 Keith Muller.
3195333Simp * Copyright (c) 1992, 1993
4195333Simp *	The Regents of the University of California.  All rights reserved.
5195333Simp *
6195333Simp * This code is derived from software contributed to Berkeley by
7195333Simp * Keith Muller of the University of California, San Diego.
8195333Simp *
9195333Simp * Redistribution and use in source and binary forms, with or without
10195333Simp * modification, are permitted provided that the following conditions
11195333Simp * are met:
12195333Simp * 1. Redistributions of source code must retain the above copyright
13195333Simp *    notice, this list of conditions and the following disclaimer.
14195333Simp * 2. Redistributions in binary form must reproduce the above copyright
15195333Simp *    notice, this list of conditions and the following disclaimer in the
16195333Simp *    documentation and/or other materials provided with the distribution.
17195333Simp * 3. All advertising materials mentioning features or use of this software
18195333Simp *    must display the following acknowledgement:
19195333Simp *	This product includes software developed by the University of
20195333Simp *	California, Berkeley and its contributors.
21195333Simp * 4. Neither the name of the University nor the names of its contributors
22195333Simp *    may be used to endorse or promote products derived from this software
23195333Simp *    without specific prior written permission.
24195333Simp *
25195333Simp * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26195333Simp * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27195333Simp * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28195333Simp * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29195333Simp * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30195333Simp * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31195333Simp * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32195333Simp * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33195333Simp * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34195333Simp * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35195333Simp * SUCH DAMAGE.
36195333Simp */
37195333Simp
38195333Simp#ifndef lint
39195333Simpstatic char sccsid[] = "@(#)file_subs.c	8.1 (Berkeley) 5/31/93";
40195333Simp#endif /* not lint */
41195333Simp
42195333Simp#include <sys/types.h>
43195333Simp#include <sys/time.h>
44195333Simp#include <sys/stat.h>
45195333Simp#include <unistd.h>
46195333Simp#include <sys/param.h>
47195333Simp#include <fcntl.h>
48195333Simp#include <string.h>
49195333Simp#include <stdio.h>
50195333Simp#include <ctype.h>
51195333Simp#include <errno.h>
52195333Simp#include <sys/uio.h>
53195333Simp#include <stdlib.h>
54195333Simp#include "pax.h"
55195333Simp#include "extern.h"
56195333Simp
57195333Simpstatic int
58195333Simpmk_link __P((register char *,register struct stat *,register char *, int));
59195333Simp
60195333Simp/*
61195333Simp * routines that deal with file operations such as: creating, removing;
62195333Simp * and setting access modes, uid/gid and times of files
63195333Simp */
64195333Simp
65195333Simp#define FILEBITS		(S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO)
66195333Simp#define SETBITS			(S_ISUID | S_ISGID)
67195333Simp#define ABITS			(FILEBITS | SETBITS)
68195333Simp
69195333Simp/*
70195333Simp * file_creat()
71195333Simp *	Create and open a file.
72195333Simp * Return:
73195333Simp *	file descriptor or -1 for failure
74195333Simp */
75195333Simp
76195333Simp#if __STDC__
77195333Simpint
78195333Simpfile_creat(register ARCHD *arcn)
79195333Simp#else
80195333Simpint
81195333Simpfile_creat(arcn)
82195333Simp	register ARCHD *arcn;
83195333Simp#endif
84195333Simp{
85195333Simp	int fd = -1;
86195333Simp	mode_t file_mode;
87195333Simp	int oerrno;
88195333Simp
89195333Simp	/*
90195333Simp	 * assume file doesn't exist, so just try to create it, most times this
91195333Simp	 * works. We have to take special handling when the file does exist. To
92195333Simp	 * detect this, we use O_EXCL. For example when trying to create a
93195333Simp	 * file and a character device or fifo exists with the same name, we
94195333Simp	 * can accidently open the device by mistake (or block waiting to open)
95195333Simp	 * If we find that the open has failed, then figure spend the effore to
96203000Sneel	 * figure out why. This strategy was found to have better average
97203000Sneel	 * performance in common use than checking the file (and the path)
98198669Srrs	 * first with lstat.
99198669Srrs	 */
100198669Srrs	file_mode = arcn->sb.st_mode & FILEBITS;
101198669Srrs	if ((fd = open(arcn->name, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL,
102198669Srrs	    file_mode)) >= 0)
103198669Srrs		return(fd);
104195333Simp
105195333Simp	/*
106195333Simp	 * the file seems to exist. First we try to get rid of it (found to be
107195333Simp	 * the second most common failure when traced). If this fails, only
108195333Simp	 * then we go to the expense to check and create the path to the file
109195333Simp	 */
110195333Simp	if (unlnk_exist(arcn->name, arcn->type) != 0)
111195333Simp		return(-1);
112195333Simp
113195333Simp	for (;;) {
114195333Simp		/*
115195333Simp		 * try to open it again, if this fails, check all the nodes in
116195333Simp		 * the path and give it a final try. if chk_path() finds that
117195333Simp		 * it cannot fix anything, we will skip the last attempt
118195333Simp		 */
119195333Simp		if ((fd = open(arcn->name, O_WRONLY | O_CREAT | O_TRUNC,
120195333Simp		    file_mode)) >= 0)
121195333Simp			break;
122195333Simp		oerrno = errno;
123195333Simp		if (chk_path(arcn->name,arcn->sb.st_uid,arcn->sb.st_gid) < 0) {
124195333Simp			syswarn(1, oerrno, "Unable to create %s", arcn->name);
125195333Simp			return(-1);
126195333Simp		}
127195333Simp	}
128195333Simp	return(fd);
129195333Simp}
130195333Simp
131195333Simp/*
132195333Simp * file_close()
133195333Simp *	Close file descriptor to a file just created by pax. Sets modes,
134195333Simp *	ownership and times as required.
135195333Simp * Return:
136195333Simp *	0 for success, -1 for failure
137195333Simp */
138195333Simp
139195333Simp#if __STDC__
140195333Simpvoid
141195333Simpfile_close(register ARCHD *arcn, int fd)
142195333Simp#else
143195333Simpvoid
144195333Simpfile_close(arcn, fd)
145195333Simp	register ARCHD *arcn;
146195333Simp	int fd;
147195333Simp#endif
148195333Simp{
149195333Simp	int res = 0;
150195333Simp
151195333Simp	if (fd < 0)
152195333Simp		return;
153195333Simp	if (close(fd) < 0)
154195333Simp		syswarn(0, errno, "Unable to close file descriptor on %s",
155195333Simp		    arcn->name);
156195333Simp
157195333Simp	/*
158195333Simp	 * set owner/groups first as this may strip off mode bits we want
159195333Simp	 * then set file permission modes. Then set file access and
160195333Simp	 * modification times.
161195333Simp	 */
162195333Simp	if (pids)
163195333Simp		res = set_ids(arcn->name, arcn->sb.st_uid, arcn->sb.st_gid);
164195333Simp
165195333Simp	/*
166195333Simp	 * IMPORTANT SECURITY NOTE:
167195333Simp	 * if not preserving mode or we cannot set uid/gid, then PROHIBIT
168195333Simp	 * set uid/gid bits
169195333Simp	 */
170195333Simp	if (!pmode || res)
171195333Simp		arcn->sb.st_mode &= ~(SETBITS);
172195333Simp	if (pmode)
173195333Simp		set_pmode(arcn->name, arcn->sb.st_mode);
174202954Sgonzo	if (patime || pmtime)
175195333Simp		set_ftime(arcn->name, arcn->sb.st_mtime, arcn->sb.st_atime, 0);
176195333Simp}
177195333Simp
178195333Simp/*
179195333Simp * lnk_creat()
180195333Simp *	Create a hard link to arcn->ln_name from arcn->name. arcn->ln_name
181195333Simp *	must exist;
182195333Simp * Return:
183195333Simp *	0 if ok, -1 otherwise
184195333Simp */
185195333Simp
186195333Simp#if __STDC__
187195333Simpint
188203000Sneellnk_creat(register ARCHD *arcn)
189203000Sneel#else
190203000Sneelint
191203000Sneellnk_creat(arcn)
192203000Sneel	register ARCHD *arcn;
193203000Sneel#endif
194203000Sneel{
195203000Sneel	struct stat sb;
196203000Sneel
197203000Sneel	/*
198203000Sneel	 * we may be running as root, so we have to be sure that link target
199203000Sneel	 * is not a directory, so we lstat and check
200203000Sneel	 */
201203000Sneel	if (lstat(arcn->ln_name, &sb) < 0) {
202203000Sneel		syswarn(1,errno,"Unable to link to %s from %s", arcn->ln_name,
203203000Sneel		    arcn->name);
204203000Sneel		return(-1);
205203000Sneel	}
206203000Sneel
207203000Sneel	if (S_ISDIR(sb.st_mode)) {
208203000Sneel		warn(1, "A hard link to the directory %s is not allowed",
209203000Sneel		    arcn->ln_name);
210195333Simp		return(-1);
211195333Simp	}
212195333Simp
213195333Simp	return(mk_link(arcn->ln_name, &sb, arcn->name, 0));
214195333Simp}
215195333Simp
216195333Simp/*
217195333Simp * cross_lnk()
218195333Simp *	Create a hard link to arcn->org_name from arcn->name. Only used in copy
219195333Simp *	with the -l flag. No warning or error if this does not succeed (we will
220195333Simp *	then just create the file)
221195333Simp * Return:
222195333Simp *	1 if copy() should try to create this file node
223195333Simp *	0 if cross_lnk() ok, -1 for fatal flaw (like linking to self).
224195333Simp */
225195333Simp
226195333Simp#if __STDC__
227195333Simpint
228195333Simpcross_lnk(register ARCHD *arcn)
229195333Simp#else
230195333Simpint
231195333Simpcross_lnk(arcn)
232195333Simp	register ARCHD *arcn;
233195333Simp#endif
234195333Simp{
235195333Simp	/*
236195333Simp	 * try to make a link to orginal file (-l flag in copy mode). make sure
237195333Simp	 * we do not try to link to directories in case we are running as root
238195333Simp	 * (and it might succeed).
239195333Simp	 */
240195333Simp	if (arcn->type == PAX_DIR)
241195333Simp		return(1);
242195333Simp	return(mk_link(arcn->org_name, &(arcn->sb), arcn->name, 1));
243195333Simp}
244195333Simp
245195333Simp/*
246195333Simp * chk_same()
247195333Simp *	In copy mode if we are not trying to make hard links between the src
248195333Simp *	and destinations, make sure we are not going to overwrite ourselves by
249195333Simp *	accident. This slows things down a little, but we have to protect all
250195333Simp *	those people who make typing errors.
251195333Simp * Return:
252195333Simp *	1 the target does not exist, go ahead and copy
253195333Simp *	0 skip it file exists (-k) or may be the same as source file
254195333Simp */
255195333Simp
256195333Simp#if __STDC__
257202864Sneelint
258202864Sneelchk_same(register ARCHD *arcn)
259202864Sneel#else
260202864Sneelint
261202864Sneelchk_same(arcn)
262202864Sneel	register ARCHD *arcn;
263202864Sneel#endif
264202864Sneel{
265202864Sneel	struct stat sb;
266202864Sneel
267202864Sneel	/*
268202864Sneel	 * if file does not exist, return. if file exists and -k, skip it
269195333Simp	 * quietly
270201631Sneel	 */
271201631Sneel	if (lstat(arcn->name, &sb) < 0)
272195333Simp		return(1);
273202864Sneel	if (kflag)
274202864Sneel		return(0);
275202864Sneel
276202864Sneel	/*
277202864Sneel	 * better make sure the user does not have src == dest by mistake
278195333Simp	 */
279195333Simp	if ((arcn->sb.st_dev == sb.st_dev) && (arcn->sb.st_ino == sb.st_ino)) {
280202954Sgonzo		warn(1, "Unable to copy %s, file would overwrite itself",
281195333Simp		    arcn->name);
282201845Simp		return(0);
283201881Simp	}
284201845Simp	return(1);
285195333Simp}
286195333Simp
287195333Simp/*
288195333Simp * mk_link()
289201631Sneel *	try to make a hard link between two files. if ign set, we do not
290201631Sneel *	complain.
291201631Sneel * Return:
292201631Sneel *	0 if successful (or we are done with this file but no error, such as
293201631Sneel *	finding the from file exists and the user has set -k).
294195333Simp *	1 when ign was set to indicates we could not make the link but we
295201631Sneel *	should try to copy/extract the file as that might work (and is an
296201631Sneel *	allowed option). -1 an error occurred.
297195333Simp */
298195333Simp
299195333Simp#if __STDC__
300195333Simpstatic int
301195333Simpmk_link(register char *to, register struct stat *to_sb, register char *from,
302195333Simp	int ign)
303195333Simp#else
304static int
305mk_link(to, to_sb, from, ign)
306	register char *to;
307	register struct stat *to_sb;
308	register char *from;
309	int ign;
310#endif
311{
312	struct stat sb;
313	int oerrno;
314
315	/*
316	 * if from file exists, it has to be unlinked to make the link. If the
317	 * file exists and -k is set, skip it quietly
318	 */
319	if (lstat(from, &sb) == 0) {
320		if (kflag)
321			return(0);
322
323		/*
324		 * make sure it is not the same file, protect the user
325		 */
326		if ((to_sb->st_dev==sb.st_dev)&&(to_sb->st_ino == sb.st_ino)) {
327			warn(1, "Unable to link file %s to itself", to);
328			return(-1);;
329		}
330
331		/*
332		 * try to get rid of the file, based on the type
333		 */
334		if (S_ISDIR(sb.st_mode)) {
335			if (rmdir(from) < 0) {
336				syswarn(1, errno, "Unable to remove %s", from);
337				return(-1);
338			}
339		} else if (unlink(from) < 0) {
340			if (!ign) {
341				syswarn(1, errno, "Unable to remove %s", from);
342				return(-1);
343			}
344			return(1);
345		}
346	}
347
348	/*
349	 * from file is gone (or did not exist), try to make the hard link.
350	 * if it fails, check the path and try it again (if chk_path() says to
351	 * try again)
352	 */
353	for (;;) {
354		if (link(to, from) == 0)
355			break;
356		oerrno = errno;
357		if (chk_path(from, to_sb->st_uid, to_sb->st_gid) == 0)
358			continue;
359		if (!ign) {
360			syswarn(1, oerrno, "Could not link to %s from %s", to,
361			    from);
362			return(-1);
363		}
364		return(1);
365	}
366
367	/*
368	 * all right the link was made
369	 */
370	return(0);
371}
372
373/*
374 * node_creat()
375 *	create an entry in the file system (other than a file or hard link).
376 *	If successful, sets uid/gid modes and times as required.
377 * Return:
378 *	0 if ok, -1 otherwise
379 */
380
381#if __STDC__
382int
383node_creat(register ARCHD *arcn)
384#else
385int
386node_creat(arcn)
387	register ARCHD *arcn;
388#endif
389{
390	register int res;
391	register int ign = 0;
392	register int oerrno;
393	register int pass = 0;
394	mode_t file_mode;
395	struct stat sb;
396
397	/*
398	 * create node based on type, if that fails try to unlink the node and
399	 * try again. finally check the path and try again. As noted in the
400	 * file and link creation routines, this method seems to exhibit the
401	 * best performance in general use workloads.
402	 */
403	file_mode = arcn->sb.st_mode & FILEBITS;
404
405	for (;;) {
406		switch(arcn->type) {
407		case PAX_DIR:
408			res = mkdir(arcn->name, file_mode);
409			if (ign)
410				res = 0;
411			break;
412		case PAX_CHR:
413			file_mode |= S_IFCHR;
414			res = mknod(arcn->name, file_mode, arcn->sb.st_rdev);
415			break;
416		case PAX_BLK:
417			file_mode |= S_IFBLK;
418			res = mknod(arcn->name, file_mode, arcn->sb.st_rdev);
419			break;
420		case PAX_FIF:
421			res = mkfifo(arcn->name, file_mode);
422			break;
423		case PAX_SCK:
424			/*
425			 * Skip sockets, operation has no meaning under BSD
426			 */
427			warn(0,
428			    "%s skipped. Sockets cannot be copied or extracted",
429			    arcn->name);
430			return(-1);
431		case PAX_SLK:
432			if ((res = symlink(arcn->ln_name, arcn->name)) == 0)
433				return(0);
434			break;
435		case PAX_CTG:
436		case PAX_HLK:
437		case PAX_HRG:
438		case PAX_REG:
439		default:
440			/*
441			 * we should never get here
442			 */
443			warn(0, "%s has an unknown file type, skipping",
444				arcn->name);
445			return(-1);
446		}
447
448		/*
449		 * if we were able to create the node break out of the loop,
450		 * otherwise try to unlink the node and try again. if that
451		 * fails check the full path and try a final time.
452		 */
453		if (res == 0)
454			break;
455
456		/*
457		 * we failed to make the node
458		 */
459		oerrno = errno;
460		if ((ign = unlnk_exist(arcn->name, arcn->type)) < 0)
461			return(-1);
462
463		if (++pass <= 1)
464			continue;
465
466		if (chk_path(arcn->name,arcn->sb.st_uid,arcn->sb.st_gid) < 0) {
467			syswarn(1, oerrno, "Could not create: %s", arcn->name);
468			return(-1);
469		}
470	}
471
472	/*
473	 * we were able to create the node. set uid/gid, modes and times
474	 */
475	if (pids)
476		res = set_ids(arcn->name, arcn->sb.st_uid, arcn->sb.st_gid);
477	else
478		res = 0;
479
480	/*
481	 * IMPORTANT SECURITY NOTE:
482	 * if not preserving mode or we cannot set uid/gid, then PROHIBIT any
483	 * set uid/gid bits
484	 */
485	if (!pmode || res)
486		arcn->sb.st_mode &= ~(SETBITS);
487	if (pmode)
488		set_pmode(arcn->name, arcn->sb.st_mode);
489
490	if (arcn->type == PAX_DIR) {
491		/*
492		 * Dirs must be processed again at end of extract to set times
493		 * and modes to agree with those stored in the archive. However
494		 * to allow extract to continue, we may have to also set owner
495		 * rights. This allows nodes in the archive that are children
496		 * of this directory to be extracted without failure. Both time
497		 * and modes will be fixed after the entire archive is read and
498		 * before pax exits.
499		 */
500		if (access(arcn->name, R_OK | W_OK | X_OK) < 0) {
501			if (lstat(arcn->name, &sb) < 0) {
502				syswarn(0, errno,"Could not access %s (stat)",
503				    arcn->name);
504				set_pmode(arcn->name,file_mode | S_IRWXU);
505			} else {
506				/*
507				 * We have to add rights to the dir, so we make
508				 * sure to restore the mode. The mode must be
509				 * restored AS CREATED and not as stored if
510				 * pmode is not set.
511				 */
512				set_pmode(arcn->name,
513				    ((sb.st_mode & FILEBITS) | S_IRWXU));
514				if (!pmode)
515					arcn->sb.st_mode = sb.st_mode;
516			}
517
518			/*
519			 * we have to force the mode to what was set here,
520			 * since we changed it from the default as created.
521			 */
522			add_dir(arcn->name, arcn->nlen, &(arcn->sb), 1);
523		} else if (pmode || patime || pmtime)
524			add_dir(arcn->name, arcn->nlen, &(arcn->sb), 0);
525	}
526
527	if (patime || pmtime)
528		set_ftime(arcn->name, arcn->sb.st_mtime, arcn->sb.st_atime, 0);
529	return(0);
530}
531
532/*
533 * unlnk_exist()
534 *	Remove node from file system with the specified name. We pass the type
535 *	of the node that is going to replace it. When we try to create a
536 *	directory and find that it already exists, we allow processing to
537 *	continue as proper modes etc will always be set for it later on.
538 * Return:
539 *	0 is ok to proceed, no file with the specified name exists
540 *	-1 we were unable to remove the node, or we should not remove it (-k)
541 *	1 we found a directory and we were going to create a directory.
542 */
543
544#if __STDC__
545int
546unlnk_exist(register char *name, register int type)
547#else
548int
549unlnk_exist(name, type)
550	register char *name;
551	register int type;
552#endif
553{
554	struct stat sb;
555
556	/*
557	 * the file does not exist, or -k we are done
558	 */
559	if (lstat(name, &sb) < 0)
560		return(0);
561	if (kflag)
562		return(-1);
563
564	if (S_ISDIR(sb.st_mode)) {
565		/*
566		 * try to remove a directory, if it fails and we were going to
567		 * create a directory anyway, tell the caller (return a 1)
568		 */
569		if (rmdir(name) < 0) {
570			if (type == PAX_DIR)
571				return(1);
572			syswarn(1,errno,"Unable to remove directory %s", name);
573			return(-1);
574		}
575		return(0);
576	}
577
578	/*
579	 * try to get rid of all non-directory type nodes
580	 */
581	if (unlink(name) < 0) {
582		syswarn(1, errno, "Could not unlink %s", name);
583		return(-1);
584	}
585	return(0);
586}
587
588/*
589 * chk_path()
590 *	We were trying to create some kind of node in the file system and it
591 *	failed. chk_path() makes sure the path up to the node exists and is
592 *	writeable. When we have to create a directory that is missing along the
593 *	path somewhere, the directory we create will be set to the same
594 *	uid/gid as the file has (when uid and gid are being preserved).
595 *	NOTE: this routine is a real performance loss. It is only used as a
596 *	last resort when trying to create entries in the file system.
597 * Return:
598 *	-1 when it could find nothing it is allowed to fix.
599 *	0 otherwise
600 */
601
602#if __STDC__
603int
604chk_path( register char *name, uid_t st_uid, gid_t st_gid)
605#else
606int
607chk_path(name, st_uid, st_gid)
608	register char *name;
609	uid_t st_uid;
610	gid_t st_gid;
611#endif
612{
613	register char *spt = name;
614	struct stat sb;
615	int retval = -1;
616
617	/*
618	 * watch out for paths with nodes stored directly in / (e.g. /bozo)
619	 */
620	if (*spt == '/')
621		++spt;
622
623	for(;;) {
624		/*
625		 * work foward from the first / and check each part of the path
626		 */
627		spt = strchr(spt, '/');
628		if (spt == NULL)
629			break;
630		*spt = '\0';
631
632		/*
633		 * if it exists we assume it is a directory, it is not within
634		 * the spec (at least it seems to read that way) to alter the
635		 * file system for nodes NOT EXPLICITLY stored on the archive.
636		 * If that assumption is changed, you would test the node here
637		 * and figure out how to get rid of it (probably like some
638		 * recursive unlink()) or fix up the directory permissions if
639		 * required (do an access()).
640		 */
641		if (lstat(name, &sb) == 0) {
642			*(spt++) = '/';
643			continue;
644		}
645
646		/*
647		 * the path fails at this point, see if we can create the
648		 * needed directory and continue on
649		 */
650		if (mkdir(name, S_IRWXU | S_IRWXG | S_IRWXO) < 0) {
651			*spt = '/';
652			retval = -1;
653			break;
654		}
655
656		/*
657		 * we were able to create the directory. We will tell the
658		 * caller that we found something to fix, and it is ok to try
659		 * and create the node again.
660		 */
661		retval = 0;
662		if (pids)
663			(void)set_ids(name, st_uid, st_gid);
664
665		/*
666		 * make sure the user doen't have some strange umask that
667		 * causes this newly created directory to be unusable. We fix
668		 * the modes and restore them back to the creation default at
669		 * the end of pax
670		 */
671		if ((access(name, R_OK | W_OK | X_OK) < 0) &&
672		    (lstat(name, &sb) == 0)) {
673			set_pmode(name, ((sb.st_mode & FILEBITS) | S_IRWXU));
674			add_dir(name, spt - name, &sb, 1);
675		}
676		*(spt++) = '/';
677		continue;
678	}
679	return(retval);
680}
681
682/*
683 * set_ftime()
684 *	Set the access time and modification time for a named file. If frc is
685 *	non-zero we force these times to be set even if the the user did not
686 *	request access and/or modification time preservation (this is also
687 *	used by -t to reset access times).
688 *	When ign is zero, only those times the user has asked for are set, the
689 *	other ones are left alone. We do not assume the un-documented feature
690 *	of many utimes() implementations that consider a 0 time value as a do
691 *	not set request.
692 */
693
694#if __STDC__
695void
696set_ftime(char *fnm, time_t mtime, time_t atime, int frc)
697#else
698void
699set_ftime(fnm, mtime, atime, frc)
700	char *fnm;
701	time_t mtime;
702	time_t atime;
703	int frc;
704#endif
705{
706	static struct timeval tv[2] = {{0L, 0L}, {0L, 0L}};
707	struct stat sb;
708
709	tv[0].tv_sec = (long)atime;
710	tv[1].tv_sec = (long)mtime;
711	if (!frc && (!patime || !pmtime)) {
712		/*
713		 * if we are not forcing, only set those times the user wants
714		 * set. We get the current values of the times if we need them.
715		 */
716		if (lstat(fnm, &sb) == 0) {
717			if (!patime)
718				tv[0].tv_sec = (long)sb.st_atime;
719			if (!pmtime)
720				tv[1].tv_sec = (long)sb.st_mtime;
721		} else
722			syswarn(0,errno,"Unable to obtain file stats %s", fnm);
723	}
724
725	/*
726	 * set the times
727	 */
728	if (utimes(fnm, tv) < 0)
729		syswarn(1, errno, "Access/modification time set failed on: %s",
730		    fnm);
731	return;
732}
733
734/*
735 * set_ids()
736 *	set the uid and gid of a file system node
737 * Return:
738 *	0 when set, -1 on failure
739 */
740
741#if __STDC__
742int
743set_ids(char *fnm, uid_t uid, gid_t gid)
744#else
745int
746set_ids(fnm, uid, gid)
747	char *fnm;
748	uid_t uid;
749	gid_t gid;
750#endif
751{
752	if (chown(fnm, uid, gid) < 0) {
753		syswarn(1, errno, "Unable to set file uid/gid of %s", fnm);
754		return(-1);
755	}
756	return(0);
757}
758
759/*
760 * set_pmode()
761 *	Set file access mode
762 */
763
764#if __STDC__
765void
766set_pmode(char *fnm, mode_t mode)
767#else
768void
769set_pmode(fnm, mode)
770	char *fnm;
771	mode_t mode;
772#endif
773{
774	mode &= ABITS;
775	if (chmod(fnm, mode) < 0)
776		syswarn(1, errno, "Could not set permissions on %s", fnm);
777	return;
778}
779
780/*
781 * file_write()
782 *	Write/copy a file (during copy or archive extract). This routine knows
783 *	how to copy files with lseek holes in it. (Which are read as file
784 *	blocks containing all 0's but do not have any file blocks associated
785 *	with the data). Typical examples of these are files created by dbm
786 *	variants (.pag files). While the file size of these files are huge, the
787 *	actual storage is quite small (the files are sparse). The problem is
788 *	the holes read as all zeros so are probably stored on the archive that
789 *	way (there is no way to determine if the file block is really a hole,
790 *	we only know that a file block of all zero's can be a hole).
791 *	At this writing, no major archive format knows how to archive files
792 *	with holes. However, on extraction (or during copy, -rw) we have to
793 *	deal with these files. Without detecting the holes, the files can
794 *	consume a lot of file space if just written to disk. This replacement
795 *	for write when passed the basic allocation size of a file system block,
796 *	uses lseek whenever it detects the input data is all 0 within that
797 *	file block. In more detail, the strategy is as follows:
798 *	While the input is all zero keep doing an lseek. Keep track of when we
799 *	pass over file block boundries. Only write when we hit a non zero
800 *	input. once we have written a file block, we continue to write it to
801 *	the end (we stop looking at the input). When we reach the start of the
802 *	next file block, start checking for zero blocks again. Working on file
803 *	block boundries significantly reduces the overhead when copying files
804 *	that are NOT very sparse. This overhead (when compared to a write) is
805 *	almost below the measurement resolution on many systems. Without it,
806 *	files with holes cannot be safely copied. It does has a side effect as
807 *	it can put holes into files that did not have them before, but that is
808 *	not a problem since the file contents are unchanged (in fact it saves
809 *	file space). (Except on paging files for diskless clients. But since we
810 *	cannot determine one of those file from here, we ignore them). If this
811 *	ever ends up on a system where CTG files are supported and the holes
812 *	are not desired, just do a conditional test in those routines that
813 *	call file_write() and have it call write() instead. BEFORE CLOSING THE
814 *	FILE, make sure to call file_flush() when the last write finishes with
815 *	an empty block. A lot of file systems will not create an lseek hole at
816 *	the end. In this case we drop a single 0 at the end to force the
817 *	trailing 0's in the file.
818 *	---Parameters---
819 *	rem: how many bytes left in this file system block
820 *	isempt: have we written to the file block yet (is it empty)
821 *	sz: basic file block allocation size
822 *	cnt: number of bytes on this write
823 *	str: buffer to write
824 * Return:
825 *	number of bytes written, -1 on write (or lseek) error.
826 */
827
828#if __STDC__
829int
830file_write(int fd, char *str, register int cnt, int *rem, int *isempt, int sz,
831	char *name)
832#else
833int
834file_write(fd, str, cnt, rem, isempt, sz, name)
835	int fd;
836	char *str;
837	register int cnt;
838	int *rem;
839	int *isempt;
840	int sz;
841	char *name;
842#endif
843{
844	register char *pt;
845	register char *end;
846	register int wcnt;
847	register char *st = str;
848
849	/*
850	 * while we have data to process
851	 */
852	while (cnt) {
853		if (!*rem) {
854			/*
855			 * We are now at the start of file system block again
856			 * (or what we think one is...). start looking for
857			 * empty blocks again
858			 */
859			*isempt = 1;
860			*rem = sz;
861		}
862
863		/*
864		 * only examine up to the end of the current file block or
865		 * remaining characters to write, whatever is smaller
866		 */
867		wcnt = MIN(cnt, *rem);
868		cnt -= wcnt;
869		*rem -= wcnt;
870		if (*isempt) {
871			/*
872			 * have not written to this block yet, so we keep
873			 * looking for zero's
874			 */
875			pt = st;
876			end = st + wcnt;
877
878			/*
879			 * look for a zero filled buffer
880			 */
881			while ((pt < end) && (*pt == '\0'))
882				++pt;
883
884			if (pt == end) {
885				/*
886				 * skip, buf is empty so far
887				 */
888				if (lseek(fd, (off_t)wcnt, SEEK_CUR) < 0) {
889					syswarn(1,errno,"File seek on %s",
890					    name);
891					return(-1);
892				}
893				st = pt;
894				continue;
895			}
896			/*
897			 * drat, the buf is not zero filled
898			 */
899			*isempt = 0;
900		}
901
902		/*
903		 * have non-zero data in this file system block, have to write
904		 */
905		if (write(fd, st, wcnt) != wcnt) {
906			syswarn(1, errno, "Failed write to file %s", name);
907			return(-1);
908		}
909		st += wcnt;
910	}
911	return(st - str);
912}
913
914/*
915 * file_flush()
916 *	when the last file block in a file is zero, many file systems will not
917 *	let us create a hole at the end. To get the last block with zeros, we
918 *	write the last BYTE with a zero (back up one byte and write a zero).
919 */
920
921#if __STDC__
922void
923file_flush(int fd, char *fname, int isempt)
924#else
925void
926file_flush(fd, fname, isempt)
927	int fd;
928	char *fname;
929	int isempt;
930#endif
931{
932	static char blnk[] = "\0";
933
934	/*
935	 * silly test, but make sure we are only called when the last block is
936	 * filled with all zeros.
937	 */
938	if (!isempt)
939		return;
940
941	/*
942	 * move back one byte and write a zero
943	 */
944	if (lseek(fd, (off_t)-1, SEEK_CUR) < 0) {
945		syswarn(1, errno, "Failed seek on file %s", fname);
946		return;
947	}
948
949	if (write(fd, blnk, 1) < 0)
950		syswarn(1, errno, "Failed write to file %s", fname);
951	return;
952}
953
954/*
955 * rdfile_close()
956 *	close a file we have beed reading (to copy or archive). If we have to
957 *	reset access time (tflag) do so (the times are stored in arcn).
958 */
959
960#if __STDC__
961void
962rdfile_close(register ARCHD *arcn, register int *fd)
963#else
964void
965rdfile_close(arcn, fd)
966	register ARCHD *arcn;
967	register int *fd;
968#endif
969{
970	/*
971	 * make sure the file is open
972	 */
973	if (*fd < 0)
974		return;
975
976	(void)close(*fd);
977	*fd = -1;
978	if (!tflag)
979		return;
980
981	/*
982	 * user wants last access time reset
983	 */
984	set_ftime(arcn->org_name, arcn->sb.st_mtime, arcn->sb.st_atime, 1);
985	return;
986}
987
988/*
989 * set_crc()
990 *	read a file to calculate its crc. This is a real drag. Archive formats
991 *	that have this, end up reading the file twice (we have to write the
992 *	header WITH the crc before writing the file contents. Oh well...
993 * Return:
994 *	0 if was able to calculate the crc, -1 otherwise
995 */
996
997#if __STDC__
998int
999set_crc(register ARCHD *arcn, register int fd)
1000#else
1001int
1002set_crc(arcn, fd)
1003	register ARCHD *arcn;
1004	register int fd;
1005#endif
1006{
1007	register int i;
1008	register int res;
1009	off_t cpcnt = 0L;
1010	u_long size;
1011	unsigned long crc = 0L;
1012	char tbuf[FILEBLK];
1013	struct stat sb;
1014
1015	if (fd < 0) {
1016		/*
1017		 * hmm, no fd, should never happen. well no crc then.
1018		 */
1019		arcn->crc = 0L;
1020		return(0);
1021	}
1022
1023	if ((size = (u_long)arcn->sb.st_blksize) > (u_long)sizeof(tbuf))
1024		size = (u_long)sizeof(tbuf);
1025
1026	/*
1027	 * read all the bytes we think that there are in the file. If the user
1028	 * is trying to archive an active file, forget this file.
1029	 */
1030	for(;;) {
1031		if ((res = read(fd, tbuf, size)) <= 0)
1032			break;
1033		cpcnt += res;
1034		for (i = 0; i < res; ++i)
1035			crc += (tbuf[i] & 0xff);
1036	}
1037
1038	/*
1039	 * safety check. we want to avoid archiving files that are active as
1040	 * they can create inconsistant archive copies.
1041	 */
1042	if (cpcnt != arcn->sb.st_size)
1043		warn(1, "File changed size %s", arcn->org_name);
1044	else if (fstat(fd, &sb) < 0)
1045		syswarn(1, errno, "Failed stat on %s", arcn->org_name);
1046	else if (arcn->sb.st_mtime != sb.st_mtime)
1047		warn(1, "File %s was modified during read", arcn->org_name);
1048	else if (lseek(fd, (off_t)0L, SEEK_SET) < 0)
1049		syswarn(1, errno, "File rewind failed on: %s", arcn->org_name);
1050	else {
1051		arcn->crc = crc;
1052		return(0);
1053	}
1054	return(-1);
1055}
1056