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