xref: /illumos-gate/usr/src/cmd/tar/tar.c (revision 15802598)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright (c) 1988, 2010, Oracle and/or its affiliates. All rights reserved.
23  * Copyright 2012 Milan Jurik. All rights reserved.
24  * Copyright 2015 Joyent, Inc.
25  * Copyright (c) 2016 by Delphix. All rights reserved.
26  */
27 
28 /*	Copyright (c) 1983, 1984, 1985, 1986, 1987, 1988, 1989 AT&T	*/
29 /*	  All Rights Reserved	*/
30 
31 /*	Copyright (c) 1987, 1988 Microsoft Corporation	*/
32 /*	  All Rights Reserved	*/
33 
34 /*
35  * Portions of this source code were derived from Berkeley 4.3 BSD
36  * under license from the Regents of the University of California.
37  */
38 
39 #include <unistd.h>
40 #include <sys/types.h>
41 #include <sys/param.h>
42 #include <sys/stat.h>
43 #include <sys/mkdev.h>
44 #include <sys/wait.h>
45 #include <dirent.h>
46 #include <errno.h>
47 #include <stdio.h>
48 #include <signal.h>
49 #include <ctype.h>
50 #include <locale.h>
51 #include <nl_types.h>
52 #include <langinfo.h>
53 #include <pwd.h>
54 #include <grp.h>
55 #include <fcntl.h>
56 #include <string.h>
57 #include <malloc.h>
58 #include <time.h>
59 #include <utime.h>
60 #include <stdlib.h>
61 #include <stdarg.h>
62 #include <widec.h>
63 #include <sys/mtio.h>
64 #include <sys/acl.h>
65 #include <strings.h>
66 #include <deflt.h>
67 #include <limits.h>
68 #include <iconv.h>
69 #include <assert.h>
70 #include <libgen.h>
71 #include <libintl.h>
72 #include <aclutils.h>
73 #include <libnvpair.h>
74 #include <archives.h>
75 
76 #if defined(__SunOS_5_6) || defined(__SunOS_5_7)
77 extern int defcntl();
78 #endif
79 #if defined(_PC_SATTR_ENABLED)
80 #include <attr.h>
81 #include <libcmdutils.h>
82 #endif
83 
84 /* Trusted Extensions */
85 #include <zone.h>
86 #include <tsol/label.h>
87 #include <sys/tsol/label_macro.h>
88 
89 #include "getresponse.h"
90 /*
91  * Source compatibility
92  */
93 
94 /*
95  * These constants come from archives.h and sys/fcntl.h
96  * and were introduced by the extended attributes project
97  * in Solaris 9.
98  */
99 #if !defined(O_XATTR)
100 #define	AT_SYMLINK_NOFOLLOW	0x1000
101 #define	AT_REMOVEDIR		0x1
102 #define	AT_FDCWD		0xffd19553
103 #define	_XATTR_HDRTYPE		'E'
104 static int attropen();
105 static int fstatat();
106 static int renameat();
107 static int unlinkat();
108 static int openat();
109 static int fchownat();
110 static int futimesat();
111 #endif
112 
113 /*
114  * Compiling with -D_XPG4_2 gets this but produces other problems, so
115  * instead of including sys/time.h and compiling with -D_XPG4_2, I'm
116  * explicitly doing the declaration here.
117  */
118 int utimes(const char *path, const struct timeval timeval_ptr[]);
119 
120 #ifndef MINSIZE
121 #define	MINSIZE 250
122 #endif
123 #define	DEF_FILE "/etc/default/tar"
124 
125 #define	min(a, b)  ((a) < (b) ? (a) : (b))
126 #define	max(a, b)  ((a) > (b) ? (a) : (b))
127 
128 #define	TBLOCK	512	/* tape block size--should be universal */
129 
130 #ifdef	BSIZE
131 #define	SYS_BLOCK BSIZE	/* from sys/param.h:  secondary block size */
132 #else	/* BSIZE */
133 #define	SYS_BLOCK 512	/* default if no BSIZE in param.h */
134 #endif	/* BSIZE */
135 
136 #define	NBLOCK	20
137 #define	NAMSIZ	100
138 #define	PRESIZ	155
139 #define	MAXNAM	256
140 #define	MODEMASK 0777777	/* file creation mode mask */
141 #define	POSIXMODES 07777	/* mask for POSIX mode bits */
142 #define	MAXEXT	9	/* reasonable max # extents for a file */
143 #define	EXTMIN	50	/* min blks left on floppy to split a file */
144 
145 /* max value dblock.dbuf.efsize can store */
146 #define	TAR_EFSIZE_MAX	 0777777777
147 
148 /*
149  * Symbols which specify the values at which the use of the 'E' function
150  * modifier is required to properly store a file.
151  *
152  *     TAR_OFFSET_MAX    - the largest file size we can archive
153  *     OCTAL7CHAR        - the limit for ustar gid, uid, dev
154  */
155 
156 #ifdef XHDR_DEBUG
157 /* tiny values which force the creation of extended header entries */
158 #define	TAR_OFFSET_MAX 9
159 #define	OCTAL7CHAR 2
160 #else
161 /* normal values */
162 #define	TAR_OFFSET_MAX	077777777777ULL
163 #define	OCTAL7CHAR	07777777
164 #endif
165 
166 #define	TBLOCKS(bytes)	(((bytes) + TBLOCK - 1) / TBLOCK)
167 #define	K(tblocks)	((tblocks+1)/2)	/* tblocks to Kbytes for printing */
168 
169 #define	MAXLEV	(PATH_MAX / 2)
170 #define	LEV0	1
171 #define	SYMLINK_LEV0	0
172 
173 #define	TRUE	1
174 #define	FALSE	0
175 
176 #define	XATTR_FILE	1
177 #define	NORMAL_FILE	0
178 
179 #define	PUT_AS_LINK	1
180 #define	PUT_NOTAS_LINK	0
181 
182 #ifndef VIEW_READONLY
183 #define	VIEW_READONLY	"SUNWattr_ro"
184 #endif
185 
186 #ifndef VIEW_READWRITE
187 #define	VIEW_READWRITE	"SUNWattr_rw"
188 #endif
189 
190 #if _FILE_OFFSET_BITS == 64
191 #define	FMT_off_t "lld"
192 #define	FMT_off_t_o "llo"
193 #define	FMT_blkcnt_t "lld"
194 #else
195 #define	FMT_off_t "ld"
196 #define	FMT_off_t_o "lo"
197 #define	FMT_blkcnt_t "ld"
198 #endif
199 
200 /* ACL support */
201 
202 static
203 struct	sec_attr {
204 	char	attr_type;
205 	char	attr_len[7];
206 	char	attr_info[1];
207 } *attr;
208 
209 #if defined(O_XATTR)
210 typedef enum {
211 	ATTR_OK,
212 	ATTR_SKIP,
213 	ATTR_CHDIR_ERR,
214 	ATTR_OPEN_ERR,
215 	ATTR_XATTR_ERR,
216 	ATTR_SATTR_ERR
217 } attr_status_t;
218 #endif
219 
220 #if defined(O_XATTR)
221 typedef enum {
222 	ARC_CREATE,
223 	ARC_RESTORE
224 } arc_action_t;
225 #endif
226 
227 typedef struct attr_data {
228 	char	*attr_parent;
229 	char	*attr_path;
230 	int	attr_parentfd;
231 	int	attr_rw_sysattr;
232 } attr_data_t;
233 
234 /*
235  *
236  * Tar has been changed to support extended attributes.
237  *
238  * As part of this change tar now uses the new *at() syscalls
239  * such as openat, fchownat(), unlinkat()...
240  *
241  * This was done so that attributes can be handled with as few code changes
242  * as possible.
243  *
244  * What this means is that tar now opens the directory that a file or directory
245  * resides in and then performs *at() functions to manipulate the entry.
246  *
247  * For example a new file is now created like this:
248  *
249  * dfd = open(<some dir path>)
250  * fd = openat(dfd, <name>,....);
251  *
252  * or in the case of an extended attribute
253  *
254  * dfd = attropen(<pathname>, ".", ....)
255  *
256  * Once we have a directory file descriptor all of the *at() functions can
257  * be applied to it.
258  *
259  * unlinkat(dfd, <component name>,...)
260  * fchownat(dfd, <component name>,..)
261  *
262  * This works for both normal namespace files and extended attribute file
263  *
264  */
265 
266 /*
267  *
268  * Extended attribute Format
269  *
270  * Extended attributes are stored in two pieces.
271  * 1. An attribute header which has information about
272  *    what file the attribute is for and what the attribute
273  *    is named.
274  * 2. The attribute record itself.  Stored as a normal file type
275  *    of entry.
276  * Both the header and attribute record have special modes/typeflags
277  * associated with them.
278  *
279  * The names of the header in the archive look like:
280  * /dev/null/attr.hdr
281  *
282  * The name of the attribute looks like:
283  * /dev/null/attr
284  *
285  * This is done so that an archiver that doesn't understand these formats
286  * can just dispose of the attribute records.
287  *
288  * The format is composed of a fixed size header followed
289  * by a variable sized xattr_buf. If the attribute is a hard link
290  * to another attribute then another xattr_buf section is included
291  * for the link.
292  *
293  * The xattr_buf is used to define the necessary "pathing" steps
294  * to get to the extended attribute.  This is necessary to support
295  * a fully recursive attribute model where an attribute may itself
296  * have an attribute.
297  *
298  * The basic layout looks like this.
299  *
300  *     --------------------------------
301  *     |                              |
302  *     |         xattr_hdr            |
303  *     |                              |
304  *     --------------------------------
305  *     --------------------------------
306  *     |                              |
307  *     |        xattr_buf             |
308  *     |                              |
309  *     --------------------------------
310  *     --------------------------------
311  *     |                              |
312  *     |      (optional link info)    |
313  *     |                              |
314  *     --------------------------------
315  *     --------------------------------
316  *     |                              |
317  *     |      attribute itself        |
318  *     |      stored as normal tar    |
319  *     |      or cpio data with       |
320  *     |      special mode or         |
321  *     |      typeflag                |
322  *     |                              |
323  *     --------------------------------
324  *
325  */
326 
327 /*
328  * xattrhead is a pointer to the xattr_hdr
329  *
330  * xattrp is a pointer to the xattr_buf structure
331  * which contains the "pathing" steps to get to attributes
332  *
333  * xattr_linkp is a pointer to another xattr_buf structure that is
334  * only used when an attribute is actually linked to another attribute
335  *
336  */
337 
338 static struct xattr_hdr *xattrhead;
339 static struct xattr_buf *xattrp;
340 static struct xattr_buf *xattr_linkp;	/* pointer to link info, if any */
341 static char *xattrapath;		/* attribute name */
342 static char *xattr_linkaname;		/* attribute attribute is linked to */
343 static char Hiddendir;			/* are we processing hidden xattr dir */
344 static char xattrbadhead;
345 
346 /* Was statically allocated tbuf[NBLOCK] */
347 static
348 union hblock {
349 	char dummy[TBLOCK];
350 	struct header {
351 		char name[NAMSIZ];	/* If non-null prefix, path is	*/
352 					/* <prefix>/<name>;  otherwise	*/
353 					/* <name>			*/
354 		char mode[8];
355 		char uid[8];
356 		char gid[8];
357 		char size[12];		/* size of this extent if file split */
358 		char mtime[12];
359 		char chksum[8];
360 		char typeflag;
361 		char linkname[NAMSIZ];
362 		char magic[6];
363 		char version[2];
364 		char uname[32];
365 		char gname[32];
366 		char devmajor[8];
367 		char devminor[8];
368 		char prefix[PRESIZ];	/* Together with "name", the path of */
369 					/* the file:  <prefix>/<name>	*/
370 		char extno;		/* extent #, null if not split */
371 		char extotal;		/* total extents */
372 		char efsize[10];	/* size of entire file */
373 	} dbuf;
374 } dblock, *tbuf, xhdr_buf;
375 
376 static
377 struct xtar_hdr {
378 	uid_t		x_uid,		/* Uid of file */
379 			x_gid;		/* Gid of file */
380 	major_t		x_devmajor;	/* Device major node */
381 	minor_t		x_devminor;	/* Device minor node */
382 	off_t		x_filesz;	/* Length of file */
383 	char		*x_uname,	/* Pointer to name of user */
384 			*x_gname,	/* Pointer to gid of user */
385 			*x_linkpath,	/* Path for a hard/symbolic link */
386 			*x_path;	/* Path of file */
387 	timestruc_t	x_mtime;	/* Seconds and nanoseconds */
388 } Xtarhdr;
389 
390 static
391 struct gen_hdr {
392 	ulong_t		g_mode;		/* Mode of file */
393 	uid_t		g_uid,		/* Uid of file */
394 			g_gid;		/* Gid of file */
395 	off_t		g_filesz;	/* Length of file */
396 	time_t		g_mtime;	/* Modification time */
397 	uint_t		g_cksum;	/* Checksum of file */
398 	ulong_t		g_devmajor,	/* File system of file */
399 			g_devminor;	/* Major/minor of special files */
400 } Gen;
401 
402 static
403 struct linkbuf {
404 	ino_t	inum;
405 	dev_t	devnum;
406 	int	count;
407 	char	pathname[MAXNAM+1];	/* added 1 for last NULL */
408 	char	attrname[MAXNAM+1];
409 	struct	linkbuf *nextp;
410 } *ihead;
411 
412 /* see comments before build_table() */
413 #define	TABLE_SIZE 512
414 typedef struct	file_list	{
415 	char	*name;			/* Name of file to {in,ex}clude */
416 	struct	file_list	*next;	/* Linked list */
417 } file_list_t;
418 static	file_list_t	*exclude_tbl[TABLE_SIZE],
419 			*include_tbl[TABLE_SIZE];
420 
421 static int	append_secattr(char **, int *, int, char *, char);
422 static void	write_ancillary(union hblock *, char *, int, char);
423 
424 static void add_file_to_table(file_list_t *table[], char *str);
425 static void assert_string(char *s, char *msg);
426 static int istape(int fd, int type);
427 static void backtape(void);
428 static void build_table(file_list_t *table[], char *file);
429 static int check_prefix(char **namep, char **dirp, char **compp);
430 static void closevol(void);
431 static void copy(void *dst, void *src);
432 static int convtoreg(off_t);
433 static void delete_target(int fd, char *comp, char *namep);
434 static void doDirTimes(char *name, timestruc_t modTime);
435 static void done(int n);
436 static void dorep(char *argv[]);
437 static void dotable(char *argv[]);
438 static void doxtract(char *argv[]);
439 static int tar_chdir(const char *path);
440 static int is_directory(char *name);
441 static int has_dot_dot(char *name);
442 static int is_absolute(char *name);
443 static char *make_relative_name(char *name, char **stripped_prefix);
444 static void fatal(char *format, ...);
445 static void vperror(int exit_status, char *fmt, ...);
446 static void flushtape(void);
447 static void getdir(void);
448 static void *getmem(size_t);
449 static void longt(struct stat *st, char aclchar);
450 static void load_info_from_xtarhdr(u_longlong_t flag, struct xtar_hdr *xhdrp);
451 static int makeDir(char *name);
452 static void mterr(char *operation, int i, int exitcode);
453 static void newvol(void);
454 static void passtape(void);
455 static void putempty(blkcnt_t n);
456 static int putfile(char *longname, char *shortname, char *parent,
457     attr_data_t *attrinfo, int filetype, int lev, int symlink_lev);
458 static void readtape(char *buffer);
459 static void seekdisk(blkcnt_t blocks);
460 static void setPathTimes(int dirfd, char *path, timestruc_t modTime);
461 static void setbytes_to_skip(struct stat *st, int err);
462 static void splitfile(char *longname, int ifd, char *name,
463 	char *prefix, int filetype);
464 static void tomodes(struct stat *sp);
465 static void usage(void);
466 static int xblocks(int issysattr, off_t bytes, int ofile);
467 static int xsfile(int issysattr, int ofd);
468 static void resugname(int dirfd, char *name, int symflag);
469 static int bcheck(char *bstr);
470 static int checkdir(char *name);
471 static int checksum(union hblock *dblockp);
472 #ifdef	EUC
473 static int checksum_signed(union hblock *dblockp);
474 #endif	/* EUC */
475 static int checkupdate(char *arg);
476 static int checkw(char c, char *name);
477 static int cmp(char *b, char *s, int n);
478 static int defset(char *arch);
479 static boolean_t endtape(void);
480 static int is_in_table(file_list_t *table[], char *str);
481 static int notsame(void);
482 static int is_prefix(char *s1, char *s2);
483 static int response(void);
484 static int build_dblock(const char *, const char *, const char,
485 	const int filetype, const struct stat *, const dev_t, const char *);
486 static unsigned int hash(char *str);
487 
488 static blkcnt_t kcheck(char *kstr);
489 static off_t bsrch(char *s, int n, off_t l, off_t h);
490 static void onintr(int sig);
491 static void onquit(int sig);
492 static void onhup(int sig);
493 static uid_t getuidbyname(char *);
494 static gid_t getgidbyname(char *);
495 static char *getname(gid_t);
496 static char *getgroup(gid_t);
497 static int checkf(char *name, int mode, int howmuch);
498 static int writetbuf(char *buffer, int n);
499 static int wantit(char *argv[], char **namep, char **dirp, char **comp,
500     attr_data_t **attrinfo);
501 static void append_ext_attr(char *shortname, char **secinfo, int *len);
502 static int get_xdata(void);
503 static void gen_num(const char *keyword, const u_longlong_t number);
504 static void gen_date(const char *keyword, const timestruc_t time_value);
505 static void gen_string(const char *keyword, const char *value);
506 static void get_xtime(char *value, timestruc_t *xtime);
507 static int chk_path_build(char *name, char *longname, char *linkname,
508     char *prefix, char type, int filetype);
509 static int gen_utf8_names(const char *filename);
510 static int utf8_local(char *option, char **Xhdr_ptrptr, char *target,
511     const char *src, int max_val);
512 static int local_utf8(char **Xhdr_ptrptr, char *target, const char *src,
513     iconv_t iconv_cd, int xhdrflg, int max_val);
514 static int c_utf8(char *target, const char *source);
515 static int getstat(int dirfd, char *longname, char *shortname,
516     char *attrparent);
517 static void xattrs_put(char *, char *, char *, char *);
518 static void prepare_xattr(char **, char	*, char	*,
519     char, struct linkbuf *, int *);
520 static int put_link(char *name, char *longname, char *component,
521     char *longattrname, char *prefix, int filetype, char typeflag);
522 static int put_extra_attributes(char *longname, char *shortname,
523     char *longattrname, char *prefix, int filetype, char typeflag);
524 static int put_xattr_hdr(char *longname, char *shortname, char *longattrname,
525     char *prefix, int typeflag, int filetype, struct linkbuf *lp);
526 static int read_xattr_hdr(attr_data_t **attrinfo);
527 
528 /* Trusted Extensions */
529 #define	AUTO_ZONE	"/zone"
530 
531 static void extract_attr(char **file_ptr, struct sec_attr *);
532 static int check_ext_attr(char *filename);
533 static void rebuild_comp_path(char *str, char **namep);
534 static int rebuild_lk_comp_path(char *str, char **namep);
535 
536 static void get_parent(char *path, char *dir);
537 static char *get_component(char *path);
538 static int retry_open_attr(int pdirfd, int cwd, char *dirp, char *pattr,
539     char *name, int oflag, mode_t mode);
540 static char *skipslashes(char *string, char *start);
541 static void chop_endslashes(char *path);
542 static pid_t compress_file(void);
543 static void compress_back(void);
544 static void decompress_file(void);
545 static pid_t uncompress_file(void);
546 static void *compress_malloc(size_t);
547 static void check_compression(void);
548 static char *bz_suffix(void);
549 static char *gz_suffix(void);
550 static char *xz_suffix(void);
551 static char *add_suffix();
552 static void wait_pid(pid_t);
553 static void verify_compress_opt(const char *t);
554 static void detect_compress(void);
555 static void dlog(const char *, ...);
556 static boolean_t should_enable_debug(void);
557 
558 static	struct stat stbuf;
559 
560 static	char	*myname;
561 static	char	*xtract_chdir = NULL;
562 static	int	checkflag = 0;
563 static	int	Xflag, Fflag, iflag, hflag, Bflag, Iflag;
564 static	int	rflag, xflag, vflag, tflag, mt, cflag, mflag, pflag;
565 static	int	uflag;
566 static	int	errflag;
567 static	int	oflag;
568 static	int	bflag, Aflag;
569 static	int	Pflag;			/* POSIX conformant archive */
570 static	int	Eflag;			/* Allow files greater than 8GB */
571 static	int	atflag;			/* traverse extended attributes */
572 static	int	saflag;			/* traverse extended sys attributes */
573 static	int	Dflag;			/* Data change flag */
574 static	int	jflag;			/* flag to use 'bzip2' */
575 static	int	zflag;			/* flag to use 'gzip' */
576 static	int	Zflag;			/* flag to use 'compress' */
577 static	int	Jflag;			/* flag to use 'xz' */
578 static	int	aflag;			/* flag to use autocompression */
579 
580 /* Trusted Extensions */
581 static	int	Tflag;			/* Trusted Extensions attr flags */
582 static	int	dir_flag;		/* for attribute extract */
583 static	int	mld_flag;		/* for attribute extract */
584 static	char	*orig_namep;		/* original namep - unadorned */
585 static	int	rpath_flag;		/* MLD real path is rebuilt */
586 static	char	real_path[MAXPATHLEN];	/* MLD real path */
587 static	int	lk_rpath_flag;		/* linked to real path is rebuilt */
588 static	char	lk_real_path[MAXPATHLEN]; /* linked real path */
589 static	bslabel_t	bs_label;	/* for attribute extract */
590 static	bslabel_t	admin_low;
591 static	bslabel_t	admin_high;
592 static	int	ignored_aprivs = 0;
593 static	int	ignored_fprivs = 0;
594 static	int	ignored_fattrs = 0;
595 
596 static	int	term, chksum, wflag,
597 		first = TRUE, defaults_used = FALSE, linkerrok;
598 static	blkcnt_t	recno;
599 static	int	freemem = 1;
600 static	int	nblock = NBLOCK;
601 static	int	Errflg = 0;
602 static	int	exitflag = 0;
603 
604 static	dev_t	mt_dev;		/* device containing output file */
605 static	ino_t	mt_ino;		/* inode number of output file */
606 static	int	mt_devtype;	/* dev type of archive, from stat structure */
607 
608 static	int update = 1;		/* for `open' call */
609 
610 static	off_t	low;
611 static	off_t	high;
612 
613 static	FILE	*tfile;
614 static	FILE	*vfile = stdout;
615 static	char	*tmpdir;
616 static	char	*tmp_suffix = "/tarXXXXXX";
617 static	char	*tname;
618 static	char	archive[] = "archive0=";
619 static	char	*Xfile;
620 static	char	*usefile;
621 static	char	tfname[1024];
622 
623 static	int	mulvol;		/* multi-volume option selected */
624 static	blkcnt_t	blocklim; /* number of blocks to accept per volume */
625 static	blkcnt_t	tapepos; /* current block number to be written */
626 static	int	NotTape;	/* true if tape is a disk */
627 static	int	dumping;	/* true if writing a tape or other archive */
628 static	int	extno;		/* number of extent:  starts at 1 */
629 static	int	extotal;	/* total extents in this file */
630 static	off_t	extsize;	/* size of current extent during extraction */
631 static	ushort_t	Oumask = 0;	/* old umask value */
632 static	boolean_t is_posix;	/* true if archive is POSIX-conformant */
633 static	const	char	*magic_type = "ustar";
634 static	size_t	xrec_size = 8 * PATH_MAX;	/* extended rec initial size */
635 static	char	*xrec_ptr;
636 static	off_t	xrec_offset = 0;
637 static	int	Xhdrflag;
638 static	int	charset_type = 0;
639 
640 static	u_longlong_t	xhdr_flgs;	/* Bits set determine which items */
641 					/*   need to be in extended header. */
642 static	pid_t	comp_pid = 0;
643 
644 static boolean_t debug_output = B_FALSE;
645 
646 #define	_X_DEVMAJOR	0x1
647 #define	_X_DEVMINOR	0x2
648 #define	_X_GID		0x4
649 #define	_X_GNAME	0x8
650 #define	_X_LINKPATH	0x10
651 #define	_X_PATH		0x20
652 #define	_X_SIZE		0x40
653 #define	_X_UID		0x80
654 #define	_X_UNAME	0x100
655 #define	_X_ATIME	0x200
656 #define	_X_CTIME	0x400
657 #define	_X_MTIME	0x800
658 #define	_X_XHDR		0x1000	/* Bit flag that determines whether 'X' */
659 				/* typeflag was followed by 'A' or non 'A' */
660 				/* typeflag. */
661 #define	_X_LAST		0x40000000
662 
663 #define	PID_MAX_DIGITS		(10 * sizeof (pid_t) / 4)
664 #define	TIME_MAX_DIGITS		(10 * sizeof (time_t) / 4)
665 #define	LONG_MAX_DIGITS		(10 * sizeof (long) / 4)
666 #define	ULONGLONG_MAX_DIGITS	(10 * sizeof (u_longlong_t) / 4)
667 /*
668  * UTF_8 encoding requires more space than the current codeset equivalent.
669  * Currently a factor of 2-3 would suffice, but it is possible for a factor
670  * of 6 to be needed in the future, so for saftey, we use that here.
671  */
672 #define	UTF_8_FACTOR	6
673 
674 static	u_longlong_t	xhdr_count = 0;
675 static char		xhdr_dirname[PRESIZ + 1];
676 static char		pidchars[PID_MAX_DIGITS + 1];
677 static char		*tchar = "";		/* null linkpath */
678 
679 static	char	local_path[UTF_8_FACTOR * PATH_MAX + 1];
680 static	char	local_linkpath[UTF_8_FACTOR * PATH_MAX + 1];
681 static	char	local_gname[UTF_8_FACTOR * _POSIX_NAME_MAX + 1];
682 static	char	local_uname[UTF_8_FACTOR * _POSIX_NAME_MAX + 1];
683 
684 /*
685  * The following mechanism is provided to allow us to debug tar in complicated
686  * situations, like when it is part of a pipe.  The idea is that you compile
687  * with -DWAITAROUND defined, and then add the 'D' function modifier to the
688  * target tar invocation, eg. "tar cDf tarfile file".  If stderr is available,
689  * it will tell you to which pid to attach the debugger; otherwise, use ps to
690  * find it.  Attach to the process from the debugger, and, *PRESTO*, you are
691  * there!
692  *
693  * Simply assign "waitaround = 0" once you attach to the process, and then
694  * proceed from there as usual.
695  */
696 
697 #ifdef WAITAROUND
698 int waitaround = 0;		/* wait for rendezvous with the debugger */
699 #endif
700 
701 #define	BZIP		"/usr/bin/bzip2"
702 #define	GZIP		"/usr/bin/gzip"
703 #define	COMPRESS	"/usr/bin/compress"
704 #define	XZ		"/usr/bin/xz"
705 #define	BZCAT		"/usr/bin/bzcat"
706 #define	GZCAT		"/usr/bin/gzcat"
707 #define	ZCAT		"/usr/bin/zcat"
708 #define	XZCAT		"/usr/bin/xzcat"
709 #define	GSUF		8	/* number of valid 'gzip' sufixes */
710 #define	BSUF		4	/* number of valid 'bzip2' sufixes */
711 #define	XSUF		1	/* number of valid 'xz' suffixes */
712 
713 static	char		*compress_opt;	/* compression type */
714 
715 static	char		*gsuffix[] = {".gz", "-gz", ".z", "-z", "_z", ".Z",
716 			".tgz", ".taz"};
717 static	char		*bsuffix[] = {".bz2", ".bz", ".tbz2", ".tbz"};
718 static	char		*xsuffix[] = {".xz"};
719 static	char		*suffix;
720 
721 
722 int
main(int argc,char * argv[])723 main(int argc, char *argv[])
724 {
725 	char		*cp;
726 	char		*tmpdirp;
727 	pid_t		thispid;
728 
729 	(void) setlocale(LC_ALL, "");
730 #if !defined(TEXT_DOMAIN)	/* Should be defined by cc -D */
731 #define	TEXT_DOMAIN "SYS_TEST"	/* Use this only if it weren't */
732 #endif
733 	(void) textdomain(TEXT_DOMAIN);
734 	if (argc < 2)
735 		usage();
736 
737 	debug_output = should_enable_debug();
738 
739 	tfile = NULL;
740 	if ((myname = strdup(argv[0])) == NULL) {
741 		(void) fprintf(stderr, gettext(
742 		    "tar: cannot allocate program name\n"));
743 		exit(1);
744 	}
745 
746 	if (init_yes() < 0) {
747 		(void) fprintf(stderr, gettext(ERR_MSG_INIT_YES),
748 		    strerror(errno));
749 		exit(2);
750 	}
751 
752 	/*
753 	 *  For XPG4 compatibility, we must be able to accept the "--"
754 	 *  argument normally recognized by getopt; it is used to delimit
755 	 *  the end opt the options section, and so can only appear in
756 	 *  the position of the first argument.  We simply skip it.
757 	 */
758 
759 	if (strcmp(argv[1], "--") == 0) {
760 		argv++;
761 		argc--;
762 		if (argc < 3)
763 			usage();
764 	}
765 
766 	argv[argc] = NULL;
767 	argv++;
768 
769 	/*
770 	 * Set up default values.
771 	 * Search the operand string looking for the first digit or an 'f'.
772 	 * If you find a digit, use the 'archive#' entry in DEF_FILE.
773 	 * If 'f' is given, bypass looking in DEF_FILE altogether.
774 	 * If no digit or 'f' is given, still look in DEF_FILE but use '0'.
775 	 */
776 	if ((usefile = getenv("TAPE")) == (char *)NULL) {
777 		for (cp = *argv; *cp; ++cp)
778 			if (isdigit(*cp) || *cp == 'f')
779 				break;
780 		if (*cp != 'f') {
781 			archive[7] = (*cp)? *cp: '0';
782 			if (!(defaults_used = defset(archive))) {
783 				usefile = NULL;
784 				nblock = 1;
785 				blocklim = 0;
786 				NotTape = 0;
787 			}
788 		}
789 	}
790 
791 	for (cp = *argv++; *cp; cp++)
792 		switch (*cp) {
793 #ifdef WAITAROUND
794 		case 'D':
795 			/* rendezvous with the debugger */
796 			waitaround = 1;
797 			break;
798 #endif
799 		case 'f':
800 			assert_string(*argv, gettext(
801 			    "tar: tarfile must be specified with 'f' "
802 			    "function modifier\n"));
803 			usefile = *argv++;
804 			break;
805 		case 'F':
806 			Fflag++;
807 			break;
808 		case 'c':
809 			cflag++;
810 			rflag++;
811 			update = 1;
812 			break;
813 #if defined(O_XATTR)
814 		case '@':
815 			atflag++;
816 			break;
817 #endif	/* O_XATTR */
818 #if defined(_PC_SATTR_ENABLED)
819 		case '/':
820 			saflag++;
821 			break;
822 #endif	/* _PC_SATTR_ENABLED */
823 		case 'u':
824 			uflag++;	/* moved code after signals caught */
825 			rflag++;
826 			update = 2;
827 			break;
828 		case 'r':
829 			rflag++;
830 			update = 2;
831 			break;
832 		case 'v':
833 			vflag++;
834 			break;
835 		case 'w':
836 			wflag++;
837 			break;
838 		case 'x':
839 			xflag++;
840 			break;
841 		case 'X':
842 			assert_string(*argv, gettext(
843 			    "tar: exclude file must be specified with 'X' "
844 			    "function modifier\n"));
845 			Xflag = 1;
846 			Xfile = *argv++;
847 			build_table(exclude_tbl, Xfile);
848 			break;
849 		case 't':
850 			tflag++;
851 			break;
852 		case 'm':
853 			mflag++;
854 			break;
855 		case 'p':
856 			pflag++;
857 			break;
858 		case 'D':
859 			Dflag++;
860 			break;
861 		case '-':
862 			/* ignore this silently */
863 			break;
864 		case '0':	/* numeric entries used only for defaults */
865 		case '1':
866 		case '2':
867 		case '3':
868 		case '4':
869 		case '5':
870 		case '6':
871 		case '7':
872 			break;
873 		case 'b':
874 			assert_string(*argv, gettext(
875 			    "tar: blocking factor must be specified "
876 			    "with 'b' function modifier\n"));
877 			bflag++;
878 			nblock = bcheck(*argv++);
879 			break;
880 		case 'n':		/* not a magtape (instead of 'k') */
881 			NotTape++;	/* assume non-magtape */
882 			break;
883 		case 'l':
884 			linkerrok++;
885 			break;
886 		case 'e':
887 			errflag++;
888 			break;
889 		case 'o':
890 			oflag++;
891 			break;
892 		case 'h':
893 			hflag++;
894 			break;
895 		case 'i':
896 			iflag++;
897 			break;
898 		case 'B':
899 			Bflag++;
900 			break;
901 		case 'P':
902 			Pflag++;
903 			break;
904 		case 'E':
905 			Eflag++;
906 			Pflag++;	/* Only POSIX archive made */
907 			break;
908 		case 'T':
909 			Tflag++;	/* Handle Trusted Extensions attrs */
910 			pflag++;	/* also set flag for ACL */
911 			break;
912 		case 'j':		/* compession "bzip2" */
913 			jflag = 1;
914 			break;
915 		case 'z':		/* compression "gzip" */
916 			zflag = 1;
917 			break;
918 		case 'Z':		/* compression "compress" */
919 			Zflag = 1;
920 			break;
921 		case 'J':		/* compression "xz" */
922 			Jflag = 1;
923 			break;
924 		case 'a':
925 			aflag = 1;	/* autocompression */
926 			break;
927 		default:
928 			(void) fprintf(stderr, gettext(
929 			"tar: %c: unknown function modifier\n"), *cp);
930 			usage();
931 		}
932 
933 	if (!rflag && !xflag && !tflag)
934 		usage();
935 	if ((rflag && xflag) || (xflag && tflag) || (rflag && tflag)) {
936 		(void) fprintf(stderr, gettext(
937 		"tar: specify only one of [ctxru].\n"));
938 		usage();
939 	}
940 	if (cflag) {
941 		if ((jflag + zflag + Zflag + Jflag + aflag) > 1) {
942 			(void) fprintf(stderr, gettext(
943 			    "tar: specify only one of [ajJzZ] to "
944 			    "create a compressed file.\n"));
945 			usage();
946 		}
947 	}
948 	/* Trusted Extensions attribute handling */
949 	if (Tflag && ((getzoneid() != GLOBAL_ZONEID) ||
950 	    !is_system_labeled())) {
951 		(void) fprintf(stderr, gettext(
952 		"tar: the 'T' option is only available with "
953 		    "Trusted Extensions\nand must be run from "
954 		    "the global zone.\n"));
955 		usage();
956 	}
957 	if (cflag && *argv == NULL)
958 		fatal(gettext("Missing filenames"));
959 	if (usefile == NULL)
960 		fatal(gettext("device argument required"));
961 
962 	/* alloc a buffer of the right size */
963 	if ((tbuf = (union hblock *)
964 	    calloc(sizeof (union hblock) * nblock, sizeof (char))) ==
965 	    (union hblock *)NULL) {
966 		(void) fprintf(stderr, gettext(
967 		"tar: cannot allocate physio buffer\n"));
968 		exit(1);
969 	}
970 
971 	if ((xrec_ptr = malloc(xrec_size)) == NULL) {
972 		(void) fprintf(stderr, gettext(
973 		    "tar: cannot allocate extended header buffer\n"));
974 		exit(1);
975 	}
976 
977 #ifdef WAITAROUND
978 	if (waitaround) {
979 		(void) fprintf(stderr, gettext("Rendezvous with tar on pid"
980 		    " %d\n"), getpid());
981 
982 		while (waitaround) {
983 			(void) sleep(10);
984 		}
985 	}
986 #endif
987 
988 	thispid = getpid();
989 	(void) sprintf(pidchars, "%ld", thispid);
990 	thispid = strlen(pidchars);
991 
992 	if ((tmpdirp = getenv("TMPDIR")) == (char *)NULL)
993 		(void) strcpy(xhdr_dirname, "/tmp");
994 	else {
995 		/*
996 		 * Make sure that dir is no longer than what can
997 		 * fit in the prefix part of the header.
998 		 */
999 		if (strlen(tmpdirp) > (size_t)(PRESIZ - thispid - 12)) {
1000 			(void) strcpy(xhdr_dirname, "/tmp");
1001 			if ((vflag > 0) && (Eflag > 0))
1002 				(void) fprintf(stderr, gettext(
1003 				    "Ignoring TMPDIR\n"));
1004 		} else
1005 			(void) strcpy(xhdr_dirname, tmpdirp);
1006 	}
1007 	(void) strcat(xhdr_dirname, "/PaxHeaders.");
1008 	(void) strcat(xhdr_dirname, pidchars);
1009 
1010 	if (rflag) {
1011 		if (cflag && usefile != NULL)  {
1012 			/* Set the compression type */
1013 			if (aflag)
1014 				detect_compress();
1015 
1016 			if (jflag) {
1017 				compress_opt = compress_malloc(strlen(BZIP)
1018 				    + 1);
1019 				(void) strcpy(compress_opt, BZIP);
1020 			} else if (zflag) {
1021 				compress_opt = compress_malloc(strlen(GZIP)
1022 				    + 1);
1023 				(void) strcpy(compress_opt, GZIP);
1024 			} else if (Zflag) {
1025 				compress_opt =
1026 				    compress_malloc(strlen(COMPRESS) + 1);
1027 				(void) strcpy(compress_opt, COMPRESS);
1028 			} else if (Jflag) {
1029 				compress_opt = compress_malloc(strlen(XZ) + 1);
1030 				(void) strcpy(compress_opt, XZ);
1031 			}
1032 		} else {
1033 			/*
1034 			 * Decompress if the file is compressed for
1035 			 * an update or replace.
1036 			 */
1037 			if (strcmp(usefile, "-") != 0) {
1038 				check_compression();
1039 				if (compress_opt != NULL) {
1040 					decompress_file();
1041 				}
1042 			}
1043 		}
1044 
1045 		if (cflag && tfile != NULL)
1046 			usage();
1047 		if (signal(SIGINT, SIG_IGN) != SIG_IGN)
1048 			(void) signal(SIGINT, onintr);
1049 		if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
1050 			(void) signal(SIGHUP, onhup);
1051 		if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1052 			(void) signal(SIGQUIT, onquit);
1053 		if (uflag) {
1054 			int tnum;
1055 			struct stat sbuf;
1056 
1057 			tmpdir = getenv("TMPDIR");
1058 			/*
1059 			 * If the name is invalid or this isn't a directory,
1060 			 * or the directory is not writable, then reset to
1061 			 * a default temporary directory.
1062 			 */
1063 			if (tmpdir == NULL || *tmpdir == '\0' ||
1064 			    (strlen(tmpdir) + strlen(tmp_suffix)) > PATH_MAX) {
1065 				tmpdir = "/tmp";
1066 			} else if (stat(tmpdir, &sbuf) < 0 ||
1067 			    (sbuf.st_mode & S_IFMT) != S_IFDIR ||
1068 			    (sbuf.st_mode & S_IWRITE) == 0) {
1069 				tmpdir = "/tmp";
1070 			}
1071 
1072 			if ((tname = calloc(1, strlen(tmpdir) +
1073 			    strlen(tmp_suffix) + 1)) == NULL) {
1074 				vperror(1, gettext("tar: out of memory, "
1075 				    "cannot create temporary file\n"));
1076 			}
1077 			(void) strcpy(tname, tmpdir);
1078 			(void) strcat(tname, tmp_suffix);
1079 
1080 			if ((tnum = mkstemp(tname)) == -1)
1081 				vperror(1, "%s", tname);
1082 			if ((tfile = fdopen(tnum, "w")) == NULL)
1083 				vperror(1, "%s", tname);
1084 		}
1085 		if (strcmp(usefile, "-") == 0) {
1086 			if (cflag == 0)
1087 				fatal(gettext(
1088 				"can only create standard output archives."));
1089 			vfile = stderr;
1090 			mt = dup(1);
1091 			++bflag;
1092 		} else {
1093 			if (cflag)
1094 				mt = open(usefile,
1095 				    O_RDWR|O_CREAT|O_TRUNC, 0666);
1096 			else
1097 				mt = open(usefile, O_RDWR);
1098 
1099 			if (mt < 0) {
1100 				if (cflag == 0 || (mt =  creat(usefile, 0666))
1101 				    < 0)
1102 				vperror(1, "%s", usefile);
1103 			}
1104 		}
1105 		/* Get inode and device number of output file */
1106 		(void) fstat(mt, &stbuf);
1107 		mt_ino = stbuf.st_ino;
1108 		mt_dev = stbuf.st_dev;
1109 		mt_devtype = stbuf.st_mode & S_IFMT;
1110 		NotTape = !istape(mt, mt_devtype);
1111 
1112 		if (rflag && !cflag && (mt_devtype == S_IFIFO))
1113 			fatal(gettext("cannot append to pipe or FIFO."));
1114 
1115 		if (Aflag && vflag)
1116 			(void) printf(
1117 			gettext("Suppressing absolute pathnames\n"));
1118 		if (cflag && compress_opt != NULL)
1119 			comp_pid = compress_file();
1120 		dorep(argv);
1121 		if (rflag && !cflag && (compress_opt != NULL))
1122 			compress_back();
1123 	} else if (xflag || tflag) {
1124 		/*
1125 		 * for each argument, check to see if there is a "-I file" pair.
1126 		 * if so, move the 3rd argument into "-I"'s place, build_table()
1127 		 * using "file"'s name and increment argc one (the second
1128 		 * increment appears in the for loop) which removes the two
1129 		 * args "-I" and "file" from the argument vector.
1130 		 */
1131 		for (argc = 0; argv[argc]; argc++) {
1132 			if (strcmp(argv[argc], "-I") == 0) {
1133 				if (!argv[argc+1]) {
1134 					(void) fprintf(stderr, gettext(
1135 					"tar: missing argument for -I flag\n"));
1136 					done(2);
1137 				} else {
1138 					Iflag = 1;
1139 					argv[argc] = argv[argc+2];
1140 					build_table(include_tbl, argv[++argc]);
1141 				}
1142 			} else if (strcmp(argv[argc], "-C") == 0) {
1143 				if (!argv[argc+1]) {
1144 					(void) fprintf(stderr, gettext("tar: "
1145 					    "missing argument for -C flag\n"));
1146 					done(2);
1147 				} else if (xtract_chdir != NULL) {
1148 					(void) fprintf(stderr, gettext("tar: "
1149 					    "extract should have only one -C "
1150 					    "flag\n"));
1151 					done(2);
1152 				} else {
1153 					argv[argc] = argv[argc+2];
1154 					xtract_chdir = argv[++argc];
1155 				}
1156 			}
1157 		}
1158 		if (strcmp(usefile, "-") == 0) {
1159 			mt = dup(0);
1160 			++bflag;
1161 			/* try to recover from short reads when reading stdin */
1162 			++Bflag;
1163 		} else if ((mt = open(usefile, 0)) < 0)
1164 			vperror(1, "%s", usefile);
1165 
1166 		/* Decompress if the file is compressed */
1167 
1168 		if (strcmp(usefile, "-") != 0) {
1169 			check_compression();
1170 			if (compress_opt != NULL)
1171 				comp_pid = uncompress_file();
1172 		}
1173 		if (xflag) {
1174 			if (xtract_chdir != NULL) {
1175 				if (tar_chdir(xtract_chdir) < 0) {
1176 					vperror(1, gettext("can't change "
1177 					    "directories to %s"), xtract_chdir);
1178 				}
1179 			}
1180 			if (Aflag && vflag)
1181 				(void) printf(gettext(
1182 				    "Suppressing absolute pathnames.\n"));
1183 
1184 			doxtract(argv);
1185 		} else if (tflag)
1186 			dotable(argv);
1187 	}
1188 	else
1189 		usage();
1190 
1191 	done(Errflg);
1192 
1193 	/* Not reached:  keep compiler quiet */
1194 	return (1);
1195 }
1196 
1197 static boolean_t
should_enable_debug(void)1198 should_enable_debug(void)
1199 {
1200 	const char *val;
1201 	const char *truth[] = {
1202 		"true",
1203 		"1",
1204 		"yes",
1205 		"y",
1206 		"please",
1207 		NULL
1208 	};
1209 	unsigned int i;
1210 
1211 	if ((val = getenv("DEBUG_TAR")) == NULL) {
1212 		return (B_FALSE);
1213 	}
1214 
1215 	for (i = 0; truth[i] != NULL; i++) {
1216 		if (strcmp(val, truth[i]) == 0) {
1217 			return (B_TRUE);
1218 		}
1219 	}
1220 
1221 	return (B_FALSE);
1222 }
1223 
1224 /*PRINTFLIKE1*/
1225 static void
dlog(const char * format,...)1226 dlog(const char *format, ...)
1227 {
1228 	va_list ap;
1229 
1230 	if (!debug_output) {
1231 		return;
1232 	}
1233 
1234 	va_start(ap, format);
1235 	(void) fprintf(stderr, "tar: DEBUG: ");
1236 	(void) vfprintf(stderr, format, ap);
1237 	va_end(ap);
1238 }
1239 
1240 static void
usage(void)1241 usage(void)
1242 {
1243 	(void) fprintf(stderr, gettext(
1244 #if defined(O_XATTR)
1245 #if defined(_PC_SATTR_ENABLED)
1246 	    "Usage: tar {c|r|t|u|x}[BDeEFhilmnopPTvw@/[0-7]][bf][X...] "
1247 #else
1248 	    "Usage: tar {c|r|t|u|x}[BDeEFhilmnopPTvw@[0-7]][bf][X...] "
1249 #endif	/* _PC_SATTR_ENABLED */
1250 #else
1251 	    "Usage: tar {c|r|t|u|x}[BDeEFhilmnopPTvw[0-7]][bf][X...] "
1252 #endif	/* O_XATTR */
1253 	    "[j|J|z|Z] "
1254 	    "[blocksize] [tarfile] [size] [exclude-file...] "
1255 	    "{file | -I include-file | -C directory file}...\n"));
1256 	done(1);
1257 }
1258 
1259 /*
1260  * dorep - do "replacements"
1261  *
1262  *	Dorep is responsible for creating ('c'),  appending ('r')
1263  *	and updating ('u');
1264  */
1265 
1266 static void
dorep(char * argv[])1267 dorep(char *argv[])
1268 {
1269 	char *cp, *cp2, *p;
1270 	char wdir[PATH_MAX+2], tempdir[PATH_MAX+2], *parent;
1271 	char file[PATH_MAX*2], origdir[PATH_MAX+1];
1272 	FILE *fp = (FILE *)NULL;
1273 	int archtype;
1274 	int ret;
1275 
1276 
1277 	if (!cflag) {
1278 		xhdr_flgs = 0;
1279 		getdir();			/* read header for next file */
1280 		if (Xhdrflag > 0) {
1281 			if (!Eflag)
1282 				fatal(gettext("Archive contains extended"
1283 				    " header.  -E flag required.\n"));
1284 			ret = get_xdata();	/* Get extended header items */
1285 						/*   and regular header */
1286 		} else {
1287 			if (Eflag)
1288 				fatal(gettext("Archive contains no extended"
1289 				    " header.  -E flag not allowed.\n"));
1290 		}
1291 		while (!endtape()) {		/* changed from a do while */
1292 			setbytes_to_skip(&stbuf, ret);
1293 			passtape();		/* skip the file data */
1294 			if (term)
1295 				done(Errflg);	/* received signal to stop */
1296 			xhdr_flgs = 0;
1297 			getdir();
1298 			if (Xhdrflag > 0)
1299 				ret = get_xdata();
1300 		}
1301 		if (ret == 0) {
1302 			if ((dblock.dbuf.typeflag != 'A') &&
1303 			    (xhdr_flgs != 0)) {
1304 				load_info_from_xtarhdr(xhdr_flgs,
1305 				    &Xtarhdr);
1306 				xhdr_flgs |= _X_XHDR;
1307 			}
1308 		}
1309 		backtape();			/* was called by endtape */
1310 		if (tfile != NULL) {
1311 			/*
1312 			 * Buffer size is calculated to be the size of the
1313 			 * tmpdir string, plus 6 times the size of the tname
1314 			 * string, plus a value that is known to be greater
1315 			 * than the command pipeline string.
1316 			 */
1317 			int buflen = strlen(tmpdir) + (6 * strlen(tname)) + 100;
1318 			char *buf;
1319 
1320 			if ((buf = (char *)calloc(1, buflen)) == NULL) {
1321 				vperror(1, gettext("tar: out of memory, "
1322 				    "cannot create sort command file\n"));
1323 			}
1324 
1325 			(void) snprintf(buf, buflen, "env 'TMPDIR=%s' "
1326 			    "sort +0 -1 +1nr %s -o %s; awk '$1 "
1327 			    "!= prev {print; prev=$1}' %s >%sX;mv %sX %s",
1328 			    tmpdir, tname, tname, tname, tname, tname, tname);
1329 			(void) fflush(tfile);
1330 			(void) system(buf);
1331 			free(buf);
1332 			(void) freopen(tname, "r", tfile);
1333 			(void) fstat(fileno(tfile), &stbuf);
1334 			high = stbuf.st_size;
1335 		}
1336 	}
1337 
1338 	dumping = 1;
1339 	if (mulvol) {	/* SP-1 */
1340 		if (nblock && (blocklim%nblock) != 0)
1341 			fatal(gettext(
1342 			"Volume size not a multiple of block size."));
1343 		blocklim -= 2;			/* for trailer records */
1344 		if (vflag)
1345 			(void) fprintf(vfile, gettext("Volume ends at %"
1346 			    FMT_blkcnt_t "K, blocking factor = %dK\n"),
1347 			    K((blocklim - 1)), K(nblock));
1348 	}
1349 
1350 	/*
1351 	 * Save the original directory before it gets
1352 	 * changed.
1353 	 */
1354 	if (getcwd(origdir, (PATH_MAX+1)) == NULL) {
1355 		vperror(0, gettext("A parent directory cannot be read"));
1356 		exit(1);
1357 	}
1358 
1359 	(void) strcpy(wdir, origdir);
1360 
1361 	while ((*argv || fp) && !term) {
1362 		if (fp || (strcmp(*argv, "-I") == 0)) {
1363 			if (fp == NULL) {
1364 				if (*++argv == NULL)
1365 					fatal(gettext(
1366 					    "missing file name for -I flag."));
1367 				else if ((fp = fopen(*argv++, "r")) == NULL)
1368 					vperror(0, "%s", argv[-1]);
1369 				continue;
1370 			} else if ((fgets(file, PATH_MAX-1, fp)) == NULL) {
1371 				(void) fclose(fp);
1372 				fp = NULL;
1373 				continue;
1374 			} else {
1375 				cp = cp2 = file;
1376 				if ((p = strchr(cp2, '\n')))
1377 					*p = 0;
1378 			}
1379 		} else if ((strcmp(*argv, "-C") == 0) && argv[1]) {
1380 			if (tar_chdir(*++argv) < 0)
1381 				vperror(0, gettext(
1382 				    "can't change directories to %s"), *argv);
1383 			else
1384 				(void) getcwd(wdir, (sizeof (wdir)));
1385 			argv++;
1386 			continue;
1387 		} else
1388 			cp = cp2 = strcpy(file, *argv++);
1389 
1390 		/*
1391 		 * point cp2 to the last '/' in file, but not
1392 		 * to a trailing '/'
1393 		 */
1394 		for (; *cp; cp++) {
1395 			if (*cp == '/') {
1396 				while (*(cp+1) == '/') {
1397 					++cp;
1398 				}
1399 				if (*(cp+1) != '\0') {
1400 					/* not trailing slash */
1401 					cp2 = cp;
1402 				}
1403 			}
1404 		}
1405 		if (cp2 != file) {
1406 			*cp2 = '\0';
1407 			if (tar_chdir(file) < 0) {
1408 				vperror(0, gettext(
1409 				    "can't change directories to %s"), file);
1410 				continue;
1411 			}
1412 			*cp2 = '/';
1413 			cp2++;
1414 		}
1415 
1416 		parent = getcwd(tempdir, (sizeof (tempdir)));
1417 
1418 		archtype = putfile(file, cp2, parent, NULL, NORMAL_FILE,
1419 		    LEV0, SYMLINK_LEV0);
1420 
1421 #if defined(O_XATTR)
1422 		if (!exitflag) {
1423 			if ((atflag || saflag) &&
1424 			    (archtype == PUT_NOTAS_LINK)) {
1425 				xattrs_put(file, cp2, parent, NULL);
1426 			}
1427 		}
1428 #endif
1429 
1430 		if (tar_chdir(origdir) < 0)
1431 			vperror(0, gettext("cannot change back?: %s"), origdir);
1432 
1433 		if (exitflag) {
1434 			/*
1435 			 * If e function modifier has been specified
1436 			 * write the files (that are listed before the
1437 			 * file causing the error) to tape.  exitflag is
1438 			 * used because only some of the error conditions
1439 			 * in putfile() recognize the e function modifier.
1440 			 */
1441 			break;
1442 		}
1443 	}
1444 
1445 	putempty((blkcnt_t)2);
1446 	flushtape();
1447 	closevol();	/* SP-1 */
1448 	if (linkerrok == 1)
1449 		for (; ihead != NULL; ihead = ihead->nextp) {
1450 			if (ihead->count == 0)
1451 				continue;
1452 			(void) fprintf(stderr, gettext(
1453 			"tar: missing links to %s\n"), ihead->pathname);
1454 			if (errflag)
1455 				done(1);
1456 			else
1457 				Errflg = 1;
1458 		}
1459 }
1460 
1461 
1462 /*
1463  * endtape - check for tape at end
1464  *
1465  *	endtape checks the entry in dblock.dbuf to see if its the
1466  *	special EOT entry.  Endtape is usually called after getdir().
1467  *
1468  *	endtape used to call backtape; it no longer does. If the caller
1469  *	wants the tape backed up, it must call backtape itself
1470  *	RETURNS:	0 if not EOT, tape position unaffected
1471  *			1 if	 EOT, tape position unaffected
1472  */
1473 
1474 static boolean_t
endtape(void)1475 endtape(void)
1476 {
1477 	if (dblock.dbuf.name[0] != '\0') {
1478 		/*
1479 		 * The name field is populated.
1480 		 */
1481 		return (B_FALSE);
1482 	}
1483 
1484 	if (is_posix && dblock.dbuf.prefix[0] != '\0') {
1485 		/*
1486 		 * This is a ustar/POSIX archive, and although the name
1487 		 * field is empty the prefix field is not.
1488 		 */
1489 		return (B_FALSE);
1490 	}
1491 
1492 	dlog("endtape(): found null header; EOT\n");
1493 	return (B_TRUE);
1494 }
1495 
1496 /*
1497  *	getdir - get directory entry from tar tape
1498  *
1499  *	getdir reads the next tarblock off the tape and cracks
1500  *	it as a directory. The checksum must match properly.
1501  *
1502  *	If tfile is non-null getdir writes the file name and mod date
1503  *	to tfile.
1504  */
1505 
1506 static void
getdir(void)1507 getdir(void)
1508 {
1509 	struct stat *sp;
1510 #ifdef EUC
1511 	static int warn_chksum_sign = 0;
1512 #endif /* EUC */
1513 
1514 top:
1515 	readtape((char *)&dblock);
1516 	if (dblock.dbuf.name[0] == '\0')
1517 		return;
1518 	sp = &stbuf;
1519 	(void) sscanf(dblock.dbuf.mode, "%8lo", &Gen.g_mode);
1520 	(void) sscanf(dblock.dbuf.uid, "%8lo", (ulong_t *)&Gen.g_uid);
1521 	(void) sscanf(dblock.dbuf.gid, "%8lo", (ulong_t *)&Gen.g_gid);
1522 	(void) sscanf(dblock.dbuf.size, "%12" FMT_off_t_o, &Gen.g_filesz);
1523 	(void) sscanf(dblock.dbuf.mtime, "%12lo", (ulong_t *)&Gen.g_mtime);
1524 	(void) sscanf(dblock.dbuf.chksum, "%8o", &Gen.g_cksum);
1525 	(void) sscanf(dblock.dbuf.devmajor, "%8lo", &Gen.g_devmajor);
1526 	(void) sscanf(dblock.dbuf.devminor, "%8lo", &Gen.g_devminor);
1527 
1528 	is_posix = (strcmp(dblock.dbuf.magic, magic_type) == 0);
1529 
1530 	sp->st_mode = Gen.g_mode;
1531 	if (is_posix && (sp->st_mode & S_IFMT) == 0) {
1532 		switch (dblock.dbuf.typeflag) {
1533 		case '0':
1534 		case 0:
1535 		case _XATTR_HDRTYPE:
1536 			sp->st_mode |= S_IFREG;
1537 			break;
1538 		case '1':	/* hard link */
1539 			break;
1540 		case '2':
1541 			sp->st_mode |= S_IFLNK;
1542 			break;
1543 		case '3':
1544 			sp->st_mode |= S_IFCHR;
1545 			break;
1546 		case '4':
1547 			sp->st_mode |= S_IFBLK;
1548 			break;
1549 		case '5':
1550 			sp->st_mode |= S_IFDIR;
1551 			break;
1552 		case '6':
1553 			sp->st_mode |= S_IFIFO;
1554 			break;
1555 		default:
1556 			if (convtoreg(Gen.g_filesz))
1557 				sp->st_mode |= S_IFREG;
1558 			break;
1559 		}
1560 	}
1561 
1562 	if ((dblock.dbuf.typeflag == 'X') || (dblock.dbuf.typeflag == 'L')) {
1563 		Xhdrflag = 1;	/* Currently processing extended header */
1564 	} else {
1565 		Xhdrflag = 0;
1566 	}
1567 
1568 	sp->st_uid = Gen.g_uid;
1569 	sp->st_gid = Gen.g_gid;
1570 	sp->st_size = Gen.g_filesz;
1571 	sp->st_mtime = Gen.g_mtime;
1572 	chksum = Gen.g_cksum;
1573 
1574 	if (dblock.dbuf.extno != '\0') {	/* split file? */
1575 		extno = dblock.dbuf.extno;
1576 		extsize = Gen.g_filesz;
1577 		extotal = dblock.dbuf.extotal;
1578 	} else {
1579 		extno = 0;	/* tell others file not split */
1580 		extsize = 0;
1581 		extotal = 0;
1582 	}
1583 
1584 #ifdef	EUC
1585 	if (chksum != checksum(&dblock)) {
1586 		if (chksum != checksum_signed(&dblock)) {
1587 			(void) fprintf(stderr, gettext(
1588 			    "tar: directory checksum error\n"));
1589 			if (iflag) {
1590 				Errflg = 2;
1591 				goto top;
1592 			}
1593 			done(2);
1594 		} else {
1595 			if (! warn_chksum_sign) {
1596 				warn_chksum_sign = 1;
1597 				(void) fprintf(stderr, gettext(
1598 			"tar: warning: tar file made with signed checksum\n"));
1599 			}
1600 		}
1601 	}
1602 #else
1603 	if (chksum != checksum(&dblock)) {
1604 		(void) fprintf(stderr, gettext(
1605 		"tar: directory checksum error\n"));
1606 		if (iflag) {
1607 			Errflg = 2;
1608 			goto top;
1609 		}
1610 		done(2);
1611 	}
1612 #endif	/* EUC */
1613 	if (tfile != NULL && Xhdrflag == 0) {
1614 		/*
1615 		 * If an extended header is present, then time is available
1616 		 * in nanoseconds in the extended header data, so set it.
1617 		 * Otherwise, give an invalid value so that checkupdate will
1618 		 * not test beyond seconds.
1619 		 */
1620 		if ((xhdr_flgs & _X_MTIME))
1621 			sp->st_mtim.tv_nsec = Xtarhdr.x_mtime.tv_nsec;
1622 		else
1623 			sp->st_mtim.tv_nsec = -1;
1624 
1625 		if (xhdr_flgs & _X_PATH)
1626 			(void) fprintf(tfile, "%s %10ld.%9.9ld\n",
1627 			    Xtarhdr.x_path, sp->st_mtim.tv_sec,
1628 			    sp->st_mtim.tv_nsec);
1629 		else
1630 			(void) fprintf(tfile, "%.*s %10ld.%9.9ld\n",
1631 			    NAMSIZ, dblock.dbuf.name, sp->st_mtim.tv_sec,
1632 			    sp->st_mtim.tv_nsec);
1633 	}
1634 
1635 #if defined(O_XATTR)
1636 	Hiddendir = 0;
1637 	if (xattrp && dblock.dbuf.typeflag == _XATTR_HDRTYPE) {
1638 		if (xattrbadhead) {
1639 			free(xattrhead);
1640 			xattrp = NULL;
1641 			xattr_linkp = NULL;
1642 			xattrhead = NULL;
1643 		} else {
1644 			char	*aname = basename(xattrapath);
1645 			size_t	xindex  = aname - xattrapath;
1646 
1647 			if (xattrapath[xindex] == '.' &&
1648 			    xattrapath[xindex + 1] == '\0' &&
1649 			    xattrp->h_typeflag == '5') {
1650 				Hiddendir = 1;
1651 				sp->st_mode =
1652 				    (S_IFDIR | (sp->st_mode & POSIXMODES));
1653 			}
1654 			dblock.dbuf.typeflag = xattrp->h_typeflag;
1655 		}
1656 	}
1657 #endif
1658 }
1659 
1660 
1661 /*
1662  *	passtape - skip over a file on the tape
1663  *
1664  *	passtape skips over the next data file on the tape.
1665  *	The tape directory entry must be in dblock.dbuf. This
1666  *	routine just eats the number of blocks computed from the
1667  *	directory size entry; the tape must be (logically) positioned
1668  *	right after the directory info.
1669  */
1670 
1671 static void
passtape(void)1672 passtape(void)
1673 {
1674 	blkcnt_t blocks;
1675 	char buf[TBLOCK];
1676 
1677 	/*
1678 	 * Print some debugging information about the directory entry
1679 	 * we are skipping over:
1680 	 */
1681 	dlog("passtape: typeflag \"%c\"\n", dblock.dbuf.typeflag);
1682 	if (dblock.dbuf.name[0] != '\0') {
1683 		dlog("passtape: name \"%s\"\n", dblock.dbuf.name);
1684 	}
1685 	if (is_posix && dblock.dbuf.prefix[0] != '\0') {
1686 		dlog("passtape: prefix \"%s\"\n", dblock.dbuf.prefix);
1687 	}
1688 
1689 	/*
1690 	 * Types link(1), sym-link(2), char special(3), blk special(4),
1691 	 *  directory(5), and FIFO(6) do not have data blocks associated
1692 	 *  with them so just skip reading the data block.
1693 	 */
1694 	if (dblock.dbuf.typeflag == '1' || dblock.dbuf.typeflag == '2' ||
1695 	    dblock.dbuf.typeflag == '3' || dblock.dbuf.typeflag == '4' ||
1696 	    dblock.dbuf.typeflag == '5' || dblock.dbuf.typeflag == '6')
1697 		return;
1698 	blocks = TBLOCKS(stbuf.st_size);
1699 
1700 	dlog("passtape: block count %" FMT_blkcnt_t "\n", blocks);
1701 
1702 	/* if operating on disk, seek instead of reading */
1703 	if (NotTape)
1704 		seekdisk(blocks);
1705 	else
1706 		while (blocks-- > 0)
1707 			readtape(buf);
1708 }
1709 
1710 #if defined(O_XATTR)
1711 static int
is_sysattr(char * name)1712 is_sysattr(char *name)
1713 {
1714 	return ((strcmp(name, VIEW_READONLY) == 0) ||
1715 	    (strcmp(name, VIEW_READWRITE) == 0));
1716 }
1717 #endif
1718 
1719 #if defined(O_XATTR)
1720 /*
1721  * Verify the attribute, attrname, is an attribute we want to restore.
1722  * Never restore read-only system attribute files.  Only restore read-write
1723  * system attributes files when -/ was specified, and only traverse into
1724  * the 2nd level attribute directory containing only system attributes if
1725  * -@ was specified.  This keeps us from archiving
1726  *	<attribute name>/<read-write system attribute file>
1727  * when -/ was specified without -@.
1728  *
1729  * attrname	- attribute file name
1730  * attrparent	- attribute's parent name within the base file's attribute
1731  *		directory hierarchy
1732  */
1733 static attr_status_t
verify_attr(char * attrname,char * attrparent,int arc_rwsysattr,int * rw_sysattr)1734 verify_attr(char *attrname, char *attrparent, int arc_rwsysattr,
1735     int *rw_sysattr)
1736 {
1737 #if defined(_PC_SATTR_ENABLED)
1738 	int	attr_supported;
1739 
1740 	/* Never restore read-only system attribute files */
1741 	if ((attr_supported = sysattr_type(attrname)) == _RO_SATTR) {
1742 		*rw_sysattr = 0;
1743 		return (ATTR_SKIP);
1744 	} else {
1745 		*rw_sysattr = (attr_supported == _RW_SATTR);
1746 	}
1747 #else
1748 	/*
1749 	 * Only need to check if this attribute is an extended system
1750 	 * attribute.
1751 	 */
1752 	if (*rw_sysattr = is_sysattr(attrname)) {
1753 		return (ATTR_SKIP);
1754 	} else {
1755 		return (ATTR_OK);
1756 	}
1757 #endif	/* _PC_SATTR_ENABLED */
1758 
1759 	/*
1760 	 * If the extended system attribute file is specified with the
1761 	 * arc_rwsysattr flag, as being transient (default extended
1762 	 * attributes), then don't archive it.
1763 	 */
1764 	if (*rw_sysattr && !arc_rwsysattr) {
1765 		return (ATTR_SKIP);
1766 	}
1767 
1768 	/*
1769 	 * Only restore read-write system attribute files
1770 	 * when -/ was specified.  Only restore extended
1771 	 * attributes when -@ was specified.
1772 	 */
1773 	if (atflag) {
1774 		if (!saflag) {
1775 			/*
1776 			 * Only archive/restore the hidden directory "." if
1777 			 * we're processing the top level hidden attribute
1778 			 * directory.  We don't want to process the
1779 			 * hidden attribute directory of the attribute
1780 			 * directory that contains only extended system
1781 			 * attributes.
1782 			 */
1783 			if (*rw_sysattr || (Hiddendir &&
1784 			    (attrparent != NULL))) {
1785 				return (ATTR_SKIP);
1786 			}
1787 		}
1788 	} else if (saflag) {
1789 		/*
1790 		 * Only archive/restore read-write extended system attribute
1791 		 * files of the base file.
1792 		 */
1793 		if (!*rw_sysattr || (attrparent != NULL)) {
1794 			return (ATTR_SKIP);
1795 		}
1796 	} else {
1797 		return (ATTR_SKIP);
1798 	}
1799 
1800 	return (ATTR_OK);
1801 }
1802 #endif
1803 
1804 static void
free_children(file_list_t * children)1805 free_children(file_list_t *children)
1806 {
1807 	file_list_t	*child = children;
1808 	file_list_t	*cptr;
1809 
1810 	while (child != NULL) {
1811 		cptr = child->next;
1812 		if (child->name != NULL) {
1813 			free(child->name);
1814 		}
1815 		child = cptr;
1816 	}
1817 }
1818 
1819 static int
putfile(char * longname,char * shortname,char * parent,attr_data_t * attrinfo,int filetype,int lev,int symlink_lev)1820 putfile(char *longname, char *shortname, char *parent, attr_data_t *attrinfo,
1821     int filetype, int lev, int symlink_lev)
1822 {
1823 	int infile = -1;	/* deliberately invalid */
1824 	blkcnt_t blocks;
1825 	char buf[PATH_MAX + 2];	/* Add trailing slash and null */
1826 	char *bigbuf;
1827 	int	maxread;
1828 	int	hint;		/* amount to write to get "in sync" */
1829 	char filetmp[PATH_MAX + 1];
1830 	char *cp;
1831 	char *name;
1832 	char *attrparent = NULL;
1833 	char *longattrname = NULL;
1834 	file_list_t	*child = NULL;
1835 	file_list_t	*child_end = NULL;
1836 	file_list_t	*cptr;
1837 	struct dirent *dp;
1838 	DIR *dirp;
1839 	int i;
1840 	int split;
1841 	int dirfd = -1;
1842 	int rc = PUT_NOTAS_LINK;
1843 	int archtype = 0;
1844 	int rw_sysattr = 0;
1845 	char newparent[PATH_MAX + MAXNAMLEN + 1];
1846 	char *prefix = "";
1847 	char *tmpbuf;
1848 	char goodbuf[PRESIZ + 2];
1849 	char junkbuf[MAXNAM+1];
1850 	char *lastslash;
1851 	int j;
1852 	struct stat sbuf;
1853 	int readlink_max;
1854 
1855 	(void) memset(goodbuf, '\0', sizeof (goodbuf));
1856 	(void) memset(junkbuf, '\0', sizeof (junkbuf));
1857 
1858 	xhdr_flgs = 0;
1859 
1860 	if (filetype == XATTR_FILE) {
1861 		attrparent = attrinfo->attr_parent;
1862 		longattrname = attrinfo->attr_path;
1863 		dirfd = attrinfo->attr_parentfd;
1864 		rw_sysattr = attrinfo->attr_rw_sysattr;
1865 	} else {
1866 		dirfd = open(".", O_RDONLY);
1867 	}
1868 
1869 	if (dirfd == -1) {
1870 		(void) fprintf(stderr, gettext(
1871 		    "tar: unable to open%sdirectory %s%s%s%s\n"),
1872 		    (filetype == XATTR_FILE) ? gettext(" attribute ") : " ",
1873 		    (attrparent == NULL) ? "" : gettext("of attribute "),
1874 		    (attrparent == NULL) ? "" : attrparent,
1875 		    (attrparent == NULL) ? "" : gettext(" of "),
1876 		    (filetype == XATTR_FILE) ? longname : parent);
1877 		goto out;
1878 	}
1879 
1880 	if (lev > MAXLEV) {
1881 		(void) fprintf(stderr,
1882 		    gettext("tar: directory nesting too deep, %s not dumped\n"),
1883 		    longname);
1884 		goto out;
1885 	}
1886 
1887 	if (getstat(dirfd, longname, shortname, attrparent))
1888 		goto out;
1889 
1890 	if (hflag) {
1891 		/*
1892 		 * Catch nesting where a file is a symlink to its directory.
1893 		 */
1894 		j = fstatat(dirfd, shortname, &sbuf, AT_SYMLINK_NOFOLLOW);
1895 		if (S_ISLNK(sbuf.st_mode)) {
1896 			if (symlink_lev++ >= MAXSYMLINKS) {
1897 				(void) fprintf(stderr, gettext(
1898 				    "tar: %s: Number of symbolic links "
1899 				    "encountered during path name traversal "
1900 				    "exceeds MAXSYMLINKS\n"), longname);
1901 				Errflg = 1;
1902 				goto out;
1903 			}
1904 		}
1905 	}
1906 
1907 	/*
1908 	 * Check if the input file is the same as the tar file we
1909 	 * are creating
1910 	 */
1911 	if ((mt_ino == stbuf.st_ino) && (mt_dev == stbuf.st_dev)) {
1912 		(void) fprintf(stderr, gettext(
1913 		    "tar: %s%s%s%s%s same as archive file\n"),
1914 		    rw_sysattr ? gettext("system ") : "",
1915 		    (longattrname == NULL) ? "" : gettext("attribute "),
1916 		    (longattrname == NULL) ? "" : longattrname,
1917 		    (longattrname == NULL) ? "" : gettext(" of "),
1918 		    longname);
1919 		Errflg = 1;
1920 		goto out;
1921 	}
1922 	/*
1923 	 * Check size limit - we can't archive files that
1924 	 * exceed TAR_OFFSET_MAX bytes because of header
1925 	 * limitations. Exclude file types that set
1926 	 * st_size to zero below because they take no
1927 	 * archive space to represent contents.
1928 	 */
1929 	if ((stbuf.st_size > (off_t)TAR_OFFSET_MAX) &&
1930 	    !S_ISDIR(stbuf.st_mode) &&
1931 	    !S_ISCHR(stbuf.st_mode) &&
1932 	    !S_ISBLK(stbuf.st_mode) &&
1933 	    (Eflag == 0)) {
1934 		(void) fprintf(stderr, gettext(
1935 		    "tar: %s%s%s%s%s too large to archive.  "
1936 		    "Use E function modifier.\n"),
1937 		    rw_sysattr ? gettext("system ") : "",
1938 		    (longattrname == NULL) ? "" : gettext("attribute "),
1939 		    (longattrname == NULL) ? "" : longattrname,
1940 		    (longattrname == NULL) ? "" : gettext(" of "),
1941 		    longname);
1942 		if (errflag)
1943 			exitflag = 1;
1944 		Errflg = 1;
1945 		goto out;
1946 	}
1947 
1948 	if (tfile != NULL && checkupdate(longname) == 0) {
1949 		goto out;
1950 	}
1951 	if (checkw('r', longname) == 0) {
1952 		goto out;
1953 	}
1954 
1955 	if (Fflag &&
1956 	    checkf(longname, (stbuf.st_mode & S_IFMT) == S_IFDIR, Fflag) == 0)
1957 		goto out;
1958 
1959 	if (Xflag) {
1960 		if (is_in_table(exclude_tbl, longname)) {
1961 			if (vflag) {
1962 				(void) fprintf(vfile, gettext(
1963 				    "a %s excluded\n"), longname);
1964 			}
1965 			goto out;
1966 		}
1967 	}
1968 
1969 	/*
1970 	 * If the length of the fullname is greater than MAXNAM,
1971 	 * print out a message and return (unless extended headers are used,
1972 	 * in which case fullname is limited to PATH_MAX).
1973 	 */
1974 
1975 	if ((((split = (int)strlen(longname)) > MAXNAM) && (Eflag == 0)) ||
1976 	    (split > PATH_MAX)) {
1977 		(void) fprintf(stderr, gettext(
1978 		    "tar: %s: file name too long\n"), longname);
1979 		if (errflag)
1980 			exitflag = 1;
1981 		Errflg = 1;
1982 		goto out;
1983 	}
1984 
1985 	/*
1986 	 * We split the fullname into prefix and name components if any one
1987 	 * of three conditions holds:
1988 	 *	-- the length of the fullname exceeds NAMSIZ,
1989 	 *	-- the length of the fullname equals NAMSIZ, and the shortname
1990 	 *	   is less than NAMSIZ, (splitting in this case preserves
1991 	 *	   compatibility with 5.6 and 5.5.1 tar), or
1992 	 *	-- the length of the fullname equals NAMSIZ, the file is a
1993 	 *	   directory and we are not in POSIX-conformant mode (where
1994 	 *	   trailing slashes are removed from directories).
1995 	 */
1996 	if ((split > NAMSIZ) ||
1997 	    (split == NAMSIZ && strlen(shortname) < NAMSIZ) ||
1998 	    (split == NAMSIZ && S_ISDIR(stbuf.st_mode) && !Pflag)) {
1999 		/*
2000 		 * Since path is limited to PRESIZ characters, look for the
2001 		 * last slash within PRESIZ + 1 characters only.
2002 		 */
2003 		(void) strncpy(&goodbuf[0], longname, min(split, PRESIZ + 1));
2004 		tmpbuf = goodbuf;
2005 		lastslash = strrchr(tmpbuf, '/');
2006 		if (lastslash == NULL) {
2007 			i = split;		/* Length of name */
2008 			j = 0;			/* Length of prefix */
2009 			goodbuf[0] = '\0';
2010 		} else {
2011 			*lastslash = '\0';	/* Terminate the prefix */
2012 			j = strlen(tmpbuf);
2013 			i = split - j - 1;
2014 		}
2015 		/*
2016 		 * If the filename is greater than NAMSIZ we can't
2017 		 * archive the file unless we are using extended headers.
2018 		 */
2019 		if ((i > NAMSIZ) || (i == NAMSIZ && S_ISDIR(stbuf.st_mode) &&
2020 		    !Pflag)) {
2021 			/* Determine which (filename or path) is too long. */
2022 			lastslash = strrchr(longname, '/');
2023 			if (lastslash != NULL)
2024 				i = strlen(lastslash + 1);
2025 			if (Eflag > 0) {
2026 				xhdr_flgs |= _X_PATH;
2027 				Xtarhdr.x_path = longname;
2028 				if (i <= NAMSIZ)
2029 					(void) strcpy(junkbuf, lastslash + 1);
2030 				else
2031 					(void) sprintf(junkbuf, "%llu",
2032 					    xhdr_count + 1);
2033 				if (split - i - 1 > PRESIZ)
2034 					(void) strcpy(goodbuf, xhdr_dirname);
2035 			} else {
2036 				if ((i > NAMSIZ) || (i == NAMSIZ &&
2037 				    S_ISDIR(stbuf.st_mode) && !Pflag))
2038 					(void) fprintf(stderr, gettext(
2039 					    "tar: %s: filename is greater than "
2040 					    "%d\n"), lastslash == NULL ?
2041 					    longname : lastslash + 1, NAMSIZ);
2042 				else
2043 					(void) fprintf(stderr, gettext(
2044 					    "tar: %s: prefix is greater than %d"
2045 					    "\n"), longname, PRESIZ);
2046 				if (errflag)
2047 					exitflag = 1;
2048 				Errflg = 1;
2049 				goto out;
2050 			}
2051 		} else
2052 			(void) strncpy(&junkbuf[0], longname + j + 1,
2053 			    strlen(longname + j + 1));
2054 		name = junkbuf;
2055 		prefix = goodbuf;
2056 	} else {
2057 		name = longname;
2058 	}
2059 	if (Aflag) {
2060 		if ((prefix != NULL) && (*prefix != '\0'))
2061 			while (*prefix == '/')
2062 				++prefix;
2063 		else
2064 			while (*name == '/')
2065 				++name;
2066 	}
2067 
2068 	switch (stbuf.st_mode & S_IFMT) {
2069 	case S_IFDIR:
2070 		stbuf.st_size = (off_t)0;
2071 		blocks = TBLOCKS(stbuf.st_size);
2072 
2073 		if (filetype != XATTR_FILE && Hiddendir == 0) {
2074 			i = 0;
2075 			cp = buf;
2076 			while ((*cp++ = longname[i++]))
2077 				;
2078 			*--cp = '/';
2079 			*++cp = 0;
2080 		}
2081 		if (!oflag) {
2082 			tomodes(&stbuf);
2083 			if (build_dblock(name, tchar, '5', filetype,
2084 			    &stbuf, stbuf.st_dev, prefix) != 0) {
2085 				goto out;
2086 			}
2087 			if (!Pflag) {
2088 				/*
2089 				 * Old archives require a slash at the end
2090 				 * of a directory name.
2091 				 *
2092 				 * XXX
2093 				 * If directory name is too long, will
2094 				 * slash overfill field?
2095 				 */
2096 				if (strlen(name) > (unsigned)NAMSIZ-1) {
2097 					(void) fprintf(stderr, gettext(
2098 					    "tar: %s: filename is greater "
2099 					    "than %d\n"), name, NAMSIZ);
2100 					if (errflag)
2101 						exitflag = 1;
2102 					Errflg = 1;
2103 					goto out;
2104 				} else {
2105 					if (strlen(name) == (NAMSIZ - 1)) {
2106 						(void) memcpy(dblock.dbuf.name,
2107 						    name, NAMSIZ);
2108 						dblock.dbuf.name[NAMSIZ-1]
2109 						    = '/';
2110 					} else
2111 						(void) sprintf(dblock.dbuf.name,
2112 						    "%s/", name);
2113 
2114 					/*
2115 					 * need to recalculate checksum
2116 					 * because the name changed.
2117 					 */
2118 					(void) sprintf(dblock.dbuf.chksum,
2119 					    "%07o", checksum(&dblock));
2120 				}
2121 			}
2122 
2123 			if (put_extra_attributes(longname, shortname,
2124 			    longattrname, prefix, filetype, '5') != 0)
2125 				goto out;
2126 
2127 #if defined(O_XATTR)
2128 			/*
2129 			 * Reset header typeflag when archiving directory, since
2130 			 * build_dblock changed it on us.
2131 			 */
2132 			if (filetype == XATTR_FILE) {
2133 				dblock.dbuf.typeflag = _XATTR_HDRTYPE;
2134 			} else {
2135 				dblock.dbuf.typeflag = '5';
2136 			}
2137 #else
2138 			dblock.dbuf.typeflag = '5';
2139 #endif
2140 
2141 			(void) sprintf(dblock.dbuf.chksum, "%07o",
2142 			    checksum(&dblock));
2143 
2144 			(void) writetbuf((char *)&dblock, 1);
2145 		}
2146 		if (vflag) {
2147 			if (NotTape) {
2148 				dlog("seek = %" FMT_blkcnt_t "K\n", K(tapepos));
2149 			}
2150 			if (filetype == XATTR_FILE && Hiddendir) {
2151 				(void) fprintf(vfile,
2152 				    gettext("a %s attribute %s "),
2153 				    longname, longattrname);
2154 
2155 			} else {
2156 				(void) fprintf(vfile, "a %s/ ", longname);
2157 			}
2158 			if (NotTape) {
2159 				(void) fprintf(vfile, "%" FMT_blkcnt_t "K\n",
2160 				    K(blocks));
2161 			} else {
2162 				(void) fprintf(vfile, gettext("%" FMT_blkcnt_t
2163 				    " tape blocks\n"), blocks);
2164 			}
2165 		}
2166 
2167 		/*
2168 		 * If hidden dir then break now since xattrs_put() will do
2169 		 * the iterating of the directory.
2170 		 *
2171 		 * At the moment, there can only be system attributes on
2172 		 * attributes.  There can be no attributes on attributes or
2173 		 * directories within the attributes hidden directory hierarchy.
2174 		 */
2175 		if (filetype == XATTR_FILE)
2176 			break;
2177 
2178 		if (*shortname != '/')
2179 			(void) sprintf(newparent, "%s/%s", parent, shortname);
2180 		else
2181 			(void) sprintf(newparent, "%s", shortname);
2182 
2183 		if (tar_chdir(shortname) < 0) {
2184 			vperror(0, "%s", newparent);
2185 			goto out;
2186 		}
2187 
2188 		if ((dirp = opendir(".")) == NULL) {
2189 			vperror(0, gettext(
2190 			    "can't open directory %s"), longname);
2191 			if (tar_chdir(parent) < 0)
2192 				vperror(0, gettext("cannot change back?: %s"),
2193 				    parent);
2194 			goto out;
2195 		}
2196 
2197 		/*
2198 		 * Create a list of files (children) in this directory to avoid
2199 		 * having to perform telldir()/seekdir().
2200 		 */
2201 		while ((dp = readdir(dirp)) != NULL && !term) {
2202 			if ((strcmp(".", dp->d_name) == 0) ||
2203 			    (strcmp("..", dp->d_name) == 0))
2204 				continue;
2205 			if (((cptr = (file_list_t *)calloc(sizeof (char),
2206 			    sizeof (file_list_t))) == NULL) ||
2207 			    ((cptr->name = strdup(dp->d_name)) == NULL)) {
2208 				vperror(1, gettext(
2209 				    "Insufficient memory for directory "
2210 				    "list entry %s/%s\n"),
2211 				    newparent, dp->d_name);
2212 			}
2213 
2214 			/* Add the file to the list */
2215 			if (child == NULL) {
2216 				child = cptr;
2217 			} else {
2218 				child_end->next = cptr;
2219 			}
2220 			child_end = cptr;
2221 		}
2222 		(void) closedir(dirp);
2223 
2224 		/*
2225 		 * Archive each of the files in the current directory.
2226 		 * If a file is a directory, putfile() is called
2227 		 * recursively to archive the file hierarchy of the
2228 		 * directory before archiving the next file in the
2229 		 * current directory.
2230 		 */
2231 		while ((child != NULL) && !term) {
2232 			(void) strcpy(cp, child->name);
2233 			archtype = putfile(buf, cp, newparent, NULL,
2234 			    NORMAL_FILE, lev + 1, symlink_lev);
2235 
2236 			if (!exitflag) {
2237 				if ((atflag || saflag) &&
2238 				    (archtype == PUT_NOTAS_LINK)) {
2239 					xattrs_put(buf, cp, newparent, NULL);
2240 				}
2241 			}
2242 			if (exitflag)
2243 				break;
2244 
2245 			/* Free each child as we are done processing it. */
2246 			cptr = child;
2247 			child = child->next;
2248 			free(cptr->name);
2249 			free(cptr);
2250 		}
2251 		if ((child != NULL) && !term) {
2252 			free_children(child);
2253 		}
2254 
2255 		if (tar_chdir(parent) < 0) {
2256 			vperror(0, gettext("cannot change back?: %s"), parent);
2257 		}
2258 
2259 		break;
2260 
2261 	case S_IFLNK:
2262 		readlink_max = NAMSIZ;
2263 		if (stbuf.st_size > NAMSIZ) {
2264 			if (Eflag > 0) {
2265 				xhdr_flgs |= _X_LINKPATH;
2266 				readlink_max = PATH_MAX;
2267 			} else {
2268 				(void) fprintf(stderr, gettext(
2269 				    "tar: %s: symbolic link too long\n"),
2270 				    longname);
2271 				if (errflag)
2272 					exitflag = 1;
2273 				Errflg = 1;
2274 				goto out;
2275 			}
2276 		}
2277 		/*
2278 		 * Sym-links need header size of zero since you
2279 		 * don't store any data for this type.
2280 		 */
2281 		stbuf.st_size = (off_t)0;
2282 		tomodes(&stbuf);
2283 		i = readlink(shortname, filetmp, readlink_max);
2284 		if (i < 0) {
2285 			vperror(0, gettext(
2286 			    "can't read symbolic link %s"), longname);
2287 			goto out;
2288 		} else {
2289 			filetmp[i] = 0;
2290 		}
2291 		if (vflag)
2292 			(void) fprintf(vfile, gettext(
2293 			    "a %s symbolic link to %s\n"),
2294 			    longname, filetmp);
2295 		if (xhdr_flgs & _X_LINKPATH) {
2296 			Xtarhdr.x_linkpath = filetmp;
2297 			if (build_dblock(name, tchar, '2', filetype, &stbuf,
2298 			    stbuf.st_dev, prefix) != 0)
2299 				goto out;
2300 		} else
2301 			if (build_dblock(name, filetmp, '2', filetype, &stbuf,
2302 			    stbuf.st_dev, prefix) != 0)
2303 				goto out;
2304 		(void) writetbuf((char *)&dblock, 1);
2305 		/*
2306 		 * No acls for symlinks: mode is always 777
2307 		 * dont call write ancillary
2308 		 */
2309 		rc = PUT_AS_LINK;
2310 		break;
2311 	case S_IFREG:
2312 		if ((infile = openat(dirfd, shortname, 0)) < 0) {
2313 			vperror(0, gettext("unable to open %s%s%s%s"), longname,
2314 			    rw_sysattr ? gettext(" system") : "",
2315 			    (filetype == XATTR_FILE) ?
2316 			    gettext(" attribute ") : "",
2317 			    (filetype == XATTR_FILE) ? (longattrname == NULL) ?
2318 			    shortname : longattrname : "");
2319 			goto out;
2320 		}
2321 
2322 		blocks = TBLOCKS(stbuf.st_size);
2323 
2324 		if (put_link(name, longname, shortname, longattrname,
2325 		    prefix, filetype, '1') == 0) {
2326 			(void) close(infile);
2327 			rc = PUT_AS_LINK;
2328 			goto out;
2329 		}
2330 
2331 		tomodes(&stbuf);
2332 
2333 		/* correctly handle end of volume */
2334 		while (mulvol && tapepos + blocks + 1 > blocklim) {
2335 			/* split if floppy has some room and file is large */
2336 			if (((blocklim - tapepos) >= EXTMIN) &&
2337 			    ((blocks + 1) >= blocklim/10)) {
2338 				splitfile(longname, infile,
2339 				    name, prefix, filetype);
2340 				(void) close(dirfd);
2341 				(void) close(infile);
2342 				goto out;
2343 			}
2344 			newvol();	/* not worth it--just get new volume */
2345 		}
2346 		dlog("putfile: %s wants %" FMT_blkcnt_t " blocks\n", longname,
2347 		    blocks);
2348 		if (build_dblock(name, tchar, '0', filetype,
2349 		    &stbuf, stbuf.st_dev, prefix) != 0) {
2350 			goto out;
2351 		}
2352 		if (vflag) {
2353 			if (NotTape) {
2354 				dlog("seek = %" FMT_blkcnt_t "K\n", K(tapepos));
2355 			}
2356 			(void) fprintf(vfile, "a %s%s%s%s ", longname,
2357 			    rw_sysattr ? gettext(" system") : "",
2358 			    (filetype == XATTR_FILE) ? gettext(
2359 			    " attribute ") : "",
2360 			    (filetype == XATTR_FILE) ?
2361 			    longattrname : "");
2362 			if (NotTape)
2363 				(void) fprintf(vfile, "%" FMT_blkcnt_t "K\n",
2364 				    K(blocks));
2365 			else
2366 				(void) fprintf(vfile,
2367 				    gettext("%" FMT_blkcnt_t " tape blocks\n"),
2368 				    blocks);
2369 		}
2370 
2371 		if (put_extra_attributes(longname, shortname, longattrname,
2372 		    prefix, filetype, '0') != 0)
2373 			goto out;
2374 
2375 		/*
2376 		 * No need to reset typeflag for extended attribute here, since
2377 		 * put_extra_attributes already set it and we haven't called
2378 		 * build_dblock().
2379 		 */
2380 		(void) sprintf(dblock.dbuf.chksum, "%07o", checksum(&dblock));
2381 		hint = writetbuf((char *)&dblock, 1);
2382 		maxread = max(min(stbuf.st_blksize, stbuf.st_size),
2383 		    (nblock * TBLOCK));
2384 		if ((bigbuf = calloc((unsigned)maxread, sizeof (char))) == 0) {
2385 			maxread = TBLOCK;
2386 			bigbuf = buf;
2387 		}
2388 
2389 		while (((i = (int)
2390 		    read(infile, bigbuf, min((hint*TBLOCK), maxread))) > 0) &&
2391 		    blocks) {
2392 			blkcnt_t nblks;
2393 
2394 			nblks = ((i-1)/TBLOCK)+1;
2395 			if (nblks > blocks)
2396 				nblks = blocks;
2397 			hint = writetbuf(bigbuf, nblks);
2398 			blocks -= nblks;
2399 		}
2400 		(void) close(infile);
2401 		if (bigbuf != buf)
2402 			free(bigbuf);
2403 		if (i < 0)
2404 			vperror(0, gettext("Read error on %s"), longname);
2405 		else if (blocks != 0 || i != 0) {
2406 			(void) fprintf(stderr, gettext(
2407 			"tar: %s: file changed size\n"), longname);
2408 			if (errflag) {
2409 				exitflag = 1;
2410 				Errflg = 1;
2411 			} else if (!Dflag) {
2412 				Errflg = 1;
2413 			}
2414 		}
2415 		putempty(blocks);
2416 		break;
2417 	case S_IFIFO:
2418 		blocks = TBLOCKS(stbuf.st_size);
2419 		stbuf.st_size = (off_t)0;
2420 
2421 		if (put_link(name, longname, shortname, longattrname,
2422 		    prefix, filetype, '6') == 0) {
2423 			rc = PUT_AS_LINK;
2424 			goto out;
2425 		}
2426 		tomodes(&stbuf);
2427 
2428 		while (mulvol && tapepos + blocks + 1 > blocklim) {
2429 			if (((blocklim - tapepos) >= EXTMIN) &&
2430 			    ((blocks + 1) >= blocklim/10)) {
2431 				splitfile(longname, infile, name,
2432 				    prefix, filetype);
2433 				(void) close(dirfd);
2434 				(void) close(infile);
2435 				goto out;
2436 			}
2437 			newvol();
2438 		}
2439 		dlog("putfile: %s wants %" FMT_blkcnt_t " blocks\n", longname,
2440 		    blocks);
2441 		if (vflag) {
2442 			if (NotTape) {
2443 				dlog("seek = %" FMT_blkcnt_t "K\n", K(tapepos));
2444 
2445 				(void) fprintf(vfile, gettext("a %s %"
2446 				    FMT_blkcnt_t "K\n "), longname, K(blocks));
2447 			} else {
2448 				(void) fprintf(vfile, gettext(
2449 				    "a %s %" FMT_blkcnt_t " tape blocks\n"),
2450 				    longname, blocks);
2451 			}
2452 		}
2453 		if (build_dblock(name, tchar, '6', filetype,
2454 		    &stbuf, stbuf.st_dev, prefix) != 0)
2455 			goto out;
2456 
2457 		if (put_extra_attributes(longname, shortname, longattrname,
2458 		    prefix, filetype, '6') != 0)
2459 			goto out;
2460 
2461 		(void) sprintf(dblock.dbuf.chksum, "%07o", checksum(&dblock));
2462 		dblock.dbuf.typeflag = '6';
2463 
2464 		(void) writetbuf((char *)&dblock, 1);
2465 		break;
2466 	case S_IFCHR:
2467 		stbuf.st_size = (off_t)0;
2468 		blocks = TBLOCKS(stbuf.st_size);
2469 		if (put_link(name, longname, shortname, longattrname,
2470 		    prefix, filetype, '3') == 0) {
2471 			rc = PUT_AS_LINK;
2472 			goto out;
2473 		}
2474 		tomodes(&stbuf);
2475 
2476 		while (mulvol && tapepos + blocks + 1 > blocklim) {
2477 			if (((blocklim - tapepos) >= EXTMIN) &&
2478 			    ((blocks + 1) >= blocklim/10)) {
2479 				splitfile(longname, infile, name,
2480 				    prefix, filetype);
2481 				(void) close(dirfd);
2482 				goto out;
2483 			}
2484 			newvol();
2485 		}
2486 		dlog("putfile: %s wants %" FMT_blkcnt_t " blocks\n", longname,
2487 		    blocks);
2488 		if (vflag) {
2489 			if (NotTape) {
2490 				dlog("seek = %" FMT_blkcnt_t "K\t", K(tapepos));
2491 
2492 				(void) fprintf(vfile, gettext("a %s %"
2493 				    FMT_blkcnt_t "K\n"), longname, K(blocks));
2494 			} else {
2495 				(void) fprintf(vfile, gettext("a %s %"
2496 				    FMT_blkcnt_t " tape blocks\n"), longname,
2497 				    blocks);
2498 			}
2499 		}
2500 		if (build_dblock(name, tchar, '3',
2501 		    filetype, &stbuf, stbuf.st_rdev, prefix) != 0)
2502 			goto out;
2503 
2504 		if (put_extra_attributes(longname, shortname, longattrname,
2505 		    prefix, filetype, '3') != 0)
2506 			goto out;
2507 
2508 		(void) sprintf(dblock.dbuf.chksum, "%07o", checksum(&dblock));
2509 		dblock.dbuf.typeflag = '3';
2510 
2511 		(void) writetbuf((char *)&dblock, 1);
2512 		break;
2513 	case S_IFBLK:
2514 		stbuf.st_size = (off_t)0;
2515 		blocks = TBLOCKS(stbuf.st_size);
2516 		if (put_link(name, longname, shortname, longattrname,
2517 		    prefix, filetype, '4') == 0) {
2518 			rc = PUT_AS_LINK;
2519 			goto out;
2520 		}
2521 		tomodes(&stbuf);
2522 
2523 		while (mulvol && tapepos + blocks + 1 > blocklim) {
2524 			if (((blocklim - tapepos) >= EXTMIN) &&
2525 			    ((blocks + 1) >= blocklim/10)) {
2526 				splitfile(longname, infile,
2527 				    name, prefix, filetype);
2528 				(void) close(dirfd);
2529 				goto out;
2530 			}
2531 			newvol();
2532 		}
2533 		dlog("putfile: %s wants %" FMT_blkcnt_t " blocks\n", longname,
2534 		    blocks);
2535 		if (vflag) {
2536 			if (NotTape) {
2537 				dlog("seek = %" FMT_blkcnt_t "K\n", K(tapepos));
2538 			}
2539 
2540 			(void) fprintf(vfile, "a %s ", longname);
2541 			if (NotTape)
2542 				(void) fprintf(vfile, "%" FMT_blkcnt_t "K\n",
2543 				    K(blocks));
2544 			else
2545 				(void) fprintf(vfile, gettext("%"
2546 				    FMT_blkcnt_t " tape blocks\n"), blocks);
2547 		}
2548 		if (build_dblock(name, tchar, '4',
2549 		    filetype, &stbuf, stbuf.st_rdev, prefix) != 0)
2550 			goto out;
2551 
2552 		if (put_extra_attributes(longname, shortname, longattrname,
2553 		    prefix, filetype, '4') != 0)
2554 			goto out;
2555 
2556 		(void) sprintf(dblock.dbuf.chksum, "%07o", checksum(&dblock));
2557 		dblock.dbuf.typeflag = '4';
2558 
2559 		(void) writetbuf((char *)&dblock, 1);
2560 		break;
2561 	default:
2562 		(void) fprintf(stderr, gettext(
2563 		    "tar: %s is not a file. Not dumped\n"), longname);
2564 		if (errflag)
2565 			exitflag = 1;
2566 		Errflg = 1;
2567 		goto out;
2568 	}
2569 
2570 out:
2571 	if ((dirfd != -1) && (filetype != XATTR_FILE)) {
2572 		(void) close(dirfd);
2573 	}
2574 	return (rc);
2575 }
2576 
2577 
2578 /*
2579  *	splitfile	dump a large file across volumes
2580  *
2581  *	splitfile(longname, fd);
2582  *		char *longname;		full name of file
2583  *		int ifd;		input file descriptor
2584  *
2585  *	NOTE:  only called by putfile() to dump a large file.
2586  */
2587 
2588 static void
splitfile(char * longname,int ifd,char * name,char * prefix,int filetype)2589 splitfile(char *longname, int ifd, char *name, char *prefix, int filetype)
2590 {
2591 	blkcnt_t blocks;
2592 	off_t bytes, s;
2593 	char buf[TBLOCK];
2594 	int i, extents;
2595 
2596 	blocks = TBLOCKS(stbuf.st_size);	/* blocks file needs */
2597 
2598 	/*
2599 	 * # extents =
2600 	 *	size of file after using up rest of this floppy
2601 	 *		blocks - (blocklim - tapepos) + 1	(for header)
2602 	 *	plus roundup value before divide by blocklim-1
2603 	 *		+ (blocklim - 1) - 1
2604 	 *	all divided by blocklim-1 (one block for each header).
2605 	 * this gives
2606 	 *	(blocks - blocklim + tapepos + 1 + blocklim - 2)/(blocklim-1)
2607 	 * which reduces to the expression used.
2608 	 * one is added to account for this first extent.
2609 	 *
2610 	 * When one is dealing with extremely large archives, one may want
2611 	 * to allow for a large number of extents.  This code should be
2612 	 * revisited to determine if extents should be changed to something
2613 	 * larger than an int.
2614 	 */
2615 	extents = (int)((blocks + tapepos - 1ULL)/(blocklim - 1ULL) + 1);
2616 
2617 	if (extents < 2 || extents > MAXEXT) {	/* let's be reasonable */
2618 		(void) fprintf(stderr, gettext(
2619 		    "tar: %s needs unusual number of volumes to split\n"
2620 		    "tar: %s not dumped\n"), longname, longname);
2621 		return;
2622 	}
2623 	if (build_dblock(name, tchar, '0', filetype,
2624 	    &stbuf, stbuf.st_dev, prefix) != 0)
2625 		return;
2626 
2627 	dblock.dbuf.extotal = extents;
2628 	bytes = stbuf.st_size;
2629 
2630 	/*
2631 	 * The value contained in dblock.dbuf.efsize was formerly used when the
2632 	 * v flag was specified in conjunction with the t flag. Although it is
2633 	 * no longer used, older versions of tar will expect the former
2634 	 * behaviour, so we must continue to write it to the archive.
2635 	 *
2636 	 * Since dblock.dbuf.efsize is 10 chars in size, the maximum value it
2637 	 * can store is TAR_EFSIZE_MAX. If bytes exceeds that value, simply
2638 	 * store 0.
2639 	 */
2640 	if (bytes <= TAR_EFSIZE_MAX)
2641 		(void) sprintf(dblock.dbuf.efsize, "%9" FMT_off_t_o, bytes);
2642 	else
2643 		(void) sprintf(dblock.dbuf.efsize, "%9" FMT_off_t_o, (off_t)0);
2644 
2645 	(void) fprintf(stderr, gettext(
2646 	    "tar: large file %s needs %d extents.\n"
2647 	    "tar: current device seek position = %" FMT_blkcnt_t "K\n"),
2648 	    longname, extents, K(tapepos));
2649 
2650 	s = (off_t)(blocklim - tapepos - 1) * TBLOCK;
2651 	for (i = 1; i <= extents; i++) {
2652 		if (i > 1) {
2653 			newvol();
2654 			if (i == extents)
2655 				s = bytes;	/* last ext. gets true bytes */
2656 			else
2657 				s = (off_t)(blocklim - 1)*TBLOCK; /* all */
2658 		}
2659 		bytes -= s;
2660 		blocks = TBLOCKS(s);
2661 
2662 		(void) sprintf(dblock.dbuf.size, "%011" FMT_off_t_o, s);
2663 		dblock.dbuf.extno = i;
2664 		(void) sprintf(dblock.dbuf.chksum, "%07o", checksum(&dblock));
2665 		(void) writetbuf((char *)&dblock, 1);
2666 
2667 		if (vflag)
2668 			(void) fprintf(vfile,
2669 			    gettext("+++ a %s %" FMT_blkcnt_t
2670 			    "K [extent #%d of %d]\n"),
2671 			    longname, K(blocks), i, extents);
2672 		while (blocks && read(ifd, buf, TBLOCK) > 0) {
2673 			blocks--;
2674 			(void) writetbuf(buf, 1);
2675 		}
2676 		if (blocks != 0) {
2677 			(void) fprintf(stderr, gettext(
2678 			    "tar: %s: file changed size\n"), longname);
2679 			(void) fprintf(stderr, gettext(
2680 			    "tar: aborting split file %s\n"), longname);
2681 			(void) close(ifd);
2682 			return;
2683 		}
2684 	}
2685 	(void) close(ifd);
2686 	if (vflag)
2687 		(void) fprintf(vfile, gettext("a %s %" FMT_off_t "K (in %d "
2688 		    "extents)\n"), longname, K(TBLOCKS(stbuf.st_size)),
2689 		    extents);
2690 }
2691 
2692 /*
2693  *	convtoreg - determines whether the file should be converted to a
2694  *	            regular file when extracted
2695  *
2696  *	Returns 1 when file size > 0 and typeflag is not recognized
2697  *	Otherwise returns 0
2698  */
2699 static int
convtoreg(off_t size)2700 convtoreg(off_t size)
2701 {
2702 	if ((size > 0) && (dblock.dbuf.typeflag != '0') &&
2703 	    (dblock.dbuf.typeflag != '\0') && (dblock.dbuf.typeflag != '1') &&
2704 	    (dblock.dbuf.typeflag != '2') && (dblock.dbuf.typeflag != '3') &&
2705 	    (dblock.dbuf.typeflag != '4') && (dblock.dbuf.typeflag != '5') &&
2706 	    (dblock.dbuf.typeflag != '6') && (dblock.dbuf.typeflag != 'A') &&
2707 	    (dblock.dbuf.typeflag != 'L') &&
2708 	    (dblock.dbuf.typeflag != _XATTR_HDRTYPE) &&
2709 	    (dblock.dbuf.typeflag != 'X')) {
2710 		return (1);
2711 	}
2712 	return (0);
2713 }
2714 
2715 #if defined(O_XATTR)
2716 static int
save_cwd(void)2717 save_cwd(void)
2718 {
2719 	return (open(".", O_RDONLY));
2720 }
2721 #endif
2722 
2723 #if defined(O_XATTR)
2724 static void
rest_cwd(int * cwd)2725 rest_cwd(int *cwd)
2726 {
2727 	if (*cwd != -1) {
2728 		if (fchdir(*cwd) < 0) {
2729 			vperror(0, gettext(
2730 			    "Cannot fchdir to attribute directory"));
2731 			exit(1);
2732 		}
2733 		(void) close(*cwd);
2734 		*cwd = -1;
2735 	}
2736 }
2737 #endif
2738 
2739 /*
2740  * Verify the underlying file system supports the attribute type.
2741  * Only archive extended attribute files when '-@' was specified.
2742  * Only archive system extended attribute files if '-/' was specified.
2743  */
2744 #if defined(O_XATTR)
2745 static attr_status_t
verify_attr_support(char * filename,int attrflg,arc_action_t actflag,int * ext_attrflg)2746 verify_attr_support(char *filename, int attrflg, arc_action_t actflag,
2747     int *ext_attrflg)
2748 {
2749 	/*
2750 	 * Verify extended attributes are supported/exist.  We only
2751 	 * need to check if we are processing a base file, not an
2752 	 * extended attribute.
2753 	 */
2754 	if (attrflg) {
2755 		*ext_attrflg = (pathconf(filename, (actflag == ARC_CREATE) ?
2756 		    _PC_XATTR_EXISTS : _PC_XATTR_ENABLED) == 1);
2757 	}
2758 
2759 	if (atflag) {
2760 		if (!*ext_attrflg) {
2761 #if defined(_PC_SATTR_ENABLED)
2762 			if (saflag) {
2763 				/* Verify system attributes are supported */
2764 				if (sysattr_support(filename,
2765 				    (actflag == ARC_CREATE) ? _PC_SATTR_EXISTS :
2766 				    _PC_SATTR_ENABLED) != 1) {
2767 					return (ATTR_SATTR_ERR);
2768 				}
2769 			} else
2770 				return (ATTR_XATTR_ERR);
2771 #else
2772 				return (ATTR_XATTR_ERR);
2773 #endif	/* _PC_SATTR_ENABLED */
2774 		}
2775 
2776 #if defined(_PC_SATTR_ENABLED)
2777 	} else if (saflag) {
2778 		/* Verify system attributes are supported */
2779 		if (sysattr_support(filename, (actflag == ARC_CREATE) ?
2780 		    _PC_SATTR_EXISTS : _PC_SATTR_ENABLED) != 1) {
2781 			return (ATTR_SATTR_ERR);
2782 		}
2783 #endif	/* _PC_SATTR_ENABLED */
2784 	} else {
2785 		return (ATTR_SKIP);
2786 	}
2787 
2788 	return (ATTR_OK);
2789 }
2790 #endif
2791 
2792 #if defined(O_XATTR)
2793 /*
2794  * Recursively open attribute directories until the attribute directory
2795  * containing the specified attribute, attrname, is opened.
2796  *
2797  * Currently, only 2 directory levels of attributes are supported, (i.e.,
2798  * extended system attributes on extended attributes).  The following are
2799  * the possible input combinations:
2800  *	1.  Open the attribute directory of the base file (don't change
2801  *	    into it).
2802  *		attrinfo->parent = NULL
2803  *		attrname = '.'
2804  *	2.  Open the attribute directory of the base file and change into it.
2805  *		attrinfo->parent = NULL
2806  *		attrname = <attr> | <sys_attr>
2807  *	3.  Open the attribute directory of the base file, change into it,
2808  *	    then recursively call open_attr_dir() to open the attribute's
2809  *	    parent directory (don't change into it).
2810  *		attrinfo->parent = <attr>
2811  *		attrname = '.'
2812  *	4.  Open the attribute directory of the base file, change into it,
2813  *	    then recursively call open_attr_dir() to open the attribute's
2814  *	    parent directory and change into it.
2815  *		attrinfo->parent = <attr>
2816  *		attrname = <attr> | <sys_attr>
2817  *
2818  * An attribute directory will be opened only if the underlying file system
2819  * supports the attribute type, and if the command line specifications (atflag
2820  * and saflag) enable the processing of the attribute type.
2821  *
2822  * On succesful return, attrinfo->parentfd will be the file descriptor of the
2823  * opened attribute directory.  In addition, if the attribute is a read-write
2824  * extended system attribute, attrinfo->rw_sysattr will be set to 1, otherwise
2825  * it will be set to 0.
2826  *
2827  * Possible return values:
2828  *	ATTR_OK		Successfully opened and, if needed, changed into the
2829  *			attribute directory containing attrname.
2830  *	ATTR_SKIP	The command line specifications don't enable the
2831  *			processing of the attribute type.
2832  *	ATTR_CHDIR_ERR	An error occurred while trying to change into an
2833  *			attribute directory.
2834  *	ATTR_OPEN_ERR	An error occurred while trying to open an
2835  *			attribute directory.
2836  *	ATTR_XATTR_ERR	The underlying file system doesn't support extended
2837  *			attributes.
2838  *	ATTR_SATTR_ERR	The underlying file system doesn't support extended
2839  *			system attributes.
2840  */
2841 static int
open_attr_dir(char * attrname,char * dirp,int cwd,attr_data_t * attrinfo)2842 open_attr_dir(char *attrname, char *dirp, int cwd, attr_data_t *attrinfo)
2843 {
2844 	attr_status_t	rc;
2845 	int		firsttime = (attrinfo->attr_parentfd == -1);
2846 	int		saveerrno;
2847 	int		ext_attr;
2848 
2849 	/*
2850 	 * open_attr_dir() was recursively called (input combination number 4),
2851 	 * close the previously opened file descriptor as we've already changed
2852 	 * into it.
2853 	 */
2854 	if (!firsttime) {
2855 		(void) close(attrinfo->attr_parentfd);
2856 		attrinfo->attr_parentfd = -1;
2857 	}
2858 
2859 	/*
2860 	 * Verify that the underlying file system supports the restoration
2861 	 * of the attribute.
2862 	 */
2863 	if ((rc = verify_attr_support(dirp, firsttime, ARC_RESTORE,
2864 	    &ext_attr)) != ATTR_OK) {
2865 		return (rc);
2866 	}
2867 
2868 	/* Open the base file's attribute directory */
2869 	if ((attrinfo->attr_parentfd = attropen(dirp, ".", O_RDONLY)) == -1) {
2870 		/*
2871 		 * Save the errno from the attropen so it can be reported
2872 		 * if the retry of the attropen fails.
2873 		 */
2874 		saveerrno = errno;
2875 		if ((attrinfo->attr_parentfd = retry_open_attr(-1, cwd, dirp,
2876 		    NULL, ".", O_RDONLY, 0)) == -1) {
2877 			/*
2878 			 * Reset typeflag back to real value so passtape
2879 			 * will skip ahead correctly.
2880 			 */
2881 			dblock.dbuf.typeflag = _XATTR_HDRTYPE;
2882 			(void) close(attrinfo->attr_parentfd);
2883 			attrinfo->attr_parentfd = -1;
2884 			errno = saveerrno;
2885 			return (ATTR_OPEN_ERR);
2886 		}
2887 	}
2888 
2889 	/*
2890 	 * Change into the parent attribute's directory unless we are
2891 	 * processing the hidden attribute directory of the base file itself.
2892 	 */
2893 	if ((Hiddendir == 0) || (firsttime && attrinfo->attr_parent != NULL)) {
2894 		if (fchdir(attrinfo->attr_parentfd) != 0) {
2895 			saveerrno = errno;
2896 			(void) close(attrinfo->attr_parentfd);
2897 			attrinfo->attr_parentfd = -1;
2898 			errno = saveerrno;
2899 			return (ATTR_CHDIR_ERR);
2900 		}
2901 	}
2902 
2903 	/* Determine if the attribute should be processed */
2904 	if ((rc = verify_attr(attrname, attrinfo->attr_parent, 1,
2905 	    &attrinfo->attr_rw_sysattr)) != ATTR_OK) {
2906 		saveerrno = errno;
2907 		(void) close(attrinfo->attr_parentfd);
2908 		attrinfo->attr_parentfd = -1;
2909 		errno = saveerrno;
2910 		return (rc);
2911 	}
2912 
2913 	/*
2914 	 * If the attribute is an extended attribute, or extended system
2915 	 * attribute, of an attribute (i.e., <attr>/<sys_attr>), then
2916 	 * recursively call open_attr_dir() to open the attribute directory
2917 	 * of the parent attribute.
2918 	 */
2919 	if (firsttime && (attrinfo->attr_parent != NULL)) {
2920 		return (open_attr_dir(attrname, attrinfo->attr_parent,
2921 		    attrinfo->attr_parentfd, attrinfo));
2922 	}
2923 
2924 	return (ATTR_OK);
2925 }
2926 #endif
2927 
2928 static void
doxtract(char * argv[])2929 doxtract(char *argv[])
2930 {
2931 	struct	stat	xtractbuf;	/* stat on file after extracting */
2932 	blkcnt_t blocks;
2933 	off_t bytes;
2934 	int ofile;
2935 	int newfile;			/* Does the file already exist  */
2936 	int xcnt = 0;			/* count # files extracted */
2937 	int fcnt = 0;			/* count # files in argv list */
2938 	int dir;
2939 	int dirfd = -1;
2940 	int cwd = -1;
2941 	int rw_sysattr;
2942 	int saveerrno;
2943 	uid_t Uid;
2944 	char *namep, *dirp, *comp, *linkp; /* for removing absolute paths */
2945 	char dirname[PATH_MAX+1];
2946 	char templink[PATH_MAX+1];	/* temp link with terminating NULL */
2947 	int once = 1;
2948 	int error;
2949 	int symflag;
2950 	int want;
2951 	attr_data_t *attrinfo = NULL;	/* attribute info */
2952 	acl_t	*aclp = NULL;	/* acl info */
2953 	char dot[] = ".";		/* dirp for using realpath */
2954 	timestruc_t	time_zero;	/* used for call to doDirTimes */
2955 	int		dircreate;
2956 	int convflag;
2957 	time_zero.tv_sec = 0;
2958 	time_zero.tv_nsec = 0;
2959 
2960 	/* reset Trusted Extensions variables */
2961 	rpath_flag = 0;
2962 	lk_rpath_flag = 0;
2963 	dir_flag = 0;
2964 	mld_flag = 0;
2965 	bslundef(&bs_label);
2966 	bsllow(&admin_low);
2967 	bslhigh(&admin_high);
2968 	orig_namep = 0;
2969 
2970 	dumping = 0;	/* for newvol(), et al:  we are not writing */
2971 
2972 	Uid = getuid();
2973 
2974 	for (;;) {
2975 		convflag = 0;
2976 		symflag = 0;
2977 		dir = 0;
2978 		Hiddendir = 0;
2979 		rw_sysattr = 0;
2980 		ofile = -1;
2981 
2982 		if (dirfd != -1) {
2983 			(void) close(dirfd);
2984 			dirfd = -1;
2985 		}
2986 		if (ofile != -1) {
2987 			if (close(ofile) != 0)
2988 				vperror(2, gettext("close error"));
2989 		}
2990 
2991 #if defined(O_XATTR)
2992 		if (cwd != -1) {
2993 			rest_cwd(&cwd);
2994 		}
2995 #endif
2996 
2997 		/* namep is set by wantit to point to the full name */
2998 		if ((want = wantit(argv, &namep, &dirp, &comp,
2999 		    &attrinfo)) == 0) {
3000 #if defined(O_XATTR)
3001 			if (xattrp != NULL) {
3002 				free(xattrhead);
3003 				xattrp = NULL;
3004 				xattr_linkp = NULL;
3005 				xattrhead = NULL;
3006 			}
3007 #endif
3008 			continue;
3009 		}
3010 		if (want == -1)
3011 			break;
3012 
3013 /* Trusted Extensions */
3014 		/*
3015 		 * During tar extract (x):
3016 		 * If the pathname of the restored file has been
3017 		 * reconstructed from the ancillary file,
3018 		 * use it to process the normal file.
3019 		 */
3020 		if (mld_flag) {		/* Skip over .MLD. directory */
3021 			mld_flag = 0;
3022 			passtape();
3023 			continue;
3024 		}
3025 		orig_namep = namep;	/* save original */
3026 		if (rpath_flag) {
3027 			namep = real_path;	/* use zone path */
3028 			comp = real_path;	/* use zone path */
3029 			dirp = dot;		/* work from the top */
3030 			rpath_flag = 0;		/* reset */
3031 		}
3032 
3033 		if (dirfd != -1)
3034 			(void) close(dirfd);
3035 
3036 		(void) strcpy(&dirname[0], namep);
3037 		dircreate = checkdir(&dirname[0]);
3038 
3039 #if defined(O_XATTR)
3040 		if (xattrp != NULL) {
3041 			int	rc;
3042 
3043 			if (((cwd = save_cwd()) == -1) ||
3044 			    ((rc = open_attr_dir(comp, dirp, cwd,
3045 			    attrinfo)) != ATTR_OK)) {
3046 				if (cwd == -1) {
3047 					vperror(0, gettext(
3048 					    "unable to save current working "
3049 					    "directory while processing "
3050 					    "attribute %s of %s"),
3051 					    dirp, attrinfo->attr_path);
3052 				} else if (rc != ATTR_SKIP) {
3053 					(void) fprintf(vfile,
3054 					    gettext("tar: cannot open "
3055 					    "%sattribute %s of file %s: %s\n"),
3056 					    attrinfo->attr_rw_sysattr ? gettext(
3057 					    "system ") : "",
3058 					    comp, dirp, strerror(errno));
3059 				}
3060 				free(xattrhead);
3061 				xattrp = NULL;
3062 				xattr_linkp = NULL;
3063 				xattrhead = NULL;
3064 
3065 				passtape();
3066 				continue;
3067 			} else {
3068 				dirfd = attrinfo->attr_parentfd;
3069 				rw_sysattr = attrinfo->attr_rw_sysattr;
3070 			}
3071 		} else {
3072 			dirfd = open(dirp, O_RDONLY);
3073 		}
3074 #else
3075 		dirfd = open(dirp, O_RDONLY);
3076 #endif
3077 		if (dirfd == -1) {
3078 			(void) fprintf(vfile, gettext(
3079 			    "tar: cannot open %s: %s\n"),
3080 			    dirp, strerror(errno));
3081 			passtape();
3082 			continue;
3083 		}
3084 
3085 		if (xhdr_flgs & _X_LINKPATH)
3086 			(void) strcpy(templink, Xtarhdr.x_linkpath);
3087 		else {
3088 #if defined(O_XATTR)
3089 			if (xattrp && dblock.dbuf.typeflag == '1') {
3090 				(void) sprintf(templink, "%.*s", NAMSIZ,
3091 				    xattrp->h_names);
3092 			} else {
3093 				(void) sprintf(templink, "%.*s", NAMSIZ,
3094 				    dblock.dbuf.linkname);
3095 			}
3096 #else
3097 			(void) sprintf(templink, "%.*s", NAMSIZ,
3098 			    dblock.dbuf.linkname);
3099 #endif
3100 		}
3101 
3102 		if (Fflag) {
3103 			if (checkf(namep, is_directory(namep), Fflag) == 0) {
3104 				passtape();
3105 				continue;
3106 			}
3107 		}
3108 
3109 		if (checkw('x', namep) == 0) {
3110 			passtape();
3111 			continue;
3112 		}
3113 		if (once) {
3114 			if (strcmp(dblock.dbuf.magic, magic_type) == 0) {
3115 				if (geteuid() == (uid_t)0) {
3116 					checkflag = 1;
3117 					pflag = 1;
3118 				} else {
3119 					/* get file creation mask */
3120 					Oumask = umask(0);
3121 					(void) umask(Oumask);
3122 				}
3123 				once = 0;
3124 			} else {
3125 				if (geteuid() == (uid_t)0) {
3126 					pflag = 1;
3127 					checkflag = 2;
3128 				}
3129 				if (!pflag) {
3130 					/* get file creation mask */
3131 					Oumask = umask(0);
3132 					(void) umask(Oumask);
3133 				}
3134 				once = 0;
3135 			}
3136 		}
3137 
3138 #if defined(O_XATTR)
3139 		/*
3140 		 * Handle extraction of hidden attr dir.
3141 		 * Dir is automatically created, we only
3142 		 * need to update mode and perm's.
3143 		 */
3144 		if ((xattrp != NULL) && Hiddendir == 1) {
3145 			bytes = stbuf.st_size;
3146 			blocks = TBLOCKS(bytes);
3147 			if (vflag) {
3148 				(void) fprintf(vfile,
3149 				    "x %s%s%s, %" FMT_off_t " %s, ", namep,
3150 				    gettext(" attribute "),
3151 				    xattrapath, bytes,
3152 				    gettext("bytes"));
3153 				if (NotTape)
3154 					(void) fprintf(vfile,
3155 					    "%" FMT_blkcnt_t "K\n", K(blocks));
3156 				else
3157 					(void) fprintf(vfile, gettext("%"
3158 					    FMT_blkcnt_t " tape blocks\n"),
3159 					    blocks);
3160 			}
3161 
3162 			/*
3163 			 * Set the permissions and mode of the attribute
3164 			 * unless the attribute is a system attribute (can't
3165 			 * successfully do this) or the hidden attribute
3166 			 * directory (".") of an attribute (when the attribute
3167 			 * is restored, the hidden attribute directory of an
3168 			 * attribute is transient).  Note:  when the permissions
3169 			 * and mode are set for the hidden attribute directory
3170 			 * of a file on a system supporting extended system
3171 			 * attributes, even though it returns successfully, it
3172 			 * will not have any affect since the attribute
3173 			 * directory is transient.
3174 			 */
3175 			if (attrinfo->attr_parent == NULL) {
3176 				if (fchownat(dirfd, ".", stbuf.st_uid,
3177 				    stbuf.st_gid, 0) != 0) {
3178 					vperror(0, gettext(
3179 					    "%s%s%s: failed to set ownership "
3180 					    "of attribute directory"), namep,
3181 					    gettext(" attribute "), xattrapath);
3182 				}
3183 
3184 				if (fchmod(dirfd, stbuf.st_mode) != 0) {
3185 					vperror(0, gettext(
3186 					    "%s%s%s: failed to set permissions "
3187 					    "of attribute directory"), namep,
3188 					    gettext(" attribute "), xattrapath);
3189 				}
3190 			}
3191 			goto filedone;
3192 		}
3193 #endif
3194 
3195 		if (dircreate && (!is_posix || dblock.dbuf.typeflag == '5')) {
3196 			dir = 1;
3197 			if (vflag) {
3198 				(void) fprintf(vfile, "x %s, 0 %s, ",
3199 				    &dirname[0], gettext("bytes"));
3200 				if (NotTape)
3201 					(void) fprintf(vfile, "0K\n");
3202 				else
3203 					(void) fprintf(vfile, gettext("%"
3204 					    FMT_blkcnt_t " tape blocks\n"),
3205 					    (blkcnt_t)0);
3206 			}
3207 			goto filedone;
3208 		}
3209 
3210 		if (dblock.dbuf.typeflag == '6') {	/* FIFO */
3211 			if (rmdir(namep) < 0) {
3212 				if (errno == ENOTDIR)
3213 					(void) unlink(namep);
3214 			}
3215 			linkp = templink;
3216 			if (*linkp != '\0') {
3217 				if (Aflag && *linkp == '/')
3218 					linkp++;
3219 				if (link(linkp, namep) < 0) {
3220 					(void) fprintf(stderr, gettext(
3221 					    "tar: %s: cannot link\n"), namep);
3222 					continue;
3223 				}
3224 				if (vflag)
3225 					(void) fprintf(vfile, gettext(
3226 					    "x %s linked to %s\n"), namep,
3227 					    linkp);
3228 				xcnt++;	 /* increment # files extracted */
3229 				continue;
3230 			}
3231 			if (mknod(namep, (int)(Gen.g_mode|S_IFIFO),
3232 			    (int)Gen.g_devmajor) < 0) {
3233 				vperror(0, gettext("%s: mknod failed"), namep);
3234 				continue;
3235 			}
3236 			bytes = stbuf.st_size;
3237 			blocks = TBLOCKS(bytes);
3238 			if (vflag) {
3239 				(void) fprintf(vfile, "x %s, %" FMT_off_t
3240 				    " %s, ", namep, bytes, gettext("bytes"));
3241 				if (NotTape)
3242 					(void) fprintf(vfile, "%" FMT_blkcnt_t
3243 					    "K\n", K(blocks));
3244 				else
3245 					(void) fprintf(vfile, gettext("%"
3246 					    FMT_blkcnt_t " tape blocks\n"),
3247 					    blocks);
3248 			}
3249 			goto filedone;
3250 		}
3251 		if (dblock.dbuf.typeflag == '3' && !Uid) { /* CHAR SPECIAL */
3252 			if (rmdir(namep) < 0) {
3253 				if (errno == ENOTDIR)
3254 					(void) unlink(namep);
3255 			}
3256 			linkp = templink;
3257 			if (*linkp != '\0') {
3258 				if (Aflag && *linkp == '/')
3259 					linkp++;
3260 				if (link(linkp, namep) < 0) {
3261 					(void) fprintf(stderr, gettext(
3262 					    "tar: %s: cannot link\n"), namep);
3263 					continue;
3264 				}
3265 				if (vflag)
3266 					(void) fprintf(vfile, gettext(
3267 					    "x %s linked to %s\n"), namep,
3268 					    linkp);
3269 				xcnt++;	 /* increment # files extracted */
3270 				continue;
3271 			}
3272 			if (mknod(namep, (int)(Gen.g_mode|S_IFCHR),
3273 			    (int)makedev(Gen.g_devmajor, Gen.g_devminor)) < 0) {
3274 				vperror(0, gettext(
3275 				    "%s: mknod failed"), namep);
3276 				continue;
3277 			}
3278 			bytes = stbuf.st_size;
3279 			blocks = TBLOCKS(bytes);
3280 			if (vflag) {
3281 				(void) fprintf(vfile, "x %s, %" FMT_off_t
3282 				    " %s, ", namep, bytes, gettext("bytes"));
3283 				if (NotTape)
3284 					(void) fprintf(vfile, "%" FMT_blkcnt_t
3285 					    "K\n", K(blocks));
3286 				else
3287 					(void) fprintf(vfile, gettext("%"
3288 					    FMT_blkcnt_t " tape blocks\n"),
3289 					    blocks);
3290 			}
3291 			goto filedone;
3292 		} else if (dblock.dbuf.typeflag == '3' && Uid) {
3293 			(void) fprintf(stderr, gettext(
3294 			    "Can't create special %s\n"), namep);
3295 			continue;
3296 		}
3297 
3298 		/* BLOCK SPECIAL */
3299 
3300 		if (dblock.dbuf.typeflag == '4' && !Uid) {
3301 			if (rmdir(namep) < 0) {
3302 				if (errno == ENOTDIR)
3303 					(void) unlink(namep);
3304 			}
3305 			linkp = templink;
3306 			if (*linkp != '\0') {
3307 				if (Aflag && *linkp == '/')
3308 					linkp++;
3309 				if (link(linkp, namep) < 0) {
3310 					(void) fprintf(stderr, gettext(
3311 					    "tar: %s: cannot link\n"), namep);
3312 					continue;
3313 				}
3314 				if (vflag)
3315 					(void) fprintf(vfile, gettext(
3316 					    "x %s linked to %s\n"), namep,
3317 					    linkp);
3318 				xcnt++;	 /* increment # files extracted */
3319 				continue;
3320 			}
3321 			if (mknod(namep, (int)(Gen.g_mode|S_IFBLK),
3322 			    (int)makedev(Gen.g_devmajor, Gen.g_devminor)) < 0) {
3323 				vperror(0, gettext("%s: mknod failed"), namep);
3324 				continue;
3325 			}
3326 			bytes = stbuf.st_size;
3327 			blocks = TBLOCKS(bytes);
3328 			if (vflag) {
3329 				(void) fprintf(vfile, gettext("x %s, %"
3330 				    FMT_off_t " bytes, "), namep, bytes);
3331 				if (NotTape)
3332 					(void) fprintf(vfile, "%" FMT_blkcnt_t
3333 					    "K\n", K(blocks));
3334 				else
3335 					(void) fprintf(vfile, gettext("%"
3336 					    FMT_blkcnt_t " tape blocks\n"),
3337 					    blocks);
3338 			}
3339 			goto filedone;
3340 		} else if (dblock.dbuf.typeflag == '4' && Uid) {
3341 			(void) fprintf(stderr,
3342 			    gettext("Can't create special %s\n"), namep);
3343 			continue;
3344 		}
3345 		if (dblock.dbuf.typeflag == '2') {	/* symlink */
3346 			if ((Tflag) && (lk_rpath_flag == 1))
3347 				linkp = lk_real_path;
3348 			else
3349 				linkp = templink;
3350 			if (Aflag && *linkp == '/')
3351 				linkp++;
3352 			if (rmdir(namep) < 0) {
3353 				if (errno == ENOTDIR)
3354 					(void) unlink(namep);
3355 			}
3356 			if (symlink(linkp, namep) < 0) {
3357 				vperror(0, gettext("%s: symbolic link failed"),
3358 				    namep);
3359 				continue;
3360 			}
3361 			if (vflag)
3362 				(void) fprintf(vfile, gettext(
3363 				    "x %s symbolic link to %s\n"),
3364 				    namep, linkp);
3365 
3366 			symflag = AT_SYMLINK_NOFOLLOW;
3367 			goto filedone;
3368 		}
3369 		if (dblock.dbuf.typeflag == '1') {
3370 			linkp = templink;
3371 			if (Aflag && *linkp == '/')
3372 				linkp++;
3373 			if (unlinkat(dirfd, comp, AT_REMOVEDIR) < 0) {
3374 				if (errno == ENOTDIR)
3375 					(void) unlinkat(dirfd, comp, 0);
3376 			}
3377 #if defined(O_XATTR)
3378 			if (xattrp && xattr_linkp) {
3379 				if (fchdir(dirfd) < 0) {
3380 					vperror(0, gettext(
3381 					    "Cannot fchdir to attribute "
3382 					    "directory %s"),
3383 					    (attrinfo->attr_parent == NULL) ?
3384 					    dirp : attrinfo->attr_parent);
3385 					exit(1);
3386 				}
3387 
3388 				error = link(xattr_linkaname, xattrapath);
3389 			} else {
3390 				error = link(linkp, namep);
3391 			}
3392 #else
3393 			error = link(linkp, namep);
3394 #endif
3395 
3396 			if (error < 0) {
3397 				(void) fprintf(stderr, gettext(
3398 				    "tar: %s%s%s: cannot link\n"),
3399 				    namep, (xattr_linkp != NULL) ?
3400 				    gettext(" attribute ") : "",
3401 				    (xattr_linkp != NULL) ?
3402 				    xattrapath : "");
3403 				continue;
3404 			}
3405 			if (vflag)
3406 				(void) fprintf(vfile, gettext(
3407 				    "x %s%s%s linked to %s%s%s\n"), namep,
3408 				    (xattr_linkp != NULL) ?
3409 				    gettext(" attribute ") : "",
3410 				    (xattr_linkp != NULL) ?
3411 				    xattr_linkaname : "",
3412 				    linkp,
3413 				    (xattr_linkp != NULL) ?
3414 				    gettext(" attribute ") : "",
3415 				    (xattr_linkp != NULL) ? xattrapath : "");
3416 			xcnt++;		/* increment # files extracted */
3417 #if defined(O_XATTR)
3418 			if (xattrp != NULL) {
3419 				free(xattrhead);
3420 				xattrp = NULL;
3421 				xattr_linkp = NULL;
3422 				xattrhead = NULL;
3423 			}
3424 #endif
3425 			continue;
3426 		}
3427 
3428 		/* REGULAR FILES */
3429 
3430 		if (convtoreg(stbuf.st_size)) {
3431 			convflag = 1;
3432 			if (errflag) {
3433 				(void) fprintf(stderr, gettext(
3434 				    "tar: %s: typeflag '%c' not recognized\n"),
3435 				    namep, dblock.dbuf.typeflag);
3436 				done(1);
3437 			} else {
3438 				(void) fprintf(stderr, gettext(
3439 				    "tar: %s: typeflag '%c' not recognized, "
3440 				    "converting to regular file\n"), namep,
3441 				    dblock.dbuf.typeflag);
3442 				Errflg = 1;
3443 			}
3444 		}
3445 		if (dblock.dbuf.typeflag == '0' ||
3446 		    dblock.dbuf.typeflag == '\0' || convflag) {
3447 			delete_target(dirfd, comp, namep);
3448 			linkp = templink;
3449 			if (*linkp != '\0') {
3450 				if (Aflag && *linkp == '/')
3451 					linkp++;
3452 				if (link(linkp, comp) < 0) {
3453 					(void) fprintf(stderr, gettext(
3454 					    "tar: %s: cannot link\n"), namep);
3455 					continue;
3456 				}
3457 				if (vflag)
3458 					(void) fprintf(vfile, gettext(
3459 					    "x %s linked to %s\n"), comp,
3460 					    linkp);
3461 				xcnt++;	 /* increment # files extracted */
3462 #if defined(O_XATTR)
3463 				if (xattrp != NULL) {
3464 					free(xattrhead);
3465 					xattrp = NULL;
3466 					xattr_linkp = NULL;
3467 					xattrhead = NULL;
3468 				}
3469 #endif
3470 				continue;
3471 			}
3472 		newfile = ((fstatat(dirfd, comp,
3473 		    &xtractbuf, 0) == -1) ? TRUE : FALSE);
3474 		ofile = openat(dirfd, comp, O_RDWR|O_CREAT|O_TRUNC,
3475 		    stbuf.st_mode & MODEMASK);
3476 		saveerrno = errno;
3477 
3478 #if defined(O_XATTR)
3479 		if (xattrp != NULL) {
3480 			if (ofile < 0) {
3481 				ofile = retry_open_attr(dirfd, cwd,
3482 				    dirp, attrinfo->attr_parent, comp,
3483 				    O_RDWR|O_CREAT|O_TRUNC,
3484 				    stbuf.st_mode & MODEMASK);
3485 			}
3486 		}
3487 #endif
3488 		if (ofile < 0) {
3489 			errno = saveerrno;
3490 			(void) fprintf(stderr, gettext(
3491 			    "tar: %s%s%s%s - cannot create\n"),
3492 			    (xattrp == NULL) ? "" : (rw_sysattr ?
3493 			    gettext("system attribute ") :
3494 			    gettext("attribute ")),
3495 			    (xattrp == NULL) ? "" : xattrapath,
3496 			    (xattrp == NULL) ? "" : gettext(" of "),
3497 			    (xattrp == NULL) ? comp : namep);
3498 			if (errflag)
3499 				done(1);
3500 			else
3501 				Errflg = 1;
3502 #if defined(O_XATTR)
3503 			if (xattrp != NULL) {
3504 				dblock.dbuf.typeflag = _XATTR_HDRTYPE;
3505 				free(xattrhead);
3506 				xattrp = NULL;
3507 				xattr_linkp = NULL;
3508 				xattrhead = NULL;
3509 			}
3510 #endif
3511 			passtape();
3512 			continue;
3513 		}
3514 
3515 		if (Tflag && (check_ext_attr(namep) == 0)) {
3516 			if (errflag)
3517 				done(1);
3518 			else
3519 				Errflg = 1;
3520 			passtape();
3521 			continue;
3522 		}
3523 
3524 		if (extno != 0) {	/* file is in pieces */
3525 			if (extotal < 1 || extotal > MAXEXT)
3526 				(void) fprintf(stderr, gettext(
3527 				    "tar: ignoring bad extent info for "
3528 				    "%s%s%s%s\n"),
3529 				    (xattrp == NULL) ? "" : (rw_sysattr ?
3530 				    gettext("system attribute ") :
3531 				    gettext("attribute ")),
3532 				    (xattrp == NULL) ? "" : xattrapath,
3533 				    (xattrp == NULL) ? "" : gettext(" of "),
3534 				    (xattrp == NULL) ? comp : namep);
3535 			else {
3536 				/* extract it */
3537 				(void) xsfile(rw_sysattr, ofile);
3538 			}
3539 		}
3540 		extno = 0;	/* let everyone know file is not split */
3541 		bytes = stbuf.st_size;
3542 		blocks = TBLOCKS(bytes);
3543 		if (vflag) {
3544 			(void) fprintf(vfile,
3545 			    "x %s%s%s, %" FMT_off_t " %s, ",
3546 			    (xattrp == NULL) ? "" : dirp,
3547 			    (xattrp == NULL) ? "" : (rw_sysattr ?
3548 			    gettext(" system attribute ") :
3549 			    gettext(" attribute ")),
3550 			    (xattrp == NULL) ? namep : xattrapath, bytes,
3551 			    gettext("bytes"));
3552 			if (NotTape)
3553 				(void) fprintf(vfile, "%" FMT_blkcnt_t "K\n",
3554 				    K(blocks));
3555 			else
3556 				(void) fprintf(vfile, gettext("%"
3557 				    FMT_blkcnt_t " tape blocks\n"), blocks);
3558 		}
3559 
3560 		if (xblocks(rw_sysattr, bytes, ofile) != 0) {
3561 #if defined(O_XATTR)
3562 			if (xattrp != NULL) {
3563 				free(xattrhead);
3564 				xattrp = NULL;
3565 				xattr_linkp = NULL;
3566 				xattrhead = NULL;
3567 			}
3568 #endif
3569 			continue;
3570 		}
3571 filedone:
3572 		if (mflag == 0 && !symflag) {
3573 			if (dir)
3574 				doDirTimes(namep, stbuf.st_mtim);
3575 
3576 			else
3577 #if defined(O_XATTR)
3578 				if (xattrp != NULL) {
3579 					/*
3580 					 * Set the time on the attribute unless
3581 					 * the attribute is a system attribute
3582 					 * (can't successfully do this) or the
3583 					 * hidden attribute directory, "." (the
3584 					 * time on the hidden attribute
3585 					 * directory will be updated when
3586 					 * attributes are restored, otherwise
3587 					 * it's transient).
3588 					 */
3589 					if (!rw_sysattr && (Hiddendir == 0)) {
3590 						setPathTimes(dirfd, comp,
3591 						    stbuf.st_mtim);
3592 					}
3593 				} else
3594 					setPathTimes(dirfd, comp,
3595 					    stbuf.st_mtim);
3596 #else
3597 				setPathTimes(dirfd, comp, stbuf.st_mtim);
3598 #endif
3599 		}
3600 
3601 		/* moved this code from above */
3602 		if (pflag && !symflag && Hiddendir == 0) {
3603 			if (xattrp != NULL)
3604 				(void) fchmod(ofile, stbuf.st_mode & MODEMASK);
3605 			else
3606 				(void) chmod(namep, stbuf.st_mode & MODEMASK);
3607 		}
3608 
3609 
3610 		/*
3611 		 * Because ancillary file preceeds the normal file,
3612 		 * acl info may have been retrieved (in aclp).
3613 		 * All file types are directed here (go filedone).
3614 		 * Always restore ACLs if there are ACLs.
3615 		 */
3616 		if (aclp != NULL) {
3617 			int ret;
3618 
3619 #if defined(O_XATTR)
3620 			if (xattrp != NULL) {
3621 				if (Hiddendir)
3622 					ret = facl_set(dirfd, aclp);
3623 				else
3624 					ret = facl_set(ofile, aclp);
3625 			} else {
3626 				ret = acl_set(namep, aclp);
3627 			}
3628 #else
3629 			ret = acl_set(namep, aclp);
3630 #endif
3631 			if (ret < 0) {
3632 				if (pflag) {
3633 					(void) fprintf(stderr, gettext(
3634 					    "%s%s%s%s: failed to set acl "
3635 					    "entries\n"), namep,
3636 					    (xattrp == NULL) ? "" :
3637 					    (rw_sysattr ? gettext(
3638 					    " system attribute ") :
3639 					    gettext(" attribute ")),
3640 					    (xattrp == NULL) ? "" :
3641 					    xattrapath);
3642 				}
3643 				/* else: silent and continue */
3644 			}
3645 			acl_free(aclp);
3646 			aclp = NULL;
3647 		}
3648 
3649 		if (!oflag)
3650 			/* set file ownership */
3651 			resugname(dirfd, comp, symflag);
3652 
3653 		if (pflag && newfile == TRUE && !dir &&
3654 		    (dblock.dbuf.typeflag == '0' ||
3655 		    dblock.dbuf.typeflag == '\0' ||
3656 		    convflag || dblock.dbuf.typeflag == '1')) {
3657 			if (fstat(ofile, &xtractbuf) == -1)
3658 				(void) fprintf(stderr, gettext(
3659 				    "tar: cannot stat extracted file "
3660 				    "%s%s%s%s\n"),
3661 				    (xattrp == NULL) ? "" : (rw_sysattr ?
3662 				    gettext("system attribute ") :
3663 				    gettext("attribute ")),
3664 				    (xattrp == NULL) ? "" : xattrapath,
3665 				    (xattrp == NULL) ? "" :
3666 				    gettext(" of "), namep);
3667 
3668 			else if ((xtractbuf.st_mode & (MODEMASK & ~S_IFMT))
3669 			    != (stbuf.st_mode & (MODEMASK & ~S_IFMT))) {
3670 				(void) fprintf(stderr, gettext(
3671 				    "tar: warning - file permissions have "
3672 				    "changed for %s%s%s%s (are 0%o, should be "
3673 				    "0%o)\n"),
3674 				    (xattrp == NULL) ? "" : (rw_sysattr ?
3675 				    gettext("system attribute ") :
3676 				    gettext("attribute ")),
3677 				    (xattrp == NULL) ? "" : xattrapath,
3678 				    (xattrp == NULL) ? "" :
3679 				    gettext(" of "), namep,
3680 				    xtractbuf.st_mode, stbuf.st_mode);
3681 
3682 			}
3683 		}
3684 #if defined(O_XATTR)
3685 		if (xattrp != NULL) {
3686 			free(xattrhead);
3687 			xattrp = NULL;
3688 			xattr_linkp = NULL;
3689 			xattrhead = NULL;
3690 		}
3691 #endif
3692 
3693 		if (ofile != -1) {
3694 			(void) close(dirfd);
3695 			dirfd = -1;
3696 			if (close(ofile) != 0)
3697 				vperror(2, gettext("close error"));
3698 			ofile = -1;
3699 		}
3700 		xcnt++;			/* increment # files extracted */
3701 		}
3702 
3703 		/*
3704 		 * Process ancillary file.
3705 		 *
3706 		 */
3707 
3708 		if (dblock.dbuf.typeflag == 'A') {	/* acl info */
3709 			char	buf[TBLOCK];
3710 			char	*secp;
3711 			char	*tp;
3712 			int	attrsize;
3713 			int	cnt;
3714 
3715 			/* reset Trusted Extensions flags */
3716 			dir_flag = 0;
3717 			mld_flag = 0;
3718 			lk_rpath_flag = 0;
3719 			rpath_flag = 0;
3720 
3721 			if (pflag) {
3722 				bytes = stbuf.st_size;
3723 				if ((secp = malloc((int)bytes)) == NULL) {
3724 					(void) fprintf(stderr, gettext(
3725 					    "Insufficient memory for acl\n"));
3726 					passtape();
3727 					continue;
3728 				}
3729 				tp = secp;
3730 				blocks = TBLOCKS(bytes);
3731 
3732 				/*
3733 				 * Display a line for each ancillary file.
3734 				 */
3735 				if (vflag && Tflag)
3736 					(void) fprintf(vfile, "x %s(A), %"
3737 					    FMT_blkcnt_t " %s, %"
3738 					    FMT_blkcnt_t " %s\n",
3739 					    namep, bytes, gettext("bytes"),
3740 					    blocks, gettext("tape blocks"));
3741 
3742 				while (blocks-- > 0) {
3743 					readtape(buf);
3744 					if (bytes <= TBLOCK) {
3745 						(void) memcpy(tp, buf,
3746 						    (size_t)bytes);
3747 						break;
3748 					} else {
3749 						(void) memcpy(tp, buf,
3750 						    TBLOCK);
3751 						tp += TBLOCK;
3752 					}
3753 					bytes -= TBLOCK;
3754 				}
3755 				bytes = stbuf.st_size;
3756 				/* got all attributes in secp */
3757 				tp = secp;
3758 				do {
3759 					attr = (struct sec_attr *)tp;
3760 					switch (attr->attr_type) {
3761 					case UFSD_ACL:
3762 					case ACE_ACL:
3763 						(void) sscanf(attr->attr_len,
3764 						    "%7o",
3765 						    (uint_t *)
3766 						    &cnt);
3767 						/* header is 8 */
3768 						attrsize = 8 + (int)strlen(
3769 						    &attr->attr_info[0]) + 1;
3770 						error =
3771 						    acl_fromtext(
3772 						    &attr->attr_info[0], &aclp);
3773 
3774 						if (error != 0) {
3775 							(void) fprintf(stderr,
3776 							    gettext(
3777 							    "aclfromtext "
3778 							    "failed: %s\n"),
3779 							    acl_strerror(
3780 							    error));
3781 							bytes -= attrsize;
3782 							break;
3783 						}
3784 						if (acl_cnt(aclp) != cnt) {
3785 							(void) fprintf(stderr,
3786 							    gettext(
3787 							    "aclcnt error\n"));
3788 							bytes -= attrsize;
3789 							break;
3790 						}
3791 						bytes -= attrsize;
3792 						break;
3793 
3794 					/* Trusted Extensions */
3795 
3796 					case DIR_TYPE:
3797 					case LBL_TYPE:
3798 					case APRIV_TYPE:
3799 					case FPRIV_TYPE:
3800 					case COMP_TYPE:
3801 					case LK_COMP_TYPE:
3802 					case ATTR_FLAG_TYPE:
3803 						attrsize =
3804 						    sizeof (struct sec_attr) +
3805 						    strlen(&attr->attr_info[0]);
3806 						bytes -= attrsize;
3807 						if (Tflag)
3808 							extract_attr(&namep,
3809 							    attr);
3810 						break;
3811 
3812 					default:
3813 						(void) fprintf(stderr, gettext(
3814 						    "unrecognized attr"
3815 						    " type\n"));
3816 						bytes = (off_t)0;
3817 						break;
3818 					}
3819 
3820 					/* next attributes */
3821 					tp += attrsize;
3822 				} while (bytes != 0);
3823 				free(secp);
3824 			} else {
3825 				passtape();
3826 			}
3827 		} /* acl */
3828 
3829 	} /* for */
3830 
3831 	/*
3832 	 *  Ensure that all the directories still on the directory stack
3833 	 *  get their modification times set correctly by flushing the
3834 	 *  stack.
3835 	 */
3836