GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: bin/pax/file_subs.c Lines: 135 341 39.6 %
Date: 2017-11-07 Branches: 74 274 27.0 %

Line Branch Exec Source
1
/*	$OpenBSD: file_subs.c,v 1.53 2017/01/21 08:17:06 krw 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
#include <sys/stat.h>
38
#include <err.h>
39
#include <errno.h>
40
#include <fcntl.h>
41
#include <limits.h>
42
#include <stdio.h>
43
#include <stdlib.h>
44
#include <string.h>
45
#include <unistd.h>
46
#include "pax.h"
47
#include "extern.h"
48
49
static int
50
mk_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
/*
58
 * file_creat()
59
 *	Create and open a file.
60
 * Return:
61
 *	file descriptor or -1 for failure
62
 */
63
64
int
65
file_creat(ARCHD *arcn)
66
{
67
	int fd = -1;
68
	mode_t file_mode;
69
	int oerrno;
70
71
	/*
72
	 * Assume file doesn't exist, so just try to create it, most times this
73
	 * works. We have to take special handling when the file does exist. To
74
	 * detect this, we use O_EXCL. For example when trying to create a
75
	 * file and a character device or fifo exists with the same name, we
76
	 * can accidently open the device by mistake (or block waiting to open).
77
	 * If we find that the open has failed, then spend the effort to
78
	 * figure out why. This strategy was found to have better average
79
	 * performance in common use than checking the file (and the path)
80
	 * first with lstat.
81
	 */
82
20502
	file_mode = arcn->sb.st_mode & FILEBITS;
83
20502
	if ((fd = open(arcn->name, O_WRONLY | O_CREAT | O_EXCL,
84
10251
	    file_mode)) >= 0)
85
10171
		return(fd);
86
87
	/*
88
	 * the file seems to exist. First we try to get rid of it (found to be
89
	 * the second most common failure when traced). If this fails, only
90
	 * then we go to the expense to check and create the path to the file
91
	 */
92
80
	if (unlnk_exist(arcn->name, arcn->type) != 0)
93
		return(-1);
94
95
	for (;;) {
96
		/*
97
		 * try to open it again, if this fails, check all the nodes in
98
		 * the path and give it a final try. if chk_path() finds that
99
		 * it cannot fix anything, we will skip the last attempt
100
		 */
101
320
		if ((fd = open(arcn->name, O_WRONLY | O_CREAT | O_TRUNC,
102
160
		    file_mode)) >= 0)
103
			break;
104
80
		oerrno = errno;
105

160
		if (nodirs || chk_path(arcn->name,arcn->sb.st_uid,arcn->sb.st_gid) < 0) {
106
			syswarn(1, oerrno, "Unable to create %s", arcn->name);
107
			return(-1);
108
		}
109
	}
110
80
	return(fd);
111
10251
}
112
113
/*
114
 * file_close()
115
 *	Close file descriptor to a file just created by pax. Sets modes,
116
 *	ownership and times as required.
117
 * Return:
118
 *	0 for success, -1 for failure
119
 */
120
121
void
122
file_close(ARCHD *arcn, int fd)
123
{
124
	int res = 0;
125
126
20502
	if (fd < 0)
127
		return;
128
129
	/*
130
	 * set owner/groups first as this may strip off mode bits we want
131
	 * then set file permission modes. Then set file access and
132
	 * modification times.
133
	 */
134
10251
	if (pids)
135
		res = fset_ids(arcn->name, fd, arcn->sb.st_uid,
136
		    arcn->sb.st_gid);
137
138
	/*
139
	 * IMPORTANT SECURITY NOTE:
140
	 * if not preserving mode or we cannot set uid/gid, then PROHIBIT
141
	 * set uid/gid bits
142
	 */
143
10251
	if (!pmode || res)
144
10251
		arcn->sb.st_mode &= ~(SETBITS);
145
10251
	if (pmode)
146
		fset_pmode(arcn->name, fd, arcn->sb.st_mode);
147
10251
	if (patime || pmtime)
148
20502
		fset_ftime(arcn->name, fd, &arcn->sb.st_mtim,
149
10251
		    &arcn->sb.st_atim, 0);
150
10251
	if (close(fd) < 0)
151
		syswarn(0, errno, "Unable to close file descriptor on %s",
152
		    arcn->name);
153
20502
}
154
155
/*
156
 * lnk_creat()
157
 *	Create a hard link to arcn->ln_name from arcn->name. arcn->ln_name
158
 *	must exist;
159
 * Return:
160
 *	0 if ok, -1 otherwise
161
 */
162
163
int
164
lnk_creat(ARCHD *arcn)
165
{
166
68
	struct stat sb;
167
	int res;
168
169
	/*
170
	 * we may be running as root, so we have to be sure that link target
171
	 * is not a directory, so we lstat and check
172
	 */
173
34
	if (lstat(arcn->ln_name, &sb) < 0) {
174
		syswarn(1,errno,"Unable to link to %s from %s", arcn->ln_name,
175
		    arcn->name);
176
		return(-1);
177
	}
178
179
34
	if (S_ISDIR(sb.st_mode)) {
180
		paxwarn(1, "A hard link to the directory %s is not allowed",
181
		    arcn->ln_name);
182
		return(-1);
183
	}
184
185
34
	res = mk_link(arcn->ln_name, &sb, arcn->name, 0);
186
34
	if (res == 0) {
187
		/* check for a hardlink to a placeholder symlink */
188
34
		res = sltab_add_link(arcn->name, &sb);
189
190
34
		if (res < 0) {
191
			/* arrgh, it failed, clean up */
192
			unlink(arcn->name);
193
		}
194
	}
195
196
34
	return (res);
197
34
}
198
199
/*
200
 * cross_lnk()
201
 *	Create a hard link to arcn->org_name from arcn->name. Only used in copy
202
 *	with the -l flag. No warning or error if this does not succeed (we will
203
 *	then just create the file)
204
 * Return:
205
 *	1 if copy() should try to create this file node
206
 *	0 if cross_lnk() ok, -1 for fatal flaw (like linking to self).
207
 */
208
209
int
210
cross_lnk(ARCHD *arcn)
211
{
212
	/*
213
	 * try to make a link to original file (-l flag in copy mode). make
214
	 * sure we do not try to link to directories in case we are running as
215
	 * root (and it might succeed).
216
	 */
217
	if (arcn->type == PAX_DIR)
218
		return(1);
219
	return(mk_link(arcn->org_name, &(arcn->sb), arcn->name, 1));
220
}
221
222
/*
223
 * chk_same()
224
 *	In copy mode if we are not trying to make hard links between the src
225
 *	and destinations, make sure we are not going to overwrite ourselves by
226
 *	accident. This slows things down a little, but we have to protect all
227
 *	those people who make typing errors.
228
 * Return:
229
 *	1 the target does not exist, go ahead and copy
230
 *	0 skip it file exists (-k) or may be the same as source file
231
 */
232
233
int
234
chk_same(ARCHD *arcn)
235
{
236
4624
	struct stat sb;
237
238
	/*
239
	 * if file does not exist, return. if file exists and -k, skip it
240
	 * quietly
241
	 */
242
2312
	if (lstat(arcn->name, &sb) < 0)
243
2312
		return(1);
244
	if (kflag)
245
		return(0);
246
247
	/*
248
	 * better make sure the user does not have src == dest by mistake
249
	 */
250
	if ((arcn->sb.st_dev == sb.st_dev) && (arcn->sb.st_ino == sb.st_ino)) {
251
		paxwarn(1, "Unable to copy %s, file would overwrite itself",
252
		    arcn->name);
253
		return(0);
254
	}
255
	return(1);
256
2312
}
257
258
/*
259
 * mk_link()
260
 *	try to make a hard link between two files. if ign set, we do not
261
 *	complain.
262
 * Return:
263
 *	0 if successful (or we are done with this file but no error, such as
264
 *	finding the from file exists and the user has set -k).
265
 *	1 when ign was set to indicates we could not make the link but we
266
 *	should try to copy/extract the file as that might work (and is an
267
 *	allowed option). -1 an error occurred.
268
 */
269
270
static int
271
mk_link(char *to, struct stat *to_sb, char *from, int ign)
272
{
273
68
	struct stat sb;
274
	int oerrno;
275
276
	/*
277
	 * if from file exists, it has to be unlinked to make the link. If the
278
	 * file exists and -k is set, skip it quietly
279
	 */
280
34
	if (lstat(from, &sb) == 0) {
281
		if (kflag)
282
			return(0);
283
284
		/*
285
		 * make sure it is not the same file, protect the user
286
		 */
287
		if ((to_sb->st_dev==sb.st_dev)&&(to_sb->st_ino == sb.st_ino)) {
288
			paxwarn(1, "Unable to link file %s to itself", to);
289
			return(-1);
290
		}
291
292
		/*
293
		 * try to get rid of the file, based on the type
294
		 */
295
		if (S_ISDIR(sb.st_mode)) {
296
			if (rmdir(from) < 0) {
297
				syswarn(1, errno, "Unable to remove %s", from);
298
				return(-1);
299
			}
300
			delete_dir(sb.st_dev, sb.st_ino);
301
		} else if (unlink(from) < 0) {
302
			if (!ign) {
303
				syswarn(1, errno, "Unable to remove %s", from);
304
				return(-1);
305
			}
306
			return(1);
307
		}
308
	}
309
310
	/*
311
	 * from file is gone (or did not exist), try to make the hard link.
312
	 * if it fails, check the path and try it again (if chk_path() says to
313
	 * try again)
314
	 */
315
	for (;;) {
316
34
		if (linkat(AT_FDCWD, to, AT_FDCWD, from, 0) == 0)
317
			break;
318
		oerrno = errno;
319
		if (!nodirs && chk_path(from, to_sb->st_uid, to_sb->st_gid) == 0)
320
			continue;
321
		if (!ign) {
322
			syswarn(1, oerrno, "Could not link to %s from %s", to,
323
			    from);
324
			return(-1);
325
		}
326
		return(1);
327
	}
328
329
	/*
330
	 * all right the link was made
331
	 */
332
34
	return(0);
333
34
}
334
335
/*
336
 * node_creat()
337
 *	create an entry in the file system (other than a file or hard link).
338
 *	If successful, sets uid/gid modes and times as required.
339
 * Return:
340
 *	0 if ok, -1 otherwise
341
 */
342
343
int
344
node_creat(ARCHD *arcn)
345
{
346
	int res;
347
	int ign = 0;
348
	int oerrno;
349
	int pass = 0;
350
	mode_t file_mode;
351
1648
	struct stat sb;
352
824
	char target[PATH_MAX];
353
824
	char *nm = arcn->name;
354
	int len, defer_pmode = 0;
355
356
	/*
357
	 * create node based on type, if that fails try to unlink the node and
358
	 * try again. finally check the path and try again. As noted in the
359
	 * file and link creation routines, this method seems to exhibit the
360
	 * best performance in general use workloads.
361
	 */
362
824
	file_mode = arcn->sb.st_mode & FILEBITS;
363
364
824
	for (;;) {
365

824
		switch (arcn->type) {
366
		case PAX_DIR:
367
			/*
368
			 * If -h (or -L) was given in tar-mode, follow the
369
			 * potential symlink chain before trying to create the
370
			 * directory.
371
			 */
372
824
			if (op_mode == OP_TAR && Lflag) {
373
				while (lstat(nm, &sb) == 0 &&
374
				    S_ISLNK(sb.st_mode)) {
375
					len = readlink(nm, target,
376
					    sizeof target - 1);
377
					if (len == -1) {
378
						syswarn(0, errno,
379
						   "cannot follow symlink %s in chain for %s",
380
						    nm, arcn->name);
381
						res = -1;
382
						goto badlink;
383
					}
384
					target[len] = '\0';
385
					nm = target;
386
				}
387
			}
388
824
			res = mkdir(nm, file_mode);
389
390
badlink:
391
824
			if (ign)
392
				res = 0;
393
			break;
394
		case PAX_CHR:
395
			file_mode |= S_IFCHR;
396
			res = mknod(nm, file_mode, arcn->sb.st_rdev);
397
			break;
398
		case PAX_BLK:
399
			file_mode |= S_IFBLK;
400
			res = mknod(nm, file_mode, arcn->sb.st_rdev);
401
			break;
402
		case PAX_FIF:
403
			res = mkfifo(nm, file_mode);
404
			break;
405
		case PAX_SCK:
406
			/*
407
			 * Skip sockets, operation has no meaning under BSD
408
			 */
409
			paxwarn(0,
410
			    "%s skipped. Sockets cannot be copied or extracted",
411
			    nm);
412
			return(-1);
413
		case PAX_SLK:
414
			if (arcn->ln_name[0] != '/' &&
415
			    !has_dotdot(arcn->ln_name))
416
				res = symlink(arcn->ln_name, nm);
417
			else {
418
				/*
419
				 * absolute symlinks and symlinks with ".."
420
				 * have to be deferred to prevent the archive
421
				 * from bootstrapping itself to outside the
422
				 * working directory.
423
				 */
424
				res = sltab_add_sym(nm, arcn->ln_name,
425
				    arcn->sb.st_mode);
426
				if (res == 0)
427
					defer_pmode = 1;
428
			}
429
			break;
430
		case PAX_CTG:
431
		case PAX_HLK:
432
		case PAX_HRG:
433
		case PAX_REG:
434
		default:
435
			/*
436
			 * we should never get here
437
			 */
438
			paxwarn(0, "%s has an unknown file type, skipping",
439
				nm);
440
			return(-1);
441
		}
442
443
		/*
444
		 * if we were able to create the node break out of the loop,
445
		 * otherwise try to unlink the node and try again. if that
446
		 * fails check the full path and try a final time.
447
		 */
448
824
		if (res == 0)
449
			break;
450
451
		/*
452
		 * we failed to make the node
453
		 */
454
		oerrno = errno;
455
		if ((ign = unlnk_exist(nm, arcn->type)) < 0)
456
			return(-1);
457
458
		if (++pass <= 1)
459
			continue;
460
461
		if (nodirs || chk_path(nm,arcn->sb.st_uid,arcn->sb.st_gid) < 0) {
462
			syswarn(1, oerrno, "Could not create: %s", nm);
463
			return(-1);
464
		}
465
	}
466
467
	/*
468
	 * we were able to create the node. set uid/gid, modes and times
469
	 */
470
824
	if (pids)
471
		res = set_ids(nm, arcn->sb.st_uid, arcn->sb.st_gid);
472
	else
473
		res = 0;
474
475
	/*
476
	 * IMPORTANT SECURITY NOTE:
477
	 * if not preserving mode or we cannot set uid/gid, then PROHIBIT any
478
	 * set uid/gid bits
479
	 */
480
824
	if (!pmode || res)
481
824
		arcn->sb.st_mode &= ~(SETBITS);
482
824
	if (pmode && !defer_pmode)
483
		set_pmode(nm, arcn->sb.st_mode);
484
485
824
	if (arcn->type == PAX_DIR && op_mode != OP_CPIO) {
486
		/*
487
		 * Dirs must be processed again at end of extract to set times
488
		 * and modes to agree with those stored in the archive. However
489
		 * to allow extract to continue, we may have to also set owner
490
		 * rights. This allows nodes in the archive that are children
491
		 * of this directory to be extracted without failure. Both time
492
		 * and modes will be fixed after the entire archive is read and
493
		 * before pax exits.  To do that safely, we want the dev+ino
494
		 * of the directory we created.
495
		 */
496
824
		if (lstat(nm, &sb) < 0) {
497
			syswarn(0, errno,"Could not access %s (stat)", nm);
498
824
		} else if (access(nm, R_OK | W_OK | X_OK) < 0) {
499
			/*
500
			 * We have to add rights to the dir, so we make
501
			 * sure to restore the mode. The mode must be
502
			 * restored AS CREATED and not as stored if
503
			 * pmode is not set.
504
			 */
505
			set_pmode(nm,
506
			    ((sb.st_mode & FILEBITS) | S_IRWXU));
507
			if (!pmode)
508
				arcn->sb.st_mode = sb.st_mode;
509
510
			/*
511
			 * we have to force the mode to what was set
512
			 * here, since we changed it from the default
513
			 * as created.
514
			 */
515
			arcn->sb.st_dev = sb.st_dev;
516
			arcn->sb.st_ino = sb.st_ino;
517
			add_dir(nm, &(arcn->sb), 1);
518
824
		} else if (pmode || patime || pmtime) {
519
824
			arcn->sb.st_dev = sb.st_dev;
520
824
			arcn->sb.st_ino = sb.st_ino;
521
824
			add_dir(nm, &(arcn->sb), 0);
522
824
		}
523
	} else if (patime || pmtime)
524
		set_ftime(nm, &arcn->sb.st_mtim, &arcn->sb.st_atim, 0);
525
824
	return(0);
526
824
}
527
528
/*
529
 * unlnk_exist()
530
 *	Remove node from file system with the specified name. We pass the type
531
 *	of the node that is going to replace it. When we try to create a
532
 *	directory and find that it already exists, we allow processing to
533
 *	continue as proper modes etc will always be set for it later on.
534
 * Return:
535
 *	0 is ok to proceed, no file with the specified name exists
536
 *	-1 we were unable to remove the node, or we should not remove it (-k)
537
 *	1 we found a directory and we were going to create a directory.
538
 */
539
540
int
541
unlnk_exist(char *name, int type)
542
{
543
160
	struct stat sb;
544
545
	/*
546
	 * the file does not exist, or -k we are done
547
	 */
548
80
	if (lstat(name, &sb) < 0)
549
80
		return(0);
550
	if (kflag)
551
		return(-1);
552
553
	if (S_ISDIR(sb.st_mode)) {
554
		/*
555
		 * try to remove a directory, if it fails and we were going to
556
		 * create a directory anyway, tell the caller (return a 1)
557
		 */
558
		if (rmdir(name) < 0) {
559
			if (type == PAX_DIR)
560
				return(1);
561
			syswarn(1,errno,"Unable to remove directory %s", name);
562
			return(-1);
563
		}
564
		delete_dir(sb.st_dev, sb.st_ino);
565
		return(0);
566
	}
567
568
	/*
569
	 * try to get rid of all non-directory type nodes
570
	 */
571
	if (unlink(name) < 0) {
572
		syswarn(1, errno, "Could not unlink %s", name);
573
		return(-1);
574
	}
575
	return(0);
576
80
}
577
578
/*
579
 * chk_path()
580
 *	We were trying to create some kind of node in the file system and it
581
 *	failed. chk_path() makes sure the path up to the node exists and is
582
 *	writeable. When we have to create a directory that is missing along the
583
 *	path somewhere, the directory we create will be set to the same
584
 *	uid/gid as the file has (when uid and gid are being preserved).
585
 *	NOTE: this routine is a real performance loss. It is only used as a
586
 *	last resort when trying to create entries in the file system.
587
 * Return:
588
 *	-1 when it could find nothing it is allowed to fix.
589
 *	0 otherwise
590
 */
591
592
int
593
chk_path(char *name, uid_t st_uid, gid_t st_gid)
594
{
595
	char *spt = name;
596
	char *next;
597
160
	struct stat sb;
598
	int retval = -1;
599
600
	/*
601
	 * watch out for paths with nodes stored directly in / (e.g. /bozo)
602
	 */
603
320
	while (*spt == '/')
604
80
		++spt;
605
606
	for (;;) {
607
		/*
608
		 * work forward from the first / and check each part of the path
609
		 */
610
404
		spt = strchr(spt, '/');
611
404
		if (spt == NULL)
612
			break;
613
614
		/*
615
		 * skip over duplicate slashes; stop if there're only
616
		 * trailing slashes left
617
		 */
618
324
		next = spt + 1;
619
648
		while (*next == '/')
620
			next++;
621
324
		if (*next == '\0')
622
			break;
623
624
324
		*spt = '\0';
625
626
		/*
627
		 * if it exists we assume it is a directory, it is not within
628
		 * the spec (at least it seems to read that way) to alter the
629
		 * file system for nodes NOT EXPLICITLY stored on the archive.
630
		 * If that assumption is changed, you would test the node here
631
		 * and figure out how to get rid of it (probably like some
632
		 * recursive unlink()) or fix up the directory permissions if
633
		 * required (do an access()).
634
		 */
635
324
		if (lstat(name, &sb) == 0) {
636
244
			*spt = '/';
637
			spt = next;
638
244
			continue;
639
		}
640
641
		/*
642
		 * the path fails at this point, see if we can create the
643
		 * needed directory and continue on
644
		 */
645
80
		if (mkdir(name, S_IRWXU | S_IRWXG | S_IRWXO) < 0) {
646
			*spt = '/';
647
			retval = -1;
648
			break;
649
		}
650
651
		/*
652
		 * we were able to create the directory. We will tell the
653
		 * caller that we found something to fix, and it is ok to try
654
		 * and create the node again.
655
		 */
656
		retval = 0;
657
80
		if (pids)
658
			(void)set_ids(name, st_uid, st_gid);
659
660
		/*
661
		 * make sure the user doesn't have some strange umask that
662
		 * causes this newly created directory to be unusable. We fix
663
		 * the modes and restore them back to the creation default at
664
		 * the end of pax
665
		 */
666

80
		if ((access(name, R_OK | W_OK | X_OK) < 0) &&
667
		    (lstat(name, &sb) == 0)) {
668
			set_pmode(name, ((sb.st_mode & FILEBITS) | S_IRWXU));
669
			add_dir(name, &sb, 1);
670
		}
671
80
		*spt = '/';
672
		spt = next;
673
80
		continue;
674
	}
675
80
	return(retval);
676
80
}
677
678
/*
679
 * set_ftime()
680
 *	Set the access time and modification time for a named file. If frc
681
 *	is non-zero we force these times to be set even if the user did not
682
 *	request access and/or modification time preservation (this is also
683
 *	used by -t to reset access times).
684
 *	When ign is zero, only those times the user has asked for are set, the
685
 *	other ones are left alone.
686
 */
687
688
void
689
set_ftime(const char *fnm, const struct timespec *mtimp,
690
    const struct timespec *atimp, int frc)
691
{
692
	struct timespec tv[2];
693
694
	tv[0] = *atimp;
695
	tv[1] = *mtimp;
696
697
	if (!frc) {
698
		/*
699
		 * if we are not forcing, only set those times the user wants
700
		 * set.
701
		 */
702
		if (!patime)
703
			tv[0].tv_nsec = UTIME_OMIT;
704
		if (!pmtime)
705
			tv[1].tv_nsec = UTIME_OMIT;
706
	}
707
708
	/*
709
	 * set the times
710
	 */
711
	if (utimensat(AT_FDCWD, fnm, tv, AT_SYMLINK_NOFOLLOW) < 0)
712
		syswarn(1, errno, "Access/modification time set failed on: %s",
713
		    fnm);
714
}
715
716
void
717
fset_ftime(const char *fnm, int fd, const struct timespec *mtimp,
718
    const struct timespec *atimp, int frc)
719
{
720
22150
	struct timespec tv[2];
721
722
723
11075
	tv[0] = *atimp;
724
11075
	tv[1] = *mtimp;
725
726
11075
	if (!frc) {
727
		/*
728
		 * if we are not forcing, only set those times the user wants
729
		 * set.
730
		 */
731
11075
		if (!patime)
732
2312
			tv[0].tv_nsec = UTIME_OMIT;
733
11075
		if (!pmtime)
734
			tv[1].tv_nsec = UTIME_OMIT;
735
	}
736
	/*
737
	 * set the times
738
	 */
739
11075
	if (futimens(fd, tv) < 0)
740
		syswarn(1, errno, "Access/modification time set failed on: %s",
741
		    fnm);
742
11075
}
743
744
/*
745
 * set_ids()
746
 *	set the uid and gid of a file system node
747
 * Return:
748
 *	0 when set, -1 on failure
749
 */
750
751
int
752
set_ids(char *fnm, uid_t uid, gid_t gid)
753
{
754
	if (fchownat(AT_FDCWD, fnm, uid, gid, AT_SYMLINK_NOFOLLOW) < 0) {
755
		/*
756
		 * ignore EPERM unless in verbose mode or being run by root.
757
		 * if running as pax, POSIX requires a warning.
758
		 */
759
		if (op_mode == OP_PAX || errno != EPERM || vflag ||
760
		    geteuid() == 0)
761
			syswarn(1, errno, "Unable to set file uid/gid of %s",
762
			    fnm);
763
		return(-1);
764
	}
765
	return(0);
766
}
767
768
int
769
fset_ids(char *fnm, int fd, uid_t uid, gid_t gid)
770
{
771
	if (fchown(fd, uid, gid) < 0) {
772
		/*
773
		 * ignore EPERM unless in verbose mode or being run by root.
774
		 * if running as pax, POSIX requires a warning.
775
		 */
776
		if (op_mode == OP_PAX || errno != EPERM || vflag ||
777
		    geteuid() == 0)
778
			syswarn(1, errno, "Unable to set file uid/gid of %s",
779
			    fnm);
780
		return(-1);
781
	}
782
	return(0);
783
}
784
785
/*
786
 * set_pmode()
787
 *	Set file access mode
788
 */
789
790
void
791
set_pmode(char *fnm, mode_t mode)
792
{
793
	mode &= ABITS;
794
	if (fchmodat(AT_FDCWD, fnm, mode, AT_SYMLINK_NOFOLLOW) < 0)
795
		syswarn(1, errno, "Could not set permissions on %s", fnm);
796
}
797
798
void
799
fset_pmode(char *fnm, int fd, mode_t mode)
800
{
801
	mode &= ABITS;
802
	if (fchmod(fd, mode) < 0)
803
		syswarn(1, errno, "Could not set permissions on %s", fnm);
804
}
805
806
/*
807
 * set_attr()
808
 *	Given a DIRDATA, restore the mode and times as indicated, but
809
 *	only after verifying that it's the directory that we wanted.
810
 */
811
int
812
set_attr(const struct file_times *ft, int force_times, mode_t mode,
813
    int do_mode, int in_sig)
814
{
815
1648
	struct stat sb;
816
	int fd, r;
817
818
824
	if (!do_mode && !force_times && !patime && !pmtime)
819
		return (0);
820
821
	/*
822
	 * We could legitimately go through a symlink here,
823
	 * so do *not* use O_NOFOLLOW.  The dev+ino check will
824
	 * protect us from evil.
825
	 */
826
824
	fd = open(ft->ft_name, O_RDONLY | O_DIRECTORY);
827
824
	if (fd == -1) {
828
		if (!in_sig)
829
			syswarn(1, errno, "Unable to restore mode and times"
830
			    " for directory: %s", ft->ft_name);
831
		return (-1);
832
	}
833
834
824
	if (fstat(fd, &sb) == -1) {
835
		if (!in_sig)
836
			syswarn(1, errno, "Unable to stat directory: %s",
837
			    ft->ft_name);
838
		r = -1;
839

1648
	} else if (ft->ft_ino != sb.st_ino || ft->ft_dev != sb.st_dev) {
840
		if (!in_sig)
841
			paxwarn(1, "Directory vanished before restoring"
842
			    " mode and times: %s", ft->ft_name);
843
		r = -1;
844
	} else {
845
		/* Whew, it's a match!  Is there anything to change? */
846

824
		if (do_mode && (mode & ABITS) != (sb.st_mode & ABITS))
847
			fset_pmode(ft->ft_name, fd, mode);
848

824
		if (((force_times || patime) &&
849

1648
		    timespeccmp(&ft->ft_atim, &sb.st_atim, !=)) ||
850
		    ((force_times || pmtime) &&
851
		    timespeccmp(&ft->ft_mtim, &sb.st_mtim, !=)))
852
1648
			fset_ftime(ft->ft_name, fd, &ft->ft_mtim,
853
824
			    &ft->ft_atim, force_times);
854
		r = 0;
855
	}
856
824
	close(fd);
857
858
824
	return (r);
859
824
}
860
861
862
/*
863
 * file_write()
864
 *	Write/copy a file (during copy or archive extract). This routine knows
865
 *	how to copy files with lseek holes in it. (Which are read as file
866
 *	blocks containing all 0's but do not have any file blocks associated
867
 *	with the data). Typical examples of these are files created by dbm
868
 *	variants (.pag files). While the file size of these files are huge, the
869
 *	actual storage is quite small (the files are sparse). The problem is
870
 *	the holes read as all zeros so are probably stored on the archive that
871
 *	way (there is no way to determine if the file block is really a hole,
872
 *	we only know that a file block of all zero's can be a hole).
873
 *	At this writing, no major archive format knows how to archive files
874
 *	with holes. However, on extraction (or during copy, -rw) we have to
875
 *	deal with these files. Without detecting the holes, the files can
876
 *	consume a lot of file space if just written to disk. This replacement
877
 *	for write when passed the basic allocation size of a file system block,
878
 *	uses lseek whenever it detects the input data is all 0 within that
879
 *	file block. In more detail, the strategy is as follows:
880
 *	While the input is all zero keep doing an lseek. Keep track of when we
881
 *	pass over file block boundaries. Only write when we hit a non zero
882
 *	input. once we have written a file block, we continue to write it to
883
 *	the end (we stop looking at the input). When we reach the start of the
884
 *	next file block, start checking for zero blocks again. Working on file
885
 *	block boundaries significantly reduces the overhead when copying files
886
 *	that are NOT very sparse. This overhead (when compared to a write) is
887
 *	almost below the measurement resolution on many systems. Without it,
888
 *	files with holes cannot be safely copied. It does has a side effect as
889
 *	it can put holes into files that did not have them before, but that is
890
 *	not a problem since the file contents are unchanged (in fact it saves
891
 *	file space). (Except on paging files for diskless clients. But since we
892
 *	cannot determine one of those file from here, we ignore them). If this
893
 *	ever ends up on a system where CTG files are supported and the holes
894
 *	are not desired, just do a conditional test in those routines that
895
 *	call file_write() and have it call write() instead. BEFORE CLOSING THE
896
 *	FILE, make sure to call file_flush() when the last write finishes with
897
 *	an empty block. A lot of file systems will not create an lseek hole at
898
 *	the end. In this case we drop a single 0 at the end to force the
899
 *	trailing 0's in the file.
900
 *	---Parameters---
901
 *	rem: how many bytes left in this file system block
902
 *	isempt: have we written to the file block yet (is it empty)
903
 *	sz: basic file block allocation size
904
 *	cnt: number of bytes on this write
905
 *	str: buffer to write
906
 * Return:
907
 *	number of bytes written, -1 on write (or lseek) error.
908
 */
909
910
int
911
file_write(int fd, char *str, int cnt, int *rem, int *isempt, int sz,
912
	char *name)
913
{
914
	char *pt;
915
	char *end;
916
	int wcnt;
917
	char *st = str;
918
	char **strp;
919
920
	/*
921
	 * while we have data to process
922
	 */
923
72483
	while (cnt) {
924
16452
		if (!*rem) {
925
			/*
926
			 * We are now at the start of file system block again
927
			 * (or what we think one is...). start looking for
928
			 * empty blocks again
929
			 */
930
3429
			*isempt = 1;
931
3429
			*rem = sz;
932
3429
		}
933
934
		/*
935
		 * only examine up to the end of the current file block or
936
		 * remaining characters to write, whatever is smaller
937
		 */
938
49356
		wcnt = MINIMUM(cnt, *rem);
939
16452
		cnt -= wcnt;
940
16452
		*rem -= wcnt;
941
16452
		if (*isempt) {
942
			/*
943
			 * have not written to this block yet, so we keep
944
			 * looking for zero's
945
			 */
946
			pt = st;
947
11315
			end = st + wcnt;
948
949
			/*
950
			 * look for a zero filled buffer
951
			 */
952

45260
			while ((pt < end) && (*pt == '\0'))
953
				++pt;
954
955
11315
			if (pt == end) {
956
				/*
957
				 * skip, buf is empty so far
958
				 */
959
				if (fd > -1 &&
960
				    lseek(fd, wcnt, SEEK_CUR) < 0) {
961
					syswarn(1,errno,"File seek on %s",
962
					    name);
963
					return(-1);
964
				}
965
				st = pt;
966
				continue;
967
			}
968
			/*
969
			 * drat, the buf is not zero filled
970
			 */
971
11315
			*isempt = 0;
972
11315
		}
973
974
		/*
975
		 * have non-zero data in this file system block, have to write
976
		 */
977
16452
		switch (fd) {
978
		case -1:
979
			strp = &gnu_name_string;
980
			break;
981
		case -2:
982
			strp = &gnu_link_string;
983
			break;
984
		default:
985
			strp = NULL;
986
16452
			break;
987
		}
988
16452
		if (strp) {
989
			if (*strp)
990
				err(1, "WARNING! Major Internal Error! GNU hack Failing!");
991
			*strp = malloc(wcnt + 1);
992
			if (*strp == NULL) {
993
				paxwarn(1, "Out of memory");
994
				return(-1);
995
			}
996
			memcpy(*strp, st, wcnt);
997
			(*strp)[wcnt] = '\0';
998
			break;
999
16452
		} else if (write(fd, st, wcnt) != wcnt) {
1000
			syswarn(1, errno, "Failed write to file %s", name);
1001
			return(-1);
1002
		}
1003
16452
		st += wcnt;
1004
	}
1005
13193
	return(st - str);
1006
13193
}
1007
1008
/*
1009
 * file_flush()
1010
 *	when the last file block in a file is zero, many file systems will not
1011
 *	let us create a hole at the end. To get the last block with zeros, we
1012
 *	write the last BYTE with a zero (back up one byte and write a zero).
1013
 */
1014
1015
void
1016
file_flush(int fd, char *fname, int isempt)
1017
{
1018
	static char blnk[] = "\0";
1019
1020
	/*
1021
	 * silly test, but make sure we are only called when the last block is
1022
	 * filled with all zeros.
1023
	 */
1024
	if (!isempt)
1025
		return;
1026
1027
	/*
1028
	 * move back one byte and write a zero
1029
	 */
1030
	if (lseek(fd, -1, SEEK_CUR) < 0) {
1031
		syswarn(1, errno, "Failed seek on file %s", fname);
1032
		return;
1033
	}
1034
1035
	if (write(fd, blnk, 1) < 0)
1036
		syswarn(1, errno, "Failed write to file %s", fname);
1037
}
1038
1039
/*
1040
 * rdfile_close()
1041
 *	close a file we have been reading (to copy or archive). If we have to
1042
 *	reset access time (tflag) do so (the times are stored in arcn).
1043
 */
1044
1045
void
1046
rdfile_close(ARCHD *arcn, int *fd)
1047
{
1048
	/*
1049
	 * make sure the file is open
1050
	 */
1051
5088
	if (*fd < 0)
1052
		return;
1053
1054
	/*
1055
	 * user wants last access time reset
1056
	 */
1057
2502
	if (tflag)
1058
		fset_ftime(arcn->org_name, *fd, &arcn->sb.st_mtim,
1059
		    &arcn->sb.st_atim, 1);
1060
1061
2502
	(void)close(*fd);
1062
2502
	*fd = -1;
1063
5046
}
1064
1065
/*
1066
 * set_crc()
1067
 *	read a file to calculate its crc. This is a real drag. Archive formats
1068
 *	that have this, end up reading the file twice (we have to write the
1069
 *	header WITH the crc before writing the file contents. Oh well...
1070
 * Return:
1071
 *	0 if was able to calculate the crc, -1 otherwise
1072
 */
1073
1074
int
1075
set_crc(ARCHD *arcn, int fd)
1076
{
1077
	int i;
1078
	int res;
1079
	off_t cpcnt = 0;
1080
	size_t size;
1081
	u_int32_t crc = 0;
1082
	char tbuf[FILEBLK];
1083
	struct stat sb;
1084
1085
	if (fd < 0) {
1086
		/*
1087
		 * hmm, no fd, should never happen. well no crc then.
1088
		 */
1089
		arcn->crc = 0;
1090
		return(0);
1091
	}
1092
1093
	if ((size = arcn->sb.st_blksize) > sizeof(tbuf))
1094
		size = sizeof(tbuf);
1095
1096
	/*
1097
	 * read all the bytes we think that there are in the file. If the user
1098
	 * is trying to archive an active file, forget this file.
1099
	 */
1100
	for (;;) {
1101
		if ((res = read(fd, tbuf, size)) <= 0)
1102
			break;
1103
		cpcnt += res;
1104
		for (i = 0; i < res; ++i)
1105
			crc += (tbuf[i] & 0xff);
1106
	}
1107
1108
	/*
1109
	 * safety check. we want to avoid archiving files that are active as
1110
	 * they can create inconsistent archive copies.
1111
	 */
1112
	if (cpcnt != arcn->sb.st_size)
1113
		paxwarn(1, "File changed size %s", arcn->org_name);
1114
	else if (fstat(fd, &sb) < 0)
1115
		syswarn(1, errno, "Failed stat on %s", arcn->org_name);
1116
	else if (timespeccmp(&arcn->sb.st_mtim, &sb.st_mtim, !=))
1117
		paxwarn(1, "File %s was modified during read", arcn->org_name);
1118
	else if (lseek(fd, 0, SEEK_SET) < 0)
1119
		syswarn(1, errno, "File rewind failed on: %s", arcn->org_name);
1120
	else {
1121
		arcn->crc = crc;
1122
		return(0);
1123
	}
1124
	return(-1);
1125
}