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