xref: /illumos-gate/usr/src/cmd/tar/tar.c (revision cde58dbc6a23d4d38db7c8866312be83221c765f)
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  */
24 
25 /*	Copyright (c) 1983, 1984, 1985, 1986, 1987, 1988, 1989 AT&T	*/
26 /*	  All Rights Reserved  	*/
27 
28 /*	Copyright (c) 1987, 1988 Microsoft Corporation	*/
29 /*	  All Rights Reserved	*/
30 
31 /*
32  * Portions of this source code were derived from Berkeley 4.3 BSD
33  * under license from the Regents of the University of California.
34  */
35 
36 #include <unistd.h>
37 #include <sys/types.h>
38 #include <sys/param.h>
39 #include <sys/stat.h>
40 #include <sys/mkdev.h>
41 #include <sys/wait.h>
42 #include <dirent.h>
43 #include <errno.h>
44 #include <stdio.h>
45 #include <signal.h>
46 #include <ctype.h>
47 #include <locale.h>
48 #include <nl_types.h>
49 #include <langinfo.h>
50 #include <pwd.h>
51 #include <grp.h>
52 #include <fcntl.h>
53 #include <string.h>
54 #include <malloc.h>
55 #include <time.h>
56 #include <utime.h>
57 #include <stdlib.h>
58 #include <stdarg.h>
59 #include <widec.h>
60 #include <sys/mtio.h>
61 #include <sys/acl.h>
62 #include <strings.h>
63 #include <deflt.h>
64 #include <limits.h>
65 #include <iconv.h>
66 #include <assert.h>
67 #include <libgen.h>
68 #include <libintl.h>
69 #include <aclutils.h>
70 #include <libnvpair.h>
71 #include <archives.h>
72 
73 #if defined(__SunOS_5_6) || defined(__SunOS_5_7)
74 extern int defcntl();
75 #endif
76 #if defined(_PC_SATTR_ENABLED)
77 #include <attr.h>
78 #include <libcmdutils.h>
79 #endif
80 
81 /* Trusted Extensions */
82 #include <zone.h>
83 #include <tsol/label.h>
84 #include <sys/tsol/label_macro.h>
85 
86 #include "getresponse.h"
87 /*
88  * Source compatibility
89  */
90 
91 /*
92  * These constants come from archives.h and sys/fcntl.h
93  * and were introduced by the extended attributes project
94  * in Solaris 9.
95  */
96 #if !defined(O_XATTR)
97 #define	AT_SYMLINK_NOFOLLOW	0x1000
98 #define	AT_REMOVEDIR		0x1
99 #define	AT_FDCWD		0xffd19553
100 #define	_XATTR_HDRTYPE		'E'
101 static int attropen();
102 static int fstatat();
103 static int renameat();
104 static int unlinkat();
105 static int openat();
106 static int fchownat();
107 static int futimesat();
108 #endif
109 
110 /*
111  * Compiling with -D_XPG4_2 gets this but produces other problems, so
112  * instead of including sys/time.h and compiling with -D_XPG4_2, I'm
113  * explicitly doing the declaration here.
114  */
115 int utimes(const char *path, const struct timeval timeval_ptr[]);
116 
117 #ifndef MINSIZE
118 #define	MINSIZE 250
119 #endif
120 #define	DEF_FILE "/etc/default/tar"
121 
122 #define	min(a, b)  ((a) < (b) ? (a) : (b))
123 #define	max(a, b)  ((a) > (b) ? (a) : (b))
124 
125 /* -DDEBUG	ONLY for debugging */
126 #ifdef	DEBUG
127 #undef	DEBUG
128 #define	DEBUG(a, b, c)\
129 	(void) fprintf(stderr, "DEBUG - "), (void) fprintf(stderr, a, b, c)
130 #endif
131 
132 #define	TBLOCK	512	/* tape block size--should be universal */
133 
134 #ifdef	BSIZE
135 #define	SYS_BLOCK BSIZE	/* from sys/param.h:  secondary block size */
136 #else	/* BSIZE */
137 #define	SYS_BLOCK 512	/* default if no BSIZE in param.h */
138 #endif	/* BSIZE */
139 
140 #define	NBLOCK	20
141 #define	NAMSIZ	100
142 #define	PRESIZ	155
143 #define	MAXNAM	256
144 #define	MODEMASK 0777777	/* file creation mode mask */
145 #define	POSIXMODES 07777	/* mask for POSIX mode bits */
146 #define	MAXEXT	9	/* reasonable max # extents for a file */
147 #define	EXTMIN	50	/* min blks left on floppy to split a file */
148 
149 /* max value dblock.dbuf.efsize can store */
150 #define	TAR_EFSIZE_MAX	 0777777777
151 
152 /*
153  * Symbols which specify the values at which the use of the 'E' function
154  * modifier is required to properly store a file.
155  *
156  *     TAR_OFFSET_MAX    - the largest file size we can archive
157  *     OCTAL7CHAR        - the limit for ustar gid, uid, dev
158  */
159 
160 #ifdef XHDR_DEBUG
161 /* tiny values which force the creation of extended header entries */
162 #define	TAR_OFFSET_MAX 9
163 #define	OCTAL7CHAR 2
164 #else
165 /* normal values */
166 #define	TAR_OFFSET_MAX	077777777777ULL
167 #define	OCTAL7CHAR	07777777
168 #endif
169 
170 #define	TBLOCKS(bytes)	(((bytes) + TBLOCK - 1) / TBLOCK)
171 #define	K(tblocks)	((tblocks+1)/2)	/* tblocks to Kbytes for printing */
172 
173 #define	MAXLEV	(PATH_MAX / 2)
174 #define	LEV0	1
175 #define	SYMLINK_LEV0	0
176 
177 #define	TRUE	1
178 #define	FALSE	0
179 
180 #define	XATTR_FILE	1
181 #define	NORMAL_FILE	0
182 
183 #define	PUT_AS_LINK	1
184 #define	PUT_NOTAS_LINK	0
185 
186 #ifndef VIEW_READONLY
187 #define	VIEW_READONLY	"SUNWattr_ro"
188 #endif
189 
190 #ifndef VIEW_READWRITE
191 #define	VIEW_READWRITE	"SUNWattr_rw"
192 #endif
193 
194 #if _FILE_OFFSET_BITS == 64
195 #define	FMT_off_t "lld"
196 #define	FMT_off_t_o "llo"
197 #define	FMT_blkcnt_t "lld"
198 #else
199 #define	FMT_off_t "ld"
200 #define	FMT_off_t_o "lo"
201 #define	FMT_blkcnt_t "ld"
202 #endif
203 
204 /* ACL support */
205 
206 static
207 struct	sec_attr {
208 	char	attr_type;
209 	char	attr_len[7];
210 	char	attr_info[1];
211 } *attr;
212 
213 #if defined(O_XATTR)
214 typedef enum {
215 	ATTR_OK,
216 	ATTR_SKIP,
217 	ATTR_CHDIR_ERR,
218 	ATTR_OPEN_ERR,
219 	ATTR_XATTR_ERR,
220 	ATTR_SATTR_ERR
221 } attr_status_t;
222 #endif
223 
224 #if defined(O_XATTR)
225 typedef enum {
226 	ARC_CREATE,
227 	ARC_RESTORE
228 } arc_action_t;
229 #endif
230 
231 typedef struct attr_data {
232 	char	*attr_parent;
233 	char	*attr_path;
234 	int	attr_parentfd;
235 	int	attr_rw_sysattr;
236 } attr_data_t;
237 
238 /*
239  *
240  * Tar has been changed to support extended attributes.
241  *
242  * As part of this change tar now uses the new *at() syscalls
243  * such as openat, fchownat(), unlinkat()...
244  *
245  * This was done so that attributes can be handled with as few code changes
246  * as possible.
247  *
248  * What this means is that tar now opens the directory that a file or directory
249  * resides in and then performs *at() functions to manipulate the entry.
250  *
251  * For example a new file is now created like this:
252  *
253  * dfd = open(<some dir path>)
254  * fd = openat(dfd, <name>,....);
255  *
256  * or in the case of an extended attribute
257  *
258  * dfd = attropen(<pathname>, ".", ....)
259  *
260  * Once we have a directory file descriptor all of the *at() functions can
261  * be applied to it.
262  *
263  * unlinkat(dfd, <component name>,...)
264  * fchownat(dfd, <component name>,..)
265  *
266  * This works for both normal namespace files and extended attribute file
267  *
268  */
269 
270 /*
271  *
272  * Extended attribute Format
273  *
274  * Extended attributes are stored in two pieces.
275  * 1. An attribute header which has information about
276  *    what file the attribute is for and what the attribute
277  *    is named.
278  * 2. The attribute record itself.  Stored as a normal file type
279  *    of entry.
280  * Both the header and attribute record have special modes/typeflags
281  * associated with them.
282  *
283  * The names of the header in the archive look like:
284  * /dev/null/attr.hdr
285  *
286  * The name of the attribute looks like:
287  * /dev/null/attr
288  *
289  * This is done so that an archiver that doesn't understand these formats
290  * can just dispose of the attribute records.
291  *
292  * The format is composed of a fixed size header followed
293  * by a variable sized xattr_buf. If the attribute is a hard link
294  * to another attribute then another xattr_buf section is included
295  * for the link.
296  *
297  * The xattr_buf is used to define the necessary "pathing" steps
298  * to get to the extended attribute.  This is necessary to support
299  * a fully recursive attribute model where an attribute may itself
300  * have an attribute.
301  *
302  * The basic layout looks like this.
303  *
304  *     --------------------------------
305  *     |                              |
306  *     |         xattr_hdr            |
307  *     |                              |
308  *     --------------------------------
309  *     --------------------------------
310  *     |                              |
311  *     |        xattr_buf             |
312  *     |                              |
313  *     --------------------------------
314  *     --------------------------------
315  *     |                              |
316  *     |      (optional link info)    |
317  *     |                              |
318  *     --------------------------------
319  *     --------------------------------
320  *     |                              |
321  *     |      attribute itself        |
322  *     |      stored as normal tar    |
323  *     |      or cpio data with       |
324  *     |      special mode or         |
325  *     |      typeflag                |
326  *     |                              |
327  *     --------------------------------
328  *
329  */
330 
331 /*
332  * xattrhead is a pointer to the xattr_hdr
333  *
334  * xattrp is a pointer to the xattr_buf structure
335  * which contains the "pathing" steps to get to attributes
336  *
337  * xattr_linkp is a pointer to another xattr_buf structure that is
338  * only used when an attribute is actually linked to another attribute
339  *
340  */
341 
342 static struct xattr_hdr *xattrhead;
343 static struct xattr_buf *xattrp;
344 static struct xattr_buf *xattr_linkp;	/* pointer to link info, if any */
345 static char *xattrapath;		/* attribute name */
346 static char *xattr_linkaname;		/* attribute attribute is linked to */
347 static char Hiddendir;			/* are we processing hidden xattr dir */
348 static char xattrbadhead;
349 
350 /* Was statically allocated tbuf[NBLOCK] */
351 static
352 union hblock {
353 	char dummy[TBLOCK];
354 	struct header {
355 		char name[NAMSIZ];	/* If non-null prefix, path is	*/
356 					/* <prefix>/<name>;  otherwise	*/
357 					/* <name>			*/
358 		char mode[8];
359 		char uid[8];
360 		char gid[8];
361 		char size[12];		/* size of this extent if file split */
362 		char mtime[12];
363 		char chksum[8];
364 		char typeflag;
365 		char linkname[NAMSIZ];
366 		char magic[6];
367 		char version[2];
368 		char uname[32];
369 		char gname[32];
370 		char devmajor[8];
371 		char devminor[8];
372 		char prefix[PRESIZ];	/* Together with "name", the path of */
373 					/* the file:  <prefix>/<name>	*/
374 		char extno;		/* extent #, null if not split */
375 		char extotal;		/* total extents */
376 		char efsize[10];	/* size of entire file */
377 	} dbuf;
378 } dblock, *tbuf, xhdr_buf;
379 
380 static
381 struct xtar_hdr {
382 	uid_t		x_uid,		/* Uid of file */
383 			x_gid;		/* Gid of file */
384 	major_t		x_devmajor;	/* Device major node */
385 	minor_t		x_devminor;	/* Device minor node */
386 	off_t		x_filesz;	/* Length of file */
387 	char		*x_uname,	/* Pointer to name of user */
388 			*x_gname,	/* Pointer to gid of user */
389 			*x_linkpath,	/* Path for a hard/symbolic link */
390 			*x_path;	/* Path of file */
391 	timestruc_t	x_mtime;	/* Seconds and nanoseconds */
392 } Xtarhdr;
393 
394 static
395 struct gen_hdr {
396 	ulong_t		g_mode;		/* Mode of file */
397 	uid_t		g_uid,		/* Uid of file */
398 			g_gid;		/* Gid of file */
399 	off_t		g_filesz;	/* Length of file */
400 	time_t		g_mtime;	/* Modification time */
401 	uint_t		g_cksum;	/* Checksum of file */
402 	ulong_t		g_devmajor,	/* File system of file */
403 			g_devminor;	/* Major/minor of special files */
404 } Gen;
405 
406 static
407 struct linkbuf {
408 	ino_t	inum;
409 	dev_t	devnum;
410 	int	count;
411 	char	pathname[MAXNAM+1];	/* added 1 for last NULL */
412 	char 	attrname[MAXNAM+1];
413 	struct	linkbuf *nextp;
414 } *ihead;
415 
416 /* see comments before build_table() */
417 #define	TABLE_SIZE 512
418 typedef struct	file_list	{
419 	char	*name;			/* Name of file to {in,ex}clude */
420 	struct	file_list	*next;	/* Linked list */
421 } file_list_t;
422 static	file_list_t	*exclude_tbl[TABLE_SIZE],
423 			*include_tbl[TABLE_SIZE];
424 
425 static int	append_secattr(char **, int *, int, char *, char);
426 static void	write_ancillary(union hblock *, char *, int, char);
427 
428 static void add_file_to_table(file_list_t *table[], char *str);
429 static void assert_string(char *s, char *msg);
430 static int istape(int fd, int type);
431 static void backtape(void);
432 static void build_table(file_list_t *table[], char *file);
433 static int check_prefix(char **namep, char **dirp, char **compp);
434 static void closevol(void);
435 static void copy(void *dst, void *src);
436 static int convtoreg(off_t);
437 static void delete_target(int fd, char *comp, char *namep);
438 static void doDirTimes(char *name, timestruc_t modTime);
439 static void done(int n);
440 static void dorep(char *argv[]);
441 #ifdef	_iBCS2
442 static void dotable(char *argv[], int cnt);
443 static void doxtract(char *argv[], int cnt);
444 #else
445 static void dotable(char *argv[]);
446 static void doxtract(char *argv[]);
447 #endif
448 static int is_directory(char *name);
449 static int has_dot_dot(char *name);
450 static int is_absolute(char *name);
451 static char *make_relative_name(char *name, char **stripped_prefix);
452 static void fatal(char *format, ...);
453 static void vperror(int exit_status, char *fmt, ...);
454 static void flushtape(void);
455 static void getdir(void);
456 static void *getmem(size_t);
457 static void longt(struct stat *st, char aclchar);
458 static void load_info_from_xtarhdr(u_longlong_t flag, struct xtar_hdr *xhdrp);
459 static int makeDir(char *name);
460 static void mterr(char *operation, int i, int exitcode);
461 static void newvol(void);
462 static void passtape(void);
463 static void putempty(blkcnt_t n);
464 static int putfile(char *longname, char *shortname, char *parent,
465     attr_data_t *attrinfo, int filetype, int lev, int symlink_lev);
466 static void readtape(char *buffer);
467 static void seekdisk(blkcnt_t blocks);
468 static void setPathTimes(int dirfd, char *path, timestruc_t modTime);
469 static void setbytes_to_skip(struct stat *st, int err);
470 static void splitfile(char *longname, int ifd, char *name,
471 	char *prefix, int filetype);
472 static void tomodes(struct stat *sp);
473 static void usage(void);
474 static int xblocks(int issysattr, off_t bytes, int ofile);
475 static int xsfile(int issysattr, int ofd);
476 static void resugname(int dirfd, char *name, int symflag);
477 static int bcheck(char *bstr);
478 static int checkdir(char *name);
479 static int checksum(union hblock *dblockp);
480 #ifdef	EUC
481 static int checksum_signed(union hblock *dblockp);
482 #endif	/* EUC */
483 static int checkupdate(char *arg);
484 static int checkw(char c, char *name);
485 static int cmp(char *b, char *s, int n);
486 static int defset(char *arch);
487 static int endtape(void);
488 static int is_in_table(file_list_t *table[], char *str);
489 static int notsame(void);
490 static int is_prefix(char *s1, char *s2);
491 static int response(void);
492 static int build_dblock(const char *, const char *, const char,
493 	const int filetype, const struct stat *, const dev_t, const char *);
494 static unsigned int hash(char *str);
495 
496 #ifdef	_iBCS2
497 static void initarg(char *argv[], char *file);
498 static char *nextarg();
499 #endif
500 static blkcnt_t kcheck(char *kstr);
501 static off_t bsrch(char *s, int n, off_t l, off_t h);
502 static void onintr(int sig);
503 static void onquit(int sig);
504 static void onhup(int sig);
505 static uid_t getuidbyname(char *);
506 static gid_t getgidbyname(char *);
507 static char *getname(gid_t);
508 static char *getgroup(gid_t);
509 static int checkf(char *name, int mode, int howmuch);
510 static int writetbuf(char *buffer, int n);
511 static int wantit(char *argv[], char **namep, char **dirp, char **comp,
512     attr_data_t **attrinfo);
513 static void append_ext_attr(char *shortname, char **secinfo, int *len);
514 static int get_xdata(void);
515 static void gen_num(const char *keyword, const u_longlong_t number);
516 static void gen_date(const char *keyword, const timestruc_t time_value);
517 static void gen_string(const char *keyword, const char *value);
518 static void get_xtime(char *value, timestruc_t *xtime);
519 static int chk_path_build(char *name, char *longname, char *linkname,
520     char *prefix, char type, int filetype);
521 static int gen_utf8_names(const char *filename);
522 static int utf8_local(char *option, char **Xhdr_ptrptr, char *target,
523     const char *src, int max_val);
524 static int local_utf8(char **Xhdr_ptrptr, char *target, const char *src,
525     iconv_t iconv_cd, int xhdrflg, int max_val);
526 static int c_utf8(char *target, const char *source);
527 static int getstat(int dirfd, char *longname, char *shortname,
528     char *attrparent);
529 static void xattrs_put(char *, char *, char *, char *);
530 static void prepare_xattr(char **, char	*, char	*,
531     char, struct linkbuf *, int *);
532 static int put_link(char *name, char *longname, char *component,
533     char *longattrname, char *prefix, int filetype, char typeflag);
534 static int put_extra_attributes(char *longname, char *shortname,
535     char *longattrname, char *prefix, int filetype, char typeflag);
536 static int put_xattr_hdr(char *longname, char *shortname, char *longattrname,
537     char *prefix, int typeflag, int filetype, struct linkbuf *lp);
538 static int read_xattr_hdr(attr_data_t **attrinfo);
539 
540 /* Trusted Extensions */
541 #define	AUTO_ZONE	"/zone"
542 
543 static void extract_attr(char **file_ptr, struct sec_attr *);
544 static int check_ext_attr(char *filename);
545 static void rebuild_comp_path(char *str, char **namep);
546 static int rebuild_lk_comp_path(char *str, char **namep);
547 
548 static void get_parent(char *path, char *dir);
549 static char *get_component(char *path);
550 static int retry_open_attr(int pdirfd, int cwd, char *dirp, char *pattr,
551     char *name, int oflag, mode_t mode);
552 static char *skipslashes(char *string, char *start);
553 static void chop_endslashes(char *path);
554 static pid_t compress_file(void);
555 static void compress_back(void);
556 static void decompress_file(void);
557 static pid_t uncompress_file(void);
558 static void *compress_malloc(size_t);
559 static void check_compression();
560 static char *bz_suffix();
561 static char *gz_suffix();
562 static char *add_suffix();
563 static void wait_pid(pid_t);
564 
565 static	struct stat stbuf;
566 
567 static	char	*myname;
568 static	int	checkflag = 0;
569 #ifdef	_iBCS2
570 static	int	Fileflag;
571 char    *sysv3_env;
572 #endif
573 static	int	Xflag, Fflag, iflag, hflag, Bflag, Iflag;
574 static	int	rflag, xflag, vflag, tflag, mt, svmt, cflag, mflag, pflag;
575 static	int	uflag;
576 static	int	eflag, errflag, qflag;
577 static	int	oflag;
578 static	int	bflag, kflag, Aflag;
579 static 	int	Pflag;			/* POSIX conformant archive */
580 static	int	Eflag;			/* Allow files greater than 8GB */
581 static	int	atflag;			/* traverse extended attributes */
582 static	int	saflag;			/* traverse extended sys attributes */
583 static	int	Dflag;			/* Data change flag */
584 static	int	jflag;			/* flag to use 'bzip2' */
585 static	int	zflag;			/* flag to use 'gzip' */
586 static	int	Zflag;			/* flag to use 'compress' */
587 
588 /* Trusted Extensions */
589 static	int	Tflag;			/* Trusted Extensions attr flags */
590 static	int	dir_flag;		/* for attribute extract */
591 static	int	mld_flag;		/* for attribute extract */
592 static	char	*orig_namep;		/* original namep - unadorned */
593 static	int	rpath_flag;		/* MLD real path is rebuilt */
594 static	char	real_path[MAXPATHLEN];	/* MLD real path */
595 static	int	lk_rpath_flag;		/* linked to real path is rebuilt */
596 static	char	lk_real_path[MAXPATHLEN]; /* linked real path */
597 static	bslabel_t	bs_label;	/* for attribute extract */
598 static	bslabel_t	admin_low;
599 static	bslabel_t	admin_high;
600 static	int	ignored_aprivs = 0;
601 static	int	ignored_fprivs = 0;
602 static	int	ignored_fattrs = 0;
603 
604 static	int	term, chksum, wflag,
605 		first = TRUE, defaults_used = FALSE, linkerrok;
606 static	blkcnt_t	recno;
607 static	int	freemem = 1;
608 static	int	nblock = NBLOCK;
609 static	int	Errflg = 0;
610 static	int	exitflag = 0;
611 
612 static	dev_t	mt_dev;		/* device containing output file */
613 static	ino_t	mt_ino;		/* inode number of output file */
614 static	int	mt_devtype;	/* dev type of archive, from stat structure */
615 
616 static	int update = 1;		/* for `open' call */
617 
618 static	off_t	low;
619 static	off_t	high;
620 
621 static	FILE	*tfile;
622 static	FILE	*vfile = stdout;
623 static	char	*tmpdir;
624 static	char	*tmp_suffix = "/tarXXXXXX";
625 static	char	*tname;
626 static	char	archive[] = "archive0=";
627 static	char	*Xfile;
628 static	char	*usefile;
629 static	char	tfname[1024];
630 static	char	*Filefile;
631 
632 static	int	mulvol;		/* multi-volume option selected */
633 static	blkcnt_t	blocklim; /* number of blocks to accept per volume */
634 static	blkcnt_t	tapepos; /* current block number to be written */
635 static	int	NotTape;	/* true if tape is a disk */
636 static	int	dumping;	/* true if writing a tape or other archive */
637 static	int	extno;		/* number of extent:  starts at 1 */
638 static	int	extotal;	/* total extents in this file */
639 static	off_t	extsize;	/* size of current extent during extraction */
640 static	ushort_t	Oumask = 0;	/* old umask value */
641 static 	int is_posix;	/* true if archive we're reading is POSIX-conformant */
642 static	const	char	*magic_type = "ustar";
643 static	size_t	xrec_size = 8 * PATH_MAX;	/* extended rec initial size */
644 static	char	*xrec_ptr;
645 static	off_t	xrec_offset = 0;
646 static	int	Xhdrflag;
647 static	int	charset_type = 0;
648 
649 static	u_longlong_t	xhdr_flgs;	/* Bits set determine which items */
650 					/*   need to be in extended header. */
651 #define	_X_DEVMAJOR	0x1
652 #define	_X_DEVMINOR	0x2
653 #define	_X_GID		0x4
654 #define	_X_GNAME	0x8
655 #define	_X_LINKPATH	0x10
656 #define	_X_PATH		0x20
657 #define	_X_SIZE		0x40
658 #define	_X_UID		0x80
659 #define	_X_UNAME	0x100
660 #define	_X_ATIME	0x200
661 #define	_X_CTIME	0x400
662 #define	_X_MTIME	0x800
663 #define	_X_XHDR		0x1000	/* Bit flag that determines whether 'X' */
664 				/* typeflag was followed by 'A' or non 'A' */
665 				/* typeflag. */
666 #define	_X_LAST		0x40000000
667 
668 #define	PID_MAX_DIGITS		(10 * sizeof (pid_t) / 4)
669 #define	TIME_MAX_DIGITS		(10 * sizeof (time_t) / 4)
670 #define	LONG_MAX_DIGITS		(10 * sizeof (long) / 4)
671 #define	ULONGLONG_MAX_DIGITS	(10 * sizeof (u_longlong_t) / 4)
672 /*
673  * UTF_8 encoding requires more space than the current codeset equivalent.
674  * Currently a factor of 2-3 would suffice, but it is possible for a factor
675  * of 6 to be needed in the future, so for saftey, we use that here.
676  */
677 #define	UTF_8_FACTOR	6
678 
679 static	u_longlong_t	xhdr_count = 0;
680 static char		xhdr_dirname[PRESIZ + 1];
681 static char		pidchars[PID_MAX_DIGITS + 1];
682 static char		*tchar = "";		/* null linkpath */
683 
684 static	char	local_path[UTF_8_FACTOR * PATH_MAX + 1];
685 static	char	local_linkpath[UTF_8_FACTOR * PATH_MAX + 1];
686 static	char	local_gname[UTF_8_FACTOR * _POSIX_NAME_MAX + 1];
687 static	char	local_uname[UTF_8_FACTOR * _POSIX_NAME_MAX + 1];
688 
689 /*
690  * The following mechanism is provided to allow us to debug tar in complicated
691  * situations, like when it is part of a pipe.  The idea is that you compile
692  * with -DWAITAROUND defined, and then add the 'D' function modifier to the
693  * target tar invocation, eg. "tar cDf tarfile file".  If stderr is available,
694  * it will tell you to which pid to attach the debugger; otherwise, use ps to
695  * find it.  Attach to the process from the debugger, and, *PRESTO*, you are
696  * there!
697  *
698  * Simply assign "waitaround = 0" once you attach to the process, and then
699  * proceed from there as usual.
700  */
701 
702 #ifdef WAITAROUND
703 int waitaround = 0;		/* wait for rendezvous with the debugger */
704 #endif
705 
706 #define	BZIP		"/usr/bin/bzip2"
707 #define	GZIP		"/usr/bin/gzip"
708 #define	COMPRESS	"/usr/bin/compress"
709 #define	BZCAT		"/usr/bin/bzcat"
710 #define	GZCAT		"/usr/bin/gzcat"
711 #define	ZCAT		"/usr/bin/zcat"
712 #define	GS		8		/* number of valid 'gzip' sufixes */
713 #define	BS		4		/* number of valid 'bzip2' sufixes */
714 
715 static	char		*compress_opt; 	/* compression type */
716 
717 static	char		*gsuffix[] = {".gz", "-gz", ".z", "-z", "_z", ".Z",
718 			".tgz", ".taz"};
719 static	char		*bsuffix[] = {".bz2", ".bz", ".tbz2", ".tbz"};
720 static	char		*suffix;
721 
722 
723 int
724 main(int argc, char *argv[])
725 {
726 	char		*cp;
727 	char		*tmpdirp;
728 	pid_t		thispid;
729 	pid_t		pid;
730 	int		wstat;
731 
732 #ifdef	_iBCS2
733 	int	tbl_cnt = 0;
734 	sysv3_env = getenv("SYSV3");
735 #endif
736 	(void) setlocale(LC_ALL, "");
737 #if !defined(TEXT_DOMAIN)	/* Should be defined by cc -D */
738 #define	TEXT_DOMAIN "SYS_TEST"	/* Use this only if it weren't */
739 #endif
740 	(void) textdomain(TEXT_DOMAIN);
741 	if (argc < 2)
742 		usage();
743 
744 	tfile = NULL;
745 	if ((myname = strdup(argv[0])) == NULL) {
746 		(void) fprintf(stderr, gettext(
747 		    "tar: cannot allocate program name\n"));
748 		exit(1);
749 	}
750 
751 	if (init_yes() < 0) {
752 		(void) fprintf(stderr, gettext(ERR_MSG_INIT_YES),
753 		    strerror(errno));
754 		exit(2);
755 	}
756 
757 	/*
758 	 *  For XPG4 compatibility, we must be able to accept the "--"
759 	 *  argument normally recognized by getopt; it is used to delimit
760 	 *  the end opt the options section, and so can only appear in
761 	 *  the position of the first argument.  We simply skip it.
762 	 */
763 
764 	if (strcmp(argv[1], "--") == 0) {
765 		argv++;
766 		argc--;
767 		if (argc < 3)
768 			usage();
769 	}
770 
771 	argv[argc] = NULL;
772 	argv++;
773 
774 	/*
775 	 * Set up default values.
776 	 * Search the operand string looking for the first digit or an 'f'.
777 	 * If you find a digit, use the 'archive#' entry in DEF_FILE.
778 	 * If 'f' is given, bypass looking in DEF_FILE altogether.
779 	 * If no digit or 'f' is given, still look in DEF_FILE but use '0'.
780 	 */
781 	if ((usefile = getenv("TAPE")) == (char *)NULL) {
782 		for (cp = *argv; *cp; ++cp)
783 			if (isdigit(*cp) || *cp == 'f')
784 				break;
785 		if (*cp != 'f') {
786 			archive[7] = (*cp)? *cp: '0';
787 			if (!(defaults_used = defset(archive))) {
788 				usefile = NULL;
789 				nblock = 1;
790 				blocklim = 0;
791 				NotTape = 0;
792 			}
793 		}
794 	}
795 
796 	for (cp = *argv++; *cp; cp++)
797 		switch (*cp) {
798 #ifdef WAITAROUND
799 		case 'D':
800 			/* rendezvous with the debugger */
801 			waitaround = 1;
802 			break;
803 #endif
804 		case 'f':
805 			assert_string(*argv, gettext(
806 			    "tar: tarfile must be specified with 'f' "
807 			    "function modifier\n"));
808 			usefile = *argv++;
809 			break;
810 		case 'F':
811 #ifdef	_iBCS2
812 			if (sysv3_env) {
813 				assert_string(*argv, gettext(
814 				    "tar: 'F' requires a file name\n"));
815 				Filefile = *argv++;
816 				Fileflag++;
817 			} else
818 #endif	/*  _iBCS2 */
819 				Fflag++;
820 			break;
821 		case 'c':
822 			cflag++;
823 			rflag++;
824 			update = 1;
825 			break;
826 #if defined(O_XATTR)
827 		case '@':
828 			atflag++;
829 			break;
830 #endif	/* O_XATTR */
831 #if defined(_PC_SATTR_ENABLED)
832 		case '/':
833 			saflag++;
834 			break;
835 #endif	/* _PC_SATTR_ENABLED */
836 		case 'u':
837 			uflag++;	/* moved code after signals caught */
838 			rflag++;
839 			update = 2;
840 			break;
841 		case 'r':
842 			rflag++;
843 			update = 2;
844 			break;
845 		case 'v':
846 			vflag++;
847 			break;
848 		case 'w':
849 			wflag++;
850 			break;
851 		case 'x':
852 			xflag++;
853 			break;
854 		case 'X':
855 			assert_string(*argv, gettext(
856 			    "tar: exclude file must be specified with 'X' "
857 			    "function modifier\n"));
858 			Xflag = 1;
859 			Xfile = *argv++;
860 			build_table(exclude_tbl, Xfile);
861 			break;
862 		case 't':
863 			tflag++;
864 			break;
865 		case 'm':
866 			mflag++;
867 			break;
868 		case 'p':
869 			pflag++;
870 			break;
871 		case 'D':
872 			Dflag++;
873 			break;
874 		case '-':
875 			/* ignore this silently */
876 			break;
877 		case '0':	/* numeric entries used only for defaults */
878 		case '1':
879 		case '2':
880 		case '3':
881 		case '4':
882 		case '5':
883 		case '6':
884 		case '7':
885 			break;
886 		case 'b':
887 			assert_string(*argv, gettext(
888 			    "tar: blocking factor must be specified "
889 			    "with 'b' function modifier\n"));
890 			bflag++;
891 			nblock = bcheck(*argv++);
892 			break;
893 		case 'q':
894 			qflag++;
895 			break;
896 		case 'k':
897 			assert_string(*argv, gettext(
898 			    "tar: size value must be specified with 'k' "
899 			    "function modifier\n"));
900 			kflag++;
901 			blocklim = kcheck(*argv++);
902 			break;
903 		case 'n':		/* not a magtape (instead of 'k') */
904 			NotTape++;	/* assume non-magtape */
905 			break;
906 		case 'l':
907 			linkerrok++;
908 			break;
909 		case 'e':
910 #ifdef	_iBCS2
911 			/* If sysv3 IS set, don't be as verbose */
912 			if (!sysv3_env)
913 #endif	/* _iBCS2 */
914 				errflag++;
915 			eflag++;
916 			break;
917 		case 'o':
918 			oflag++;
919 			break;
920 		case 'h':
921 			hflag++;
922 			break;
923 		case 'i':
924 			iflag++;
925 			break;
926 		case 'B':
927 			Bflag++;
928 			break;
929 		case 'P':
930 			Pflag++;
931 			break;
932 		case 'E':
933 			Eflag++;
934 			Pflag++;	/* Only POSIX archive made */
935 			break;
936 		case 'T':
937 			Tflag++;	/* Handle Trusted Extensions attrs */
938 			pflag++;	/* also set flag for ACL */
939 			break;
940 		case 'j':		/* compession "bzip2" */
941 			jflag++;
942 			break;
943 		case 'z':		/* compression "gzip" */
944 			zflag++;
945 			break;
946 		case 'Z':		/* compression "compress" */
947 			Zflag++;
948 			break;
949 		default:
950 			(void) fprintf(stderr, gettext(
951 			"tar: %c: unknown function modifier\n"), *cp);
952 			usage();
953 		}
954 
955 #ifdef	_iBCS2
956 	if (Xflag && Fileflag) {
957 		(void) fprintf(stderr, gettext(
958 		"tar: specify only one of X or F.\n"));
959 		usage();
960 	}
961 #endif	/*  _iBCS2 */
962 
963 	if (!rflag && !xflag && !tflag)
964 		usage();
965 	if ((rflag && xflag) || (xflag && tflag) || (rflag && tflag)) {
966 		(void) fprintf(stderr, gettext(
967 		"tar: specify only one of [ctxru].\n"));
968 		usage();
969 	}
970 	if (cflag) {
971 		if ((zflag && jflag) || (zflag && Zflag) ||
972 		    (jflag && Zflag)) {
973 			(void) fprintf(stderr, gettext(
974 			    "tar: specify only one of [jzZ] to "
975 			    "create a compressed file.\n"));
976 			usage();
977 		}
978 	}
979 	/* Trusted Extensions attribute handling */
980 	if (Tflag && ((getzoneid() != GLOBAL_ZONEID) ||
981 	    !is_system_labeled())) {
982 		(void) fprintf(stderr, gettext(
983 		"tar: the 'T' option is only available with "
984 		    "Trusted Extensions\nand must be run from "
985 		    "the global zone.\n"));
986 		usage();
987 	}
988 	if (cflag && *argv == NULL && Filefile == NULL)
989 		fatal(gettext("Missing filenames"));
990 	if (usefile == NULL)
991 		fatal(gettext("device argument required"));
992 
993 	/* alloc a buffer of the right size */
994 	if ((tbuf = (union hblock *)
995 	    calloc(sizeof (union hblock) * nblock, sizeof (char))) ==
996 	    (union hblock *)NULL) {
997 		(void) fprintf(stderr, gettext(
998 		"tar: cannot allocate physio buffer\n"));
999 		exit(1);
1000 	}
1001 
1002 	if ((xrec_ptr = malloc(xrec_size)) == NULL) {
1003 		(void) fprintf(stderr, gettext(
1004 		    "tar: cannot allocate extended header buffer\n"));
1005 		exit(1);
1006 	}
1007 
1008 #ifdef WAITAROUND
1009 	if (waitaround) {
1010 		(void) fprintf(stderr, gettext("Rendezvous with tar on pid"
1011 		    " %d\n"), getpid());
1012 
1013 		while (waitaround) {
1014 			(void) sleep(10);
1015 		}
1016 	}
1017 #endif
1018 
1019 	thispid = getpid();
1020 	(void) sprintf(pidchars, "%ld", thispid);
1021 	thispid = strlen(pidchars);
1022 
1023 	if ((tmpdirp = getenv("TMPDIR")) == (char *)NULL)
1024 		(void) strcpy(xhdr_dirname, "/tmp");
1025 	else {
1026 		/*
1027 		 * Make sure that dir is no longer than what can
1028 		 * fit in the prefix part of the header.
1029 		 */
1030 		if (strlen(tmpdirp) > (size_t)(PRESIZ - thispid - 12)) {
1031 			(void) strcpy(xhdr_dirname, "/tmp");
1032 			if ((vflag > 0) && (Eflag > 0))
1033 				(void) fprintf(stderr, gettext(
1034 				    "Ignoring TMPDIR\n"));
1035 		} else
1036 			(void) strcpy(xhdr_dirname, tmpdirp);
1037 	}
1038 	(void) strcat(xhdr_dirname, "/PaxHeaders.");
1039 	(void) strcat(xhdr_dirname, pidchars);
1040 
1041 	if (rflag) {
1042 		if (cflag && usefile != NULL)  {
1043 			/* Set the compression type */
1044 			if (jflag) {
1045 				compress_opt = compress_malloc(strlen(BZIP)
1046 				    + 1);
1047 				(void) strcpy(compress_opt, BZIP);
1048 			} else if (zflag) {
1049 				compress_opt = compress_malloc(strlen(GZIP)
1050 				    + 1);
1051 				(void) strcpy(compress_opt, GZIP);
1052 			} else if (Zflag) {
1053 				compress_opt =
1054 				    compress_malloc(strlen(COMPRESS) + 1);
1055 				(void) strcpy(compress_opt, COMPRESS);
1056 			}
1057 		} else {
1058 			/*
1059 			 * Decompress if the file is compressed for
1060 			 * an update or replace.
1061 			 */
1062 			if (strcmp(usefile, "-") != 0) {
1063 				check_compression();
1064 				if (compress_opt != NULL) {
1065 					decompress_file();
1066 				}
1067 			}
1068 		}
1069 
1070 		if (cflag && tfile != NULL)
1071 			usage();
1072 		if (signal(SIGINT, SIG_IGN) != SIG_IGN)
1073 			(void) signal(SIGINT, onintr);
1074 		if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
1075 			(void) signal(SIGHUP, onhup);
1076 		if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
1077 			(void) signal(SIGQUIT, onquit);
1078 		if (uflag) {
1079 			int tnum;
1080 			struct stat sbuf;
1081 
1082 			tmpdir = getenv("TMPDIR");
1083 			/*
1084 			 * If the name is invalid or this isn't a directory,
1085 			 * or the directory is not writable, then reset to
1086 			 * a default temporary directory.
1087 			 */
1088 			if (tmpdir == NULL || *tmpdir == '\0' ||
1089 			    (strlen(tmpdir) + strlen(tmp_suffix)) > PATH_MAX) {
1090 				tmpdir = "/tmp";
1091 			} else if (stat(tmpdir, &sbuf) < 0 ||
1092 			    (sbuf.st_mode & S_IFMT) != S_IFDIR ||
1093 			    (sbuf.st_mode & S_IWRITE) == 0) {
1094 				tmpdir = "/tmp";
1095 			}
1096 
1097 			if ((tname = calloc(1, strlen(tmpdir) +
1098 			    strlen(tmp_suffix) + 1)) == NULL) {
1099 				vperror(1, gettext("tar: out of memory, "
1100 				    "cannot create temporary file\n"));
1101 			}
1102 			(void) strcpy(tname, tmpdir);
1103 			(void) strcat(tname, tmp_suffix);
1104 
1105 			if ((tnum = mkstemp(tname)) == -1)
1106 				vperror(1, "%s", tname);
1107 			if ((tfile = fdopen(tnum, "w")) == NULL)
1108 				vperror(1, "%s", tname);
1109 		}
1110 		if (strcmp(usefile, "-") == 0) {
1111 			if (cflag == 0)
1112 				fatal(gettext(
1113 				"can only create standard output archives."));
1114 			vfile = stderr;
1115 			mt = dup(1);
1116 			++bflag;
1117 		} else {
1118 			if (cflag)
1119 				mt = open(usefile,
1120 				    O_RDWR|O_CREAT|O_TRUNC, 0666);
1121 			else
1122 				mt = open(usefile, O_RDWR);
1123 
1124 			if (mt < 0) {
1125 				if (cflag == 0 || (mt =  creat(usefile, 0666))
1126 				    < 0)
1127 				vperror(1, "%s", usefile);
1128 			}
1129 		}
1130 		/* Get inode and device number of output file */
1131 		(void) fstat(mt, &stbuf);
1132 		mt_ino = stbuf.st_ino;
1133 		mt_dev = stbuf.st_dev;
1134 		mt_devtype = stbuf.st_mode & S_IFMT;
1135 		NotTape = !istape(mt, mt_devtype);
1136 
1137 		if (rflag && !cflag && (mt_devtype == S_IFIFO))
1138 			fatal(gettext("cannot append to pipe or FIFO."));
1139 
1140 		if (Aflag && vflag)
1141 			(void) printf(
1142 			gettext("Suppressing absolute pathnames\n"));
1143 		if (cflag && compress_opt != NULL) {
1144 			pid = compress_file();
1145 			wait_pid(pid);
1146 		}
1147 		dorep(argv);
1148 		if (rflag && !cflag && (compress_opt != NULL))
1149 			compress_back();
1150 	} else if (xflag || tflag) {
1151 		/*
1152 		 * for each argument, check to see if there is a "-I file" pair.
1153 		 * if so, move the 3rd argument into "-I"'s place, build_table()
1154 		 * using "file"'s name and increment argc one (the second
1155 		 * increment appears in the for loop) which removes the two
1156 		 * args "-I" and "file" from the argument vector.
1157 		 */
1158 		for (argc = 0; argv[argc]; argc++) {
1159 			if (strcmp(argv[argc], "-I") == 0) {
1160 				if (!argv[argc+1]) {
1161 					(void) fprintf(stderr, gettext(
1162 					"tar: missing argument for -I flag\n"));
1163 					done(2);
1164 				} else {
1165 					Iflag = 1;
1166 					argv[argc] = argv[argc+2];
1167 					build_table(include_tbl, argv[++argc]);
1168 #ifdef	_iBCS2
1169 					if (Fileflag) {
1170 						(void) fprintf(stderr, gettext(
1171 						"tar: only one of I or F.\n"));
1172 						usage();
1173 					}
1174 #endif	/*  _iBCS2 */
1175 
1176 				}
1177 			}
1178 		}
1179 		if (strcmp(usefile, "-") == 0) {
1180 			mt = dup(0);
1181 			++bflag;
1182 			/* try to recover from short reads when reading stdin */
1183 			++Bflag;
1184 		} else if ((mt = open(usefile, 0)) < 0)
1185 			vperror(1, "%s", usefile);
1186 
1187 		/* Decompress if the file is compressed */
1188 
1189 		if (strcmp(usefile, "-") != 0) {
1190 			check_compression();
1191 			if (compress_opt != NULL) {
1192 				pid = uncompress_file();
1193 				wait_pid(pid);
1194 			}
1195 		}
1196 		if (xflag) {
1197 			if (Aflag && vflag)
1198 				(void) printf(gettext(
1199 				    "Suppressing absolute pathnames.\n"));
1200 
1201 #ifdef	_iBCS2
1202 			doxtract(argv, tbl_cnt);
1203 #else
1204 			doxtract(argv);
1205 #endif
1206 		} else if (tflag)
1207 
1208 #ifdef	_iBCS2
1209 			dotable(argv, tbl_cnt);
1210 #else
1211 			dotable(argv);
1212 #endif
1213 	}
1214 	else
1215 		usage();
1216 
1217 	done(Errflg);
1218 
1219 	/* Not reached:  keep compiler quiet */
1220 	return (1);
1221 }
1222 
1223 static void
1224 usage(void)
1225 {
1226 
1227 #ifdef	_iBCS2
1228 	if (sysv3_env) {
1229 		(void) fprintf(stderr, gettext(
1230 #if defined(O_XATTR)
1231 #if defined(_PC_SATTR_ENABLED)
1232 		"Usage: tar {c|r|t|u|x}[BDeEhilmnopPqTvw@/[0-7]][bfFk][X...] "
1233 #else
1234 		"Usage: tar {c|r|t|u|x}[BDeEhilmnopPqTvw@[0-7]][bfFk][X...] "
1235 #endif	/* _PC_SATTR_ENABLED */
1236 #else
1237 		"Usage: tar {c|r|t|u|x}[BDeEhilmnopPqTvw[0-7]][bfFk][X...] "
1238 #endif	/* O_XATTR */
1239 		"[j|z|Z] "
1240 		"[blocksize] [tarfile] [filename] [size] [exclude-file...] "
1241 		"{file | -I include-file | -C directory file}...\n"));
1242 	} else
1243 #endif	/* _iBCS2 */
1244 	{
1245 		(void) fprintf(stderr, gettext(
1246 #if defined(O_XATTR)
1247 #if defined(_PC_SATTR_ENABLED)
1248 		"Usage: tar {c|r|t|u|x}[BDeEFhilmnopPqTvw@/[0-7]][bfk][X...] "
1249 #else
1250 		"Usage: tar {c|r|t|u|x}[BDeEFhilmnopPqTvw@[0-7]][bfk][X...] "
1251 #endif	/* _PC_SATTR_ENABLED */
1252 #else
1253 		"Usage: tar {c|r|t|u|x}[BDeEFhilmnopPqTvw[0-7]][bfk][X...] "
1254 #endif	/* O_XATTR */
1255 		"[j|z|Z] "
1256 		"[blocksize] [tarfile] [size] [exclude-file...] "
1257 		"{file | -I include-file | -C directory file}...\n"));
1258 	}
1259 	done(1);
1260 }
1261 
1262 /*
1263  * dorep - do "replacements"
1264  *
1265  *	Dorep is responsible for creating ('c'),  appending ('r')
1266  *	and updating ('u');
1267  */
1268 
1269 static void
1270 dorep(char *argv[])
1271 {
1272 	char *cp, *cp2, *p;
1273 	char wdir[PATH_MAX+2], tempdir[PATH_MAX+2], *parent;
1274 	char file[PATH_MAX*2], origdir[PATH_MAX+1];
1275 	FILE *fp = (FILE *)NULL;
1276 	FILE *ff = (FILE *)NULL;
1277 	int archtype;
1278 	int ret;
1279 
1280 
1281 	if (!cflag) {
1282 		xhdr_flgs = 0;
1283 		getdir();			/* read header for next file */
1284 		if (Xhdrflag > 0) {
1285 			if (!Eflag)
1286 				fatal(gettext("Archive contains extended"
1287 				    " header.  -E flag required.\n"));
1288 			ret = get_xdata();	/* Get extended header items */
1289 						/*   and regular header */
1290 		} else {
1291 			if (Eflag)
1292 				fatal(gettext("Archive contains no extended"
1293 				    " header.  -E flag not allowed.\n"));
1294 		}
1295 		while (!endtape()) {		/* changed from a do while */
1296 			setbytes_to_skip(&stbuf, ret);
1297 			passtape();		/* skip the file data */
1298 			if (term)
1299 				done(Errflg);	/* received signal to stop */
1300 			xhdr_flgs = 0;
1301 			getdir();
1302 			if (Xhdrflag > 0)
1303 				ret = get_xdata();
1304 		}
1305 		if (ret == 0) {
1306 			if ((dblock.dbuf.typeflag != 'A') &&
1307 			    (xhdr_flgs != 0)) {
1308 				load_info_from_xtarhdr(xhdr_flgs,
1309 				    &Xtarhdr);
1310 				xhdr_flgs |= _X_XHDR;
1311 			}
1312 		}
1313 		backtape();			/* was called by endtape */
1314 		if (tfile != NULL) {
1315 			/*
1316 			 * Buffer size is calculated to be the size of the
1317 			 * tmpdir string, plus 6 times the size of the tname
1318 			 * string, plus a value that is known to be greater
1319 			 * than the command pipeline string.
1320 			 */
1321 			int buflen = strlen(tmpdir) + (6 * strlen(tname)) + 100;
1322 			char *buf;
1323 
1324 			if ((buf = (char *)calloc(1, buflen)) == NULL) {
1325 				vperror(1, gettext("tar: out of memory, "
1326 				    "cannot create sort command file\n"));
1327 			}
1328 
1329 			(void) snprintf(buf, buflen, "env 'TMPDIR=%s' "
1330 			    "sort +0 -1 +1nr %s -o %s; awk '$1 "
1331 			    "!= prev {print; prev=$1}' %s >%sX;mv %sX %s",
1332 			    tmpdir, tname, tname, tname, tname, tname, tname);
1333 			(void) fflush(tfile);
1334 			(void) system(buf);
1335 			free(buf);
1336 			(void) freopen(tname, "r", tfile);
1337 			(void) fstat(fileno(tfile), &stbuf);
1338 			high = stbuf.st_size;
1339 		}
1340 	}
1341 
1342 	dumping = 1;
1343 	if (mulvol) {	/* SP-1 */
1344 		if (nblock && (blocklim%nblock) != 0)
1345 			fatal(gettext(
1346 			"Volume size not a multiple of block size."));
1347 		blocklim -= 2;			/* for trailer records */
1348 		if (vflag)
1349 			(void) fprintf(vfile, gettext("Volume ends at %"
1350 			    FMT_blkcnt_t "K, blocking factor = %dK\n"),
1351 			    K((blocklim - 1)), K(nblock));
1352 	}
1353 
1354 #ifdef	_iBCS2
1355 	if (Fileflag) {
1356 		if (Filefile != NULL) {
1357 			if ((ff = fopen(Filefile, "r")) == NULL)
1358 				vperror(0, "%s", Filefile);
1359 		} else {
1360 			(void) fprintf(stderr, gettext(
1361 			    "tar: F requires a file name.\n"));
1362 			usage();
1363 		}
1364 	}
1365 #endif	/*  _iBCS2 */
1366 
1367 	/*
1368 	 * Save the original directory before it gets
1369 	 * changed.
1370 	 */
1371 	if (getcwd(origdir, (PATH_MAX+1)) == NULL) {
1372 		vperror(0, gettext("A parent directory cannot be read"));
1373 		exit(1);
1374 	}
1375 
1376 	(void) strcpy(wdir, origdir);
1377 
1378 	while ((*argv || fp || ff) && !term) {
1379 		if (fp || (strcmp(*argv, "-I") == 0)) {
1380 #ifdef	_iBCS2
1381 			if (Fileflag) {
1382 				(void) fprintf(stderr, gettext(
1383 				"tar: only one of I or F.\n"));
1384 				usage();
1385 			}
1386 #endif	/*  _iBCS2 */
1387 			if (fp == NULL) {
1388 				if (*++argv == NULL)
1389 					fatal(gettext(
1390 					    "missing file name for -I flag."));
1391 				else if ((fp = fopen(*argv++, "r")) == NULL)
1392 					vperror(0, "%s", argv[-1]);
1393 				continue;
1394 			} else if ((fgets(file, PATH_MAX-1, fp)) == NULL) {
1395 				(void) fclose(fp);
1396 				fp = NULL;
1397 				continue;
1398 			} else {
1399 				cp = cp2 = file;
1400 				if ((p = strchr(cp2, '\n')))
1401 					*p = 0;
1402 			}
1403 		} else if ((strcmp(*argv, "-C") == 0) && argv[1]) {
1404 #ifdef	_iBCS2
1405 			if (Fileflag) {
1406 				(void) fprintf(stderr, gettext(
1407 				"tar: only one of F or C\n"));
1408 				usage();
1409 			}
1410 #endif	/*  _iBCS2 */
1411 
1412 			if (chdir(*++argv) < 0)
1413 				vperror(0, gettext(
1414 				    "can't change directories to %s"), *argv);
1415 			else
1416 				(void) getcwd(wdir, (sizeof (wdir)));
1417 			argv++;
1418 			continue;
1419 #ifdef	_iBCS2
1420 		} else if (Fileflag && (ff != NULL)) {
1421 			if ((fgets(file, PATH_MAX-1, ff)) == NULL) {
1422 				(void) fclose(ff);
1423 				ff = NULL;
1424 				continue;
1425 			} else {
1426 				cp = cp2 = file;
1427 				if (p = strchr(cp2, '\n'))
1428 					*p = 0;
1429 			}
1430 #endif	/*  _iBCS2 */
1431 		} else
1432 			cp = cp2 = strcpy(file, *argv++);
1433 
1434 		/*
1435 		 * point cp2 to the last '/' in file, but not
1436 		 * to a trailing '/'
1437 		 */
1438 		for (; *cp; cp++) {
1439 			if (*cp == '/') {
1440 				while (*(cp+1) == '/') {
1441 					++cp;
1442 				}
1443 				if (*(cp+1) != '\0') {
1444 					/* not trailing slash */
1445 					cp2 = cp;
1446 				}
1447 			}
1448 		}
1449 		if (cp2 != file) {
1450 			*cp2 = '\0';
1451 			if (chdir(file) < 0) {
1452 				vperror(0, gettext(
1453 				    "can't change directories to %s"), file);
1454 				continue;
1455 			}
1456 			*cp2 = '/';
1457 			cp2++;
1458 		}
1459 
1460 		parent = getcwd(tempdir, (sizeof (tempdir)));
1461 
1462 		archtype = putfile(file, cp2, parent, NULL, NORMAL_FILE,
1463 		    LEV0, SYMLINK_LEV0);
1464 
1465 #if defined(O_XATTR)
1466 		if (!exitflag) {
1467 			if ((atflag || saflag) &&
1468 			    (archtype == PUT_NOTAS_LINK)) {
1469 				xattrs_put(file, cp2, parent, NULL);
1470 			}
1471 		}
1472 #endif
1473 
1474 		if (chdir(origdir) < 0)
1475 			vperror(0, gettext("cannot change back?: %s"), origdir);
1476 
1477 		if (exitflag) {
1478 			/*
1479 			 * If e function modifier has been specified
1480 			 * write the files (that are listed before the
1481 			 * file causing the error) to tape.  exitflag is
1482 			 * used because only some of the error conditions
1483 			 * in putfile() recognize the e function modifier.
1484 			 */
1485 			break;
1486 		}
1487 	}
1488 
1489 	putempty((blkcnt_t)2);
1490 	flushtape();
1491 	closevol();	/* SP-1 */
1492 	if (linkerrok == 1)
1493 		for (; ihead != NULL; ihead = ihead->nextp) {
1494 			if (ihead->count == 0)
1495 				continue;
1496 			(void) fprintf(stderr, gettext(
1497 			"tar: missing links to %s\n"), ihead->pathname);
1498 			if (errflag)
1499 				done(1);
1500 			else
1501 				Errflg = 1;
1502 		}
1503 }
1504 
1505 
1506 /*
1507  * endtape - check for tape at end
1508  *
1509  *	endtape checks the entry in dblock.dbuf to see if its the
1510  *	special EOT entry.  Endtape is usually called after getdir().
1511  *
1512  *	endtape used to call backtape; it no longer does, he who
1513  *	wants it backed up must call backtape himself
1514  *	RETURNS:	0 if not EOT, tape position unaffected
1515  *			1 if	 EOT, tape position unaffected
1516  */
1517 
1518 static int
1519 endtape(void)
1520 {
1521 	if (dblock.dbuf.name[0] == '\0') {	/* null header = EOT */
1522 		return (1);
1523 	} else
1524 		return (0);
1525 }
1526 
1527 /*
1528  *	getdir - get directory entry from tar tape
1529  *
1530  *	getdir reads the next tarblock off the tape and cracks
1531  *	it as a directory. The checksum must match properly.
1532  *
1533  *	If tfile is non-null getdir writes the file name and mod date
1534  *	to tfile.
1535  */
1536 
1537 static void
1538 getdir(void)
1539 {
1540 	struct stat *sp;
1541 #ifdef EUC
1542 	static int warn_chksum_sign = 0;
1543 #endif /* EUC */
1544 
1545 top:
1546 	readtape((char *)&dblock);
1547 	if (dblock.dbuf.name[0] == '\0')
1548 		return;
1549 	sp = &stbuf;
1550 	(void) sscanf(dblock.dbuf.mode, "%8lo", &Gen.g_mode);
1551 	(void) sscanf(dblock.dbuf.uid, "%8lo", (ulong_t *)&Gen.g_uid);
1552 	(void) sscanf(dblock.dbuf.gid, "%8lo", (ulong_t *)&Gen.g_gid);
1553 	(void) sscanf(dblock.dbuf.size, "%12" FMT_off_t_o, &Gen.g_filesz);
1554 	(void) sscanf(dblock.dbuf.mtime, "%12lo", (ulong_t *)&Gen.g_mtime);
1555 	(void) sscanf(dblock.dbuf.chksum, "%8o", &Gen.g_cksum);
1556 	(void) sscanf(dblock.dbuf.devmajor, "%8lo", &Gen.g_devmajor);
1557 	(void) sscanf(dblock.dbuf.devminor, "%8lo", &Gen.g_devminor);
1558 
1559 	is_posix = (strcmp(dblock.dbuf.magic, magic_type) == 0);
1560 
1561 	sp->st_mode = Gen.g_mode;
1562 	if (is_posix && (sp->st_mode & S_IFMT) == 0)
1563 		switch (dblock.dbuf.typeflag) {
1564 		case '0': case 0: case _XATTR_HDRTYPE:
1565 			sp->st_mode |= S_IFREG;
1566 			break;
1567 		case '1':	/* hard link */
1568 			break;
1569 		case '2':
1570 			sp->st_mode |= S_IFLNK;
1571 			break;
1572 		case '3':
1573 			sp->st_mode |= S_IFCHR;
1574 			break;
1575 		case '4':
1576 			sp->st_mode |= S_IFBLK;
1577 			break;
1578 		case '5':
1579 			sp->st_mode |= S_IFDIR;
1580 			break;
1581 		case '6':
1582 			sp->st_mode |= S_IFIFO;
1583 			break;
1584 		default:
1585 			if (convtoreg(Gen.g_filesz))
1586 				sp->st_mode |= S_IFREG;
1587 			break;
1588 		}
1589 
1590 	if ((dblock.dbuf.typeflag == 'X') || (dblock.dbuf.typeflag == 'L')) {
1591 		Xhdrflag = 1;	/* Currently processing extended header */
1592 	} else {
1593 		Xhdrflag = 0;
1594 	}
1595 
1596 	sp->st_uid = Gen.g_uid;
1597 	sp->st_gid = Gen.g_gid;
1598 	sp->st_size = Gen.g_filesz;
1599 	sp->st_mtime = Gen.g_mtime;
1600 	chksum = Gen.g_cksum;
1601 
1602 	if (dblock.dbuf.extno != '\0') {	/* split file? */
1603 		extno = dblock.dbuf.extno;
1604 		extsize = Gen.g_filesz;
1605 		extotal = dblock.dbuf.extotal;
1606 	} else {
1607 		extno = 0;	/* tell others file not split */
1608 		extsize = 0;
1609 		extotal = 0;
1610 	}
1611 
1612 #ifdef	EUC
1613 	if (chksum != checksum(&dblock)) {
1614 		if (chksum != checksum_signed(&dblock)) {
1615 			(void) fprintf(stderr, gettext(
1616 			    "tar: directory checksum error\n"));
1617 			if (iflag)
1618 				goto top;
1619 			done(2);
1620 		} else {
1621 			if (! warn_chksum_sign) {
1622 				warn_chksum_sign = 1;
1623 				(void) fprintf(stderr, gettext(
1624 			"tar: warning: tar file made with signed checksum\n"));
1625 			}
1626 		}
1627 	}
1628 #else
1629 	if (chksum != checksum(&dblock)) {
1630 		(void) fprintf(stderr, gettext(
1631 		"tar: directory checksum error\n"));
1632 		if (iflag)
1633 			goto top;
1634 		done(2);
1635 	}
1636 #endif	/* EUC */
1637 	if (tfile != NULL && Xhdrflag == 0) {
1638 		/*
1639 		 * If an extended header is present, then time is available
1640 		 * in nanoseconds in the extended header data, so set it.
1641 		 * Otherwise, give an invalid value so that checkupdate will
1642 		 * not test beyond seconds.
1643 		 */
1644 		if ((xhdr_flgs & _X_MTIME))
1645 			sp->st_mtim.tv_nsec = Xtarhdr.x_mtime.tv_nsec;
1646 		else
1647 			sp->st_mtim.tv_nsec = -1;
1648 
1649 		if (xhdr_flgs & _X_PATH)
1650 			(void) fprintf(tfile, "%s %10ld.%9.9ld\n",
1651 			    Xtarhdr.x_path, sp->st_mtim.tv_sec,
1652 			    sp->st_mtim.tv_nsec);
1653 		else
1654 			(void) fprintf(tfile, "%.*s %10ld.%9.9ld\n",
1655 			    NAMSIZ, dblock.dbuf.name, sp->st_mtim.tv_sec,
1656 			    sp->st_mtim.tv_nsec);
1657 	}
1658 
1659 #if defined(O_XATTR)
1660 	Hiddendir = 0;
1661 	if (xattrp && dblock.dbuf.typeflag == _XATTR_HDRTYPE) {
1662 		if (xattrbadhead) {
1663 			free(xattrhead);
1664 			xattrp = NULL;
1665 			xattr_linkp = NULL;
1666 			xattrhead = NULL;
1667 		} else {
1668 			char	*aname = basename(xattrapath);
1669 			size_t	xindex  = aname - xattrapath;
1670 
1671 			if (xattrapath[xindex] == '.' &&
1672 			    xattrapath[xindex + 1] == '\0' &&
1673 			    xattrp->h_typeflag == '5') {
1674 				Hiddendir = 1;
1675 				sp->st_mode =
1676 				    (S_IFDIR | (sp->st_mode & POSIXMODES));
1677 			}
1678 			dblock.dbuf.typeflag = xattrp->h_typeflag;
1679 		}
1680 	}
1681 #endif
1682 }
1683 
1684 
1685 /*
1686  *	passtape - skip over a file on the tape
1687  *
1688  *	passtape skips over the next data file on the tape.
1689  *	The tape directory entry must be in dblock.dbuf. This
1690  *	routine just eats the number of blocks computed from the
1691  *	directory size entry; the tape must be (logically) positioned
1692  *	right after thee directory info.
1693  */
1694 
1695 static void
1696 passtape(void)
1697 {
1698 	blkcnt_t blocks;
1699 	char buf[TBLOCK];
1700 
1701 	/*
1702 	 * Types link(1), sym-link(2), char special(3), blk special(4),
1703 	 *  directory(5), and FIFO(6) do not have data blocks associated
1704 	 *  with them so just skip reading the data block.
1705 	 */
1706 	if (dblock.dbuf.typeflag == '1' || dblock.dbuf.typeflag == '2' ||
1707 	    dblock.dbuf.typeflag == '3' || dblock.dbuf.typeflag == '4' ||
1708 	    dblock.dbuf.typeflag == '5' || dblock.dbuf.typeflag == '6')
1709 		return;
1710 	blocks = TBLOCKS(stbuf.st_size);
1711 
1712 	/* if operating on disk, seek instead of reading */
1713 	if (NotTape)
1714 		seekdisk(blocks);
1715 	else
1716 		while (blocks-- > 0)
1717 			readtape(buf);
1718 }
1719 
1720 #if defined(O_XATTR)
1721 static int
1722 is_sysattr(char *name)
1723 {
1724 	return ((strcmp(name, VIEW_READONLY) == 0) ||
1725 	    (strcmp(name, VIEW_READWRITE) == 0));
1726 }
1727 #endif
1728 
1729 #if defined(O_XATTR)
1730 /*
1731  * Verify the attribute, attrname, is an attribute we want to restore.
1732  * Never restore read-only system attribute files.  Only restore read-write
1733  * system attributes files when -/ was specified, and only traverse into
1734  * the 2nd level attribute directory containing only system attributes if
1735  * -@ was specified.  This keeps us from archiving
1736  *	<attribute name>/<read-write system attribute file>
1737  * when -/ was specified without -@.
1738  *
1739  * attrname	- attribute file name
1740  * attrparent	- attribute's parent name within the base file's attribute
1741  *		directory hierarchy
1742  */
1743 static attr_status_t
1744 verify_attr(char *attrname, char *attrparent, int arc_rwsysattr,
1745     int *rw_sysattr)
1746 {
1747 #if defined(_PC_SATTR_ENABLED)
1748 	int	attr_supported;
1749 
1750 	/* Never restore read-only system attribute files */
1751 	if ((attr_supported = sysattr_type(attrname)) == _RO_SATTR) {
1752 		*rw_sysattr = 0;
1753 		return (ATTR_SKIP);
1754 	} else {
1755 		*rw_sysattr = (attr_supported == _RW_SATTR);
1756 	}
1757 #else
1758 	/*
1759 	 * Only need to check if this attribute is an extended system
1760 	 * attribute.
1761 	 */
1762 	if (*rw_sysattr = is_sysattr(attrname)) {
1763 		return (ATTR_SKIP);
1764 	} else {
1765 		return (ATTR_OK);
1766 	}
1767 #endif	/* _PC_SATTR_ENABLED */
1768 
1769 	/*
1770 	 * If the extended system attribute file is specified with the
1771 	 * arc_rwsysattr flag, as being transient (default extended
1772 	 * attributes), then don't archive it.
1773 	 */
1774 	if (*rw_sysattr && !arc_rwsysattr) {
1775 		return (ATTR_SKIP);
1776 	}
1777 
1778 	/*
1779 	 * Only restore read-write system attribute files
1780 	 * when -/ was specified.  Only restore extended
1781 	 * attributes when -@ was specified.
1782 	 */
1783 	if (atflag) {
1784 		if (!saflag) {
1785 			/*
1786 			 * Only archive/restore the hidden directory "." if
1787 			 * we're processing the top level hidden attribute
1788 			 * directory.  We don't want to process the
1789 			 * hidden attribute directory of the attribute
1790 			 * directory that contains only extended system
1791 			 * attributes.
1792 			 */
1793 			if (*rw_sysattr || (Hiddendir &&
1794 			    (attrparent != NULL))) {
1795 				return (ATTR_SKIP);
1796 			}
1797 		}
1798 	} else if (saflag) {
1799 		/*
1800 		 * Only archive/restore read-write extended system attribute
1801 		 * files of the base file.
1802 		 */
1803 		if (!*rw_sysattr || (attrparent != NULL)) {
1804 			return (ATTR_SKIP);
1805 		}
1806 	} else {
1807 		return (ATTR_SKIP);
1808 	}
1809 
1810 	return (ATTR_OK);
1811 }
1812 #endif
1813 
1814 static void
1815 free_children(file_list_t *children)
1816 {
1817 	file_list_t	*child = children;
1818 	file_list_t	*cptr;
1819 
1820 	while (child != NULL) {
1821 		cptr = child->next;
1822 		if (child->name != NULL) {
1823 			free(child->name);
1824 		}
1825 		child = cptr;
1826 	}
1827 }
1828 
1829 static int
1830 putfile(char *longname, char *shortname, char *parent, attr_data_t *attrinfo,
1831     int filetype, int lev, int symlink_lev)
1832 {
1833 	int infile = -1;	/* deliberately invalid */
1834 	blkcnt_t blocks;
1835 	char buf[PATH_MAX + 2];	/* Add trailing slash and null */
1836 	char *bigbuf;
1837 	int	maxread;
1838 	int	hint;		/* amount to write to get "in sync" */
1839 	char filetmp[PATH_MAX + 1];
1840 	char *cp;
1841 	char *name;
1842 	char *attrparent = NULL;
1843 	char *longattrname = NULL;
1844 	file_list_t	*child = NULL;
1845 	file_list_t	*child_end = NULL;
1846 	file_list_t	*cptr;
1847 	struct dirent *dp;
1848 	DIR *dirp;
1849 	int i;
1850 	int split;
1851 	int dirfd = -1;
1852 	int rc = PUT_NOTAS_LINK;
1853 	int archtype = 0;
1854 	int rw_sysattr = 0;
1855 	char newparent[PATH_MAX + MAXNAMLEN + 1];
1856 	char *prefix = "";
1857 	char *tmpbuf;
1858 	char goodbuf[PRESIZ + 2];
1859 	char junkbuf[MAXNAM+1];
1860 	char *lastslash;
1861 	int j;
1862 	struct stat sbuf;
1863 	int readlink_max;
1864 
1865 	(void) memset(goodbuf, '\0', sizeof (goodbuf));
1866 	(void) memset(junkbuf, '\0', sizeof (junkbuf));
1867 
1868 	xhdr_flgs = 0;
1869 
1870 	if (filetype == XATTR_FILE) {
1871 		attrparent = attrinfo->attr_parent;
1872 		longattrname = attrinfo->attr_path;
1873 		dirfd = attrinfo->attr_parentfd;
1874 		rw_sysattr = attrinfo->attr_rw_sysattr;
1875 	} else {
1876 		dirfd = open(".", O_RDONLY);
1877 	}
1878 
1879 	if (dirfd == -1) {
1880 		(void) fprintf(stderr, gettext(
1881 		    "tar: unable to open%sdirectory %s%s%s%s\n"),
1882 		    (filetype == XATTR_FILE) ? gettext(" attribute ") : " ",
1883 		    (attrparent == NULL) ? "" : gettext("of attribute "),
1884 		    (attrparent == NULL) ? "" : attrparent,
1885 		    (attrparent == NULL) ? "" : gettext(" of "),
1886 		    (filetype == XATTR_FILE) ? longname : parent);
1887 		goto out;
1888 	}
1889 
1890 	if (lev > MAXLEV) {
1891 		(void) fprintf(stderr,
1892 		    gettext("tar: directory nesting too deep, %s not dumped\n"),
1893 		    longname);
1894 		goto out;
1895 	}
1896 
1897 	if (getstat(dirfd, longname, shortname, attrparent))
1898 		goto out;
1899 
1900 	if (hflag) {
1901 		/*
1902 		 * Catch nesting where a file is a symlink to its directory.
1903 		 */
1904 		j = fstatat(dirfd, shortname, &sbuf, AT_SYMLINK_NOFOLLOW);
1905 		if (S_ISLNK(sbuf.st_mode)) {
1906 			if (symlink_lev++ >= MAXSYMLINKS) {
1907 				(void) fprintf(stderr, gettext(
1908 				    "tar: %s: Number of symbolic links "
1909 				    "encountered during path name traversal "
1910 				    "exceeds MAXSYMLINKS\n"), longname);
1911 				Errflg = 1;
1912 				goto out;
1913 			}
1914 		}
1915 	}
1916 
1917 	/*
1918 	 * Check if the input file is the same as the tar file we
1919 	 * are creating
1920 	 */
1921 	if ((mt_ino == stbuf.st_ino) && (mt_dev == stbuf.st_dev)) {
1922 		(void) fprintf(stderr, gettext(
1923 		    "tar: %s%s%s%s%s same as archive file\n"),
1924 		    rw_sysattr ? gettext("system ") : "",
1925 		    (longattrname == NULL) ? "" : gettext("attribute "),
1926 		    (longattrname == NULL) ? "" : longattrname,
1927 		    (longattrname == NULL) ? "" : gettext(" of "),
1928 		    longname);
1929 		Errflg = 1;
1930 		goto out;
1931 	}
1932 	/*
1933 	 * Check size limit - we can't archive files that
1934 	 * exceed TAR_OFFSET_MAX bytes because of header
1935 	 * limitations. Exclude file types that set
1936 	 * st_size to zero below because they take no
1937 	 * archive space to represent contents.
1938 	 */
1939 	if ((stbuf.st_size > (off_t)TAR_OFFSET_MAX) &&
1940 	    !S_ISDIR(stbuf.st_mode) &&
1941 	    !S_ISCHR(stbuf.st_mode) &&
1942 	    !S_ISBLK(stbuf.st_mode) &&
1943 	    (Eflag == 0)) {
1944 		(void) fprintf(stderr, gettext(
1945 		    "tar: %s%s%s%s%s too large to archive.  "
1946 		    "Use E function modifier.\n"),
1947 		    rw_sysattr ? gettext("system ") : "",
1948 		    (longattrname == NULL) ? "" : gettext("attribute "),
1949 		    (longattrname == NULL) ? "" : longattrname,
1950 		    (longattrname == NULL) ? "" : gettext(" of "),
1951 		    longname);
1952 		if (errflag)
1953 			exitflag = 1;
1954 		Errflg = 1;
1955 		goto out;
1956 	}
1957 
1958 	if (tfile != NULL && checkupdate(longname) == 0) {
1959 		goto out;
1960 	}
1961 	if (checkw('r', longname) == 0) {
1962 		goto out;
1963 	}
1964 
1965 	if (Fflag &&
1966 	    checkf(longname, (stbuf.st_mode & S_IFMT) == S_IFDIR, Fflag) == 0)
1967 		goto out;
1968 
1969 	if (Xflag) {
1970 		if (is_in_table(exclude_tbl, longname)) {
1971 			if (vflag) {
1972 				(void) fprintf(vfile, gettext(
1973 				    "a %s excluded\n"), longname);
1974 			}
1975 			goto out;
1976 		}
1977 	}
1978 
1979 	/*
1980 	 * If the length of the fullname is greater than MAXNAM,
1981 	 * print out a message and return (unless extended headers are used,
1982 	 * in which case fullname is limited to PATH_MAX).
1983 	 */
1984 
1985 	if ((((split = (int)strlen(longname)) > MAXNAM) && (Eflag == 0)) ||
1986 	    (split > PATH_MAX)) {
1987 		(void) fprintf(stderr, gettext(
1988 		    "tar: %s: file name too long\n"), longname);
1989 		if (errflag)
1990 			exitflag = 1;
1991 		Errflg = 1;
1992 		goto out;
1993 	}
1994 
1995 	/*
1996 	 * We split the fullname into prefix and name components if any one
1997 	 * of three conditions holds:
1998 	 *	-- the length of the fullname exceeds NAMSIZ,
1999 	 *	-- the length of the fullname equals NAMSIZ, and the shortname
2000 	 *	   is less than NAMSIZ, (splitting in this case preserves
2001 	 *	   compatibility with 5.6 and 5.5.1 tar), or
2002 	 * 	-- the length of the fullname equals NAMSIZ, the file is a
2003 	 *	   directory and we are not in POSIX-conformant mode (where
2004 	 *	   trailing slashes are removed from directories).
2005 	 */
2006 	if ((split > NAMSIZ) ||
2007 	    (split == NAMSIZ && strlen(shortname) < NAMSIZ) ||
2008 	    (split == NAMSIZ && S_ISDIR(stbuf.st_mode) && !Pflag)) {
2009 		/*
2010 		 * Since path is limited to PRESIZ characters, look for the
2011 		 * last slash within PRESIZ + 1 characters only.
2012 		 */
2013 		(void) strncpy(&goodbuf[0], longname, min(split, PRESIZ + 1));
2014 		tmpbuf = goodbuf;
2015 		lastslash = strrchr(tmpbuf, '/');
2016 		if (lastslash == NULL) {
2017 			i = split;		/* Length of name */
2018 			j = 0;			/* Length of prefix */
2019 			goodbuf[0] = '\0';
2020 		} else {
2021 			*lastslash = '\0';	/* Terminate the prefix */
2022 			j = strlen(tmpbuf);
2023 			i = split - j - 1;
2024 		}
2025 		/*
2026 		 * If the filename is greater than NAMSIZ we can't
2027 		 * archive the file unless we are using extended headers.
2028 		 */
2029 		if ((i > NAMSIZ) || (i == NAMSIZ && S_ISDIR(stbuf.st_mode) &&
2030 		    !Pflag)) {
2031 			/* Determine which (filename or path) is too long. */
2032 			lastslash = strrchr(longname, '/');
2033 			if (lastslash != NULL)
2034 				i = strlen(lastslash + 1);
2035 			if (Eflag > 0) {
2036 				xhdr_flgs |= _X_PATH;
2037 				Xtarhdr.x_path = longname;
2038 				if (i <= NAMSIZ)
2039 					(void) strcpy(junkbuf, lastslash + 1);
2040 				else
2041 					(void) sprintf(junkbuf, "%llu",
2042 					    xhdr_count + 1);
2043 				if (split - i - 1 > PRESIZ)
2044 					(void) strcpy(goodbuf, xhdr_dirname);
2045 			} else {
2046 				if ((i > NAMSIZ) || (i == NAMSIZ &&
2047 				    S_ISDIR(stbuf.st_mode) && !Pflag))
2048 					(void) fprintf(stderr, gettext(
2049 					    "tar: %s: filename is greater than "
2050 					    "%d\n"), lastslash == NULL ?
2051 					    longname : lastslash + 1, NAMSIZ);
2052 				else
2053 					(void) fprintf(stderr, gettext(
2054 					    "tar: %s: prefix is greater than %d"
2055 					    "\n"), longname, PRESIZ);
2056 				if (errflag)
2057 					exitflag = 1;
2058 				Errflg = 1;
2059 				goto out;
2060 			}
2061 		} else
2062 			(void) strncpy(&junkbuf[0], longname + j + 1,
2063 			    strlen(longname + j + 1));
2064 		name = junkbuf;
2065 		prefix = goodbuf;
2066 	} else {
2067 		name = longname;
2068 	}
2069 	if (Aflag) {
2070 		if ((prefix != NULL) && (*prefix != '\0'))
2071 			while (*prefix == '/')
2072 				++prefix;
2073 		else
2074 			while (*name == '/')
2075 				++name;
2076 	}
2077 
2078 	switch (stbuf.st_mode & S_IFMT) {
2079 	case S_IFDIR:
2080 		stbuf.st_size = (off_t)0;
2081 		blocks = TBLOCKS(stbuf.st_size);
2082 
2083 		if (filetype != XATTR_FILE && Hiddendir == 0) {
2084 			i = 0;
2085 			cp = buf;
2086 			while ((*cp++ = longname[i++]))
2087 				;
2088 			*--cp = '/';
2089 			*++cp = 0;
2090 		}
2091 		if (!oflag) {
2092 			tomodes(&stbuf);
2093 			if (build_dblock(name, tchar, '5', filetype,
2094 			    &stbuf, stbuf.st_dev, prefix) != 0) {
2095 				goto out;
2096 			}
2097 			if (!Pflag) {
2098 				/*
2099 				 * Old archives require a slash at the end
2100 				 * of a directory name.
2101 				 *
2102 				 * XXX
2103 				 * If directory name is too long, will
2104 				 * slash overfill field?
2105 				 */
2106 				if (strlen(name) > (unsigned)NAMSIZ-1) {
2107 					(void) fprintf(stderr, gettext(
2108 					    "tar: %s: filename is greater "
2109 					    "than %d\n"), name, NAMSIZ);
2110 					if (errflag)
2111 						exitflag = 1;
2112 					Errflg = 1;
2113 					goto out;
2114 				} else {
2115 					if (strlen(name) == (NAMSIZ - 1)) {
2116 						(void) memcpy(dblock.dbuf.name,
2117 						    name, NAMSIZ);
2118 						dblock.dbuf.name[NAMSIZ-1]
2119 						    = '/';
2120 					} else
2121 						(void) sprintf(dblock.dbuf.name,
2122 						    "%s/", name);
2123 
2124 					/*
2125 					 * need to recalculate checksum
2126 					 * because the name changed.
2127 					 */
2128 					(void) sprintf(dblock.dbuf.chksum,
2129 					    "%07o", checksum(&dblock));
2130 				}
2131 			}
2132 
2133 			if (put_extra_attributes(longname, shortname,
2134 			    longattrname, prefix, filetype, '5') != 0)
2135 				goto out;
2136 
2137 #if defined(O_XATTR)
2138 			/*
2139 			 * Reset header typeflag when archiving directory, since
2140 			 * build_dblock changed it on us.
2141 			 */
2142 			if (filetype == XATTR_FILE) {
2143 				dblock.dbuf.typeflag = _XATTR_HDRTYPE;
2144 			} else {
2145 				dblock.dbuf.typeflag = '5';
2146 			}
2147 #else
2148 			dblock.dbuf.typeflag = '5';
2149 #endif
2150 
2151 			(void) sprintf(dblock.dbuf.chksum, "%07o",
2152 			    checksum(&dblock));
2153 
2154 			(void) writetbuf((char *)&dblock, 1);
2155 		}
2156 		if (vflag) {
2157 #ifdef DEBUG
2158 			if (NotTape)
2159 				DEBUG("seek = %" FMT_blkcnt_t "K\t", K(tapepos),
2160 				    0);
2161 #endif
2162 			if (filetype == XATTR_FILE && Hiddendir) {
2163 				(void) fprintf(vfile,
2164 				    gettext("a %s attribute %s "),
2165 				    longname, longattrname);
2166 
2167 			} else {
2168 				(void) fprintf(vfile, "a %s/ ", longname);
2169 			}
2170 			if (NotTape)
2171 				(void) fprintf(vfile, "%" FMT_blkcnt_t "K\n",
2172 				    K(blocks));
2173 			else
2174 				(void) fprintf(vfile, gettext("%" FMT_blkcnt_t
2175 				    " tape blocks\n"), blocks);
2176 		}
2177 
2178 		/*
2179 		 * If hidden dir then break now since xattrs_put() will do
2180 		 * the iterating of the directory.
2181 		 *
2182 		 * At the moment, there can only be system attributes on
2183 		 * attributes.  There can be no attributes on attributes or
2184 		 * directories within the attributes hidden directory hierarchy.
2185 		 */
2186 		if (filetype == XATTR_FILE)
2187 			break;
2188 
2189 		if (*shortname != '/')
2190 			(void) sprintf(newparent, "%s/%s", parent, shortname);
2191 		else
2192 			(void) sprintf(newparent, "%s", shortname);
2193 
2194 		if (chdir(shortname) < 0) {
2195 			vperror(0, "%s", newparent);
2196 			goto out;
2197 		}
2198 
2199 		if ((dirp = opendir(".")) == NULL) {
2200 			vperror(0, gettext(
2201 			    "can't open directory %s"), longname);
2202 			if (chdir(parent) < 0)
2203 				vperror(0, gettext("cannot change back?: %s"),
2204 				    parent);
2205 			goto out;
2206 		}
2207 
2208 		/*
2209 		 * Create a list of files (children) in this directory to avoid
2210 		 * having to perform telldir()/seekdir().
2211 		 */
2212 		while ((dp = readdir(dirp)) != NULL && !term) {
2213 			if ((strcmp(".", dp->d_name) == 0) ||
2214 			    (strcmp("..", dp->d_name) == 0))
2215 				continue;
2216 			if (((cptr = (file_list_t *)calloc(sizeof (char),
2217 			    sizeof (file_list_t))) == NULL) ||
2218 			    ((cptr->name = strdup(dp->d_name)) == NULL)) {
2219 				vperror(1, gettext(
2220 				    "Insufficient memory for directory "
2221 				    "list entry %s/%s\n"),
2222 				    newparent, dp->d_name);
2223 			}
2224 
2225 			/* Add the file to the list */
2226 			if (child == NULL) {
2227 				child = cptr;
2228 			} else {
2229 				child_end->next = cptr;
2230 			}
2231 			child_end = cptr;
2232 		}
2233 		(void) closedir(dirp);
2234 
2235 		/*
2236 		 * Archive each of the files in the current directory.
2237 		 * If a file is a directory, putfile() is called
2238 		 * recursively to archive the file hierarchy of the
2239 		 * directory before archiving the next file in the
2240 		 * current directory.
2241 		 */
2242 		while ((child != NULL) && !term) {
2243 			(void) strcpy(cp, child->name);
2244 			archtype = putfile(buf, cp, newparent, NULL,
2245 			    NORMAL_FILE, lev + 1, symlink_lev);
2246 
2247 			if (!exitflag) {
2248 				if ((atflag || saflag) &&
2249 				    (archtype == PUT_NOTAS_LINK)) {
2250 					xattrs_put(buf, cp, newparent, NULL);
2251 				}
2252 			}
2253 			if (exitflag)
2254 				break;
2255 
2256 			/* Free each child as we are done processing it. */
2257 			cptr = child;
2258 			child = child->next;
2259 			free(cptr->name);
2260 			free(cptr);
2261 		}
2262 		if ((child != NULL) && !term) {
2263 			free_children(child);
2264 		}
2265 
2266 		if (chdir(parent) < 0) {
2267 			vperror(0, gettext("cannot change back?: %s"), parent);
2268 		}
2269 
2270 		break;
2271 
2272 	case S_IFLNK:
2273 		readlink_max = NAMSIZ;
2274 		if (stbuf.st_size > NAMSIZ) {
2275 			if (Eflag > 0) {
2276 				xhdr_flgs |= _X_LINKPATH;
2277 				readlink_max = PATH_MAX;
2278 			} else {
2279 				(void) fprintf(stderr, gettext(
2280 				    "tar: %s: symbolic link too long\n"),
2281 				    longname);
2282 				if (errflag)
2283 					exitflag = 1;
2284 				Errflg = 1;
2285 				goto out;
2286 			}
2287 		}
2288 		/*
2289 		 * Sym-links need header size of zero since you
2290 		 * don't store any data for this type.
2291 		 */
2292 		stbuf.st_size = (off_t)0;
2293 		tomodes(&stbuf);
2294 		i = readlink(shortname, filetmp, readlink_max);
2295 		if (i < 0) {
2296 			vperror(0, gettext(
2297 			    "can't read symbolic link %s"), longname);
2298 			goto out;
2299 		} else {
2300 			filetmp[i] = 0;
2301 		}
2302 		if (vflag)
2303 			(void) fprintf(vfile, gettext(
2304 			    "a %s symbolic link to %s\n"),
2305 			    longname, filetmp);
2306 		if (xhdr_flgs & _X_LINKPATH) {
2307 			Xtarhdr.x_linkpath = filetmp;
2308 			if (build_dblock(name, tchar, '2', filetype, &stbuf,
2309 			    stbuf.st_dev, prefix) != 0)
2310 				goto out;
2311 		} else
2312 			if (build_dblock(name, filetmp, '2', filetype, &stbuf,
2313 			    stbuf.st_dev, prefix) != 0)
2314 				goto out;
2315 		(void) writetbuf((char *)&dblock, 1);
2316 		/*
2317 		 * No acls for symlinks: mode is always 777
2318 		 * dont call write ancillary
2319 		 */
2320 		rc = PUT_AS_LINK;
2321 		break;
2322 	case S_IFREG:
2323 		if ((infile = openat(dirfd, shortname, 0)) < 0) {
2324 			vperror(0, gettext("unable to open %s%s%s%s"), longname,
2325 			    rw_sysattr ? gettext(" system") : "",
2326 			    (filetype == XATTR_FILE) ?
2327 			    gettext(" attribute ") : "",
2328 			    (filetype == XATTR_FILE) ? (longattrname == NULL) ?
2329 			    shortname : longattrname : "");
2330 			goto out;
2331 		}
2332 
2333 		blocks = TBLOCKS(stbuf.st_size);
2334 
2335 		if (put_link(name, longname, shortname, longattrname,
2336 		    prefix, filetype, '1') == 0) {
2337 			(void) close(infile);
2338 			rc = PUT_AS_LINK;
2339 			goto out;
2340 		}
2341 
2342 		tomodes(&stbuf);
2343 
2344 		/* correctly handle end of volume */
2345 		while (mulvol && tapepos + blocks + 1 > blocklim) {
2346 			/* file won't fit */
2347 			if (eflag) {
2348 				if (blocks <= blocklim) {
2349 					newvol();
2350 					break;
2351 				}
2352 				(void) fprintf(stderr, gettext(
2353 				    "tar: Single file cannot fit on volume\n"));
2354 				done(3);
2355 			}
2356 			/* split if floppy has some room and file is large */
2357 			if (((blocklim - tapepos) >= EXTMIN) &&
2358 			    ((blocks + 1) >= blocklim/10)) {
2359 				splitfile(longname, infile,
2360 				    name, prefix, filetype);
2361 				(void) close(dirfd);
2362 				(void) close(infile);
2363 				goto out;
2364 			}
2365 			newvol();	/* not worth it--just get new volume */
2366 		}
2367 #ifdef DEBUG
2368 		DEBUG("putfile: %s wants %" FMT_blkcnt_t " blocks\n", longname,
2369 		    blocks);
2370 #endif
2371 		if (build_dblock(name, tchar, '0', filetype,
2372 		    &stbuf, stbuf.st_dev, prefix) != 0) {
2373 			goto out;
2374 		}
2375 		if (vflag) {
2376 #ifdef DEBUG
2377 			if (NotTape)
2378 				DEBUG("seek = %" FMT_blkcnt_t "K\t", K(tapepos),
2379 				    0);
2380 #endif
2381 			(void) fprintf(vfile, "a %s%s%s%s ", longname,
2382 			    rw_sysattr ? gettext(" system") : "",
2383 			    (filetype == XATTR_FILE) ? gettext(
2384 			    " attribute ") : "",
2385 			    (filetype == XATTR_FILE) ?
2386 			    longattrname : "");
2387 			if (NotTape)
2388 				(void) fprintf(vfile, "%" FMT_blkcnt_t "K\n",
2389 				    K(blocks));
2390 			else
2391 				(void) fprintf(vfile,
2392 				    gettext("%" FMT_blkcnt_t " tape blocks\n"),
2393 				    blocks);
2394 		}
2395 
2396 		if (put_extra_attributes(longname, shortname, longattrname,
2397 		    prefix, filetype, '0') != 0)
2398 			goto out;
2399 
2400 		/*
2401 		 * No need to reset typeflag for extended attribute here, since
2402 		 * put_extra_attributes already set it and we haven't called
2403 		 * build_dblock().
2404 		 */
2405 		(void) sprintf(dblock.dbuf.chksum, "%07o", checksum(&dblock));
2406 		hint = writetbuf((char *)&dblock, 1);
2407 		maxread = max(min(stbuf.st_blksize, stbuf.st_size),
2408 		    (nblock * TBLOCK));
2409 		if ((bigbuf = calloc((unsigned)maxread, sizeof (char))) == 0) {
2410 			maxread = TBLOCK;
2411 			bigbuf = buf;
2412 		}
2413 
2414 		while (((i = (int)
2415 		    read(infile, bigbuf, min((hint*TBLOCK), maxread))) > 0) &&
2416 		    blocks) {
2417 			blkcnt_t nblks;
2418 
2419 			nblks = ((i-1)/TBLOCK)+1;
2420 			if (nblks > blocks)
2421 				nblks = blocks;
2422 			hint = writetbuf(bigbuf, nblks);
2423 			blocks -= nblks;
2424 		}
2425 		(void) close(infile);
2426 		if (bigbuf != buf)
2427 			free(bigbuf);
2428 		if (i < 0)
2429 			vperror(0, gettext("Read error on %s"), longname);
2430 		else if (blocks != 0 || i != 0) {
2431 			(void) fprintf(stderr, gettext(
2432 			"tar: %s: file changed size\n"), longname);
2433 			if (errflag) {
2434 				exitflag = 1;
2435 				Errflg = 1;
2436 			} else if (!Dflag) {
2437 				Errflg = 1;
2438 			}
2439 		}
2440 		putempty(blocks);
2441 		break;
2442 	case S_IFIFO:
2443 		blocks = TBLOCKS(stbuf.st_size);
2444 		stbuf.st_size = (off_t)0;
2445 
2446 		if (put_link(name, longname, shortname, longattrname,
2447 		    prefix, filetype, '6') == 0) {
2448 			rc = PUT_AS_LINK;
2449 			goto out;
2450 		}
2451 		tomodes(&stbuf);
2452 
2453 		while (mulvol && tapepos + blocks + 1 > blocklim) {
2454 			if (eflag) {
2455 				if (blocks <= blocklim) {
2456 					newvol();
2457 					break;
2458 				}
2459 				(void) fprintf(stderr, gettext(
2460 				    "tar: Single file cannot fit on volume\n"));
2461 				done(3);
2462 			}
2463 
2464 			if (((blocklim - tapepos) >= EXTMIN) &&
2465 			    ((blocks + 1) >= blocklim/10)) {
2466 				splitfile(longname, infile, name,
2467 				    prefix, filetype);
2468 				(void) close(dirfd);
2469 				(void) close(infile);
2470 				goto out;
2471 			}
2472 			newvol();
2473 		}
2474 #ifdef DEBUG
2475 		DEBUG("putfile: %s wants %" FMT_blkcnt_t " blocks\n", longname,
2476 		    blocks);
2477 #endif
2478 		if (vflag) {
2479 #ifdef DEBUG
2480 			if (NotTape)
2481 				DEBUG("seek = %" FMT_blkcnt_t "K\t", K(tapepos),
2482 				    0);
2483 #endif
2484 			if (NotTape)
2485 				(void) fprintf(vfile, gettext("a %s %"
2486 				    FMT_blkcnt_t "K\n "), longname, K(blocks));
2487 			else
2488 				(void) fprintf(vfile, gettext(
2489 				    "a %s %" FMT_blkcnt_t " tape blocks\n"),
2490 				    longname, blocks);
2491 		}
2492 		if (build_dblock(name, tchar, '6', filetype,
2493 		    &stbuf, stbuf.st_dev, prefix) != 0)
2494 			goto out;
2495 
2496 		if (put_extra_attributes(longname, shortname, longattrname,
2497 		    prefix, filetype, '6') != 0)
2498 			goto out;
2499 
2500 		(void) sprintf(dblock.dbuf.chksum, "%07o", checksum(&dblock));
2501 		dblock.dbuf.typeflag = '6';
2502 
2503 		(void) writetbuf((char *)&dblock, 1);
2504 		break;
2505 	case S_IFCHR:
2506 		stbuf.st_size = (off_t)0;
2507 		blocks = TBLOCKS(stbuf.st_size);
2508 		if (put_link(name, longname, shortname, longattrname,
2509 		    prefix, filetype, '3') == 0) {
2510 			rc = PUT_AS_LINK;
2511 			goto out;
2512 		}
2513 		tomodes(&stbuf);
2514 
2515 		while (mulvol && tapepos + blocks + 1 > blocklim) {
2516 			if (eflag) {
2517 				if (blocks <= blocklim) {
2518 					newvol();
2519 					break;
2520 				}
2521 				(void) fprintf(stderr, gettext(
2522 				    "tar: Single file cannot fit on volume\n"));
2523 				done(3);
2524 			}
2525 
2526 			if (((blocklim - tapepos) >= EXTMIN) &&
2527 			    ((blocks + 1) >= blocklim/10)) {
2528 				splitfile(longname, infile, name,
2529 				    prefix, filetype);
2530 				(void) close(dirfd);
2531 				goto out;
2532 			}
2533 			newvol();
2534 		}
2535 #ifdef DEBUG
2536 		DEBUG("putfile: %s wants %" FMT_blkcnt_t " blocks\n", longname,
2537 		    blocks);
2538 #endif
2539 		if (vflag) {
2540 #ifdef DEBUG
2541 			if (NotTape)
2542 				DEBUG("seek = %" FMT_blkcnt_t "K\t", K(tapepos),
2543 				    0);
2544 #endif
2545 			if (NotTape)
2546 				(void) fprintf(vfile, gettext("a %s %"
2547 				    FMT_blkcnt_t "K\n"), longname, K(blocks));
2548 			else
2549 				(void) fprintf(vfile, gettext("a %s %"
2550 				    FMT_blkcnt_t " tape blocks\n"), longname,
2551 				    blocks);
2552 		}
2553 		if (build_dblock(name, tchar, '3',
2554 		    filetype, &stbuf, stbuf.st_rdev, prefix) != 0)
2555 			goto out;
2556 
2557 		if (put_extra_attributes(longname, shortname, longattrname,
2558 		    prefix, filetype, '3') != 0)
2559 			goto out;
2560 
2561 		(void) sprintf(dblock.dbuf.chksum, "%07o", checksum(&dblock));
2562 		dblock.dbuf.typeflag = '3';
2563 
2564 		(void) writetbuf((char *)&dblock, 1);
2565 		break;
2566 	case S_IFBLK:
2567 		stbuf.st_size = (off_t)0;
2568 		blocks = TBLOCKS(stbuf.st_size);
2569 		if (put_link(name, longname, shortname, longattrname,
2570 		    prefix, filetype, '4') == 0) {
2571 			rc = PUT_AS_LINK;
2572 			goto out;
2573 		}
2574 		tomodes(&stbuf);
2575 
2576 		while (mulvol && tapepos + blocks + 1 > blocklim) {
2577 			if (eflag) {
2578 				if (blocks <= blocklim) {
2579 					newvol();
2580 					break;
2581 				}
2582 				(void) fprintf(stderr, gettext(
2583 				    "tar: Single file cannot fit on volume\n"));
2584 				done(3);
2585 			}
2586 
2587 			if (((blocklim - tapepos) >= EXTMIN) &&
2588 			    ((blocks + 1) >= blocklim/10)) {
2589 				splitfile(longname, infile,
2590 				    name, prefix, filetype);
2591 				(void) close(dirfd);
2592 				goto out;
2593 			}
2594 			newvol();
2595 		}
2596 #ifdef DEBUG
2597 		DEBUG("putfile: %s wants %" FMT_blkcnt_t " blocks\n", longname,
2598 		    blocks);
2599 #endif
2600 		if (vflag) {
2601 #ifdef DEBUG
2602 			if (NotTape)
2603 				DEBUG("seek = %" FMT_blkcnt_t "K\t", K(tapepos),
2604 				    0);
2605 #endif
2606 			(void) fprintf(vfile, "a %s ", longname);
2607 			if (NotTape)
2608 				(void) fprintf(vfile, "%" FMT_blkcnt_t "K\n",
2609 				    K(blocks));
2610 			else
2611 				(void) fprintf(vfile, gettext("%"
2612 				    FMT_blkcnt_t " tape blocks\n"), blocks);
2613 		}
2614 		if (build_dblock(name, tchar, '4',
2615 		    filetype, &stbuf, stbuf.st_rdev, prefix) != 0)
2616 			goto out;
2617 
2618 		if (put_extra_attributes(longname, shortname, longattrname,
2619 		    prefix, filetype, '4') != 0)
2620 			goto out;
2621 
2622 		(void) sprintf(dblock.dbuf.chksum, "%07o", checksum(&dblock));
2623 		dblock.dbuf.typeflag = '4';
2624 
2625 		(void) writetbuf((char *)&dblock, 1);
2626 		break;
2627 	default:
2628 		(void) fprintf(stderr, gettext(
2629 		    "tar: %s is not a file. Not dumped\n"), longname);
2630 		if (errflag)
2631 			exitflag = 1;
2632 		Errflg = 1;
2633 		goto out;
2634 	}
2635 
2636 out:
2637 	if ((dirfd != -1) && (filetype != XATTR_FILE)) {
2638 		(void) close(dirfd);
2639 	}
2640 	return (rc);
2641 }
2642 
2643 
2644 /*
2645  *	splitfile	dump a large file across volumes
2646  *
2647  *	splitfile(longname, fd);
2648  *		char *longname;		full name of file
2649  *		int ifd;		input file descriptor
2650  *
2651  *	NOTE:  only called by putfile() to dump a large file.
2652  */
2653 
2654 static void
2655 splitfile(char *longname, int ifd, char *name, char *prefix, int filetype)
2656 {
2657 	blkcnt_t blocks;
2658 	off_t bytes, s;
2659 	char buf[TBLOCK];
2660 	int i, extents;
2661 
2662 	blocks = TBLOCKS(stbuf.st_size);	/* blocks file needs */
2663 
2664 	/*
2665 	 * # extents =
2666 	 *	size of file after using up rest of this floppy
2667 	 *		blocks - (blocklim - tapepos) + 1	(for header)
2668 	 *	plus roundup value before divide by blocklim-1
2669 	 *		+ (blocklim - 1) - 1
2670 	 *	all divided by blocklim-1 (one block for each header).
2671 	 * this gives
2672 	 *	(blocks - blocklim + tapepos + 1 + blocklim - 2)/(blocklim-1)
2673 	 * which reduces to the expression used.
2674 	 * one is added to account for this first extent.
2675 	 *
2676 	 * When one is dealing with extremely large archives, one may want
2677 	 * to allow for a large number of extents.  This code should be
2678 	 * revisited to determine if extents should be changed to something
2679 	 * larger than an int.
2680 	 */
2681 	extents = (int)((blocks + tapepos - 1ULL)/(blocklim - 1ULL) + 1);
2682 
2683 	if (extents < 2 || extents > MAXEXT) {	/* let's be reasonable */
2684 		(void) fprintf(stderr, gettext(
2685 		    "tar: %s needs unusual number of volumes to split\n"
2686 		    "tar: %s not dumped\n"), longname, longname);
2687 		return;
2688 	}
2689 	if (build_dblock(name, tchar, '0', filetype,
2690 	    &stbuf, stbuf.st_dev, prefix) != 0)
2691 		return;
2692 
2693 	dblock.dbuf.extotal = extents;
2694 	bytes = stbuf.st_size;
2695 
2696 	/*
2697 	 * The value contained in dblock.dbuf.efsize was formerly used when the
2698 	 * v flag was specified in conjunction with the t flag. Although it is
2699 	 * no longer used, older versions of tar will expect the former
2700 	 * behaviour, so we must continue to write it to the archive.
2701 	 *
2702 	 * Since dblock.dbuf.efsize is 10 chars in size, the maximum value it
2703 	 * can store is TAR_EFSIZE_MAX. If bytes exceeds that value, simply
2704 	 * store 0.
2705 	 */
2706 	if (bytes <= TAR_EFSIZE_MAX)
2707 		(void) sprintf(dblock.dbuf.efsize, "%9" FMT_off_t_o, bytes);
2708 	else
2709 		(void) sprintf(dblock.dbuf.efsize, "%9" FMT_off_t_o, (off_t)0);
2710 
2711 	(void) fprintf(stderr, gettext(
2712 	    "tar: large file %s needs %d extents.\n"
2713 	    "tar: current device seek position = %" FMT_blkcnt_t "K\n"),
2714 	    longname, extents, K(tapepos));
2715 
2716 	s = (off_t)(blocklim - tapepos - 1) * TBLOCK;
2717 	for (i = 1; i <= extents; i++) {
2718 		if (i > 1) {
2719 			newvol();
2720 			if (i == extents)
2721 				s = bytes;	/* last ext. gets true bytes */
2722 			else
2723 				s = (off_t)(blocklim - 1)*TBLOCK; /* all */
2724 		}
2725 		bytes -= s;
2726 		blocks = TBLOCKS(s);
2727 
2728 		(void) sprintf(dblock.dbuf.size, "%011" FMT_off_t_o, s);
2729 		dblock.dbuf.extno = i;
2730 		(void) sprintf(dblock.dbuf.chksum, "%07o", checksum(&dblock));
2731 		(void) writetbuf((char *)&dblock, 1);
2732 
2733 		if (vflag)
2734 			(void) fprintf(vfile,
2735 			    gettext("+++ a %s %" FMT_blkcnt_t
2736 			    "K [extent #%d of %d]\n"),
2737 			    longname, K(blocks), i, extents);
2738 		while (blocks && read(ifd, buf, TBLOCK) > 0) {
2739 			blocks--;
2740 			(void) writetbuf(buf, 1);
2741 		}
2742 		if (blocks != 0) {
2743 			(void) fprintf(stderr, gettext(
2744 			    "tar: %s: file changed size\n"), longname);
2745 			(void) fprintf(stderr, gettext(
2746 			    "tar: aborting split file %s\n"), longname);
2747 			(void) close(ifd);
2748 			return;
2749 		}
2750 	}
2751 	(void) close(ifd);
2752 	if (vflag)
2753 		(void) fprintf(vfile, gettext("a %s %" FMT_off_t "K (in %d "
2754 		    "extents)\n"), longname, K(TBLOCKS(stbuf.st_size)),
2755 		    extents);
2756 }
2757 
2758 /*
2759  *	convtoreg - determines whether the file should be converted to a
2760  *	            regular file when extracted
2761  *
2762  *	Returns 1 when file size > 0 and typeflag is not recognized
2763  * 	Otherwise returns 0
2764  */
2765 static int
2766 convtoreg(off_t size)
2767 {
2768 	if ((size > 0) && (dblock.dbuf.typeflag != '0') &&
2769 	    (dblock.dbuf.typeflag != NULL) && (dblock.dbuf.typeflag != '1') &&
2770 	    (dblock.dbuf.typeflag != '2') && (dblock.dbuf.typeflag != '3') &&
2771 	    (dblock.dbuf.typeflag != '4') && (dblock.dbuf.typeflag != '5') &&
2772 	    (dblock.dbuf.typeflag != '6') && (dblock.dbuf.typeflag != 'A') &&
2773 	    (dblock.dbuf.typeflag != 'L') &&
2774 	    (dblock.dbuf.typeflag != _XATTR_HDRTYPE) &&
2775 	    (dblock.dbuf.typeflag != 'X')) {
2776 		return (1);
2777 	}
2778 	return (0);
2779 }
2780 
2781 #if defined(O_XATTR)
2782 static int
2783 save_cwd(void)
2784 {
2785 	return (open(".", O_RDONLY));
2786 }
2787 #endif
2788 
2789 #if defined(O_XATTR)
2790 static void
2791 rest_cwd(int *cwd)
2792 {
2793 	if (*cwd != -1) {
2794 		if (fchdir(*cwd) < 0) {
2795 			vperror(0, gettext(
2796 			    "Cannot fchdir to attribute directory"));
2797 			exit(1);
2798 		}
2799 		(void) close(*cwd);
2800 		*cwd = -1;
2801 	}
2802 }
2803 #endif
2804 
2805 /*
2806  * Verify the underlying file system supports the attribute type.
2807  * Only archive extended attribute files when '-@' was specified.
2808  * Only archive system extended attribute files if '-/' was specified.
2809  */
2810 #if defined(O_XATTR)
2811 static attr_status_t
2812 verify_attr_support(char *filename, int attrflg, arc_action_t actflag,
2813     int *ext_attrflg)
2814 {
2815 	/*
2816 	 * Verify extended attributes are supported/exist.  We only
2817 	 * need to check if we are processing a base file, not an
2818 	 * extended attribute.
2819 	 */
2820 	if (attrflg) {
2821 		*ext_attrflg = (pathconf(filename, (actflag == ARC_CREATE) ?
2822 		    _PC_XATTR_EXISTS : _PC_XATTR_ENABLED) == 1);
2823 	}
2824 
2825 	if (atflag) {
2826 		if (!*ext_attrflg) {
2827 #if defined(_PC_SATTR_ENABLED)
2828 			if (saflag) {
2829 				/* Verify system attributes are supported */
2830 				if (sysattr_support(filename,
2831 				    (actflag == ARC_CREATE) ? _PC_SATTR_EXISTS :
2832 				    _PC_SATTR_ENABLED) != 1) {
2833 					return (ATTR_SATTR_ERR);
2834 				}
2835 			} else
2836 				return (ATTR_XATTR_ERR);
2837 #else
2838 				return (ATTR_XATTR_ERR);
2839 #endif	/* _PC_SATTR_ENABLED */
2840 		}
2841 
2842 #if defined(_PC_SATTR_ENABLED)
2843 	} else if (saflag) {
2844 		/* Verify system attributes are supported */
2845 		if (sysattr_support(filename, (actflag == ARC_CREATE) ?
2846 		    _PC_SATTR_EXISTS : _PC_SATTR_ENABLED) != 1) {
2847 			return (ATTR_SATTR_ERR);
2848 		}
2849 #endif	/* _PC_SATTR_ENABLED */
2850 	} else {
2851 		return (ATTR_SKIP);
2852 	}
2853 
2854 	return (ATTR_OK);
2855 }
2856 #endif
2857 
2858 #if defined(O_XATTR)
2859 /*
2860  * Recursively open attribute directories until the attribute directory
2861  * containing the specified attribute, attrname, is opened.
2862  *
2863  * Currently, only 2 directory levels of attributes are supported, (i.e.,
2864  * extended system attributes on extended attributes).  The following are
2865  * the possible input combinations:
2866  *	1.  Open the attribute directory of the base file (don't change
2867  *	    into it).
2868  *		attrinfo->parent = NULL
2869  *		attrname = '.'
2870  *	2.  Open the attribute directory of the base file and change into it.
2871  *		attrinfo->parent = NULL
2872  *		attrname = <attr> | <sys_attr>
2873  *	3.  Open the attribute directory of the base file, change into it,
2874  *	    then recursively call open_attr_dir() to open the attribute's
2875  *	    parent directory (don't change into it).
2876  *		attrinfo->parent = <attr>
2877  *		attrname = '.'
2878  *	4.  Open the attribute directory of the base file, change into it,
2879  *	    then recursively call open_attr_dir() to open the attribute's
2880  *	    parent directory and change into it.
2881  *		attrinfo->parent = <attr>
2882  *		attrname = <attr> | <sys_attr>
2883  *
2884  * An attribute directory will be opened only if the underlying file system
2885  * supports the attribute type, and if the command line specifications (atflag
2886  * and saflag) enable the processing of the attribute type.
2887  *
2888  * On succesful return, attrinfo->parentfd will be the file descriptor of the
2889  * opened attribute directory.  In addition, if the attribute is a read-write
2890  * extended system attribute, attrinfo->rw_sysattr will be set to 1, otherwise
2891  * it will be set to 0.
2892  *
2893  * Possible return values:
2894  * 	ATTR_OK		Successfully opened and, if needed, changed into the
2895  *			attribute directory containing attrname.
2896  *	ATTR_SKIP	The command line specifications don't enable the
2897  *			processing of the attribute type.
2898  * 	ATTR_CHDIR_ERR	An error occurred while trying to change into an
2899  *			attribute directory.
2900  * 	ATTR_OPEN_ERR	An error occurred while trying to open an
2901  *			attribute directory.
2902  *	ATTR_XATTR_ERR	The underlying file system doesn't support extended
2903  *			attributes.
2904  *	ATTR_SATTR_ERR	The underlying file system doesn't support extended
2905  *			system attributes.
2906  */
2907 static int
2908 open_attr_dir(char *attrname, char *dirp, int cwd, attr_data_t *attrinfo)
2909 {
2910 	attr_status_t	rc;
2911 	int		firsttime = (attrinfo->attr_parentfd == -1);
2912 	int		saveerrno;
2913 	int		ext_attr;
2914 
2915 	/*
2916 	 * open_attr_dir() was recursively called (input combination number 4),
2917 	 * close the previously opened file descriptor as we've already changed
2918 	 * into it.
2919 	 */
2920 	if (!firsttime) {
2921 		(void) close(attrinfo->attr_parentfd);
2922 		attrinfo->attr_parentfd = -1;
2923 	}
2924 
2925 	/*
2926 	 * Verify that the underlying file system supports the restoration
2927 	 * of the attribute.
2928 	 */
2929 	if ((rc = verify_attr_support(dirp, firsttime, ARC_RESTORE,
2930 	    &ext_attr)) != ATTR_OK) {
2931 		return (rc);
2932 	}
2933 
2934 	/* Open the base file's attribute directory */
2935 	if ((attrinfo->attr_parentfd = attropen(dirp, ".", O_RDONLY)) == -1) {
2936 		/*
2937 		 * Save the errno from the attropen so it can be reported
2938 		 * if the retry of the attropen fails.
2939 		 */
2940 		saveerrno = errno;
2941 		if ((attrinfo->attr_parentfd = retry_open_attr(-1, cwd, dirp,
2942 		    NULL, ".", O_RDONLY, 0)) == -1) {
2943 			/*
2944 			 * Reset typeflag back to real value so passtape
2945 			 * will skip ahead correctly.
2946 			 */
2947 			dblock.dbuf.typeflag = _XATTR_HDRTYPE;
2948 			(void) close(attrinfo->attr_parentfd);
2949 			attrinfo->attr_parentfd = -1;
2950 			errno = saveerrno;
2951 			return (ATTR_OPEN_ERR);
2952 		}
2953 	}
2954 
2955 	/*
2956 	 * Change into the parent attribute's directory unless we are
2957 	 * processing the hidden attribute directory of the base file itself.
2958 	 */
2959 	if ((Hiddendir == 0) || (firsttime && attrinfo->attr_parent != NULL)) {
2960 		if (fchdir(attrinfo->attr_parentfd) != 0) {
2961 			saveerrno = errno;
2962 			(void) close(attrinfo->attr_parentfd);
2963 			attrinfo->attr_parentfd = -1;
2964 			errno = saveerrno;
2965 			return (ATTR_CHDIR_ERR);
2966 		}
2967 	}
2968 
2969 	/* Determine if the attribute should be processed */
2970 	if ((rc = verify_attr(attrname, attrinfo->attr_parent, 1,
2971 	    &attrinfo->attr_rw_sysattr)) != ATTR_OK) {
2972 		saveerrno = errno;
2973 		(void) close(attrinfo->attr_parentfd);
2974 		attrinfo->attr_parentfd = -1;
2975 		errno = saveerrno;
2976 		return (rc);
2977 	}
2978 
2979 	/*
2980 	 * If the attribute is an extended attribute, or extended system
2981 	 * attribute, of an attribute (i.e., <attr>/<sys_attr>), then
2982 	 * recursively call open_attr_dir() to open the attribute directory
2983 	 * of the parent attribute.
2984 	 */
2985 	if (firsttime && (attrinfo->attr_parent != NULL)) {
2986 		return (open_attr_dir(attrname, attrinfo->attr_parent,
2987 		    attrinfo->attr_parentfd, attrinfo));
2988 	}
2989 
2990 	return (ATTR_OK);
2991 }
2992 #endif
2993 
2994 static void
2995 #ifdef	_iBCS2
2996 doxtract(char *argv[], int tbl_cnt)
2997 #else
2998 doxtract(char *argv[])
2999 #endif
3000 {
3001 	struct	stat	xtractbuf;	/* stat on file after extracting */
3002 	blkcnt_t blocks;
3003 	off_t bytes;
3004 	int ofile;
3005 	int newfile;			/* Does the file already exist  */
3006 	int xcnt = 0;			/* count # files extracted */
3007 	int fcnt = 0;			/* count # files in argv list */
3008 	int dir;
3009 	int dirfd = -1;
3010 	int cwd = -1;
3011 	int rw_sysattr;
3012 	int saveerrno;
3013 	uid_t Uid;
3014 	char *namep, *dirp, *comp, *linkp; /* for removing absolute paths */
3015 	char dirname[PATH_MAX+1];
3016 	char templink[PATH_MAX+1];	/* temp link with terminating NULL */
3017 	int once = 1;
3018 	int error;
3019 	int symflag;
3020 	int want;
3021 	attr_data_t *attrinfo = NULL;	/* attribute info */
3022 	acl_t	*aclp = NULL;	/* acl info */
3023 	char dot[] = ".";		/* dirp for using realpath */
3024 	timestruc_t	time_zero;	/* used for call to doDirTimes */
3025 	int		dircreate;
3026 	int convflag;
3027 	time_zero.tv_sec = 0;
3028 	time_zero.tv_nsec = 0;
3029 
3030 	/* reset Trusted Extensions variables */
3031 	rpath_flag = 0;
3032 	lk_rpath_flag = 0;
3033 	dir_flag = 0;
3034 	mld_flag = 0;
3035 	bslundef(&bs_label);
3036 	bsllow(&admin_low);
3037 	bslhigh(&admin_high);
3038 	orig_namep = 0;
3039 
3040 	dumping = 0;	/* for newvol(), et al:  we are not writing */
3041 
3042 	/*
3043 	 * Count the number of files that are to be extracted
3044 	 */
3045 	Uid = getuid();
3046 
3047 #ifdef	_iBCS2
3048 	initarg(argv, Filefile);
3049 	while (nextarg() != NULL)
3050 		++fcnt;
3051 	fcnt += tbl_cnt;
3052 #endif	/*  _iBCS2 */
3053 
3054 	for (;;) {
3055 		convflag = 0;
3056 		symflag = 0;
3057 		dir = 0;
3058 		Hiddendir = 0;
3059 		rw_sysattr = 0;
3060 		ofile = -1;
3061 
3062 		if (dirfd != -1) {
3063 			(void) close(dirfd);
3064 			dirfd = -1;
3065 		}
3066 		if (ofile != -1) {
3067 			if (close(ofile) != 0)
3068 				vperror(2, gettext("close error"));
3069 		}
3070 
3071 #if defined(O_XATTR)
3072 		if (cwd != -1) {
3073 			rest_cwd(&cwd);
3074 		}
3075 #endif
3076 
3077 		/* namep is set by wantit to point to the full name */
3078 		if ((want = wantit(argv, &namep, &dirp, &comp,
3079 		    &attrinfo)) == 0) {
3080 #if defined(O_XATTR)
3081 			if (xattrp != NULL) {
3082 				free(xattrhead);
3083 				xattrp = NULL;
3084 				xattr_linkp = NULL;
3085 				xattrhead = NULL;
3086 			}
3087 #endif
3088 			continue;
3089 		}
3090 		if (want == -1)
3091 			break;
3092 
3093 /* Trusted Extensions */
3094 		/*
3095 		 * During tar extract (x):
3096 		 * If the pathname of the restored file has been
3097 		 * reconstructed from the ancillary file,
3098 		 * use it to process the normal file.
3099 		 */
3100 		if (mld_flag) {		/* Skip over .MLD. directory */
3101 			mld_flag = 0;
3102 			passtape();
3103 			continue;
3104 		}
3105 		orig_namep = namep;	/* save original */
3106 		if (rpath_flag) {
3107 			namep = real_path;	/* use zone path */
3108 			comp = real_path;	/* use zone path */
3109 			dirp = dot;		/* work from the top */
3110 			rpath_flag = 0;		/* reset */
3111 		}
3112 
3113 		if (dirfd != -1)
3114 			(void) close(dirfd);
3115 
3116 		(void) strcpy(&dirname[0], namep);
3117 		dircreate = checkdir(&dirname[0]);
3118 
3119 #if defined(O_XATTR)
3120 		if (xattrp != NULL) {
3121 			int	rc;
3122 
3123 			if (((cwd = save_cwd()) == -1) ||
3124 			    ((rc = open_attr_dir(comp, dirp, cwd,
3125 			    attrinfo)) != ATTR_OK)) {
3126 				if (cwd == -1) {
3127 					vperror(0, gettext(
3128 					    "unable to save current working "
3129 					    "directory while processing "
3130 					    "attribute %s of %s"),
3131 					    dirp, attrinfo->attr_path);
3132 				} else if (rc != ATTR_SKIP) {
3133 					(void) fprintf(vfile,
3134 					    gettext("tar: cannot open "
3135 					    "%sattribute %s of file %s: %s\n"),
3136 					    attrinfo->attr_rw_sysattr ? gettext(
3137 					    "system ") : "",
3138 					    comp, dirp, strerror(errno));
3139 				}
3140 				free(xattrhead);
3141 				xattrp = NULL;
3142 				xattr_linkp = NULL;
3143 				xattrhead = NULL;
3144 
3145 				passtape();
3146 				continue;
3147 			} else {
3148 				dirfd = attrinfo->attr_parentfd;
3149 				rw_sysattr = attrinfo->attr_rw_sysattr;
3150 			}
3151 		} else {
3152 			dirfd = open(dirp, O_RDONLY);
3153 		}
3154 #else
3155 		dirfd = open(dirp, O_RDONLY);
3156 #endif
3157 		if (dirfd == -1) {
3158 			(void) fprintf(vfile, gettext(
3159 			    "tar: cannot open %s: %s\n"),
3160 			    dirp, strerror(errno));
3161 			passtape();
3162 			continue;
3163 		}
3164 
3165 		if (xhdr_flgs & _X_LINKPATH)
3166 			(void) strcpy(templink, Xtarhdr.x_linkpath);
3167 		else {
3168 #if defined(O_XATTR)
3169 			if (xattrp && dblock.dbuf.typeflag == '1') {
3170 				(void) sprintf(templink, "%.*s", NAMSIZ,
3171 				    xattrp->h_names);
3172 			} else {
3173 				(void) sprintf(templink, "%.*s", NAMSIZ,
3174 				    dblock.dbuf.linkname);
3175 			}
3176 #else
3177 			(void) sprintf(templink, "%.*s", NAMSIZ,
3178 			    dblock.dbuf.linkname);
3179 #endif
3180 		}
3181 
3182 		if (Fflag) {
3183 			if (checkf(namep, is_directory(namep), Fflag) == 0) {
3184 				passtape();
3185 				continue;
3186 			}
3187 		}
3188 
3189 		if (checkw('x', namep) == 0) {
3190 			passtape();
3191 			continue;
3192 		}
3193 		if (once) {
3194 			if (strcmp(dblock.dbuf.magic, magic_type) == 0) {
3195 				if (geteuid() == (uid_t)0) {
3196 					checkflag = 1;
3197 					pflag = 1;
3198 				} else {
3199 					/* get file creation mask */
3200 					Oumask = umask(0);
3201 					(void) umask(Oumask);
3202 				}
3203 				once = 0;
3204 			} else {
3205 				if (geteuid() == (uid_t)0) {
3206 					pflag = 1;
3207 					checkflag = 2;
3208 				}
3209 				if (!pflag) {
3210 					/* get file creation mask */
3211 					Oumask = umask(0);
3212 					(void) umask(Oumask);
3213 				}
3214 				once = 0;
3215 			}
3216 		}
3217 
3218 #if defined(O_XATTR)
3219 		/*
3220 		 * Handle extraction of hidden attr dir.
3221 		 * Dir is automatically created, we only
3222 		 * need to update mode and perm's.
3223 		 */
3224 		if ((xattrp != NULL) && Hiddendir == 1) {
3225 			bytes = stbuf.st_size;
3226 			blocks = TBLOCKS(bytes);
3227 			if (vflag) {
3228 				(void) fprintf(vfile,
3229 				    "x %s%s%s, %" FMT_off_t " %s, ", namep,
3230 				    gettext(" attribute "),
3231 				    xattrapath, bytes,
3232 				    gettext("bytes"));
3233 				if (NotTape)
3234 					(void) fprintf(vfile,
3235 					    "%" FMT_blkcnt_t "K\n", K(blocks));
3236 				else
3237 					(void) fprintf(vfile, gettext("%"
3238 					    FMT_blkcnt_t " tape blocks\n"),
3239 					    blocks);
3240 			}
3241 
3242 			/*
3243 			 * Set the permissions and mode of the attribute
3244 			 * unless the attribute is a system attribute (can't
3245 			 * successfully do this) or the hidden attribute
3246 			 * directory (".") of an attribute (when the attribute
3247 			 * is restored, the hidden attribute directory of an
3248 			 * attribute is transient).  Note:  when the permissions
3249 			 * and mode are set for the hidden attribute directory
3250 			 * of a file on a system supporting extended system
3251 			 * attributes, even though it returns successfully, it
3252 			 * will not have any affect since the attribute
3253 			 * directory is transient.
3254 			 */
3255 			if (attrinfo->attr_parent == NULL) {
3256 				if (fchownat(dirfd, ".", stbuf.st_uid,
3257 				    stbuf.st_gid, 0) != 0) {
3258 					vperror(0, gettext(
3259 					    "%s%s%s: failed to set ownership "
3260 					    "of attribute directory"), namep,
3261 					    gettext(" attribute "), xattrapath);
3262 				}
3263 
3264 				if (fchmod(dirfd, stbuf.st_mode) != 0) {
3265 					vperror(0, gettext(
3266 					    "%s%s%s: failed to set permissions "
3267 					    "of attribute directory"), namep,
3268 					    gettext(" attribute "), xattrapath);
3269 				}
3270 			}
3271 			goto filedone;
3272 		}
3273 #endif
3274 
3275 		if (dircreate && (!is_posix || dblock.dbuf.typeflag == '5')) {
3276 			dir = 1;
3277 			if (vflag) {
3278 				(void) fprintf(vfile, "x %s, 0 %s, ",
3279 				    &dirname[0], gettext("bytes"));
3280 				if (NotTape)
3281 					(void) fprintf(vfile, "0K\n");
3282 				else
3283 					(void) fprintf(vfile, gettext("%"
3284 					    FMT_blkcnt_t " tape blocks\n"),
3285 					    (blkcnt_t)0);
3286 			}
3287 			goto filedone;
3288 		}
3289 
3290 		if (dblock.dbuf.typeflag == '6') {	/* FIFO */
3291 			if (rmdir(namep) < 0) {
3292 				if (errno == ENOTDIR)
3293 					(void) unlink(namep);
3294 			}
3295 			linkp = templink;
3296 			if (*linkp !=  NULL) {
3297 				if (Aflag && *linkp == '/')
3298 					linkp++;
3299 				if (link(linkp, namep) < 0) {
3300 					(void) fprintf(stderr, gettext(
3301 					    "tar: %s: cannot link\n"), namep);
3302 					continue;
3303 				}
3304 				if (vflag)
3305 					(void) fprintf(vfile, gettext(
3306 					    "x %s linked to %s\n"), namep,
3307 					    linkp);
3308 				xcnt++;	 /* increment # files extracted */
3309 				continue;
3310 			}
3311 			if (mknod(namep, (int)(Gen.g_mode|S_IFIFO),
3312 			    (int)Gen.g_devmajor) < 0) {
3313 				vperror(0, gettext("%s: mknod failed"), namep);
3314 				continue;
3315 			}
3316 			bytes = stbuf.st_size;
3317 			blocks = TBLOCKS(bytes);
3318 			if (vflag) {
3319 				(void) fprintf(vfile, "x %s, %" FMT_off_t
3320 				    " %s, ", namep, bytes, gettext("bytes"));
3321 				if (NotTape)
3322 					(void) fprintf(vfile, "%" FMT_blkcnt_t
3323 					    "K\n", K(blocks));
3324 				else
3325 					(void) fprintf(vfile, gettext("%"
3326 					    FMT_blkcnt_t " tape blocks\n"),
3327 					    blocks);
3328 			}
3329 			goto filedone;
3330 		}
3331 		if (dblock.dbuf.typeflag == '3' && !Uid) { /* CHAR SPECIAL */
3332 			if (rmdir(namep) < 0) {
3333 				if (errno == ENOTDIR)
3334 					(void) unlink(namep);
3335 			}
3336 			linkp = templink;
3337 			if (*linkp != NULL) {
3338 				if (Aflag && *linkp == '/')
3339 					linkp++;
3340 				if (link(linkp, namep) < 0) {
3341 					(void) fprintf(stderr, gettext(
3342 					    "tar: %s: cannot link\n"), namep);
3343 					continue;
3344 				}
3345 				if (vflag)
3346 					(void) fprintf(vfile, gettext(
3347 					    "x %s linked to %s\n"), namep,
3348 					    linkp);
3349 				xcnt++;	 /* increment # files extracted */
3350 				continue;
3351 			}
3352 			if (mknod(namep, (int)(Gen.g_mode|S_IFCHR),
3353 			    (int)makedev(Gen.g_devmajor, Gen.g_devminor)) < 0) {
3354 				vperror(0, gettext(
3355 				    "%s: mknod failed"), namep);
3356 				continue;
3357 			}
3358 			bytes = stbuf.st_size;
3359 			blocks = TBLOCKS(bytes);
3360 			if (vflag) {
3361 				(void) fprintf(vfile, "x %s, %" FMT_off_t
3362 				    " %s, ", namep, bytes, gettext("bytes"));
3363 				if (NotTape)
3364 					(void) fprintf(vfile, "%" FMT_blkcnt_t
3365 					    "K\n", K(blocks));
3366 				else
3367 					(void) fprintf(vfile, gettext("%"
3368 					    FMT_blkcnt_t " tape blocks\n"),
3369 					    blocks);
3370 			}
3371 			goto filedone;
3372 		} else if (dblock.dbuf.typeflag == '3' && Uid) {
3373 			(void) fprintf(stderr, gettext(
3374 			    "Can't create special %s\n"), namep);
3375 			continue;
3376 		}
3377 
3378 		/* BLOCK SPECIAL */
3379 
3380 		if (dblock.dbuf.typeflag == '4' && !Uid) {
3381 			if (rmdir(namep) < 0) {
3382 				if (errno == ENOTDIR)
3383 					(void) unlink(namep);
3384 			}
3385 			linkp = templink;
3386 			if (*linkp != NULL) {
3387 				if (Aflag && *linkp == '/')
3388 					linkp++;
3389 				if (link(linkp, namep) < 0) {
3390 					(void) fprintf(stderr, gettext(
3391 					    "tar: %s: cannot link\n"), namep);
3392 					continue;
3393 				}
3394 				if (vflag)
3395 					(void) fprintf(vfile, gettext(
3396 					    "x %s linked to %s\n"), namep,
3397 					    linkp);
3398 				xcnt++;	 /* increment # files extracted */
3399 				continue;
3400 			}
3401 			if (mknod(namep, (int)(Gen.g_mode|S_IFBLK),
3402 			    (int)makedev(Gen.g_devmajor, Gen.g_devminor)) < 0) {
3403 				vperror(0, gettext("%s: mknod failed"), namep);
3404 				continue;
3405 			}
3406 			bytes = stbuf.st_size;
3407 			blocks = TBLOCKS(bytes);
3408 			if (vflag) {
3409 				(void) fprintf(vfile, gettext("x %s, %"
3410 				    FMT_off_t " bytes, "), namep, bytes);
3411 				if (NotTape)
3412 					(void) fprintf(vfile, "%" FMT_blkcnt_t
3413 					    "K\n", K(blocks));
3414 				else
3415 					(void) fprintf(vfile, gettext("%"
3416 					    FMT_blkcnt_t " tape blocks\n"),
3417 					    blocks);
3418 			}
3419 			goto filedone;
3420 		} else if (dblock.dbuf.typeflag == '4' && Uid) {
3421 			(void) fprintf(stderr,
3422 			    gettext("Can't create special %s\n"), namep);
3423 			continue;
3424 		}
3425 		if (dblock.dbuf.typeflag == '2') {	/* symlink */
3426 			if ((Tflag) && (lk_rpath_flag == 1))
3427 				linkp = lk_real_path;
3428 			else
3429 				linkp = templink;
3430 			if (Aflag && *linkp == '/')
3431 				linkp++;
3432 			if (rmdir(namep) < 0) {
3433 				if (errno == ENOTDIR)
3434 					(void) unlink(namep);
3435 			}
3436 			if (symlink(linkp, namep) < 0) {
3437 				vperror(0, gettext("%s: symbolic link failed"),
3438 				    namep);
3439 				continue;
3440 			}
3441 			if (vflag)
3442 				(void) fprintf(vfile, gettext(
3443 				    "x %s symbolic link to %s\n"),
3444 				    namep, linkp);
3445 
3446 			symflag = AT_SYMLINK_NOFOLLOW;
3447 			goto filedone;
3448 		}
3449 		if (dblock.dbuf.typeflag == '1') {
3450 			linkp = templink;
3451 			if (Aflag && *linkp == '/')
3452 				linkp++;
3453 			if (unlinkat(dirfd, comp, AT_REMOVEDIR) < 0) {
3454 				if (errno == ENOTDIR)
3455 					(void) unlinkat(dirfd, comp, 0);
3456 			}
3457 #if defined(O_XATTR)
3458 			if (xattrp && xattr_linkp) {
3459 				if (fchdir(dirfd) < 0) {
3460 					vperror(0, gettext(
3461 					    "Cannot fchdir to attribute "
3462 					    "directory %s"),
3463 					    (attrinfo->attr_parent == NULL) ?
3464 					    dirp : attrinfo->attr_parent);
3465 					exit(1);
3466 				}
3467 
3468 				error = link(xattr_linkaname, xattrapath);
3469 			} else {
3470 				error = link(linkp, namep);
3471 			}
3472 #else
3473 			error = link(linkp, namep);
3474 #endif
3475 
3476 			if (error < 0) {
3477 				(void) fprintf(stderr, gettext(
3478 				    "tar: %s%s%s: cannot link\n"),
3479 				    namep, (xattr_linkp != NULL) ?
3480 				    gettext(" attribute ") : "",
3481 				    (xattr_linkp != NULL) ?
3482 				    xattrapath : "");
3483 				continue;
3484 			}
3485 			if (vflag)
3486 				(void) fprintf(vfile, gettext(
3487 				    "x %s%s%s linked to %s%s%s\n"), namep,
3488 				    (xattr_linkp != NULL) ?
3489 				    gettext(" attribute ") : "",
3490 				    (xattr_linkp != NULL) ?
3491 				    xattr_linkaname : "",
3492 				    linkp,
3493 				    (xattr_linkp != NULL) ?
3494 				    gettext(" attribute ") : "",
3495 				    (xattr_linkp != NULL) ? xattrapath : "");
3496 			xcnt++;		/* increment # files extracted */
3497 #if defined(O_XATTR)
3498 			if (xattrp != NULL) {
3499 				free(xattrhead);
3500 				xattrp = NULL;
3501 				xattr_linkp = NULL;
3502 				xattrhead = NULL;
3503 			}
3504 #endif
3505 			continue;
3506 		}
3507 
3508 		/* REGULAR FILES */
3509 
3510 		if (convtoreg(stbuf.st_size)) {
3511 			convflag = 1;
3512 			if (errflag) {
3513 				(void) fprintf(stderr, gettext(
3514 				    "tar: %s: typeflag '%c' not recognized\n"),
3515 				    namep, dblock.dbuf.typeflag);
3516 				done(1);
3517 			} else {
3518 				(void) fprintf(stderr, gettext(
3519 				    "tar: %s: typeflag '%c' not recognized, "
3520 				    "converting to regular file\n"), namep,
3521 				    dblock.dbuf.typeflag);
3522 				Errflg = 1;
3523 			}
3524 		}
3525 		if (dblock.dbuf.typeflag == '0' ||
3526 		    dblock.dbuf.typeflag == NULL || convflag) {
3527 			delete_target(dirfd, comp, namep);
3528 			linkp = templink;
3529 			if (*linkp != NULL) {
3530 				if (Aflag && *linkp == '/')
3531 					linkp++;
3532 				if (link(linkp, comp) < 0) {
3533 					(void) fprintf(stderr, gettext(
3534 					    "tar: %s: cannot link\n"), namep);
3535 					continue;
3536 				}
3537 				if (vflag)
3538 					(void) fprintf(vfile, gettext(
3539 					    "x %s linked to %s\n"), comp,
3540 					    linkp);
3541 				xcnt++;	 /* increment # files extracted */
3542 #if defined(O_XATTR)
3543 				if (xattrp != NULL) {
3544 					free(xattrhead);
3545 					xattrp = NULL;
3546 					xattr_linkp = NULL;
3547 					xattrhead = NULL;
3548 				}
3549 #endif
3550 				continue;
3551 			}
3552 		newfile = ((fstatat(dirfd, comp,
3553 		    &xtractbuf, 0) == -1) ? TRUE : FALSE);
3554 		ofile = openat(dirfd, comp, O_RDWR|O_CREAT|O_TRUNC,
3555 		    stbuf.st_mode & MODEMASK);
3556 		saveerrno = errno;
3557 
3558 #if defined(O_XATTR)
3559 		if (xattrp != NULL) {
3560 			if (ofile < 0) {
3561 				ofile = retry_open_attr(dirfd, cwd,
3562 				    dirp, attrinfo->attr_parent, comp,
3563 				    O_RDWR|O_CREAT|O_TRUNC,
3564 				    stbuf.st_mode & MODEMASK);
3565 			}
3566 		}
3567 #endif
3568 		if (ofile < 0) {
3569 			errno = saveerrno;
3570 			(void) fprintf(stderr, gettext(
3571 			    "tar: %s%s%s%s - cannot create\n"),
3572 			    (xattrp == NULL) ? "" : (rw_sysattr ?
3573 			    gettext("system attribute ") :
3574 			    gettext("attribute ")),
3575 			    (xattrp == NULL) ? "" : xattrapath,
3576 			    (xattrp == NULL) ? "" : gettext(" of "),
3577 			    (xattrp == NULL) ? comp : namep);
3578 			if (errflag)
3579 				done(1);
3580 			else
3581 				Errflg = 1;
3582 #if defined(O_XATTR)
3583 			if (xattrp != NULL) {
3584 				dblock.dbuf.typeflag = _XATTR_HDRTYPE;
3585 				free(xattrhead);
3586 				xattrp = NULL;
3587 				xattr_linkp = NULL;
3588 				xattrhead = NULL;
3589 			}
3590 #endif
3591 			passtape();
3592 			continue;
3593 		}
3594 
3595 		if (Tflag && (check_ext_attr(namep) == 0)) {
3596 			if (errflag)
3597 				done(1);
3598 			else
3599 				Errflg = 1;
3600 			passtape();
3601 			continue;
3602 		}
3603 
3604 		if (extno != 0) {	/* file is in pieces */
3605 			if (extotal < 1 || extotal > MAXEXT)
3606 				(void) fprintf(stderr, gettext(
3607 				    "tar: ignoring bad extent info for "
3608 				    "%s%s%s%s\n"),
3609 				    (xattrp == NULL) ? "" : (rw_sysattr ?
3610 				    gettext("system attribute ") :
3611 				    gettext("attribute ")),
3612 				    (xattrp == NULL) ? "" : xattrapath,
3613 				    (xattrp == NULL) ? "" : gettext(" of "),
3614 				    (xattrp == NULL) ? comp : namep);
3615 			else {
3616 				/* extract it */
3617 				(void) xsfile(rw_sysattr, ofile);
3618 			}
3619 		}
3620 		extno = 0;	/* let everyone know file is not split */
3621 		bytes = stbuf.st_size;
3622 		blocks = TBLOCKS(bytes);
3623 		if (vflag) {
3624 			(void) fprintf(vfile,
3625 			    "x %s%s%s, %" FMT_off_t " %s, ",
3626 			    (xattrp == NULL) ? "" : dirp,
3627 			    (xattrp == NULL) ? "" : (rw_sysattr ?
3628 			    gettext(" system attribute ") :
3629 			    gettext(" attribute ")),
3630 			    (xattrp == NULL) ? namep : xattrapath, bytes,
3631 			    gettext("bytes"));
3632 			if (NotTape)
3633 				(void) fprintf(vfile, "%" FMT_blkcnt_t "K\n",
3634 				    K(blocks));
3635 			else
3636 				(void) fprintf(vfile, gettext("%"
3637 				    FMT_blkcnt_t " tape blocks\n"), blocks);
3638 		}
3639 
3640 		if (xblocks(rw_sysattr, bytes, ofile) != 0) {
3641 #if defined(O_XATTR)
3642 			if (xattrp != NULL) {
3643 				free(xattrhead);
3644 				xattrp = NULL;
3645 				xattr_linkp = NULL;
3646 				xattrhead = NULL;
3647 			}
3648 #endif
3649 			continue;
3650 		}
3651 filedone:
3652 		if (mflag == 0 && !symflag) {
3653 			if (dir)
3654 				doDirTimes(namep, stbuf.st_mtim);
3655 
3656 			else
3657 #if defined(O_XATTR)
3658 				if (xattrp != NULL) {
3659 					/*
3660 					 * Set the time on the attribute unless
3661 					 * the attribute is a system attribute
3662 					 * (can't successfully do this) or the
3663 					 * hidden attribute directory, "." (the
3664 					 * time on the hidden attribute
3665 					 * directory will be updated when
3666 					 * attributes are restored, otherwise
3667 					 * it's transient).
3668 					 */
3669 					if (!rw_sysattr && (Hiddendir == 0)) {
3670 						setPathTimes(dirfd, comp,
3671 						    stbuf.st_mtim);
3672 					}
3673 				} else
3674 					setPathTimes(dirfd, comp,
3675 					    stbuf.st_mtim);
3676 #else
3677 				setPathTimes(dirfd, comp, stbuf.st_mtim);
3678 #endif
3679 		}
3680 
3681 		/* moved this code from above */
3682 		if (pflag && !symflag && Hiddendir == 0) {
3683 			if (xattrp != NULL)
3684 				(void) fchmod(ofile, stbuf.st_mode & MODEMASK);
3685 			else
3686 				(void) chmod(namep, stbuf.st_mode & MODEMASK);
3687 		}
3688 
3689 
3690 		/*
3691 		 * Because ancillary file preceeds the normal file,
3692 		 * acl info may have been retrieved (in aclp).
3693 		 * All file types are directed here (go filedone).
3694 		 * Always restore ACLs if there are ACLs.
3695 		 */
3696 		if (aclp != NULL) {
3697 			int ret;
3698 
3699 #if defined(O_XATTR)
3700 			if (xattrp != NULL) {
3701 				if (Hiddendir)
3702 					ret = facl_set(dirfd, aclp);
3703 				else
3704 					ret = facl_set(ofile, aclp);
3705 			} else {
3706 				ret = acl_set(namep, aclp);
3707 			}
3708 #else
3709 			ret = acl_set(namep, aclp);
3710 #endif
3711 			if (ret < 0) {
3712 				if (pflag) {
3713 					(void) fprintf(stderr, gettext(
3714 					    "%s%s%s%s: failed to set acl "
3715 					    "entries\n"), namep,
3716 					    (xattrp == NULL) ? "" :
3717 					    (rw_sysattr ? gettext(
3718 					    " system attribute ") :
3719 					    gettext(" attribute ")),
3720 					    (xattrp == NULL) ? "" :
3721 					    xattrapath);
3722 				}
3723 				/* else: silent and continue */
3724 			}
3725 			acl_free(aclp);
3726 			aclp = NULL;
3727 		}
3728 
3729 		if (!oflag)
3730 		    resugname(dirfd, comp, symflag); /* set file ownership */
3731 
3732 		if (pflag && newfile == TRUE && !dir &&
3733 		    (dblock.dbuf.typeflag == '0' ||
3734 		    dblock.dbuf.typeflag == NULL ||
3735 		    convflag || dblock.dbuf.typeflag == '1')) {
3736 			if (fstat(ofile, &xtractbuf) == -1)
3737 				(void) fprintf(stderr, gettext(
3738 				    "tar: cannot stat extracted file "
3739 				    "%s%s%s%s\n"),
3740 				    (xattrp == NULL) ? "" : (rw_sysattr ?
3741 				    gettext("system attribute ") :
3742 				    gettext("attribute ")),
3743 				    (xattrp == NULL) ? "" : xattrapath,
3744 				    (xattrp == NULL) ? "" :
3745 				    gettext(" of "), namep);
3746 
3747 			else if ((xtractbuf.st_mode & (MODEMASK & ~S_IFMT))
3748 			    != (stbuf.st_mode & (MODEMASK & ~S_IFMT))) {
3749 				(void) fprintf(stderr, gettext(
3750 				    "tar: warning - file permissions have "
3751 				    "changed for %s%s%s%s (are 0%o, should be "
3752 				    "0%o)\n"),
3753 				    (xattrp == NULL) ? "" : (rw_sysattr ?
3754 				    gettext("system attribute ") :
3755 				    gettext("attribute ")),
3756 				    (xattrp == NULL) ? "" : xattrapath,
3757 				    (xattrp == NULL) ? "" :
3758 				    gettext(" of "), namep,
3759 				    xtractbuf.st_mode, stbuf.st_mode);
3760 
3761 			}
3762 		}
3763 #if defined(O_XATTR)
3764 		if (xattrp != NULL) {
3765 			free(xattrhead);
3766 			xattrp = NULL;
3767 			xattr_linkp = NULL;
3768 			xattrhead = NULL;
3769 		}
3770 #endif
3771 
3772 		if (ofile != -1) {
3773 			(void) close(dirfd);
3774 			dirfd = -1;
3775 			if (close(ofile) != 0)
3776 				vperror(2, gettext("close error"));
3777 			ofile = -1;
3778 		}
3779 		xcnt++;			/* increment # files extracted */
3780 		}
3781 
3782 		/*
3783 		 * Process ancillary file.
3784 		 *
3785 		 */
3786 
3787 		if (dblock.dbuf.typeflag == 'A') {	/* acl info */
3788 			char	buf[TBLOCK];
3789 			char	*secp;
3790 			char	*tp;
3791 			int	attrsize;
3792 			int	cnt;
3793 
3794 			/* reset Trusted Extensions flags */
3795 			dir_flag = 0;
3796 			mld_flag = 0;
3797 			lk_rpath_flag = 0;
3798 			rpath_flag = 0;
3799 
3800 			if (pflag) {
3801 				bytes = stbuf.st_size;
3802 				if ((secp = malloc((int)bytes)) == NULL) {
3803 					(void) fprintf(stderr, gettext(
3804 					    "Insufficient memory for acl\n"));
3805 					passtape();
3806 					continue;
3807 				}
3808 				tp = secp;
3809 				blocks = TBLOCKS(bytes);
3810 
3811 				/*
3812 				 * Display a line for each ancillary file.
3813 				 */
3814 				if (vflag && Tflag)
3815 					(void) fprintf(vfile, "x %s(A), %"
3816 					    FMT_blkcnt_t " %s, %"
3817 					    FMT_blkcnt_t " %s\n",
3818 					    namep, bytes, gettext("bytes"),
3819 					    blocks, gettext("tape blocks"));
3820 
3821 				while (blocks-- > 0) {
3822 					readtape(buf);
3823 					if (bytes <= TBLOCK) {
3824 						(void) memcpy(tp, buf,
3825 						    (size_t)bytes);
3826 						break;
3827 					} else {
3828 						(void) memcpy(tp, buf,
3829 						    TBLOCK);
3830 						tp += TBLOCK;
3831 					}
3832 					bytes -= TBLOCK;
3833 				}
3834 				bytes = stbuf.st_size;
3835 				/* got all attributes in secp */
3836 				tp = secp;
3837 				do {
3838 					attr = (struct sec_attr *)tp;
3839 					switch (attr->attr_type) {
3840 					case UFSD_ACL:
3841 					case ACE_ACL:
3842 						(void) sscanf(attr->attr_len,
3843 						    "%7o",
3844 						    (uint_t *)
3845 						    &cnt);
3846 						/* header is 8 */
3847 						attrsize = 8 + (int)strlen(
3848 						    &attr->attr_info[0]) + 1;
3849 						error =
3850 						    acl_fromtext(
3851 						    &attr->attr_info[0], &aclp);
3852 
3853 						if (error != 0) {
3854 							(void) fprintf(stderr,
3855 							    gettext(
3856 							    "aclfromtext "
3857 							    "failed: %s\n"),
3858 							    acl_strerror(
3859 							    error));
3860 							bytes -= attrsize;
3861 							break;
3862 						}
3863 						if (acl_cnt(aclp) != cnt) {
3864 							(void) fprintf(stderr,
3865 							    gettext(
3866 							    "aclcnt error\n"));
3867 							bytes -= attrsize;
3868 							break;
3869 						}
3870 						bytes -= attrsize;
3871 						break;
3872 
3873 					/* Trusted Extensions */
3874 
3875 					case DIR_TYPE:
3876 					case LBL_TYPE:
3877 					case APRIV_TYPE:
3878 					case FPRIV_TYPE:
3879 					case COMP_TYPE:
3880 					case LK_COMP_TYPE:
3881 					case ATTR_FLAG_TYPE:
3882 						attrsize =
3883 						    sizeof (struct sec_attr) +
3884 						    strlen(&attr->attr_info[0]);
3885 						bytes -= attrsize;
3886 						if (Tflag)
3887 							extract_attr(&namep,
3888 							    attr);
3889 						break;
3890 
3891 					default:
3892 						(void) fprintf(stderr, gettext(
3893 						    "unrecognized attr"
3894 						    " type\n"));
3895 						bytes = (off_t)0;
3896 						break;
3897 					}
3898 
3899 					/* next attributes */
3900 					tp += attrsize;
3901 				} while (bytes != 0);
3902 				free(secp);
3903 			} else {
3904 				passtape();
3905 			}
3906 		} /* acl */
3907 
3908 	} /* for */
3909 
3910 	/*
3911 	 *  Ensure that all the directories still on the directory stack
3912 	 *  get their modification times set correctly by flushing the
3913 	 *  stack.
3914 	 */
3915 
3916 	doDirTimes(NULL, time_zero);
3917 
3918 #if defined(O_XATTR)
3919 		if (xattrp != NULL) {
3920 			free(xattrhead);
3921 			xattrp = NULL;
3922 			xattr_linkp = NULL;
3923 			xattrhead = NULL;
3924 		}
3925 #endif
3926 
3927 	/*
3928 	 * Check if the number of files extracted is different from the
3929 	 * number of files listed on the command line
3930 	 */
3931 	if (fcnt > xcnt) {
3932 		(void) fprintf(stderr,
3933 		    gettext("tar: %d file(s) not extracted\n"),
3934 		fcnt-xcnt);
3935 		Errflg = 1;
3936 	}
3937 }
3938 
3939 /*
3940  *	xblocks		extract file/extent from tape to output file
3941  *
3942  *	xblocks(issysattr, bytes, ofile);
3943  *
3944  *	issysattr			flag set if the files being extracted
3945  *					is an extended system attribute file.
3946  *	unsigned long long bytes	size of extent or file to be extracted
3947  *	ofile				output file
3948  *
3949  *	called by doxtract() and xsfile()
3950  */
3951 
3952 static int
3953 xblocks(int issysattr, off_t bytes, int ofile)
3954 {
3955 	char *buf;
3956 	char tempname[NAMSIZ+1];
3957 	size_t maxwrite;
3958 	size_t bytesread;
3959 	size_t piosize;		/* preferred I/O size */
3960 	struct stat tsbuf;
3961 
3962 	/* Don't need to do anything if this is a zero size file */
3963 	if (bytes <= 0) {
3964 		return (0);
3965 	}
3966 
3967 	/*
3968 	 * To figure out the size of the buffer used to accumulate data
3969 	 * from readtape() and to write to the file, we need to determine
3970 	 * the largest chunk of data to be written to the file at one time.
3971 	 * This is determined based on the smallest of the following two
3972 	 * things:
3973 	 *	1) The size of the archived file.
3974 	 *	2) The preferred I/O size of the file.
3975 	 */
3976 	if (issysattr || (bytes <= TBLOCK)) {
3977 		/*
3978 		 * Writes to system attribute files must be
3979 		 * performed in one operation.
3980 		 */
3981 		maxwrite = bytes;
3982 	} else {
3983 		/*
3984 		 * fstat() the file to get the preferred I/O size.
3985 		 * If it fails, then resort back to just writing
3986 		 * one block at a time.
3987 		 */
3988 		if (fstat(ofile, &tsbuf) == 0) {
3989 			piosize = tsbuf.st_blksize;
3990 		} else {
3991 			piosize = TBLOCK;
3992 		}
3993 		maxwrite = min(bytes, piosize);
3994 	}
3995 
3996 	/*
3997 	 * The buffer used to accumulate the data for the write operation
3998 	 * needs to be the maximum number of bytes to be written rounded up
3999 	 * to the nearest TBLOCK since readtape reads one block at a time.
4000 	 */
4001 	if ((buf = malloc(TBLOCKS(maxwrite) * TBLOCK)) == NULL) {
4002 		fatal(gettext("cannot allocate buffer"));
4003 	}
4004 
4005 	while (bytes > 0) {
4006 
4007 		/*
4008 		 * readtape() obtains one block (TBLOCK) of data at a time.
4009 		 * Accumulate as many blocks of data in buf as we can write
4010 		 * in one operation.
4011 		 */
4012 		for (bytesread = 0; bytesread < maxwrite; bytesread += TBLOCK) {
4013 			readtape(buf + bytesread);
4014 		}
4015 
4016 		if (write(ofile, buf, maxwrite) < 0) {
4017 			int saveerrno = errno;
4018 
4019 			if (xhdr_flgs & _X_PATH)
4020 				(void) strlcpy(tempname, Xtarhdr.x_path,
4021 				    sizeof (tempname));
4022 			else
4023 				(void) sprintf(tempname, "%.*s", NAMSIZ,
4024 				    dblock.dbuf.name);
4025 			/*
4026 			 * If the extended system attribute being extracted
4027 			 * contains attributes that the user needs privileges
4028 			 * for, then just display a warning message, skip
4029 			 * the extraction of this file, and return.
4030 			 */
4031 			if ((saveerrno == EPERM) && issysattr) {
4032 				(void) fprintf(stderr, gettext(
4033 				    "tar: unable to extract system attribute "
4034 				    "%s: insufficient privileges\n"), tempname);
4035 				Errflg = 1;
4036 				(void) free(buf);
4037 				return (1);
4038 			} else {
4039 				(void) fprintf(stderr, gettext(
4040 				    "tar: %s: HELP - extract write error\n"),
4041 				    tempname);
4042 				done(2);
4043 			}
4044 		}
4045 		bytes -= maxwrite;
4046 
4047 		/*
4048 		 * If we've reached this point and there is still data
4049 		 * to be written, maxwrite had to have been determined
4050 		 * by the preferred I/O size.  If the number of bytes
4051 		 * left to write is smaller than the preferred I/O size,
4052 		 * then we're about to do our final write to the file, so
4053 		 * just set maxwrite to the number of bytes left to write.
4054 		 */
4055 		if ((bytes > 0) && (bytes < maxwrite)) {
4056 			maxwrite = bytes;
4057 		}
4058 	}
4059 	free(buf);
4060 
4061 	return (0);
4062 }
4063 
4064 /*
4065  * 	xsfile	extract split file
4066  *
4067  *	xsfile(ofd);	ofd = output file descriptor
4068  *
4069  *	file extracted and put in ofd via xblocks()
4070  *
4071  *	NOTE:  only called by doxtract() to extract one large file
4072  */
4073 
4074 static	union	hblock	savedblock;	/* to ensure same file across volumes */
4075 
4076 static int
4077 xsfile(int issysattr, int ofd)
4078 {
4079 	int i, c;
4080 	int sysattrerr = 0;
4081 	char name[PATH_MAX+1];	/* holds name for diagnostics */
4082 	int extents, totalext;
4083 	off_t bytes, totalbytes;
4084 
4085 	if (xhdr_flgs & _X_PATH)
4086 		(void) strcpy(name, Xtarhdr.x_path);
4087 	else
4088 		(void) sprintf(name, "%.*s", NAMSIZ, dblock.dbuf.name);
4089 
4090 	totalbytes = (off_t)0;		/* in case we read in half the file */
4091 	totalext = 0;		/* these keep count */
4092 
4093 	(void) fprintf(stderr, gettext(
4094 	    "tar: %s split across %d volumes\n"), name, extotal);
4095 
4096 	/* make sure we do extractions in order */
4097 	if (extno != 1) {	/* starting in middle of file? */
4098 		(void) printf(gettext(
4099 		    "tar: first extent read is not #1\n"
4100 		    "OK to read file beginning with extent #%d (%s/%s) ? "),
4101 		    extno, yesstr, nostr);
4102 		if (yes() == 0) {
4103 canit:
4104 			passtape();
4105 			if (close(ofd) != 0)
4106 				vperror(2, gettext("close error"));
4107 			if (sysattrerr) {
4108 				return (1);
4109 			} else {
4110 				return (0);
4111 			}
4112 		}
4113 	}
4114 	extents = extotal;
4115 	i = extno;
4116 	/*CONSTCOND*/
4117 	while (1) {
4118 		if (xhdr_flgs & _X_SIZE) {
4119 			bytes = extsize;
4120 		} else {
4121 			bytes = stbuf.st_size;
4122 		}
4123 
4124 		if (vflag)
4125 			(void) fprintf(vfile, "+++ x %s [%s #%d], %"
4126 			    FMT_off_t " %s, %ldK\n",
4127 			    name, gettext("extent"), extno,
4128 			    bytes, gettext("bytes"),
4129 			    (long)K(TBLOCKS(bytes)));
4130 		if (xblocks(issysattr, bytes, ofd) != 0) {
4131 			sysattrerr = 1;
4132 			goto canit;
4133 		}
4134 
4135 		totalbytes += bytes;
4136 		totalext++;
4137 		if (++i > extents)
4138 			break;
4139 
4140 		/* get next volume and verify it's the right one */
4141 		copy(&savedblock, &dblock);
4142 tryagain:
4143 		newvol();
4144 		xhdr_flgs = 0;
4145 		getdir();
4146 		if (Xhdrflag > 0)
4147 			(void) get_xdata();	/* Get x-header & regular hdr */
4148 		if ((dblock.dbuf.typeflag != 'A') && (xhdr_flgs != 0)) {
4149 			load_info_from_xtarhdr(xhdr_flgs, &Xtarhdr);
4150 			xhdr_flgs |= _X_XHDR;
4151 		}
4152 		if (endtape()) {	/* seemingly empty volume */
4153 			(void) fprintf(stderr, gettext(
4154 			    "tar: first record is null\n"));
4155 asknicely:
4156 			(void) fprintf(stderr, gettext(
4157 			    "tar: need volume with extent #%d of %s\n"),
4158 			    i, name);
4159 			goto tryagain;
4160 		}
4161 		if (notsame()) {
4162 			(void) fprintf(stderr, gettext(
4163 			    "tar: first file on that volume is not "
4164 			    "the same file\n"));
4165 			goto asknicely;
4166 		}
4167 		if (i != extno) {
4168 			(void) fprintf(stderr, gettext(
4169 			    "tar: extent #%d received out of order\ntar: "
4170 			    "should be #%d\n"), extno, i);
4171 			(void) fprintf(stderr, gettext(
4172 			    "Ignore error, Abort this file, or "
4173 			    "load New volume (i/a/n) ? "));
4174 			c = response();
4175 			if (c == 'a')
4176 				goto canit;
4177 			if (c != 'i')		/* default to new volume */
4178 				goto asknicely;
4179 			i = extno;		/* okay, start from there */
4180 		}
4181 	}
4182 	if (vflag)
4183 		(void) fprintf(vfile, gettext(
4184 		    "x %s (in %d extents), %" FMT_off_t " bytes, %ldK\n"),
4185 		    name, totalext, totalbytes, (long)K(TBLOCKS(totalbytes)));
4186 
4187 	return (0);
4188 }
4189 
4190 
4191 /*
4192  *	notsame()	check if extract file extent is invalid
4193  *
4194  *	returns true if anything differs between savedblock and dblock
4195  *	except extno (extent number), checksum, or size (extent size).
4196  *	Determines if this header belongs to the same file as the one we're
4197  *	extracting.
4198  *
4199  *	NOTE:	though rather bulky, it is only called once per file
4200  *		extension, and it can withstand changes in the definition
4201  *		of the header structure.
4202  *
4203  *	WARNING:	this routine is local to xsfile() above
4204  */
4205 
4206 static int
4207 notsame(void)
4208 {
4209 	return (
4210 	    (strncmp(savedblock.dbuf.name, dblock.dbuf.name, NAMSIZ)) ||
4211 	    (strcmp(savedblock.dbuf.mode, dblock.dbuf.mode)) ||
4212 	    (strcmp(savedblock.dbuf.uid, dblock.dbuf.uid)) ||
4213 	    (strcmp(savedblock.dbuf.gid, dblock.dbuf.gid)) ||
4214 	    (strcmp(savedblock.dbuf.mtime, dblock.dbuf.mtime)) ||
4215 	    (savedblock.dbuf.typeflag != dblock.dbuf.typeflag) ||
4216 	    (strncmp(savedblock.dbuf.linkname, dblock.dbuf.linkname, NAMSIZ)) ||
4217 	    (savedblock.dbuf.extotal != dblock.dbuf.extotal) ||
4218 	    (strcmp(savedblock.dbuf.efsize, dblock.dbuf.efsize)));
4219 }
4220 
4221 static void
4222 #ifdef	_iBCS2
4223 dotable(char *argv[], int tbl_cnt)
4224 #else
4225 dotable(char *argv[])
4226 #endif
4227 
4228 {
4229 	int tcnt;			/* count # files tabled */
4230 	int fcnt;			/* count # files in argv list */
4231 	char *namep, *dirp, *comp;
4232 	int want;
4233 	char aclchar = ' ';			/* either blank or '+' */
4234 	char templink[PATH_MAX+1];
4235 	attr_data_t *attrinfo = NULL;
4236 
4237 	dumping = 0;
4238 
4239 	/* if not on magtape, maximize seek speed */
4240 	if (NotTape && !bflag) {
4241 #if SYS_BLOCK > TBLOCK
4242 		nblock = SYS_BLOCK / TBLOCK;
4243 #else
4244 		nblock = 1;
4245 #endif
4246 	}
4247 	/*
4248 	 * Count the number of files that are to be tabled
4249 	 */
4250 	fcnt = tcnt = 0;
4251 
4252 #ifdef	_iBCS2
4253 	initarg(argv, Filefile);
4254 	while (nextarg() != NULL)
4255 		++fcnt;
4256 	fcnt += tbl_cnt;
4257 #endif	/*  _iBCS2 */
4258 
4259 	for (;;) {
4260 
4261 		/* namep is set by wantit to point to the full name */
4262 		if ((want = wantit(argv, &namep, &dirp, &comp, &attrinfo)) == 0)
4263 			continue;
4264 		if (want == -1)
4265 			break;
4266 		if (dblock.dbuf.typeflag != 'A')
4267 			++tcnt;
4268 
4269 		if (Fflag) {
4270 			if (checkf(namep, is_directory(namep), Fflag) == 0) {
4271 				passtape();
4272 				continue;
4273 			}
4274 		}
4275 		/*
4276 		 * ACL support:
4277 		 * aclchar is introduced to indicate if there are
4278 		 * acl entries. longt() now takes one extra argument.
4279 		 */
4280 		if (vflag) {
4281 			if (dblock.dbuf.typeflag == 'A') {
4282 				aclchar = '+';
4283 				passtape();
4284 				continue;
4285 			}
4286 			longt(&stbuf, aclchar);
4287 			aclchar = ' ';
4288 		}
4289 
4290 
4291 #if defined(O_XATTR)
4292 		if (xattrp != NULL) {
4293 			int	issysattr;
4294 			char	*bn = basename(attrinfo->attr_path);
4295 
4296 			/*
4297 			 * We could use sysattr_type() to test whether or not
4298 			 * the attribute we are processing is really an
4299 			 * extended system attribute, which as of this writing
4300 			 * just does a strcmp(), however, sysattr_type() may
4301 			 * be changed to issue a pathconf() call instead, which
4302 			 * would require being changed into the parent attribute
4303 			 * directory.  So instead, just do simple string
4304 			 * comparisons to see if we are processing an extended
4305 			 * system attribute.
4306 			 */
4307 			issysattr = is_sysattr(bn);
4308 
4309 			(void) printf(gettext("%s %sattribute %s"),
4310 			    xattrp->h_names,
4311 			    issysattr ? gettext("system ") : "",
4312 			    attrinfo->attr_path);
4313 		} else {
4314 			(void) printf("%s", namep);
4315 		}
4316 #else
4317 			(void) printf("%s", namep);
4318 #endif
4319 
4320 		if (extno != 0) {
4321 			if (vflag) {
4322 				/* keep the '\n' for backwards compatibility */
4323 				(void) fprintf(vfile, gettext(
4324 				    "\n [extent #%d of %d]"), extno, extotal);
4325 			} else {
4326 				(void) fprintf(vfile, gettext(
4327 				    " [extent #%d of %d]"), extno, extotal);
4328 			}
4329 		}
4330 		if (xhdr_flgs & _X_LINKPATH) {
4331 			(void) strcpy(templink, Xtarhdr.x_linkpath);
4332 		} else {
4333 #if defined(O_XATTR)
4334 			if (xattrp != NULL) {
4335 				(void) sprintf(templink,
4336 				    "file %.*s", NAMSIZ, xattrp->h_names);
4337 			} else {
4338 				(void) sprintf(templink, "%.*s", NAMSIZ,
4339 				    dblock.dbuf.linkname);
4340 			}
4341 #else
4342 			(void) sprintf(templink, "%.*s", NAMSIZ,
4343 			    dblock.dbuf.linkname);
4344 #endif
4345 			templink[NAMSIZ] = '\0';
4346 		}
4347 		if (dblock.dbuf.typeflag == '1') {
4348 			/*
4349 			 * TRANSLATION_NOTE
4350 			 *	Subject is omitted here.
4351 			 *	Translate this as if
4352 			 *		<subject> linked to %s
4353 			 */
4354 #if defined(O_XATTR)
4355 			if (xattrp != NULL) {
4356 				(void) printf(
4357 				    gettext(" linked to attribute %s"),
4358 				    xattr_linkp->h_names +
4359 				    strlen(xattr_linkp->h_names) + 1);
4360 			} else {
4361 				(void) printf(
4362 				    gettext(" linked to %s"), templink);
4363 			}
4364 #else
4365 				(void) printf(
4366 				    gettext(" linked to %s"), templink);
4367 
4368 #endif
4369 		}
4370 		if (dblock.dbuf.typeflag == '2')
4371 			(void) printf(gettext(
4372 			/*
4373 			 * TRANSLATION_NOTE
4374 			 *	Subject is omitted here.
4375 			 *	Translate this as if
4376 			 *		<subject> symbolic link to %s
4377 			 */
4378 			" symbolic link to %s"), templink);
4379 		(void) printf("\n");
4380 #if defined(O_XATTR)
4381 		if (xattrp != NULL) {
4382 			free(xattrhead);
4383 			xattrp = NULL;
4384 			xattrhead = NULL;
4385 		}
4386 #endif
4387 		passtape();
4388 	}
4389 	/*
4390 	 * Check if the number of files tabled is different from the
4391 	 * number of files listed on the command line
4392 	 */
4393 	if (fcnt > tcnt) {
4394 		(void) fprintf(stderr, gettext(
4395 		    "tar: %d file(s) not found\n"), fcnt-tcnt);
4396 		Errflg = 1;
4397 	}
4398 }
4399 
4400 static void
4401 putempty(blkcnt_t n)
4402 {
4403 	char buf[TBLOCK];
4404 	char *cp;
4405 
4406 	for (cp = buf; cp < &buf[TBLOCK]; )
4407 		*cp++ = '\0';
4408 	while (n-- > 0)
4409 		(void) writetbuf(buf, 1);
4410 }
4411 
4412 static	ushort_t	Ftype = S_IFMT;
4413 
4414 static	void
4415 verbose(struct stat *st, char aclchar)
4416 {
4417 	int i, j, temp;
4418 	mode_t mode;
4419 	char modestr[12];
4420 
4421 	for (i = 0; i < 11; i++)
4422 		modestr[i] = '-';
4423 	modestr[i] = '\0';
4424 
4425 	/* a '+' sign is printed if there is ACL */
4426 	modestr[i-1] = aclchar;
4427 
4428 	mode = st->st_mode;
4429 	for (i = 0; i < 3; i++) {
4430 		temp = (mode >> (6 - (i * 3)));
4431 		j = (i * 3) + 1;
4432 		if (S_IROTH & temp)
4433 			modestr[j] = 'r';
4434 		if (S_IWOTH & temp)
4435 			modestr[j + 1] = 'w';
4436 		if (S_IXOTH & temp)
4437 			modestr[j + 2] = 'x';
4438 	}
4439 	temp = st->st_mode & Ftype;
4440 	switch (temp) {
4441 	case (S_IFIFO):
4442 		modestr[0] = 'p';
4443 		break;
4444 	case (S_IFCHR):
4445 		modestr[0] = 'c';
4446 		break;
4447 	case (S_IFDIR):
4448 		modestr[0] = 'd';
4449 		break;
4450 	case (S_IFBLK):
4451 		modestr[0] = 'b';
4452 		break;
4453 	case (S_IFREG): /* was initialized to '-' */
4454 		break;
4455 	case (S_IFLNK):
4456 		modestr[0] = 'l';
4457 		break;
4458 	default:
4459 		/* This field may be zero in old archives. */
4460 		if (is_posix && dblock.dbuf.typeflag != '1') {
4461 			/*
4462 			 * For POSIX compliant archives, the mode field
4463 			 * consists of 12 bits, ie:  the file type bits
4464 			 * are not stored in dblock.dbuf.mode.
4465 			 * For files other than hard links, getdir() sets
4466 			 * the file type bits in the st_mode field of the
4467 			 * stat structure based upon dblock.dbuf.typeflag.
4468 			 */
4469 			(void) fprintf(stderr, gettext(
4470 			    "tar: impossible file type"));
4471 		}
4472 	}
4473 
4474 	if ((S_ISUID & Gen.g_mode) == S_ISUID)
4475 		modestr[3] = 's';
4476 	if ((S_ISVTX & Gen.g_mode) == S_ISVTX)
4477 		modestr[9] = 't';
4478 	if ((S_ISGID & Gen.g_mode) == S_ISGID && modestr[6] == 'x')
4479 		modestr[6] = 's';
4480 	else if ((S_ENFMT & Gen.g_mode) == S_ENFMT && modestr[6] != 'x')
4481 		modestr[6] = 'l';
4482 	(void) fprintf(vfile, "%s", modestr);
4483 }
4484 
4485 static void
4486 longt(struct stat *st, char aclchar)
4487 {
4488 	char fileDate[30];
4489 	struct tm *tm;
4490 
4491 	verbose(st, aclchar);
4492 	(void) fprintf(vfile, "%3ld/%-3ld", st->st_uid, st->st_gid);
4493 
4494 	if (dblock.dbuf.typeflag == '2') {
4495 		if (xhdr_flgs & _X_LINKPATH)
4496 			st->st_size = (off_t)strlen(Xtarhdr.x_linkpath);
4497 		else
4498 			st->st_size = (off_t)(memchr(dblock.dbuf.linkname,
4499 			    '\0', NAMSIZ) ?
4500 			    (strlen(dblock.dbuf.linkname)) : (NAMSIZ));
4501 	}
4502 	(void) fprintf(vfile, " %6" FMT_off_t, st->st_size);
4503 
4504 	tm = localtime(&(st->st_mtime));
4505 	(void) strftime(fileDate, sizeof (fileDate),
4506 	    dcgettext((const char *)0, "%b %e %R %Y", LC_TIME), tm);
4507 	(void) fprintf(vfile, " %s ", fileDate);
4508 }
4509 
4510 
4511 /*
4512  *  checkdir - Attempt to ensure that the path represented in name
4513  *             exists, and return 1 if this is true and name itself is a
4514  *             directory.
4515  *             Return 0 if this path cannot be created or if name is not
4516  *             a directory.
4517  */
4518 
4519 static int
4520 checkdir(char *name)
4521 {
4522 	char lastChar;		   /* the last character in name */
4523 	char *cp;		   /* scratch pointer into name */
4524 	char *firstSlash = NULL;   /* first slash in name */
4525 	char *lastSlash = NULL;	   /* last slash in name */
4526 	int  nameLen;		   /* length of name */
4527 	int  trailingSlash;	   /* true if name ends in slash */
4528 	int  leadingSlash;	   /* true if name begins with slash */
4529 	int  markedDir;		   /* true if name denotes a directory */
4530 	int  success;		   /* status of makeDir call */
4531 
4532 
4533 	/*
4534 	 *  Scan through the name, and locate first and last slashes.
4535 	 */
4536 
4537 	for (cp = name; *cp; cp++) {
4538 		if (*cp == '/') {
4539 			if (! firstSlash) {
4540 				firstSlash = cp;
4541 			}
4542 			lastSlash = cp;
4543 		}
4544 	}
4545 
4546 	/*
4547 	 *  Determine what you can from the proceeds of the scan.
4548 	 */
4549 
4550 	lastChar	= *(cp - 1);
4551 	nameLen		= (int)(cp - name);
4552 	trailingSlash	= (lastChar == '/');
4553 	leadingSlash	= (*name == '/');
4554 	markedDir	= (dblock.dbuf.typeflag == '5' || trailingSlash);
4555 
4556 	if (! lastSlash && ! markedDir) {
4557 		/*
4558 		 *  The named file does not have any subdrectory
4559 		 *  structure; just bail out.
4560 		 */
4561 
4562 		return (0);
4563 	}
4564 
4565 	/*
4566 	 *  Make sure that name doesn`t end with slash for the loop.
4567 	 *  This ensures that the makeDir attempt after the loop is
4568 	 *  meaningful.
4569 	 */
4570 
4571 	if (trailingSlash) {
4572 		name[nameLen-1] = '\0';
4573 	}
4574 
4575 	/*
4576 	 *  Make the path one component at a time.
4577 	 */
4578 
4579 	for (cp = strchr(leadingSlash ? name+1 : name, '/');
4580 	    cp;
4581 	    cp = strchr(cp+1, '/')) {
4582 		*cp = '\0';
4583 		success = makeDir(name);
4584 		*cp = '/';
4585 
4586 		if (!success) {
4587 			name[nameLen-1] = lastChar;
4588 			return (0);
4589 		}
4590 	}
4591 
4592 	/*
4593 	 *  This makes the last component of the name, if it is a
4594 	 *  directory.
4595 	 */
4596 
4597 	if (markedDir) {
4598 		if (! makeDir(name)) {
4599 			name[nameLen-1] = lastChar;
4600 			return (0);
4601 		}
4602 	}
4603 
4604 	name[nameLen-1] = (lastChar == '/') ? '\0' : lastChar;
4605 	return (markedDir);
4606 }
4607 
4608 /*
4609  * resugname - Restore the user name and group name.  Search the NIS
4610  *             before using the uid and gid.
4611  *             (It is presumed that an archive entry cannot be
4612  *	       simultaneously a symlink and some other type.)
4613  */
4614 
4615 static void
4616 resugname(int dirfd, 	/* dir fd file resides in */
4617 	char *name,	/* name of the file to be modified */
4618 	int symflag)	/* true if file is a symbolic link */
4619 {
4620 	uid_t duid;
4621 	gid_t dgid;
4622 	struct stat *sp = &stbuf;
4623 	char	*u_g_name;
4624 
4625 	if (checkflag == 1) { /* Extended tar format and euid == 0 */
4626 
4627 		/*
4628 		 * Try and extract the intended uid and gid from the name
4629 		 * service before believing the uid and gid in the header.
4630 		 *
4631 		 * In the case where we archived a setuid or setgid file
4632 		 * owned by someone with a large uid, then it will
4633 		 * have made it into the archive with a uid of nobody.  If
4634 		 * the corresponding username doesn't appear to exist, then we
4635 		 * want to make sure it *doesn't* end up as setuid nobody!
4636 		 *
4637 		 * Our caller will print an error message about the fact
4638 		 * that the restore didn't work out quite right ..
4639 		 */
4640 		if (xhdr_flgs & _X_UNAME)
4641 			u_g_name = Xtarhdr.x_uname;
4642 		else
4643 			u_g_name = dblock.dbuf.uname;
4644 		if ((duid = getuidbyname(u_g_name)) == -1) {
4645 			if (S_ISREG(sp->st_mode) && sp->st_uid == UID_NOBODY &&
4646 			    (sp->st_mode & S_ISUID) == S_ISUID)
4647 				(void) chmod(name,
4648 				    MODEMASK & sp->st_mode & ~S_ISUID);
4649 			duid = sp->st_uid;
4650 		}
4651 
4652 		/* (Ditto for gids) */
4653 
4654 		if (xhdr_flgs & _X_GNAME)
4655 			u_g_name = Xtarhdr.x_gname;
4656 		else
4657 			u_g_name = dblock.dbuf.gname;
4658 		if ((dgid = getgidbyname(u_g_name)) == -1) {
4659 			if (S_ISREG(sp->st_mode) && sp->st_gid == GID_NOBODY &&
4660 			    (sp->st_mode & S_ISGID) == S_ISGID)
4661 				(void) chmod(name,
4662 				    MODEMASK & sp->st_mode & ~S_ISGID);
4663 			dgid = sp->st_gid;
4664 		}
4665 	} else if (checkflag == 2) { /* tar format and euid == 0 */
4666 		duid = sp->st_uid;
4667 		dgid = sp->st_gid;
4668 	}
4669 	if ((checkflag == 1) || (checkflag == 2))
4670 		(void) fchownat(dirfd, name, duid, dgid, symflag);
4671 }
4672 
4673 /*ARGSUSED*/
4674 static void
4675 onintr(int sig)
4676 {
4677 	(void) signal(SIGINT, SIG_IGN);
4678 	term++;
4679 }
4680 
4681 /*ARGSUSED*/
4682 static void
4683 onquit(int sig)
4684 {
4685 	(void) signal(SIGQUIT, SIG_IGN);
4686 	term++;
4687 }
4688 
4689 /*ARGSUSED*/
4690 static void
4691 onhup(int sig)
4692 {
4693 	(void) signal(SIGHUP, SIG_IGN);
4694 	term++;
4695 }
4696 
4697 static void
4698 tomodes(struct stat *sp)
4699 {
4700 	uid_t uid;
4701 	gid_t gid;
4702 
4703 	bzero(dblock.dummy, TBLOCK);
4704 
4705 	/*
4706 	 * If the uid or gid is too large, we can't put it into
4707 	 * the archive.  We could fail to put anything in the
4708 	 * archive at all .. but most of the time the name service
4709 	 * will save the day when we do a lookup at restore time.
4710 	 *
4711 	 * Instead we choose a "safe" uid and gid, and fix up whether
4712 	 * or not the setuid and setgid bits are left set to extraction
4713 	 * time.
4714 	 */
4715 	if (Eflag) {
4716 		if ((ulong_t)(uid = sp->st_uid) > (ulong_t)OCTAL7CHAR) {
4717 			xhdr_flgs |= _X_UID;
4718 			Xtarhdr.x_uid = uid;
4719 		}
4720 		if ((ulong_t)(gid = sp->st_gid) > (ulong_t)OCTAL7CHAR) {
4721 			xhdr_flgs |= _X_GID;
4722 			Xtarhdr.x_gid = gid;
4723 		}
4724 		if (sp->st_size > TAR_OFFSET_MAX) {
4725 			xhdr_flgs |= _X_SIZE;
4726 			Xtarhdr.x_filesz = sp->st_size;
4727 			(void) sprintf(dblock.dbuf.size, "%011" FMT_off_t_o,
4728 			    (off_t)0);
4729 		} else
4730 			(void) sprintf(dblock.dbuf.size, "%011" FMT_off_t_o,
4731 			    sp->st_size);
4732 	} else {
4733 		(void) sprintf(dblock.dbuf.size, "%011" FMT_off_t_o,
4734 		    sp->st_size);
4735 	}
4736 	if ((ulong_t)(uid = sp->st_uid) > (ulong_t)OCTAL7CHAR)
4737 		uid = UID_NOBODY;
4738 	if ((ulong_t)(gid = sp->st_gid) > (ulong_t)OCTAL7CHAR)
4739 		gid = GID_NOBODY;
4740 	(void) sprintf(dblock.dbuf.gid, "%07lo", gid);
4741 	(void) sprintf(dblock.dbuf.uid, "%07lo", uid);
4742 	(void) sprintf(dblock.dbuf.mode, "%07lo", sp->st_mode & POSIXMODES);
4743 	(void) sprintf(dblock.dbuf.mtime, "%011lo", sp->st_mtime);
4744 }
4745 
4746 static	int
4747 #ifdef	EUC
4748 /*
4749  * Warning:  the result of this function depends whether 'char' is a
4750  * signed or unsigned data type.  This a source of potential
4751  * non-portability among heterogeneous systems.  It is retained here
4752  * for backward compatibility.
4753  */
4754 checksum_signed(union hblock *dblockp)
4755 #else
4756 checksum(union hblock *dblockp)
4757 #endif	/* EUC */
4758 {
4759 	int i;
4760 	char *cp;
4761 
4762 	for (cp = dblockp->dbuf.chksum;
4763 	    cp < &dblockp->dbuf.chksum[sizeof (dblockp->dbuf.chksum)]; cp++)
4764 		*cp = ' ';
4765 	i = 0;
4766 	for (cp = dblockp->dummy; cp < &(dblockp->dummy[TBLOCK]); cp++)
4767 		i += *cp;
4768 	return (i);
4769 }
4770 
4771 #ifdef	EUC
4772 /*
4773  * Generate unsigned checksum, regardless of what C compiler is
4774  * used.  Survives in the face of arbitrary 8-bit clean filenames,
4775  * e.g., internationalized filenames.
4776  */
4777 static int
4778 checksum(union hblock *dblockp)
4779 {
4780 	unsigned i;
4781 	unsigned char *cp;
4782 
4783 	for (cp = (unsigned char *) dblockp->dbuf.chksum;
4784 	    cp < (unsigned char *)
4785 	    &(dblockp->dbuf.chksum[sizeof (dblockp->dbuf.chksum)]); cp++)
4786 		*cp = ' ';
4787 	i = 0;
4788 	for (cp = (unsigned char *) dblockp->dummy;
4789 	    cp < (unsigned char *) &(dblockp->dummy[TBLOCK]); cp++)
4790 		i += *cp;
4791 
4792 	return (i);
4793 }
4794 #endif	/* EUC */
4795 
4796 /*
4797  * If the w flag is set, output the action to be taken and the name of the
4798  * file.  Perform the action if the user response is affirmative.
4799  */
4800 
4801 static int
4802 checkw(char c, char *name)
4803 {
4804 	if (wflag) {
4805 		(void) fprintf(vfile, "%c ", c);
4806 		if (vflag)
4807 			longt(&stbuf, ' ');	/* do we have acl info here */
4808 		(void) fprintf(vfile, "%s: ", name);
4809 		if (yes() == 1) {
4810 			return (1);
4811 		}
4812 		return (0);
4813 	}
4814 	return (1);
4815 }
4816 
4817 /*
4818  * When the F flag is set, exclude RCS and SCCS directories (and any files
4819  * or directories under them).  If F is set twice, also exclude .o files,
4820  * and files names errs, core, and a.out.
4821  *
4822  * Return 0 if file should be excluded, 1 otherwise.
4823  */
4824 
4825 static int
4826 checkf(char *longname, int is_dir, int howmuch)
4827 {
4828 	static char fullname[PATH_MAX + 1];
4829 	char *dir, *name;
4830 
4831 #if defined(O_XATTR)
4832 	/*
4833 	 * If there is an xattr_buf structure associated with this file,
4834 	 * always return 1.
4835 	 */
4836 	if (xattrp) {
4837 		return (1);
4838 	}
4839 #endif
4840 
4841 	/*
4842 	 * First check to see if the base name is an RCS or SCCS directory.
4843 	 */
4844 	if (strlcpy(fullname, longname, sizeof (fullname)) >= sizeof (fullname))
4845 		return (1);
4846 
4847 	name = basename(fullname);
4848 	if (is_dir) {
4849 		if ((strcmp(name, "SCCS") == 0) || (strcmp(name, "RCS") == 0))
4850 			return (0);
4851 	}
4852 
4853 	/*
4854 	 * If two -F command line options were given then exclude .o files,
4855 	 * and files named errs, core, and a.out.
4856 	 */
4857 	if (howmuch > 1 && !is_dir) {
4858 		size_t l = strlen(name);
4859 
4860 		if (l >= 3 && name[l - 2] == '.' && name[l - 1] == 'o')
4861 			return (0);
4862 		if (strcmp(name, "core") == 0 || strcmp(name, "errs") == 0 ||
4863 		    strcmp(name, "a.out") == 0)
4864 			return (0);
4865 	}
4866 
4867 	/*
4868 	 * At this point, check to see if this file has a parent directory
4869 	 * named RCS or SCCS.  If so, then this file should be excluded too.
4870 	 * The strcpy() operation is done again, because basename(3C) may
4871 	 * modify the path string passed to it.
4872 	 */
4873 	if (strlcpy(fullname, longname, sizeof (fullname)) >= sizeof (fullname))
4874 		return (1);
4875 
4876 	dir = dirname(fullname);
4877 	while (strcmp(dir, ".") != 0) {
4878 		name = basename(dir);
4879 		if ((strcmp(name, "SCCS") == 0) || (strcmp(name, "RCS") == 0))
4880 			return (0);
4881 		dir = dirname(dir);
4882 	}
4883 
4884 	return (1);
4885 }
4886 
4887 static int
4888 response(void)
4889 {
4890 	int c;
4891 
4892 	c = getchar();
4893 	if (c != '\n')
4894 		while (getchar() != '\n')
4895 			;
4896 	else c = 'n';
4897 	return ((c >= 'A' && c <= 'Z') ? c + ('a'-'A') : c);
4898 }
4899 
4900 /* Has file been modified since being put into archive? If so, return > 0. */
4901 
4902 static off_t	lookup(char *);
4903 
4904 static int
4905 checkupdate(char *arg)
4906 {
4907 	char name[PATH_MAX+1];
4908 	time_t	mtime;
4909 	long nsecs;
4910 	off_t seekp;
4911 
4912 	rewind(tfile);
4913 	if ((seekp = lookup(arg)) < 0)
4914 		return (1);
4915 	(void) fseek(tfile, seekp, 0);
4916 	(void) fscanf(tfile, "%s %ld.%ld", name, &mtime, &nsecs);
4917 
4918 	/*
4919 	 * Unless nanoseconds were stored in the file, only use seconds for
4920 	 * comparison of time.  Nanoseconds are stored when -E is specified.
4921 	 */
4922 	if (Eflag == 0)
4923 		return (stbuf.st_mtime > mtime);
4924 
4925 	if ((stbuf.st_mtime < mtime) ||
4926 	    ((stbuf.st_mtime == mtime) && (stbuf.st_mtim.tv_nsec <= nsecs)))
4927 		return (0);
4928 	return (1);
4929 }
4930 
4931 
4932 /*
4933  *	newvol	get new floppy (or tape) volume
4934  *
4935  *	newvol();		resets tapepos and first to TRUE, prompts for
4936  *				for new volume, and waits.
4937  *	if dumping, end-of-file is written onto the tape.
4938  */
4939 
4940 static void
4941 newvol(void)
4942 {
4943 	int c;
4944 
4945 	if (dumping) {
4946 #ifdef DEBUG
4947 		DEBUG("newvol called with 'dumping' set\n", 0, 0);
4948 #endif
4949 		putempty((blkcnt_t)2);	/* 2 EOT marks */
4950 		closevol();
4951 		flushtape();
4952 		sync();
4953 		tapepos = 0;
4954 	} else
4955 		first = TRUE;
4956 	if (close(mt) != 0)
4957 		vperror(2, gettext("close error"));
4958 	mt = 0;
4959 	(void) fprintf(stderr, gettext(
4960 	    "tar: \007please insert new volume, then press RETURN."));
4961 	(void) fseek(stdin, (off_t)0, 2);	/* scan over read-ahead */
4962 	while ((c = getchar()) != '\n' && ! term)
4963 		if (c == EOF)
4964 			done(Errflg);
4965 	if (term)
4966 		done(Errflg);
4967 
4968 	errno = 0;
4969 
4970 	if (strcmp(usefile, "-") == 0) {
4971 		mt = dup(1);
4972 	} else {
4973 		mt = open(usefile, dumping ? update : 0);
4974 	}
4975 
4976 	if (mt < 0) {
4977 		(void) fprintf(stderr, gettext(
4978 		    "tar: cannot reopen %s (%s)\n"),
4979 		    dumping ? gettext("output") : gettext("input"), usefile);
4980 
4981 #ifdef DEBUG
4982 		DEBUG("update=%d, usefile=%s ", update, usefile);
4983 		DEBUG("mt=%d, [%s]\n", mt, strerror(errno));
4984 #endif
4985 
4986 		done(2);
4987 	}
4988 }
4989 
4990 /*
4991  * Write a trailer portion to close out the current output volume.
4992  */
4993 
4994 static void
4995 closevol(void)
4996 {
4997 	if (mulvol) {
4998 		/*
4999 		 * blocklim does not count the 2 EOT marks;
5000 		 * tapepos  does count the 2 EOT marks;
5001 		 * therefore we need the +2 below.
5002 		 */
5003 		putempty(blocklim + (blkcnt_t)2 - tapepos);
5004 	}
5005 }
5006 
5007 static void
5008 done(int n)
5009 {
5010 	if (tfile != NULL)
5011 		(void) unlink(tname);
5012 	if (compress_opt != NULL)
5013 		(void) free(compress_opt);
5014 	if (mt > 0) {
5015 		if ((close(mt) != 0) || (fclose(stdout) != 0)) {
5016 			perror(gettext("tar: close error"));
5017 			exit(2);
5018 		}
5019 	}
5020 	exit(n);
5021 }
5022 
5023 /*
5024  * Determine if s1 is a prefix portion of s2 (or the same as s2).
5025  */
5026 
5027 static	int
5028 is_prefix(char *s1, char *s2)
5029 {
5030 	while (*s1)
5031 		if (*s1++ != *s2++)
5032 			return (0);
5033 	if (*s2)
5034 		return (*s2 == '/');
5035 	return (1);
5036 }
5037 
5038 /*
5039  * lookup and bsrch look through tfile entries to find a match for a name.
5040  * The name can be up to PATH_MAX bytes.  bsrch compares what it sees between
5041  * a pair of newline chars, so the buffer it uses must be long enough for
5042  * two lines:  name and modification time as well as period, newline and space.
5043  *
5044  * A kludge was added to bsrch to take care of matching on the first entry
5045  * in the file--there is no leading newline.  So, if we are reading from the
5046  * start of the file, read into byte two and set the first byte to a newline.
5047  * Otherwise, the first entry cannot be matched.
5048  *
5049  */
5050 
5051 #define	N	(2 * (PATH_MAX + TIME_MAX_DIGITS + LONG_MAX_DIGITS + 3))
5052 static	off_t
5053 lookup(char *s)
5054 {
5055 	int i;
5056 	off_t a;
5057 
5058 	for (i = 0; s[i]; i++)
5059 		if (s[i] == ' ')
5060 			break;
5061 	a = bsrch(s, i, low, high);
5062 	return (a);
5063 }
5064 
5065 static off_t
5066 bsrch(char *s, int n, off_t l, off_t h)
5067 {
5068 	int i, j;
5069 	char b[N];
5070 	off_t m, m1;
5071 
5072 
5073 loop:
5074 	if (l >= h)
5075 		return ((off_t)-1);
5076 	m = l + (h-l)/2 - N/2;
5077 	if (m < l)
5078 		m = l;
5079 	(void) fseek(tfile, m, 0);
5080 	if (m == 0) {
5081 		(void) fread(b+1, 1, N-1, tfile);
5082 		b[0] = '\n';
5083 		m--;
5084 	} else
5085 		(void) fread(b, 1, N, tfile);
5086 	for (i = 0; i < N; i++) {
5087 		if (b[i] == '\n')
5088 			break;
5089 		m++;
5090 	}
5091 	if (m >= h)
5092 		return ((off_t)-1);
5093 	m1 = m;
5094 	j = i;
5095 	for (i++; i < N; i++) {
5096 		m1++;
5097 		if (b[i] == '\n')
5098 			break;
5099 	}
5100 	i = cmp(b+j, s, n);
5101 	if (i < 0) {
5102 		h = m;
5103 		goto loop;
5104 	}
5105 	if (i > 0) {
5106 		l = m1;
5107 		goto loop;
5108 	}
5109 	if (m < 0)
5110 		m = 0;
5111 	return (m);
5112 }
5113 
5114 static int
5115 cmp(char *b, char *s, int n)
5116 {
5117 	int i;
5118 
5119 	assert(b[0] == '\n');
5120 
5121 	for (i = 0; i < n; i++) {
5122 		if (b[i+1] > s[i])
5123 			return (-1);
5124 		if (b[i+1] < s[i])
5125 			return (1);
5126 	}
5127 	return (b[i+1] == ' '? 0 : -1);
5128 }
5129 
5130 
5131 /*
5132  *	seekdisk	seek to next file on archive
5133  *
5134  *	called by passtape() only
5135  *
5136  *	WARNING: expects "nblock" to be set, that is, readtape() to have
5137  *		already been called.  Since passtape() is only called
5138  *		after a file header block has been read (why else would
5139  *		we skip to next file?), this is currently safe.
5140  *
5141  *	changed to guarantee SYS_BLOCK boundary
5142  */
5143 
5144 static void
5145 seekdisk(blkcnt_t blocks)
5146 {
5147 	off_t seekval;
5148 #if SYS_BLOCK > TBLOCK
5149 	/* handle non-multiple of SYS_BLOCK */
5150 	blkcnt_t nxb;	/* # extra blocks */
5151 #endif
5152 
5153 	tapepos += blocks;
5154 #ifdef DEBUG
5155 	DEBUG("seekdisk(%" FMT_blkcnt_t ") called\n", blocks, 0);
5156 #endif
5157 	if (recno + blocks <= nblock) {
5158 		recno += blocks;
5159 		return;
5160 	}
5161 	if (recno > nblock)
5162 		recno = nblock;
5163 	seekval = (off_t)blocks - (nblock - recno);
5164 	recno = nblock;	/* so readtape() reads next time through */
5165 #if SYS_BLOCK > TBLOCK
5166 	nxb = (blkcnt_t)(seekval % (off_t)(SYS_BLOCK / TBLOCK));
5167 #ifdef DEBUG
5168 	DEBUG("xtrablks=%" FMT_blkcnt_t " seekval=%" FMT_blkcnt_t " blks\n",
5169 	    nxb, seekval);
5170 #endif
5171 	if (nxb && nxb > seekval) /* don't seek--we'll read */
5172 		goto noseek;
5173 	seekval -=  nxb;	/* don't seek quite so far */
5174 #endif
5175 	if (lseek(mt, (off_t)(TBLOCK * seekval), 1) == (off_t)-1) {
5176 		(void) fprintf(stderr, gettext(
5177 		    "tar: device seek error\n"));
5178 		done(3);
5179 	}
5180 #if SYS_BLOCK > TBLOCK
5181 	/* read those extra blocks */
5182 noseek:
5183 	if (nxb) {
5184 #ifdef DEBUG
5185 		DEBUG("reading extra blocks\n", 0, 0);
5186 #endif
5187 		if (read(mt, tbuf, TBLOCK*nblock) < 0) {
5188 			(void) fprintf(stderr, gettext(
5189 			    "tar: read error while skipping file\n"));
5190 			done(8);
5191 		}
5192 		recno = nxb;	/* so we don't read in next readtape() */
5193 	}
5194 #endif
5195 }
5196 
5197 static void
5198 readtape(char *buffer)
5199 {
5200 	int i, j;
5201 
5202 	++tapepos;
5203 	if (recno >= nblock || first) {
5204 		if (first) {
5205 			/*
5206 			 * set the number of blocks to read initially, based on
5207 			 * the defined defaults for the device, or on the
5208 			 * explicit block factor given.
5209 			 */
5210 			if (bflag || defaults_used || NotTape)
5211 				j = nblock;
5212 			else
5213 				j = NBLOCK;
5214 		} else
5215 			j = nblock;
5216 
5217 		if ((i = read(mt, tbuf, TBLOCK*j)) < 0) {
5218 			(void) fprintf(stderr, gettext(
5219 			    "tar: tape read error\n"));
5220 			done(3);
5221 		/*
5222 		 * i == 0 and !rflag means that EOF is reached and we are
5223 		 * trying to update or replace an empty tar file, so exit
5224 		 * with an error.
5225 		 *
5226 		 * If i == 0 and !first and NotTape, it means the pointer
5227 		 * has gone past the EOF. It could happen if two processes
5228 		 * try to update the same tar file simultaneously. So exit
5229 		 * with an error.
5230 		 */
5231 
5232 		} else if (i == 0) {
5233 			if (first && !rflag) {
5234 				(void) fprintf(stderr, gettext(
5235 				    "tar: blocksize = %d\n"), i);
5236 				done(Errflg);
5237 			} else if (!first && (!rflag || NotTape)) {
5238 				mterr("read", 0, 2);
5239 			}
5240 		} else if ((!first || Bflag) && i != TBLOCK*j) {
5241 			/*
5242 			 * Short read - try to get the remaining bytes.
5243 			 */
5244 
5245 			int remaining = (TBLOCK * j) - i;
5246 			char *b = (char *)tbuf + i;
5247 			int r;
5248 
5249 			do {
5250 				if ((r = read(mt, b, remaining)) < 0) {
5251 					(void) fprintf(stderr,
5252 					    gettext("tar: tape read error\n"));
5253 					done(3);
5254 				}
5255 				b += r;
5256 				remaining -= r;
5257 				i += r;
5258 			} while (remaining > 0 && r != 0);
5259 		}
5260 		if (first) {
5261 			if ((i % TBLOCK) != 0) {
5262 				(void) fprintf(stderr, gettext(
5263 				    "tar: tape blocksize error\n"));
5264 				done(3);
5265 			}
5266 			i /= TBLOCK;
5267 			if (vflag && i != nblock && i != 1) {
5268 				if (!NotTape)
5269 					(void) fprintf(stderr, gettext(
5270 					    "tar: blocksize = %d\n"), i);
5271 			}
5272 
5273 			/*
5274 			 * If we are reading a tape, then a short read is
5275 			 * understood to signify that the amount read is
5276 			 * the tape's actual blocking factor.  We adapt
5277 			 * nblock accordingly.  There is no reason to do
5278 			 * this when the device is not blocked.
5279 			 */
5280 
5281 			if (!NotTape)
5282 				nblock = i;
5283 		}
5284 		recno = 0;
5285 	}
5286 
5287 	first = FALSE;
5288 	copy(buffer, &tbuf[recno++]);
5289 }
5290 
5291 
5292 /*
5293  * replacement for writetape.
5294  */
5295 
5296 static int
5297 writetbuf(char *buffer, int n)
5298 {
5299 	int i;
5300 
5301 	tapepos += n;		/* output block count */
5302 
5303 	if (recno >= nblock) {
5304 		i = write(mt, (char *)tbuf, TBLOCK*nblock);
5305 		if (i != TBLOCK*nblock)
5306 			mterr("write", i, 2);
5307 		recno = 0;
5308 	}
5309 
5310 	/*
5311 	 *  Special case:  We have an empty tape buffer, and the
5312 	 *  users data size is >= the tape block size:  Avoid
5313 	 *  the bcopy and dma direct to tape.  BIG WIN.  Add the
5314 	 *  residual to the tape buffer.
5315 	 */
5316 	while (recno == 0 && n >= nblock) {
5317 		i = (int)write(mt, buffer, TBLOCK*nblock);
5318 		if (i != TBLOCK*nblock)
5319 			mterr("write", i, 2);
5320 		n -= nblock;
5321 		buffer += (nblock * TBLOCK);
5322 	}
5323 
5324 	while (n-- > 0) {
5325 		(void) memcpy((char *)&tbuf[recno++], buffer, TBLOCK);
5326 		buffer += TBLOCK;
5327 		if (recno >= nblock) {
5328 			i = (int)write(mt, (char *)tbuf, TBLOCK*nblock);
5329 			if (i != TBLOCK*nblock)
5330 				mterr("write", i, 2);
5331 			recno = 0;
5332 		}
5333 	}
5334 
5335 	/* Tell the user how much to write to get in sync */
5336 	return (nblock - recno);
5337 }
5338 
5339 /*
5340  *	backtape - reposition tape after reading soft "EOF" record
5341  *
5342  *	Backtape tries to reposition the tape back over the EOF
5343  *	record.  This is for the 'u' and 'r' function letters so that the
5344  *	tape can be extended.  This code is not well designed, but
5345  *	I'm confident that the only callers who care about the
5346  *	backspace-over-EOF feature are those involved in 'u' and 'r'.
5347  *
5348  *	The proper way to backup the tape is through the use of mtio.
5349  *	Earlier spins used lseek combined with reads in a confusing
5350  *	maneuver that only worked on 4.x, but shouldn't have, even
5351  *	there.  Lseeks are explicitly not supported for tape devices.
5352  */
5353 
5354 static void
5355 backtape(void)
5356 {
5357 	struct mtop mtcmd;
5358 #ifdef DEBUG
5359 	DEBUG("backtape() called, recno=%" FMT_blkcnt_t " nblock=%d\n", recno,
5360 	    nblock);
5361 #endif
5362 	/*
5363 	 * Backup to the position in the archive where the record
5364 	 * currently sitting in the tbuf buffer is situated.
5365 	 */
5366 
5367 	if (NotTape) {
5368 		/*
5369 		 * For non-tape devices, this means lseeking to the
5370 		 * correct position.  The absolute location tapepos-recno
5371 		 * should be the beginning of the current record.
5372 		 */
5373 
5374 		if (lseek(mt, (off_t)(TBLOCK*(tapepos-recno)), SEEK_SET) ==
5375 		    (off_t)-1) {
5376 			(void) fprintf(stderr,
5377 			    gettext("tar: lseek to end of archive failed\n"));
5378 			done(4);
5379 		}
5380 	} else {
5381 		/*
5382 		 * For tape devices, we backup over the most recently
5383 		 * read record.
5384 		 */
5385 
5386 		mtcmd.mt_op = MTBSR;
5387 		mtcmd.mt_count = 1;
5388 
5389 		if (ioctl(mt, MTIOCTOP, &mtcmd) < 0) {
5390 			(void) fprintf(stderr,
5391 			    gettext("tar: backspace over record failed\n"));
5392 			done(4);
5393 		}
5394 	}
5395 
5396 	/*
5397 	 * Decrement the tape and tbuf buffer indices to prepare for the
5398 	 * coming write to overwrite the soft EOF record.
5399 	 */
5400 
5401 	recno--;
5402 	tapepos--;
5403 }
5404 
5405 
5406 /*
5407  *	flushtape  write buffered block(s) onto tape
5408  *
5409  *      recno points to next free block in tbuf.  If nonzero, a write is done.
5410  *	Care is taken to write in multiples of SYS_BLOCK when device is
5411  *	non-magtape in case raw i/o is used.
5412  *
5413  *	NOTE: this is called by writetape() to do the actual writing
5414  */
5415 
5416 static void
5417 flushtape(void)
5418 {
5419 #ifdef DEBUG
5420 	DEBUG("flushtape() called, recno=%" FMT_blkcnt_t "\n", recno, 0);
5421 #endif
5422 	if (recno > 0) {	/* anything buffered? */
5423 		if (NotTape) {
5424 #if SYS_BLOCK > TBLOCK
5425 			int i;
5426 
5427 			/*
5428 			 * an odd-block write can only happen when
5429 			 * we are at the end of a volume that is not a tape.
5430 			 * Here we round recno up to an even SYS_BLOCK
5431 			 * boundary.
5432 			 */
5433 			if ((i = recno % (SYS_BLOCK / TBLOCK)) != 0) {
5434 #ifdef DEBUG
5435 				DEBUG("flushtape() %d rounding blocks\n", i, 0);
5436 #endif
5437 				recno += i;	/* round up to even SYS_BLOCK */
5438 			}
5439 #endif
5440 			if (recno > nblock)
5441 				recno = nblock;
5442 		}
5443 #ifdef DEBUG
5444 		DEBUG("writing out %" FMT_blkcnt_t " blocks of %" FMT_blkcnt_t
5445 		    " bytes\n", (blkcnt_t)(NotTape ? recno : nblock),
5446 		    (blkcnt_t)(NotTape ? recno : nblock) * TBLOCK);
5447 #endif
5448 		if (write(mt, tbuf,
5449 		    (size_t)(NotTape ? recno : nblock) * TBLOCK) < 0) {
5450 			(void) fprintf(stderr, gettext(
5451 			    "tar: tape write error\n"));
5452 			done(2);
5453 		}
5454 		recno = 0;
5455 	}
5456 }
5457 
5458 static void
5459 copy(void *dst, void *src)
5460 {
5461 	(void) memcpy(dst, src, TBLOCK);
5462 }
5463 
5464 #ifdef	_iBCS2
5465 /*
5466  *	initarg -- initialize things for nextarg.
5467  *
5468  *	argv		filename list, a la argv.
5469  *	filefile	name of file containing filenames.  Unless doing
5470  *		a create, seeks must be allowable (e.g. no named pipes).
5471  *
5472  *	- if filefile is non-NULL, it will be used first, and argv will
5473  *	be used when the data in filefile are exhausted.
5474  *	- otherwise argv will be used.
5475  */
5476 static char **Cmdargv = NULL;
5477 static FILE *FILEFile = NULL;
5478 static long seekFile = -1;
5479 static char *ptrtoFile, *begofFile, *endofFile;
5480 
5481 static	void
5482 initarg(char *argv[], char *filefile)
5483 {
5484 	struct stat statbuf;
5485 	char *p;
5486 	int nbytes;
5487 
5488 	Cmdargv = argv;
5489 	if (filefile == NULL)
5490 		return;		/* no -F file */
5491 	if (FILEFile != NULL) {
5492 		/*
5493 		 * need to REinitialize
5494 		 */
5495 		if (seekFile != -1)
5496 			(void) fseek(FILEFile, seekFile, 0);
5497 		ptrtoFile = begofFile;
5498 		return;
5499 	}
5500 	/*
5501 	 * first time initialization
5502 	 */
5503 	if ((FILEFile = fopen(filefile, "r")) == NULL)
5504 		fatal(gettext("cannot open (%s)"), filefile);
5505 	(void) fstat(fileno(FILEFile), &statbuf);
5506 	if ((statbuf.st_mode & S_IFMT) != S_IFREG) {
5507 		(void) fprintf(stderr, gettext(
5508 		    "tar: %s is not a regular file\n"), filefile);
5509 		(void) fclose(FILEFile);
5510 		done(1);
5511 	}
5512 	ptrtoFile = begofFile = endofFile;
5513 	seekFile = 0;
5514 	if (!xflag)
5515 		return;		/* the file will be read only once anyway */
5516 	nbytes = statbuf.st_size;
5517 	while ((begofFile = calloc(nbytes, sizeof (char))) == NULL)
5518 		nbytes -= 20;
5519 	if (nbytes < 50) {
5520 		free(begofFile);
5521 		begofFile = endofFile;
5522 		return;		/* no room so just do plain reads */
5523 	}
5524 	if (fread(begofFile, 1, nbytes, FILEFile) != nbytes)
5525 		fatal(gettext("could not read %s"), filefile);
5526 	ptrtoFile = begofFile;
5527 	endofFile = begofFile + nbytes;
5528 	for (p = begofFile; p < endofFile; ++p)
5529 		if (*p == '\n')
5530 			*p = '\0';
5531 	if (nbytes != statbuf.st_size)
5532 		seekFile = nbytes + 1;
5533 	else
5534 		(void) fclose(FILEFile);
5535 }
5536 
5537 /*
5538  *	nextarg -- get next argument of arglist.
5539  *
5540  *	The argument is taken from wherever is appropriate.
5541  *
5542  *	If the 'F file' function modifier has been specified, the argument
5543  *	will be taken from the file, unless EOF has been reached.
5544  *	Otherwise the argument will be taken from argv.
5545  *
5546  *	WARNING:
5547  *	  Return value may point to static data, whose contents are over-
5548  *	  written on each call.
5549  */
5550 static	char  *
5551 nextarg(void)
5552 {
5553 	static char nameFile[PATH_MAX + 1];
5554 	int n;
5555 	char *p;
5556 
5557 	if (FILEFile) {
5558 		if (ptrtoFile < endofFile) {
5559 			p = ptrtoFile;
5560 			while (*ptrtoFile)
5561 				++ptrtoFile;
5562 			++ptrtoFile;
5563 			return (p);
5564 		}
5565 		if (fgets(nameFile, PATH_MAX + 1, FILEFile) != NULL) {
5566 			n = strlen(nameFile);
5567 			if (n > 0 && nameFile[n-1] == '\n')
5568 				nameFile[n-1] = '\0';
5569 			return (nameFile);
5570 		}
5571 	}
5572 	return (*Cmdargv++);
5573 }
5574 #endif	/*  _iBCS2 */
5575 
5576 /*
5577  * kcheck()
5578  *	- checks the validity of size values for non-tape devices
5579  *	- if size is zero, mulvol tar is disabled and size is
5580  *	  assumed to be infinite.
5581  *	- returns volume size in TBLOCKS
5582  */
5583 
5584 static blkcnt_t
5585 kcheck(char *kstr)
5586 {
5587 	blkcnt_t kval;
5588 
5589 	kval = strtoll(kstr, NULL, 0);
5590 	if (kval == (blkcnt_t)0) {	/* no multi-volume; size is infinity. */
5591 		mulvol = 0;	/* definitely not mulvol, but we must  */
5592 		return (0);	/* took out setting of NotTape */
5593 	}
5594 	if (kval < (blkcnt_t)MINSIZE) {
5595 		(void) fprintf(stderr, gettext(
5596 		    "tar: sizes below %luK not supported (%" FMT_blkcnt_t
5597 		    ").\n"), (ulong_t)MINSIZE, kval);
5598 		if (!kflag)
5599 			(void) fprintf(stderr, gettext(
5600 			    "bad size entry for %s in %s.\n"),
5601 			    archive, DEF_FILE);
5602 		done(1);
5603 	}
5604 	mulvol++;
5605 	NotTape++;			/* implies non-tape */
5606 	return (kval * 1024 / TBLOCK);	/* convert to TBLOCKS */
5607 }
5608 
5609 
5610 /*
5611  * bcheck()
5612  *	- checks the validity of blocking factors
5613  *	- returns blocking factor
5614  */
5615 
5616 static int
5617 bcheck(char *bstr)
5618 {
5619 	blkcnt_t bval;
5620 
5621 	bval = strtoll(bstr, NULL, 0);
5622 	if ((bval <= 0) || (bval > INT_MAX / TBLOCK)) {
5623 		(void) fprintf(stderr, gettext(
5624 		    "tar: invalid blocksize \"%s\".\n"), bstr);
5625 		if (!bflag)
5626 			(void) fprintf(stderr, gettext(
5627 			    "bad blocksize entry for '%s' in %s.\n"),
5628 			    archive, DEF_FILE);
5629 		done(1);
5630 	}
5631 
5632 	return ((int)bval);
5633 }
5634 
5635 
5636 /*
5637  * defset()
5638  *	- reads DEF_FILE for the set of default values specified.
5639  *	- initializes 'usefile', 'nblock', and 'blocklim', and 'NotTape'.
5640  *	- 'usefile' points to static data, so will be overwritten
5641  *	  if this routine is called a second time.
5642  *	- the pattern specified by 'arch' must be followed by four
5643  *	  blank-separated fields (1) device (2) blocking,
5644  *				 (3) size(K), and (4) tape
5645  *	  for example: archive0=/dev/fd 1 400 n
5646  */
5647 
5648 static int
5649 defset(char *arch)
5650 {
5651 	char *bp;
5652 
5653 	if (defopen(DEF_FILE) != 0)
5654 		return (FALSE);
5655 	if (defcntl(DC_SETFLAGS, (DC_STD & ~(DC_CASE))) == -1) {
5656 		(void) fprintf(stderr, gettext(
5657 		    "tar: error setting parameters for %s.\n"), DEF_FILE);
5658 		return (FALSE);			/* & following ones too */
5659 	}
5660 	if ((bp = defread(arch)) == NULL) {
5661 		(void) fprintf(stderr, gettext(
5662 		    "tar: missing or invalid '%s' entry in %s.\n"),
5663 		    arch, DEF_FILE);
5664 		return (FALSE);
5665 	}
5666 	if ((usefile = strtok(bp, " \t")) == NULL) {
5667 		(void) fprintf(stderr, gettext(
5668 		    "tar: '%s' entry in %s is empty!\n"), arch, DEF_FILE);
5669 		return (FALSE);
5670 	}
5671 	if ((bp = strtok(NULL, " \t")) == NULL) {
5672 		(void) fprintf(stderr, gettext(
5673 		    "tar: block component missing in '%s' entry in %s.\n"),
5674 		    arch, DEF_FILE);
5675 		return (FALSE);
5676 	}
5677 	nblock = bcheck(bp);
5678 	if ((bp = strtok(NULL, " \t")) == NULL) {
5679 		(void) fprintf(stderr, gettext(
5680 		    "tar: size component missing in '%s' entry in %s.\n"),
5681 		    arch, DEF_FILE);
5682 		return (FALSE);
5683 	}
5684 	blocklim = kcheck(bp);
5685 	if ((bp = strtok(NULL, " \t")) != NULL)
5686 		NotTape = (*bp == 'n' || *bp == 'N');
5687 	else
5688 		NotTape = (blocklim != 0);
5689 	(void) defopen(NULL);
5690 #ifdef DEBUG
5691 	DEBUG("defset: archive='%s'; usefile='%s'\n", arch, usefile);
5692 	DEBUG("defset: nblock='%d'; blocklim='%" FMT_blkcnt_t "'\n",
5693 	    nblock, blocklim);
5694 	DEBUG("defset: not tape = %d\n", NotTape, 0);
5695 #endif
5696 	return (TRUE);
5697 }
5698 
5699 
5700 /*
5701  * Following code handles excluded and included files.
5702  * A hash table of file names to be {in,ex}cluded is built.
5703  * For excluded files, before writing or extracting a file
5704  * check to see if it is in the exclude_tbl.
5705  * For included files, the wantit() procedure will check to
5706  * see if the named file is in the include_tbl.
5707  */
5708 
5709 static void
5710 build_table(file_list_t *table[], char *file)
5711 {
5712 	FILE	*fp;
5713 	char	buf[PATH_MAX + 1];
5714 
5715 	if ((fp = fopen(file, "r")) == (FILE *)NULL)
5716 		vperror(1, gettext("could not open %s"), file);
5717 	while (fgets(buf, sizeof (buf), fp) != NULL) {
5718 		if (buf[strlen(buf) - 1] == '\n')
5719 			buf[strlen(buf) - 1] = '\0';
5720 		/* Only add to table if line has something in it */
5721 		if (strspn(buf, " \t") != strlen(buf))
5722 			add_file_to_table(table, buf);
5723 	}
5724 	(void) fclose(fp);
5725 }
5726 
5727 
5728 /*
5729  * Add a file name to the the specified table, if the file name has any
5730  * trailing '/'s then delete them before inserting into the table
5731  */
5732 
5733 static void
5734 add_file_to_table(file_list_t *table[], char *str)
5735 {
5736 	char	name[PATH_MAX + 1];
5737 	unsigned int h;
5738 	file_list_t	*exp;
5739 
5740 	(void) strcpy(name, str);
5741 	while (name[strlen(name) - 1] == '/') {
5742 		name[strlen(name) - 1] = NULL;
5743 	}
5744 
5745 	h = hash(name);
5746 	if ((exp = (file_list_t *)calloc(sizeof (file_list_t),
5747 	    sizeof (char))) == NULL) {
5748 		(void) fprintf(stderr, gettext(
5749 		    "tar: out of memory, exclude/include table(entry)\n"));
5750 		exit(1);
5751 	}
5752 
5753 	if ((exp->name = strdup(name)) == NULL) {
5754 		(void) fprintf(stderr, gettext(
5755 		    "tar: out of memory, exclude/include table(file name)\n"));
5756 		exit(1);
5757 	}
5758 
5759 	exp->next = table[h];
5760 	table[h] = exp;
5761 }
5762 
5763 
5764 /*
5765  * See if a file name or any of the file's parent directories is in the
5766  * specified table, if the file name has any trailing '/'s then delete
5767  * them before searching the table
5768  */
5769 
5770 static int
5771 is_in_table(file_list_t *table[], char *str)
5772 {
5773 	char	name[PATH_MAX + 1];
5774 	unsigned int	h;
5775 	file_list_t	*exp;
5776 	char	*ptr;
5777 
5778 	(void) strcpy(name, str);
5779 	while (name[strlen(name) - 1] == '/') {
5780 		name[strlen(name) - 1] = NULL;
5781 	}
5782 
5783 	/*
5784 	 * check for the file name in the passed list
5785 	 */
5786 	h = hash(name);
5787 	exp = table[h];
5788 	while (exp != NULL) {
5789 		if (strcmp(name, exp->name) == 0) {
5790 			return (1);
5791 		}
5792 		exp = exp->next;
5793 	}
5794 
5795 	/*
5796 	 * check for any parent directories in the file list
5797 	 */
5798 	while ((ptr = strrchr(name, '/'))) {
5799 		*ptr = NULL;
5800 		h = hash(name);
5801 		exp = table[h];
5802 		while (exp != NULL) {
5803 			if (strcmp(name, exp->name) == 0) {
5804 				return (1);
5805 			}
5806 			exp = exp->next;
5807 		}
5808 	}
5809 
5810 	return (0);
5811 }
5812 
5813 
5814 /*
5815  * Compute a hash from a string.
5816  */
5817 
5818 static unsigned int
5819 hash(char *str)
5820 {
5821 	char	*cp;
5822 	unsigned int	h;
5823 
5824 	h = 0;
5825 	for (cp = str; *cp; cp++) {
5826 		h += *cp;
5827 	}
5828 	return (h % TABLE_SIZE);
5829 }
5830 
5831 static	void *
5832 getmem(size_t size)
5833 {
5834 	void *p = calloc((unsigned)size, sizeof (char));
5835 
5836 	if (p == NULL && freemem) {
5837 		(void) fprintf(stderr, gettext(
5838 		    "tar: out of memory, link and directory modtime "
5839 		    "info lost\n"));
5840 		freemem = 0;
5841 		if (errflag)
5842 			done(1);
5843 		else
5844 			Errflg = 1;
5845 	}
5846 	return (p);
5847 }
5848 
5849 /*
5850  * vperror() --variable argument perror.
5851  * Takes 3 args: exit_status, formats, args.  If exit_status is 0, then
5852  * the errflag (exit on error) is checked -- if it is non-zero, tar exits
5853  * with the value of whatever "errno" is set to.  If exit_status is not
5854  * zero, then tar exits with that error status. If errflag and exit_status
5855  * are both zero, the routine returns to where it was called and sets Errflg
5856  * to errno.
5857  */
5858 
5859 static void
5860 vperror(int exit_status, char *fmt, ...)
5861 {
5862 	va_list	ap;
5863 
5864 	va_start(ap, fmt);
5865 	(void) fputs("tar: ", stderr);
5866 	(void) vfprintf(stderr, fmt, ap);
5867 	(void) fprintf(stderr, ": %s\n", strerror(errno));
5868 	va_end(ap);
5869 	if (exit_status)
5870 		done(exit_status);
5871 	else
5872 		if (errflag)
5873 			done(errno);
5874 		else
5875 			Errflg = errno;
5876 }
5877 
5878 
5879 static void
5880 fatal(char *format, ...)
5881 {
5882 	va_list	ap;
5883 
5884 	va_start(ap, format);
5885 	(void) fprintf(stderr, "tar: ");
5886 	(void) vfprintf(stderr, format, ap);
5887 	(void) fprintf(stderr, "\n");
5888 	va_end(ap);
5889 	done(1);
5890 }
5891 
5892 
5893 /*
5894  * Check to make sure that argument is a char * ptr.
5895  * Actually, we just check to see that it is non-null.
5896  * If it is null, print out the message and call usage(), bailing out.
5897  */
5898 
5899 static void
5900 assert_string(char *s, char *msg)
5901 {
5902 	if (s == NULL) {
5903 		(void) fprintf(stderr, msg);
5904 		usage();
5905 	}
5906 }
5907 
5908 
5909 static void
5910 mterr(char *operation, int i, int exitcode)
5911 {
5912 	(void) fprintf(stderr, gettext(
5913 	    "tar: %s error: "), operation);
5914 	if (i < 0)
5915 		perror("");
5916 	else
5917 		(void) fprintf(stderr, gettext("unexpected EOF\n"));
5918 	done(exitcode);
5919 }
5920 
5921 static int
5922 wantit(char *argv[], char **namep, char **dirp, char **component,
5923     attr_data_t **attrinfo)
5924 {
5925 	char **cp;
5926 	int gotit;		/* true if we've found a match */
5927 	int ret;
5928 
5929 top:
5930 	if (xhdr_flgs & _X_XHDR) {
5931 		xhdr_flgs = 0;
5932 	}
5933 	getdir();
5934 	if (Xhdrflag > 0) {
5935 		ret = get_xdata();
5936 		if (ret != 0) {	/* Xhdr items and regular header */
5937 			setbytes_to_skip(&stbuf, ret);
5938 			passtape();
5939 			return (0);	/* Error--don't want to extract  */
5940 		}
5941 	}
5942 
5943 	/*
5944 	 * If typeflag is not 'A' and xhdr_flgs is set, then processing
5945 	 * of ancillary file is either over or ancillary file
5946 	 * processing is not required, load info from Xtarhdr and set
5947 	 * _X_XHDR bit in xhdr_flgs.
5948 	 */
5949 	if ((dblock.dbuf.typeflag != 'A') && (xhdr_flgs != 0)) {
5950 		load_info_from_xtarhdr(xhdr_flgs, &Xtarhdr);
5951 		xhdr_flgs |= _X_XHDR;
5952 	}
5953 
5954 #if defined(O_XATTR)
5955 	if (dblock.dbuf.typeflag == _XATTR_HDRTYPE && xattrbadhead == 0) {
5956 		/*
5957 		 * Always needs to read the extended header.  If atflag, saflag,
5958 		 * or tflag isn't set, then we'll have the correct info for
5959 		 * passtape() later.
5960 		 */
5961 		(void) read_xattr_hdr(attrinfo);
5962 		goto top;
5963 	}
5964 	/*
5965 	 * Now that we've read the extended header, call passtape()
5966 	 * if we don't want to restore attributes or system attributes.
5967 	 * Don't restore the attribute if we are extracting
5968 	 * a file from an archive (as opposed to doing a table of
5969 	 * contents) and any of the following are true:
5970 	 * 1. neither -@ or -/ was specified.
5971 	 * 2. -@ was specified, -/ wasn't specified, and we're
5972 	 * processing a hidden attribute directory of an attribute
5973 	 * or we're processing a read-write system attribute file.
5974 	 * 3. -@ wasn't specified, -/ was specified, and the file
5975 	 * we're processing is not a read-write system attribute file,
5976 	 * or we're processing the hidden attribute directory of an
5977 	 * attribute.
5978 	 *
5979 	 * We always process the attributes if we're just generating
5980 	 * generating a table of contents, or if both -@ and -/ were
5981 	 * specified.
5982 	 */
5983 	if (xattrp != NULL) {
5984 		attr_data_t *ainfo = *attrinfo;
5985 
5986 		if (!tflag &&
5987 		    ((!atflag && !saflag) ||
5988 		    (atflag && !saflag && ((ainfo->attr_parent != NULL) ||
5989 		    ainfo->attr_rw_sysattr)) ||
5990 		    (!atflag && saflag && ((ainfo->attr_parent != NULL) ||
5991 		    !ainfo->attr_rw_sysattr)))) {
5992 			passtape();
5993 			return (0);
5994 		}
5995 	}
5996 #endif
5997 
5998 	/* sets *namep to point at the proper name */
5999 	if (check_prefix(namep, dirp, component) != 0) {
6000 		passtape();
6001 		return (0);
6002 	}
6003 
6004 	if (endtape()) {
6005 		if (Bflag) {
6006 			/*
6007 			 * Logically at EOT - consume any extra blocks
6008 			 * so that write to our stdin won't fail and
6009 			 * emit an error message; otherwise something
6010 			 * like "dd if=foo.tar | (cd bar; tar xvf -)"
6011 			 * will produce a bogus error message from "dd".
6012 			 */
6013 
6014 			while (read(mt, tbuf, TBLOCK*nblock) > 0) {
6015 				/* empty body */
6016 			}
6017 		}
6018 		return (-1);
6019 	}
6020 
6021 	gotit = 0;
6022 
6023 	if ((Iflag && is_in_table(include_tbl, *namep)) ||
6024 	    (! Iflag && *argv == NULL)) {
6025 		gotit = 1;
6026 	} else {
6027 		for (cp = argv; *cp; cp++) {
6028 			if (is_prefix(*cp, *namep)) {
6029 				gotit = 1;
6030 				break;
6031 			}
6032 		}
6033 	}
6034 
6035 	if (! gotit) {
6036 		passtape();
6037 		return (0);
6038 	}
6039 
6040 	if (Xflag && is_in_table(exclude_tbl, *namep)) {
6041 		if (vflag) {
6042 			(void) fprintf(stderr, gettext("%s excluded\n"),
6043 			    *namep);
6044 		}
6045 		passtape();
6046 		return (0);
6047 	}
6048 
6049 	return (1);
6050 }
6051 
6052 
6053 static void
6054 setbytes_to_skip(struct stat *st, int err)
6055 {
6056 	/*
6057 	 * In a scenario where a typeflag 'X' was followed by
6058 	 * a typeflag 'A' and typeflag 'O', then the number of
6059 	 * bytes to skip should be the size of ancillary file,
6060 	 * plus the dblock for regular file, and the size
6061 	 * from Xtarhdr. However, if the typeflag was just 'X'
6062 	 * followed by typeflag 'O', then the number of bytes
6063 	 * to skip should be the size from Xtarhdr.
6064 	 */
6065 	if ((err != 0) && (dblock.dbuf.typeflag == 'A') &&
6066 	    (xhdr_flgs & _X_SIZE)) {
6067 		st->st_size += TBLOCK + Xtarhdr.x_filesz;
6068 		xhdr_flgs |= _X_XHDR;
6069 	} else if ((dblock.dbuf.typeflag != 'A') &&
6070 	    (xhdr_flgs & _X_SIZE)) {
6071 		st->st_size += Xtarhdr.x_filesz;
6072 		xhdr_flgs |= _X_XHDR;
6073 	}
6074 }
6075 
6076 static int
6077 fill_in_attr_info(char *attr, char *longname, char *attrparent, int atparentfd,
6078     int rw_sysattr, attr_data_t **attrinfo)
6079 {
6080 	size_t	pathlen;
6081 	char	*tpath;
6082 	char	*tparent;
6083 
6084 	/* parent info */
6085 	if (attrparent != NULL) {
6086 		if ((tparent = strdup(attrparent)) == NULL) {
6087 			vperror(0, gettext(
6088 			    "unable to allocate memory for attribute parent "
6089 			    "name for %sattribute %s/%s of %s"),
6090 			    rw_sysattr ? gettext("system ") : "",
6091 			    attrparent, attr, longname);
6092 			return (1);
6093 		}
6094 	} else {
6095 		tparent = NULL;
6096 	}
6097 
6098 	/* path info */
6099 	pathlen = strlen(attr) + 1;
6100 	if (attrparent != NULL) {
6101 		pathlen += strlen(attrparent) + 1;	/* add 1 for '/' */
6102 	}
6103 	if ((tpath = calloc(1, pathlen)) == NULL) {
6104 		vperror(0, gettext(
6105 		    "unable to allocate memory for full "
6106 		    "attribute path name for %sattribute %s%s%s of %s"),
6107 		    rw_sysattr ? gettext("system ") : "",
6108 		    (attrparent == NULL) ? "" : attrparent,
6109 		    (attrparent == NULL) ? "" : "/",
6110 		    attr, longname);
6111 		if (tparent != NULL) {
6112 			free(tparent);
6113 		}
6114 		return (1);
6115 	}
6116 	(void) snprintf(tpath, pathlen, "%s%s%s",
6117 	    (attrparent == NULL) ? "" : attrparent,
6118 	    (attrparent == NULL) ? "" : "/",
6119 	    attr);
6120 
6121 	/* fill in the attribute info */
6122 	if (*attrinfo == NULL) {
6123 		if ((*attrinfo = malloc(sizeof (attr_data_t))) == NULL) {
6124 			vperror(0, gettext(
6125 			    "unable to allocate memory for attribute "
6126 			    "information for %sattribute %s%s%s of %s"),
6127 			    rw_sysattr ? gettext("system ") : "",
6128 			    (attrparent == NULL) ? "" : attrparent,
6129 			    (attrparent == NULL) ? "" : gettext("/"),
6130 			    attr, longname);
6131 			if (tparent != NULL) {
6132 				free(tparent);
6133 			}
6134 			free(tpath);
6135 			return (1);
6136 		}
6137 	} else {
6138 		if ((*attrinfo)->attr_parent != NULL) {
6139 			free((*attrinfo)->attr_parent);
6140 		}
6141 		if ((*attrinfo)->attr_path != NULL) {
6142 			free((*attrinfo)->attr_path);
6143 		}
6144 		/*
6145 		 * The parent file descriptor is passed in, so don't
6146 		 * close it here as it should be closed by the function
6147 		 * that opened it.
6148 		 */
6149 	}
6150 	(*attrinfo)->attr_parent = tparent;
6151 	(*attrinfo)->attr_path = tpath;
6152 	(*attrinfo)->attr_rw_sysattr = rw_sysattr;
6153 	(*attrinfo)->attr_parentfd = atparentfd;
6154 
6155 	return (0);
6156 }
6157 
6158 /*
6159  * Test to see if name is a directory.
6160  *
6161  * Return 1 if true, 0 otherwise.
6162  */
6163 
6164 static int
6165 is_directory(char *name)
6166 {
6167 #if defined(O_XATTR)
6168 	/*
6169 	 * If there is an xattr_buf structure associated with this file,
6170 	 * then the directory test is based on whether the name has a
6171 	 * trailing slash.
6172 	 */
6173 	if (xattrp)
6174 		return (name[strlen(name) - 1] == '/');
6175 #endif
6176 	if (is_posix)
6177 		return (dblock.dbuf.typeflag == '5');
6178 	else
6179 		return (name[strlen(name) - 1] == '/');
6180 }
6181 
6182 /*
6183  * Test if name has a '..' sequence in it.
6184  *
6185  * Return 1 if found, 0 otherwise.
6186  */
6187 
6188 static int
6189 has_dot_dot(char *name)
6190 {
6191 	char *s;
6192 	size_t name_len = strlen(name);
6193 
6194 	for (s = name; s < (name + name_len - 2); s++) {
6195 		if (s[0] == '.' && s[1] == '.' && ((s[2] == '/') || !s[2]))
6196 			return (1);
6197 
6198 		while (! (*s == '/')) {
6199 			if (! *s++)
6200 				return (0);
6201 		}
6202 	}
6203 
6204 	return (0);
6205 }
6206 
6207 /*
6208  * Test if name is an absolute path name.
6209  *
6210  * Return 1 if true, 0 otherwise.
6211  */
6212 
6213 static int
6214 is_absolute(char *name)
6215 {
6216 #if defined(O_XATTR)
6217 	/*
6218 	 * If this is an extended attribute (whose name will begin with
6219 	 * "/dev/null/", always return 0 as they should be extracted with
6220 	 * the name intact, to allow other tar archiving programs that
6221 	 * don't understand extended attributes, to correctly throw them away.
6222 	 */
6223 	if (xattrp)
6224 		return (0);
6225 #endif
6226 
6227 	return (name[0] == '/');
6228 }
6229 
6230 /*
6231  * Adjust the pathname to make it a relative one. Strip off any leading
6232  * '/' characters and if the pathname contains any '..' sequences, strip
6233  * upto and including the last occurance of '../' (or '..' if found at
6234  * the very end of the pathname).
6235  *
6236  * Return the relative pathname. stripped_prefix will also return the
6237  * portion of name that was stripped off and should be freed by the
6238  * calling routine when no longer needed.
6239  */
6240 
6241 static char *
6242 make_relative_name(char *name, char **stripped_prefix)
6243 {
6244 	char *s;
6245 	size_t prefix_len = 0;
6246 	size_t name_len = strlen(name);
6247 
6248 	for (s = name + prefix_len; s < (name + name_len - 2); ) {
6249 		if (s[0] == '.' && s[1] == '.' && ((s[2] == '/') || !s[2]))
6250 			prefix_len = s + 2 - name;
6251 
6252 		do {
6253 			char c = *s++;
6254 
6255 			if (c == '/')
6256 				break;
6257 		} while (*s);
6258 	}
6259 
6260 	for (s = name + prefix_len; *s == '/'; s++)
6261 		continue;
6262 	prefix_len = s - name;
6263 
6264 	/* Create the portion of the name that was stripped off. */
6265 	s = malloc(prefix_len + 1);
6266 	memcpy(s, name, prefix_len);
6267 	s[prefix_len] = 0;
6268 	*stripped_prefix = s;
6269 	s = &name[prefix_len];
6270 
6271 	return (s);
6272 }
6273 
6274 /*
6275  *  Return through *namep a pointer to the proper fullname (i.e  "<name> |
6276  *  <prefix>/<name>"), as represented in the header entry dblock.dbuf.
6277  *
6278  * Returns 0 if successful, otherwise returns 1.
6279  */
6280 
6281 static int
6282 check_prefix(char **namep, char **dirp, char **compp)
6283 {
6284 	static char fullname[PATH_MAX + 1];
6285 	static char dir[PATH_MAX + 1];
6286 	static char component[PATH_MAX + 1];
6287 	static char savename[PATH_MAX + 1];
6288 	char *s;
6289 
6290 	(void) memset(dir, 0, sizeof (dir));
6291 	(void) memset(component, 0, sizeof (component));
6292 
6293 	if (xhdr_flgs & _X_PATH) {
6294 		(void) strcpy(fullname, Xtarhdr.x_path);
6295 	} else {
6296 		if (dblock.dbuf.prefix[0] != '\0')
6297 			(void) sprintf(fullname, "%.*s/%.*s", PRESIZ,
6298 			    dblock.dbuf.prefix, NAMSIZ, dblock.dbuf.name);
6299 		else
6300 			(void) sprintf(fullname, "%.*s", NAMSIZ,
6301 			    dblock.dbuf.name);
6302 	}
6303 
6304 	/*
6305 	 * If we are printing a table of contents or extracting an archive,
6306 	 * make absolute pathnames relative and prohibit the unpacking of
6307 	 * files contain ".." in their name (unless the user has supplied
6308 	 * the -P option).
6309 	 */
6310 	if ((tflag || xflag) && !Pflag) {
6311 		if (is_absolute(fullname) || has_dot_dot(fullname)) {
6312 			char *stripped_prefix;
6313 			size_t prefix_len = 0;
6314 
6315 			(void) strcpy(savename, fullname);
6316 			strcpy(fullname,
6317 			    make_relative_name(savename, &stripped_prefix));
6318 			(void) fprintf(stderr,
6319 			    gettext("tar: Removing leading '%s' from '%s'\n"),
6320 			    stripped_prefix, savename);
6321 			free(stripped_prefix);
6322 		}
6323 	}
6324 
6325 	/*
6326 	 * Set dir and component names
6327 	 */
6328 
6329 	get_parent(fullname, dir);
6330 
6331 #if defined(O_XATTR)
6332 	if (xattrp == NULL) {
6333 #endif
6334 		/*
6335 		 * Save of real name since were going to chop off the
6336 		 * trailing slashes.
6337 		 */
6338 		(void) strcpy(savename, fullname);
6339 		/*
6340 		 * first strip of trailing slashes.
6341 		 */
6342 		chop_endslashes(savename);
6343 		s = get_component(savename);
6344 		(void) strcpy(component, s);
6345 
6346 #if defined(O_XATTR)
6347 	} else {
6348 		(void) strcpy(fullname, xattrp->h_names);
6349 		(void) strcpy(dir, fullname);
6350 		(void) strcpy(component, basename(xattrp->h_names +
6351 		    strlen(xattrp->h_names) + 1));
6352 	}
6353 #endif
6354 	*namep = fullname;
6355 	*dirp = dir;
6356 	*compp = component;
6357 
6358 	return (0);
6359 }
6360 
6361 /*
6362  * Return true if the object indicated by the file descriptor and type
6363  * is a tape device, false otherwise
6364  */
6365 
6366 static int
6367 istape(int fd, int type)
6368 {
6369 	int result = 0;
6370 
6371 	if (S_ISCHR(type)) {
6372 		struct mtget mtg;
6373 
6374 		if (ioctl(fd, MTIOCGET, &mtg) != -1) {
6375 			result = 1;
6376 		}
6377 	}
6378 
6379 	return (result);
6380 }
6381 
6382 #include <utmpx.h>
6383 
6384 struct utmpx utmpx;
6385 
6386 #define	NMAX	(sizeof (utmpx.ut_name))
6387 
6388 typedef struct cachenode {	/* this struct must be zeroed before using */
6389 	struct cachenode *next;	/* next in hash chain */
6390 	int val;		/* the uid or gid of this entry */
6391 	int namehash;		/* name's hash signature */
6392 	char name[NMAX+1];	/* the string that val maps to */
6393 } cachenode_t;
6394 
6395 #define	HASHSIZE	256
6396 
6397 static cachenode_t *names[HASHSIZE];
6398 static cachenode_t *groups[HASHSIZE];
6399 static cachenode_t *uids[HASHSIZE];
6400 static cachenode_t *gids[HASHSIZE];
6401 
6402 static int
6403 hash_byname(char *name)
6404 {
6405 	int i, c, h = 0;
6406 
6407 	for (i = 0; i < NMAX; i++) {
6408 		c = name[i];
6409 		if (c == '\0')
6410 			break;
6411 		h = (h << 4) + h + c;
6412 	}
6413 	return (h);
6414 }
6415 
6416 static cachenode_t *
6417 hash_lookup_byval(cachenode_t *table[], int val)
6418 {
6419 	int h = val;
6420 	cachenode_t *c;
6421 
6422 	for (c = table[h & (HASHSIZE - 1)]; c != NULL; c = c->next) {
6423 		if (c->val == val)
6424 			return (c);
6425 	}
6426 	return (NULL);
6427 }
6428 
6429 static cachenode_t *
6430 hash_lookup_byname(cachenode_t *table[], char *name)
6431 {
6432 	int h = hash_byname(name);
6433 	cachenode_t *c;
6434 
6435 	for (c = table[h & (HASHSIZE - 1)]; c != NULL; c = c->next) {
6436 		if (c->namehash == h && strcmp(c->name, name) == 0)
6437 			return (c);
6438 	}
6439 	return (NULL);
6440 }
6441 
6442 static cachenode_t *
6443 hash_insert(cachenode_t *table[], char *name, int value)
6444 {
6445 	cachenode_t *c;
6446 	int signature;
6447 
6448 	c = calloc(1, sizeof (cachenode_t));
6449 	if (c == NULL) {
6450 		perror("malloc");
6451 		exit(1);
6452 	}
6453 	if (name != NULL) {
6454 		(void) strncpy(c->name, name, NMAX);
6455 		c->namehash = hash_byname(name);
6456 	}
6457 	c->val = value;
6458 	if (table == uids || table == gids)
6459 		signature = c->val;
6460 	else
6461 		signature = c->namehash;
6462 	c->next = table[signature & (HASHSIZE - 1)];
6463 	table[signature & (HASHSIZE - 1)] = c;
6464 	return (c);
6465 }
6466 
6467 static char *
6468 getname(uid_t uid)
6469 {
6470 	cachenode_t *c;
6471 
6472 	if ((c = hash_lookup_byval(uids, uid)) == NULL) {
6473 		struct passwd *pwent = getpwuid(uid);
6474 		c = hash_insert(uids, pwent ? pwent->pw_name : NULL, uid);
6475 	}
6476 	return (c->name);
6477 }
6478 
6479 static char *
6480 getgroup(gid_t gid)
6481 {
6482 	cachenode_t *c;
6483 
6484 	if ((c = hash_lookup_byval(gids, gid)) == NULL) {
6485 		struct group *grent = getgrgid(gid);
6486 		c = hash_insert(gids, grent ? grent->gr_name : NULL, gid);
6487 	}
6488 	return (c->name);
6489 }
6490 
6491 static uid_t
6492 getuidbyname(char *name)
6493 {
6494 	cachenode_t *c;
6495 
6496 	if ((c = hash_lookup_byname(names, name)) == NULL) {
6497 		struct passwd *pwent = getpwnam(name);
6498 		c = hash_insert(names, name, pwent ? (int)pwent->pw_uid : -1);
6499 	}
6500 	return ((uid_t)c->val);
6501 }
6502 
6503 static gid_t
6504 getgidbyname(char *group)
6505 {
6506 	cachenode_t *c;
6507 
6508 	if ((c = hash_lookup_byname(groups, group)) == NULL) {
6509 		struct group *grent = getgrnam(group);
6510 		c = hash_insert(groups, group, grent ? (int)grent->gr_gid : -1);
6511 	}
6512 	return ((gid_t)c->val);
6513 }
6514 
6515 /*
6516  * Build the header.
6517  * Determine whether or not an extended header is also needed.  If needed,
6518  * create and write the extended header and its data.
6519  * Writing of the extended header assumes that "tomodes" has been called and
6520  * the relevant information has been placed in the header block.
6521  */
6522 
6523 static int
6524 build_dblock(
6525 	const char		*name,
6526 	const char		*linkname,
6527 	const char		typeflag,
6528 	const int		filetype,
6529 	const struct stat	*sp,
6530 	const dev_t		device,
6531 	const char		*prefix)
6532 {
6533 	int nblks;
6534 	major_t		dev;
6535 	const char	*filename;
6536 	const char	*lastslash;
6537 
6538 	if (filetype == XATTR_FILE)
6539 		dblock.dbuf.typeflag = _XATTR_HDRTYPE;
6540 	else
6541 		dblock.dbuf.typeflag = typeflag;
6542 	(void) memset(dblock.dbuf.name, '\0', NAMSIZ);
6543 	(void) memset(dblock.dbuf.linkname, '\0', NAMSIZ);
6544 	(void) memset(dblock.dbuf.prefix, '\0', PRESIZ);
6545 
6546 	if (xhdr_flgs & _X_PATH)
6547 		filename = Xtarhdr.x_path;
6548 	else
6549 		filename = name;
6550 
6551 	if ((dev = major(device)) > OCTAL7CHAR) {
6552 		if (Eflag) {
6553 			xhdr_flgs |= _X_DEVMAJOR;
6554 			Xtarhdr.x_devmajor = dev;
6555 		} else {
6556 			(void) fprintf(stderr, gettext(
6557 			    "Device major too large for %s.  Use -E flag."),
6558 			    filename);
6559 			if (errflag)
6560 				done(1);
6561 			else
6562 				Errflg = 1;
6563 		}
6564 		dev = 0;
6565 	}
6566 	(void) sprintf(dblock.dbuf.devmajor, "%07lo", dev);
6567 	if ((dev = minor(device)) > OCTAL7CHAR) {
6568 		if (Eflag) {
6569 			xhdr_flgs |= _X_DEVMINOR;
6570 			Xtarhdr.x_devminor = dev;
6571 		} else {
6572 			(void) fprintf(stderr, gettext(
6573 			    "Device minor too large for %s.  Use -E flag."),
6574 			    filename);
6575 			if (errflag)
6576 				done(1);
6577 			else
6578 				Errflg = 1;
6579 		}
6580 		dev = 0;
6581 	}
6582 	(void) sprintf(dblock.dbuf.devminor, "%07lo", dev);
6583 
6584 	(void) strncpy(dblock.dbuf.name, name, NAMSIZ);
6585 	(void) strncpy(dblock.dbuf.linkname, linkname, NAMSIZ);
6586 	(void) sprintf(dblock.dbuf.magic, "%.5s", magic_type);
6587 	(void) sprintf(dblock.dbuf.version, "00");
6588 	(void) sprintf(dblock.dbuf.uname, "%.31s", getname(sp->st_uid));
6589 	(void) sprintf(dblock.dbuf.gname, "%.31s", getgroup(sp->st_gid));
6590 	(void) strncpy(dblock.dbuf.prefix, prefix, PRESIZ);
6591 	(void) sprintf(dblock.dbuf.chksum, "%07o", checksum(&dblock));
6592 
6593 	if (Eflag) {
6594 		(void) bcopy(dblock.dummy, xhdr_buf.dummy, TBLOCK);
6595 		(void) memset(xhdr_buf.dbuf.name, '\0', NAMSIZ);
6596 		lastslash = strrchr(name, '/');
6597 		if (lastslash == NULL)
6598 			lastslash = name;
6599 		else
6600 			lastslash++;
6601 		(void) strcpy(xhdr_buf.dbuf.name, lastslash);
6602 		(void) memset(xhdr_buf.dbuf.linkname, '\0', NAMSIZ);
6603 		(void) memset(xhdr_buf.dbuf.prefix, '\0', PRESIZ);
6604 		(void) strcpy(xhdr_buf.dbuf.prefix, xhdr_dirname);
6605 		xhdr_count++;
6606 		xrec_offset = 0;
6607 		gen_date("mtime", sp->st_mtim);
6608 		xhdr_buf.dbuf.typeflag = 'X';
6609 		if (gen_utf8_names(filename) != 0)
6610 			return (1);
6611 
6612 #ifdef XHDR_DEBUG
6613 		Xtarhdr.x_uname = dblock.dbuf.uname;
6614 		Xtarhdr.x_gname = dblock.dbuf.gname;
6615 		xhdr_flgs |= (_X_UNAME | _X_GNAME);
6616 #endif
6617 		if (xhdr_flgs) {
6618 			if (xhdr_flgs & _X_DEVMAJOR)
6619 				gen_num("SUN.devmajor", Xtarhdr.x_devmajor);
6620 			if (xhdr_flgs & _X_DEVMINOR)
6621 				gen_num("SUN.devminor", Xtarhdr.x_devminor);
6622 			if (xhdr_flgs & _X_GID)
6623 				gen_num("gid", Xtarhdr.x_gid);
6624 			if (xhdr_flgs & _X_UID)
6625 				gen_num("uid", Xtarhdr.x_uid);
6626 			if (xhdr_flgs & _X_SIZE)
6627 				gen_num("size", Xtarhdr.x_filesz);
6628 			if (xhdr_flgs & _X_PATH)
6629 				gen_string("path", Xtarhdr.x_path);
6630 			if (xhdr_flgs & _X_LINKPATH)
6631 				gen_string("linkpath", Xtarhdr.x_linkpath);
6632 			if (xhdr_flgs & _X_GNAME)
6633 				gen_string("gname", Xtarhdr.x_gname);
6634 			if (xhdr_flgs & _X_UNAME)
6635 				gen_string("uname", Xtarhdr.x_uname);
6636 		}
6637 		(void) sprintf(xhdr_buf.dbuf.size,
6638 		    "%011" FMT_off_t_o, xrec_offset);
6639 		(void) sprintf(xhdr_buf.dbuf.chksum, "%07o",
6640 		    checksum(&xhdr_buf));
6641 		(void) writetbuf((char *)&xhdr_buf, 1);
6642 		nblks = TBLOCKS(xrec_offset);
6643 		(void) writetbuf(xrec_ptr, nblks);
6644 	}
6645 	return (0);
6646 }
6647 
6648 
6649 /*
6650  *  makeDir - ensure that a directory with the pathname denoted by name
6651  *            exists, and return 1 on success, and 0 on failure (e.g.,
6652  *	      read-only file system, exists but not-a-directory).
6653  */
6654 
6655 static int
6656 makeDir(char *name)
6657 {
6658 	struct stat buf;
6659 
6660 	if (access(name, 0) < 0) {  /* name doesn't exist */
6661 		if (mkdir(name, 0777) < 0) {
6662 			vperror(0, "%s", name);
6663 			return (0);
6664 		}
6665 	} else {		   /* name exists */
6666 		if (stat(name, &buf) < 0) {
6667 			vperror(0, "%s", name);
6668 			return (0);
6669 		}
6670 
6671 		return ((buf.st_mode & S_IFMT) == S_IFDIR);
6672 	}
6673 
6674 	return (1);
6675 }
6676 
6677 
6678 /*
6679  * Save this directory and its mtime on the stack, popping and setting
6680  * the mtimes of any stacked dirs which aren't parents of this one.
6681  * A null name causes the entire stack to be unwound and set.
6682  *
6683  * Since all the elements of the directory "stack" share a common
6684  * prefix, we can make do with one string.  We keep only the current
6685  * directory path, with an associated array of mtime's. A negative
6686  * mtime means no mtime.
6687  *
6688  * This stack algorithm is not guaranteed to work for tapes created
6689  * with the 'r' function letter, but the vast majority of tapes with
6690  * directories are not.  This avoids saving every directory record on
6691  * the tape and setting all the times at the end.
6692  *
6693  * (This was borrowed from the 4.1.3 source, and adapted to the 5.x
6694  *  environment)
6695  */
6696 
6697 static void
6698 doDirTimes(char *name, timestruc_t modTime)
6699 {
6700 	static char dirstack[PATH_MAX+2];
6701 			/* Add spaces for the last slash and last NULL */
6702 	static timestruc_t	modtimes[PATH_MAX+1]; /* hash table */
6703 	char *p = dirstack;
6704 	char *q = name;
6705 	char *savp;
6706 
6707 	if (q) {
6708 		/*
6709 		 * Find common prefix
6710 		 */
6711 
6712 		while (*p == *q && *p) {
6713 			p++; q++;
6714 		}
6715 	}
6716 
6717 	savp = p;
6718 	while (*p) {
6719 		/*
6720 		 * Not a child: unwind the stack, setting the times.
6721 		 * The order we do this doesn't matter, so we go "forward."
6722 		 */
6723 
6724 		if (*p == '/')
6725 			if (modtimes[p - dirstack].tv_sec >= 0) {
6726 				*p = '\0';	 /* zap the slash */
6727 				setPathTimes(AT_FDCWD, dirstack,
6728 				    modtimes[p - dirstack]);
6729 				*p = '/';
6730 			}
6731 		++p;
6732 	}
6733 
6734 	p = savp;
6735 
6736 	/*
6737 	 *  Push this one on the "stack"
6738 	 */
6739 
6740 	if (q) {
6741 
6742 		/*
6743 		 * Since the name parameter points the dir pathname
6744 		 * which is limited only to contain PATH_MAX chars
6745 		 * at maximum, we can ignore the overflow case of p.
6746 		 */
6747 
6748 		while ((*p = *q++)) {	/* append the rest of the new dir */
6749 			modtimes[p - dirstack].tv_sec = -1;
6750 			p++;
6751 		}
6752 
6753 		/*
6754 		 * If the tar file had used 'P' or 'E' function modifier,
6755 		 * append the last slash.
6756 		 */
6757 		if (*(p - 1) != '/') {
6758 			*p++ = '/';
6759 			*p = '\0';
6760 		}
6761 		/* overwrite the last one */
6762 		modtimes[p - dirstack - 1] = modTime;
6763 	}
6764 }
6765 
6766 
6767 /*
6768  *  setPathTimes - set the modification time for given path.  Return 1 if
6769  *                 successful and 0 if not successful.
6770  */
6771 
6772 static void
6773 setPathTimes(int dirfd, char *path, timestruc_t modTime)
6774 
6775 {
6776 	struct timeval timebuf[2];
6777 
6778 	/*
6779 	 * futimesat takes an array of two timeval structs.
6780 	 * The first entry contains access time.
6781 	 * The second entry contains modification time.
6782 	 * Unlike a timestruc_t, which uses nanoseconds, timeval uses
6783 	 * microseconds.
6784 	 */
6785 	timebuf[0].tv_sec = time((time_t *)0);
6786 	timebuf[0].tv_usec = 0;
6787 	timebuf[1].tv_sec = modTime.tv_sec;
6788 
6789 	/* Extended header: use microseconds */
6790 	timebuf[1].tv_usec = (xhdr_flgs & _X_MTIME) ? modTime.tv_nsec/1000 : 0;
6791 
6792 	if (futimesat(dirfd, path, timebuf) < 0)
6793 		vperror(0, gettext("can't set time on %s"), path);
6794 }
6795 
6796 
6797 /*
6798  * If hflag is set then delete the symbolic link's target.
6799  * If !hflag then delete the target.
6800  */
6801 
6802 static void
6803 delete_target(int fd, char *comp, char *namep)
6804 {
6805 	struct	stat	xtractbuf;
6806 	char buf[PATH_MAX + 1];
6807 	int n;
6808 
6809 
6810 	if (unlinkat(fd, comp, AT_REMOVEDIR) < 0) {
6811 		if (errno == ENOTDIR && !hflag) {
6812 			(void) unlinkat(fd, comp, 0);
6813 		} else if (errno == ENOTDIR && hflag) {
6814 			if (!lstat(namep, &xtractbuf)) {
6815 				if ((xtractbuf.st_mode & S_IFMT) != S_IFLNK) {
6816 					(void) unlinkat(fd, comp, 0);
6817 				} else if ((n = readlink(namep, buf,
6818 				    PATH_MAX)) != -1) {
6819 					buf[n] = (char)NULL;
6820 					(void) unlinkat(fd, buf,
6821 					    AT_REMOVEDIR);
6822 					if (errno == ENOTDIR)
6823 						(void) unlinkat(fd, buf, 0);
6824 				} else {
6825 					(void) unlinkat(fd, comp, 0);
6826 				}
6827 			} else {
6828 				(void) unlinkat(fd, comp, 0);
6829 			}
6830 		}
6831 	}
6832 }
6833 
6834 
6835 /*
6836  * ACL changes:
6837  *	putfile():
6838  *		Get acl info after stat. Write out ancillary file
6839  *		before the normal file, i.e. directory, regular, FIFO,
6840  *		link, special. If acl count is less than 4, no need to
6841  *		create ancillary file. (i.e. standard permission is in
6842  *		use.
6843  *	doxtract():
6844  *		Process ancillary file. Read it in and set acl info.
6845  *		watch out for 'o' function modifier.
6846  *	't' function letter to display table
6847  */
6848 
6849 /*
6850  * New functions for ACLs and other security attributes
6851  */
6852 
6853 /*
6854  * The function appends the new security attribute info to the end of
6855  * existing secinfo.
6856  */
6857 int
6858 append_secattr(
6859 	char	 **secinfo,	/* existing security info */
6860 	int	 *secinfo_len,	/* length of existing security info */
6861 	int	 size,		/* new attribute size: unit depends on type */
6862 	char	*attrtext,	/* new attribute text */
6863 	char	 attr_type)	/* new attribute type */
6864 {
6865 	char	*new_secinfo;
6866 	int	newattrsize;
6867 	int	oldsize;
6868 	struct sec_attr	*attr;
6869 
6870 	/* no need to add */
6871 	if (attr_type != DIR_TYPE) {
6872 		if (attrtext == NULL)
6873 			return (0);
6874 	}
6875 
6876 	switch (attr_type) {
6877 	case UFSD_ACL:
6878 	case ACE_ACL:
6879 		if (attrtext == NULL) {
6880 			(void) fprintf(stderr, gettext("acltotext failed\n"));
6881 			return (-1);
6882 		}
6883 		/* header: type + size = 8 */
6884 		newattrsize = 8 + (int)strlen(attrtext) + 1;
6885 		attr = (struct sec_attr *)malloc(newattrsize);
6886 		if (attr == NULL) {
6887 			(void) fprintf(stderr,
6888 			    gettext("can't allocate memory\n"));
6889 			return (-1);
6890 		}
6891 		attr->attr_type = attr_type;
6892 		(void) sprintf(attr->attr_len,
6893 		    "%06o", size); /* acl entry count */
6894 		(void) strcpy((char *)&attr->attr_info[0], attrtext);
6895 		free(attrtext);
6896 		break;
6897 
6898 	/* Trusted Extensions */
6899 	case DIR_TYPE:
6900 	case LBL_TYPE:
6901 		newattrsize = sizeof (struct sec_attr) + strlen(attrtext);
6902 		attr = (struct sec_attr *)malloc(newattrsize);
6903 		if (attr == NULL) {
6904 			(void) fprintf(stderr,
6905 			gettext("can't allocate memory\n"));
6906 			return (-1);
6907 		}
6908 		attr->attr_type = attr_type;
6909 		(void) sprintf(attr->attr_len,
6910 		    "%06d", size); /* len of attr data */
6911 		(void) strcpy((char *)&attr->attr_info[0], attrtext);
6912 		break;
6913 
6914 	default:
6915 		(void) fprintf(stderr,
6916 		    gettext("unrecognized attribute type\n"));
6917 		return (-1);
6918 	}
6919 
6920 	/* old security info + new attr header(8) + new attr */
6921 	oldsize = *secinfo_len;
6922 	*secinfo_len += newattrsize;
6923 	new_secinfo = (char *)malloc(*secinfo_len);
6924 	if (new_secinfo == NULL) {
6925 		(void) fprintf(stderr, gettext("can't allocate memory\n"));
6926 		*secinfo_len -= newattrsize;
6927 		free(attr);
6928 		return (-1);
6929 	}
6930 
6931 	(void) memcpy(new_secinfo, *secinfo, oldsize);
6932 	(void) memcpy(new_secinfo + oldsize, attr, newattrsize);
6933 
6934 	free(*secinfo);
6935 	free(attr);
6936 	*secinfo = new_secinfo;
6937 	return (0);
6938 }
6939 
6940 /*
6941  * write_ancillary(): write out an ancillary file.
6942  *      The file has the same header as normal file except the type and size
6943  *      fields. The type is 'A' and size is the sum of all attributes
6944  *	in bytes.
6945  *	The body contains a list of attribute type, size and info. Currently,
6946  *	there is only ACL info.  This file is put before the normal file.
6947  */
6948 void
6949 write_ancillary(union hblock *dblockp, char *secinfo, int len, char hdrtype)
6950 {
6951 	long    blocks;
6952 	int	savflag;
6953 	int	savsize;
6954 
6955 	/* Just tranditional permissions or no security attribute info */
6956 	if (len == 0 || secinfo == NULL)
6957 		return;
6958 
6959 	/* save flag and size */
6960 	savflag = (dblockp->dbuf).typeflag;
6961 	(void) sscanf(dblockp->dbuf.size, "%12o", (uint_t *)&savsize);
6962 
6963 	/* special flag for ancillary file */
6964 	if (hdrtype == _XATTR_HDRTYPE)
6965 		dblockp->dbuf.typeflag = _XATTR_HDRTYPE;
6966 	else
6967 		dblockp->dbuf.typeflag = 'A';
6968 
6969 	/* for pre-2.5 versions of tar, need to make sure */
6970 	/* the ACL file is readable			  */
6971 	(void) sprintf(dblock.dbuf.mode, "%07lo",
6972 	    (stbuf.st_mode & POSIXMODES) | 0000200);
6973 	(void) sprintf(dblockp->dbuf.size, "%011o", len);
6974 	(void) sprintf(dblockp->dbuf.chksum, "%07o", checksum(dblockp));
6975 
6976 	/* write out the header */
6977 	(void) writetbuf((char *)dblockp, 1);
6978 
6979 	/* write out security info */
6980 	blocks = TBLOCKS(len);
6981 	(void) writetbuf((char *)secinfo, (int)blocks);
6982 
6983 	/* restore mode, flag and size */
6984 	(void) sprintf(dblock.dbuf.mode, "%07lo", stbuf.st_mode & POSIXMODES);
6985 	dblockp->dbuf.typeflag = savflag;
6986 	(void) sprintf(dblockp->dbuf.size, "%011o", savsize);
6987 }
6988 
6989 /*
6990  * Read the data record for extended headers and then the regular header.
6991  * The data are read into the buffer and then null-terminated.  Entries
6992  * for typeflag 'X' extended headers are of the format:
6993  * 	"%d %s=%s\n"
6994  *
6995  * When an extended header record is found, the extended header must
6996  * be processed and its values used to override the values in the
6997  * normal header.  The way this is done is to process the extended
6998  * header data record and set the data values, then call getdir
6999  * to process the regular header, then then to reconcile the two
7000  * sets of data.
7001  */
7002 
7003 static int
7004 get_xdata(void)
7005 {
7006 	struct keylist_pair {
7007 		int keynum;
7008 		char *keylist;
7009 	}	keylist_pair[] = {	_X_DEVMAJOR, "SUN.devmajor",
7010 					_X_DEVMINOR, "SUN.devminor",
7011 					_X_GID, "gid",
7012 					_X_GNAME, "gname",
7013 					_X_LINKPATH, "linkpath",
7014 					_X_PATH, "path",
7015 					_X_SIZE, "size",
7016 					_X_UID, "uid",
7017 					_X_UNAME, "uname",
7018 					_X_MTIME, "mtime",
7019 					_X_LAST, "NULL" };
7020 	char		*lineloc;
7021 	int		length, i;
7022 	char		*keyword, *value;
7023 	blkcnt_t	nblocks;
7024 	int		bufneeded;
7025 	int		errors;
7026 
7027 	(void) memset(&Xtarhdr, 0, sizeof (Xtarhdr));
7028 	xhdr_count++;
7029 	errors = 0;
7030 
7031 	nblocks = TBLOCKS(stbuf.st_size);
7032 	bufneeded = nblocks * TBLOCK;
7033 	if (bufneeded >= xrec_size) {
7034 		free(xrec_ptr);
7035 		xrec_size = bufneeded + 1;
7036 		if ((xrec_ptr = malloc(xrec_size)) == NULL)
7037 			fatal(gettext("cannot allocate buffer"));
7038 	}
7039 
7040 	lineloc = xrec_ptr;
7041 
7042 	while (nblocks-- > 0) {
7043 		readtape(lineloc);
7044 		lineloc += TBLOCK;
7045 	}
7046 	lineloc = xrec_ptr;
7047 	xrec_ptr[stbuf.st_size] = '\0';
7048 	while (lineloc < xrec_ptr + stbuf.st_size) {
7049 		if (dblock.dbuf.typeflag == 'L') {
7050 			length = xrec_size;
7051 			keyword = "path";
7052 			value = lineloc;
7053 		} else {
7054 			length = atoi(lineloc);
7055 			*(lineloc + length - 1) = '\0';
7056 			keyword = strchr(lineloc, ' ') + 1;
7057 			value = strchr(keyword, '=') + 1;
7058 			*(value - 1) = '\0';
7059 		}
7060 		i = 0;
7061 		lineloc += length;
7062 		while (keylist_pair[i].keynum != (int)_X_LAST) {
7063 			if (strcmp(keyword, keylist_pair[i].keylist) == 0)
7064 				break;
7065 			i++;
7066 		}
7067 		errno = 0;
7068 		switch (keylist_pair[i].keynum) {
7069 		case _X_DEVMAJOR:
7070 			Xtarhdr.x_devmajor = (major_t)strtoul(value, NULL, 0);
7071 			if (errno) {
7072 				(void) fprintf(stderr, gettext(
7073 				    "tar: Extended header major value error "
7074 				    "for file # %llu.\n"), xhdr_count);
7075 				errors++;
7076 			} else
7077 				xhdr_flgs |= _X_DEVMAJOR;
7078 			break;
7079 		case _X_DEVMINOR:
7080 			Xtarhdr.x_devminor = (minor_t)strtoul(value, NULL, 0);
7081 			if (errno) {
7082 				(void) fprintf(stderr, gettext(
7083 				    "tar: Extended header minor value error "
7084 				    "for file # %llu.\n"), xhdr_count);
7085 				errors++;
7086 			} else
7087 				xhdr_flgs |= _X_DEVMINOR;
7088 			break;
7089 		case _X_GID:
7090 			xhdr_flgs |= _X_GID;
7091 			Xtarhdr.x_gid = strtol(value, NULL, 0);
7092 			if ((errno) || (Xtarhdr.x_gid > UID_MAX)) {
7093 				(void) fprintf(stderr, gettext(
7094 				    "tar: Extended header gid value error "
7095 				    "for file # %llu.\n"), xhdr_count);
7096 				Xtarhdr.x_gid = GID_NOBODY;
7097 			}
7098 			break;
7099 		case _X_GNAME:
7100 			if (utf8_local("gname", &Xtarhdr.x_gname,
7101 			    local_gname, value, _POSIX_NAME_MAX) == 0)
7102 				xhdr_flgs |= _X_GNAME;
7103 			break;
7104 		case _X_LINKPATH:
7105 			if (utf8_local("linkpath", &Xtarhdr.x_linkpath,
7106 			    local_linkpath, value, PATH_MAX) == 0)
7107 				xhdr_flgs |= _X_LINKPATH;
7108 			else
7109 				errors++;
7110 			break;
7111 		case _X_PATH:
7112 			if (utf8_local("path", &Xtarhdr.x_path,
7113 			    local_path, value, PATH_MAX) == 0)
7114 				xhdr_flgs |= _X_PATH;
7115 			else
7116 				errors++;
7117 			break;
7118 		case _X_SIZE:
7119 			Xtarhdr.x_filesz = strtoull(value, NULL, 0);
7120 			if (errno) {
7121 				(void) fprintf(stderr, gettext(
7122 				    "tar: Extended header invalid filesize "
7123 				    "for file # %llu.\n"), xhdr_count);
7124 				errors++;
7125 			} else
7126 				xhdr_flgs |= _X_SIZE;
7127 			break;
7128 		case _X_UID:
7129 			xhdr_flgs |= _X_UID;
7130 			Xtarhdr.x_uid = strtol(value, NULL, 0);
7131 			if ((errno) || (Xtarhdr.x_uid > UID_MAX)) {
7132 				(void) fprintf(stderr, gettext(
7133 				    "tar: Extended header uid value error "
7134 				    "for file # %llu.\n"), xhdr_count);
7135 				Xtarhdr.x_uid = UID_NOBODY;
7136 			}
7137 			break;
7138 		case _X_UNAME:
7139 			if (utf8_local("uname", &Xtarhdr.x_uname,
7140 			    local_uname, value, _POSIX_NAME_MAX) == 0)
7141 				xhdr_flgs |= _X_UNAME;
7142 			break;
7143 		case _X_MTIME:
7144 			get_xtime(value, &(Xtarhdr.x_mtime));
7145 			if (errno)
7146 				(void) fprintf(stderr, gettext(
7147 				    "tar: Extended header modification time "
7148 				    "value error for file # %llu.\n"),
7149 				    xhdr_count);
7150 			else
7151 				xhdr_flgs |= _X_MTIME;
7152 			break;
7153 		default:
7154 			(void) fprintf(stderr,
7155 			    gettext("tar:  unrecognized extended"
7156 			    " header keyword '%s'.  Ignored.\n"), keyword);
7157 			break;
7158 		}
7159 	}
7160 
7161 	getdir();	/* get regular header */
7162 	if (errors && errflag)
7163 		done(1);
7164 	else
7165 		if (errors)
7166 			Errflg = 1;
7167 	return (errors);
7168 }
7169 
7170 /*
7171  * load_info_from_xtarhdr - sets Gen and stbuf variables from
7172  *	extended header
7173  *	load_info_from_xtarhdr(flag, xhdrp);
7174  *	u_longlong_t flag;	xhdr_flgs
7175  *	struct xtar_hdr *xhdrp; pointer to extended header
7176  *	NOTE:	called when typeflag is not 'A' and xhdr_flgs
7177  *		is set.
7178  */
7179 static void
7180 load_info_from_xtarhdr(u_longlong_t flag, struct xtar_hdr *xhdrp)
7181 {
7182 	if (flag & _X_DEVMAJOR) {
7183 		Gen.g_devmajor = xhdrp->x_devmajor;
7184 	}
7185 	if (flag & _X_DEVMINOR) {
7186 		Gen.g_devminor = xhdrp->x_devminor;
7187 	}
7188 	if (flag & _X_GID) {
7189 		Gen.g_gid = xhdrp->x_gid;
7190 		stbuf.st_gid = xhdrp->x_gid;
7191 	}
7192 	if (flag & _X_UID) {
7193 		Gen.g_uid = xhdrp->x_uid;
7194 		stbuf.st_uid  = xhdrp->x_uid;
7195 	}
7196 	if (flag & _X_SIZE) {
7197 		Gen.g_filesz = xhdrp->x_filesz;
7198 		stbuf.st_size = xhdrp->x_filesz;
7199 	}
7200 	if (flag & _X_MTIME) {
7201 		Gen.g_mtime = xhdrp->x_mtime.tv_sec;
7202 		stbuf.st_mtim.tv_sec = xhdrp->x_mtime.tv_sec;
7203 		stbuf.st_mtim.tv_nsec = xhdrp->x_mtime.tv_nsec;
7204 	}
7205 }
7206 
7207 /*
7208  * gen_num creates a string from a keyword and an usigned long long in the
7209  * format:  %d %s=%s\n
7210  * This is part of the extended header data record.
7211  */
7212 
7213 void
7214 gen_num(const char *keyword, const u_longlong_t number)
7215 {
7216 	char	save_val[ULONGLONG_MAX_DIGITS + 1];
7217 	int	len;
7218 	char	*curr_ptr;
7219 
7220 	(void) sprintf(save_val, "%llu", number);
7221 	/*
7222 	 * len = length of entire line, including itself.  len will be
7223 	 * two digits.  So, add the string lengths plus the length of len,
7224 	 * plus a blank, an equal sign, and a newline.
7225 	 */
7226 	len = strlen(save_val) + strlen(keyword) + 5;
7227 	if (xrec_offset + len > xrec_size) {
7228 		if (((curr_ptr = realloc(xrec_ptr, 2 * xrec_size)) == NULL))
7229 			fatal(gettext(
7230 			    "cannot allocate extended header buffer"));
7231 		xrec_ptr = curr_ptr;
7232 		xrec_size *= 2;
7233 	}
7234 	(void) sprintf(&xrec_ptr[xrec_offset],
7235 	    "%d %s=%s\n", len, keyword, save_val);
7236 	xrec_offset += len;
7237 }
7238 
7239 /*
7240  * gen_date creates a string from a keyword and a timestruc_t in the
7241  * format:  %d %s=%s\n
7242  * This is part of the extended header data record.
7243  * Currently, granularity is only microseconds, so the low-order three digits
7244  * will be truncated.
7245  */
7246 
7247 void
7248 gen_date(const char *keyword, const timestruc_t time_value)
7249 {
7250 	/* Allow for <seconds>.<nanoseconds>\n */
7251 	char	save_val[TIME_MAX_DIGITS + LONG_MAX_DIGITS + 2];
7252 	int	len;
7253 	char	*curr_ptr;
7254 
7255 	(void) sprintf(save_val, "%ld", time_value.tv_sec);
7256 	len = strlen(save_val);
7257 	save_val[len] = '.';
7258 	(void) sprintf(&save_val[len + 1], "%9.9ld", time_value.tv_nsec);
7259 
7260 	/*
7261 	 * len = length of entire line, including itself.  len will be
7262 	 * two digits.  So, add the string lengths plus the length of len,
7263 	 * plus a blank, an equal sign, and a newline.
7264 	 */
7265 	len = strlen(save_val) + strlen(keyword) + 5;
7266 	if (xrec_offset + len > xrec_size) {
7267 		if (((curr_ptr = realloc(xrec_ptr, 2 * xrec_size)) == NULL))
7268 			fatal(gettext(
7269 			    "cannot allocate extended header buffer"));
7270 		xrec_ptr = curr_ptr;
7271 		xrec_size *= 2;
7272 	}
7273 	(void) sprintf(&xrec_ptr[xrec_offset],
7274 	    "%d %s=%s\n", len, keyword, save_val);
7275 	xrec_offset += len;
7276 }
7277 
7278 /*
7279  * gen_string creates a string from a keyword and a char * in the
7280  * format:  %d %s=%s\n
7281  * This is part of the extended header data record.
7282  */
7283 
7284 void
7285 gen_string(const char *keyword, const char *value)
7286 {
7287 	int	len;
7288 	char	*curr_ptr;
7289 
7290 	/*
7291 	 * len = length of entire line, including itself.  The character length
7292 	 * of len must be 1-4 characters, because the maximum size of the path
7293 	 * or the name is PATH_MAX, which is 1024.  So, assume 1 character
7294 	 * for len, one for the space, one for the "=", and one for the newline.
7295 	 * Then adjust as needed.
7296 	 */
7297 	/* LINTED constant expression */
7298 	assert(PATH_MAX <= 9996);
7299 	len = strlen(value) + strlen(keyword) + 4;
7300 	if (len > 997)
7301 		len += 3;
7302 	else if (len > 98)
7303 		len += 2;
7304 	else if (len > 9)
7305 		len += 1;
7306 	if (xrec_offset + len > xrec_size) {
7307 		if (((curr_ptr = realloc(xrec_ptr, 2 * xrec_size)) == NULL))
7308 			fatal(gettext(
7309 			    "cannot allocate extended header buffer"));
7310 		xrec_ptr = curr_ptr;
7311 		xrec_size *= 2;
7312 	}
7313 #ifdef XHDR_DEBUG
7314 	if (strcmp(keyword+1, "name") != 0)
7315 #endif
7316 	(void) sprintf(&xrec_ptr[xrec_offset],
7317 	    "%d %s=%s\n", len, keyword, value);
7318 #ifdef XHDR_DEBUG
7319 	else {
7320 	len += 11;
7321 	(void) sprintf(&xrec_ptr[xrec_offset],
7322 	    "%d %s=%snametoolong\n", len, keyword, value);
7323 	}
7324 #endif
7325 	xrec_offset += len;
7326 }
7327 
7328 /*
7329  * Convert time found in the extended header data to seconds and nanoseconds.
7330  */
7331 
7332 void
7333 get_xtime(char *value, timestruc_t *xtime)
7334 {
7335 	char nanosec[10];
7336 	char *period;
7337 	int i;
7338 
7339 	(void) memset(nanosec, '0', 9);
7340 	nanosec[9] = '\0';
7341 
7342 	period = strchr(value, '.');
7343 	if (period != NULL)
7344 		period[0] = '\0';
7345 	xtime->tv_sec = strtol(value, NULL, 10);
7346 	if (period == NULL)
7347 		xtime->tv_nsec = 0;
7348 	else {
7349 		i = strlen(period +1);
7350 		(void) strncpy(nanosec, period + 1, min(i, 9));
7351 		xtime->tv_nsec = strtol(nanosec, NULL, 10);
7352 	}
7353 }
7354 
7355 /*
7356  *	Check linkpath for length.
7357  *	Emit an error message and return 1 if too long.
7358  */
7359 
7360 int
7361 chk_path_build(
7362 	char	*name,
7363 	char	*longname,
7364 	char	*linkname,
7365 	char	*prefix,
7366 	char	type,
7367 	int	filetype)
7368 {
7369 
7370 	if (strlen(linkname) > (size_t)NAMSIZ) {
7371 		if (Eflag > 0) {
7372 			xhdr_flgs |= _X_LINKPATH;
7373 			Xtarhdr.x_linkpath = linkname;
7374 		} else {
7375 			(void) fprintf(stderr, gettext(
7376 			    "tar: %s: linked to %s\n"), longname, linkname);
7377 			(void) fprintf(stderr, gettext(
7378 			    "tar: %s: linked name too long\n"), linkname);
7379 			if (errflag)
7380 				done(1);
7381 			else
7382 				Errflg = 1;
7383 			return (1);
7384 		}
7385 	}
7386 	if (xhdr_flgs & _X_LINKPATH)
7387 		return (build_dblock(name, tchar, type,
7388 		    filetype, &stbuf, stbuf.st_dev,
7389 		    prefix));
7390 	else
7391 		return (build_dblock(name, linkname, type,
7392 		    filetype, &stbuf, stbuf.st_dev, prefix));
7393 }
7394 
7395 /*
7396  * Convert from UTF-8 to local character set.
7397  */
7398 
7399 static int
7400 utf8_local(
7401 	char		*option,
7402 	char		**Xhdr_ptrptr,
7403 	char		*target,
7404 	const char	*source,
7405 	int		max_val)
7406 {
7407 	static	iconv_t	iconv_cd;
7408 	char		*nl_target;
7409 	const	char	*iconv_src;
7410 	char		*iconv_trg;
7411 	size_t		inlen;
7412 	size_t		outlen;
7413 
7414 	if (charset_type == -1) {	/* iconv_open failed in earlier try */
7415 		(void) fprintf(stderr, gettext(
7416 		    "tar:  file # %llu: (%s) UTF-8 conversion failed.\n"),
7417 		    xhdr_count, source);
7418 		return (1);
7419 	} else if (charset_type == 0) {	/* iconv_open has not yet been done */
7420 		nl_target = nl_langinfo(CODESET);
7421 		if (strlen(nl_target) == 0)	/* locale using 7-bit codeset */
7422 			nl_target = "646";
7423 		if (strcmp(nl_target, "646") == 0)
7424 			charset_type = 1;
7425 		else if (strcmp(nl_target, "UTF-8") == 0)
7426 			charset_type = 3;
7427 		else {
7428 			if (strncmp(nl_target, "ISO", 3) == 0)
7429 				nl_target += 3;
7430 			charset_type = 2;
7431 			errno = 0;
7432 			if ((iconv_cd = iconv_open(nl_target, "UTF-8")) ==
7433 			    (iconv_t)-1) {
7434 				if (errno == EINVAL)
7435 					(void) fprintf(stderr, gettext(
7436 					    "tar: conversion routines not "
7437 					    "available for current locale.  "));
7438 				(void) fprintf(stderr, gettext(
7439 				    "file # %llu: (%s) UTF-8 conversion"
7440 				    " failed.\n"), xhdr_count, source);
7441 				charset_type = -1;
7442 				return (1);
7443 			}
7444 		}
7445 	}
7446 
7447 	/* locale using 7-bit codeset or UTF-8 locale */
7448 	if (charset_type == 1 || charset_type == 3) {
7449 		if (strlen(source) > max_val) {
7450 			(void) fprintf(stderr, gettext(
7451 			    "tar: file # %llu: Extended header %s too long.\n"),
7452 			    xhdr_count, option);
7453 			return (1);
7454 		}
7455 		if (charset_type == 3)
7456 			(void) strcpy(target, source);
7457 		else if (c_utf8(target, source) != 0) {
7458 			(void) fprintf(stderr, gettext(
7459 			    "tar:  file # %llu: (%s) UTF-8 conversion"
7460 			    " failed.\n"), xhdr_count, source);
7461 			return (1);
7462 		}
7463 		*Xhdr_ptrptr = target;
7464 		return (0);
7465 	}
7466 
7467 	iconv_src = source;
7468 	iconv_trg = target;
7469 	inlen = strlen(source);
7470 	outlen = max_val * UTF_8_FACTOR;
7471 	if (iconv(iconv_cd, &iconv_src, &inlen, &iconv_trg, &outlen) ==
7472 	    (size_t)-1) {	/* Error occurred:  didn't convert */
7473 		(void) fprintf(stderr, gettext(
7474 		    "tar:  file # %llu: (%s) UTF-8 conversion failed.\n"),
7475 		    xhdr_count, source);
7476 		/* Get remaining output; reinitialize conversion descriptor */
7477 		iconv_src = (const char *)NULL;
7478 		inlen = 0;
7479 		(void) iconv(iconv_cd, &iconv_src, &inlen, &iconv_trg, &outlen);
7480 		return (1);
7481 	}
7482 	/* Get remaining output; reinitialize conversion descriptor */
7483 	iconv_src = (const char *)NULL;
7484 	inlen = 0;
7485 	if (iconv(iconv_cd, &iconv_src, &inlen, &iconv_trg, &outlen) ==
7486 	    (size_t)-1) {	/* Error occurred:  didn't convert */
7487 		(void) fprintf(stderr, gettext(
7488 		    "tar:  file # %llu: (%s) UTF-8 conversion failed.\n"),
7489 		    xhdr_count, source);
7490 		return (1);
7491 	}
7492 
7493 	*iconv_trg = '\0';	/* Null-terminate iconv output string */
7494 	if (strlen(target) > max_val) {
7495 		(void) fprintf(stderr, gettext(
7496 		    "tar: file # %llu: Extended header %s too long.\n"),
7497 		    xhdr_count, option);
7498 		return (1);
7499 	}
7500 	*Xhdr_ptrptr = target;
7501 	return (0);
7502 }
7503 
7504 /*
7505  * Check gname, uname, path, and linkpath to see if they need to go in an
7506  * extended header.  If they are already slated to be in an extended header,
7507  * or if they are not ascii, then they need to be in the extended header.
7508  * Then, convert all extended names to UTF-8.
7509  */
7510 
7511 int
7512 gen_utf8_names(const char *filename)
7513 {
7514 	static	iconv_t	iconv_cd;
7515 	char		*nl_target;
7516 	char		tempbuf[MAXNAM + 1];
7517 	int		nbytes;
7518 	int		errors;
7519 
7520 	if (charset_type == -1)	{	/* Previous failure to open. */
7521 		(void) fprintf(stderr, gettext(
7522 		    "tar: file # %llu: UTF-8 conversion failed.\n"),
7523 		    xhdr_count);
7524 		return (1);
7525 	}
7526 
7527 	if (charset_type == 0) {	/* Need to get conversion descriptor */
7528 		nl_target = nl_langinfo(CODESET);
7529 		if (strlen(nl_target) == 0)	/* locale using 7-bit codeset */
7530 			nl_target = "646";
7531 		if (strcmp(nl_target, "646") == 0)
7532 			charset_type = 1;
7533 		else if (strcmp(nl_target, "UTF-8") == 0)
7534 			charset_type = 3;
7535 		else {
7536 			if (strncmp(nl_target, "ISO", 3) == 0)
7537 				nl_target += 3;
7538 			charset_type = 2;
7539 			errno = 0;
7540 #ifdef ICONV_DEBUG
7541 			(void) fprintf(stderr,
7542 			    gettext("Opening iconv_cd with target %s\n"),
7543 			    nl_target);
7544 #endif
7545 			if ((iconv_cd = iconv_open("UTF-8", nl_target)) ==
7546 			    (iconv_t)-1) {
7547 				if (errno == EINVAL)
7548 					(void) fprintf(stderr, gettext(
7549 					    "tar: conversion routines not "
7550 					    "available for current locale.  "));
7551 				(void) fprintf(stderr, gettext(
7552 				    "file (%s): UTF-8 conversion failed.\n"),
7553 				    filename);
7554 				charset_type = -1;
7555 				return (1);
7556 			}
7557 		}
7558 	}
7559 
7560 	errors = 0;
7561 
7562 	errors += local_utf8(&Xtarhdr.x_gname, local_gname,
7563 	    dblock.dbuf.gname, iconv_cd, _X_GNAME, _POSIX_NAME_MAX);
7564 	errors += local_utf8(&Xtarhdr.x_uname, local_uname,
7565 	    dblock.dbuf.uname, iconv_cd, _X_UNAME,  _POSIX_NAME_MAX);
7566 	if ((xhdr_flgs & _X_LINKPATH) == 0) {	/* Need null-terminated str. */
7567 		(void) strncpy(tempbuf, dblock.dbuf.linkname, NAMSIZ);
7568 		tempbuf[NAMSIZ] = '\0';
7569 	}
7570 	errors += local_utf8(&Xtarhdr.x_linkpath, local_linkpath,
7571 	    tempbuf, iconv_cd, _X_LINKPATH, PATH_MAX);
7572 	if ((xhdr_flgs & _X_PATH) == 0) {	/* Concatenate prefix & name */
7573 		(void) strncpy(tempbuf, dblock.dbuf.prefix, PRESIZ);
7574 		tempbuf[PRESIZ] = '\0';
7575 		nbytes = strlen(tempbuf);
7576 		if (nbytes > 0) {
7577 			tempbuf[nbytes++] = '/';
7578 			tempbuf[nbytes] = '\0';
7579 		}
7580 		(void) strncat(tempbuf + nbytes, dblock.dbuf.name,
7581 		    (MAXNAM - nbytes));
7582 		tempbuf[MAXNAM] = '\0';
7583 	}
7584 	errors += local_utf8(&Xtarhdr.x_path, local_path,
7585 	    tempbuf, iconv_cd, _X_PATH, PATH_MAX);
7586 
7587 	if (errors > 0)
7588 		(void) fprintf(stderr, gettext(
7589 		    "tar: file (%s): UTF-8 conversion failed.\n"), filename);
7590 
7591 	if (errors && errflag)
7592 		done(1);
7593 	else
7594 		if (errors)
7595 			Errflg = 1;
7596 	return (errors);
7597 }
7598 
7599 static int
7600 local_utf8(
7601 		char	**Xhdr_ptrptr,
7602 		char	*target,
7603 		const	char	*source,
7604 		iconv_t	iconv_cd,
7605 		int	xhdrflg,
7606 		int	max_val)
7607 {
7608 	const	char	*iconv_src;
7609 	const	char	*starting_src;
7610 	char		*iconv_trg;
7611 	size_t		inlen;
7612 	size_t		outlen;
7613 #ifdef ICONV_DEBUG
7614 	unsigned char	c_to_hex;
7615 #endif
7616 
7617 	/*
7618 	 * If the item is already slated for extended format, get the string
7619 	 * to convert from the extended header record.  Otherwise, get it from
7620 	 * the regular (dblock) area.
7621 	 */
7622 	if (xhdr_flgs & xhdrflg) {
7623 		if (charset_type == 3) {	/* Already UTF-8, just copy */
7624 			(void) strcpy(target, *Xhdr_ptrptr);
7625 			*Xhdr_ptrptr = target;
7626 			return (0);
7627 		} else
7628 			iconv_src = (const char *) *Xhdr_ptrptr;
7629 	} else {
7630 		if (charset_type == 3)		/* Already in UTF-8 format */
7631 			return (0);		/* Don't create xhdr record */
7632 		iconv_src = source;
7633 	}
7634 	starting_src = iconv_src;
7635 	iconv_trg = target;
7636 	if ((inlen = strlen(iconv_src)) == 0)
7637 		return (0);
7638 
7639 	if (charset_type == 1) {	/* locale using 7-bit codeset */
7640 		if (c_utf8(target, starting_src) != 0) {
7641 			(void) fprintf(stderr,
7642 			    gettext("tar: invalid character in"
7643 			    " UTF-8 conversion of '%s'\n"), starting_src);
7644 			return (1);
7645 		}
7646 		return (0);
7647 	}
7648 
7649 	outlen = max_val * UTF_8_FACTOR;
7650 	errno = 0;
7651 	if (iconv(iconv_cd, &iconv_src, &inlen, &iconv_trg, &outlen) ==
7652 	    (size_t)-1) {
7653 		/* An error occurred, or not all characters were converted */
7654 		if (errno == EILSEQ)
7655 			(void) fprintf(stderr,
7656 			    gettext("tar: invalid character in"
7657 			    " UTF-8 conversion of '%s'\n"), starting_src);
7658 		else
7659 			(void) fprintf(stderr, gettext(
7660 			    "tar: conversion to UTF-8 aborted for '%s'.\n"),
7661 			    starting_src);
7662 		/* Get remaining output; reinitialize conversion descriptor */
7663 		iconv_src = (const char *)NULL;
7664 		inlen = 0;
7665 		(void) iconv(iconv_cd, &iconv_src, &inlen, &iconv_trg, &outlen);
7666 		return (1);
7667 	}
7668 	/* Get remaining output; reinitialize conversion descriptor */
7669 	iconv_src = (const char *)NULL;
7670 	inlen = 0;
7671 	if (iconv(iconv_cd, &iconv_src, &inlen, &iconv_trg, &outlen) ==
7672 	    (size_t)-1) {	/* Error occurred:  didn't convert */
7673 		if (errno == EILSEQ)
7674 			(void) fprintf(stderr,
7675 			    gettext("tar: invalid character in"
7676 			    " UTF-8 conversion of '%s'\n"), starting_src);
7677 		else
7678 			(void) fprintf(stderr, gettext(
7679 			    "tar: conversion to UTF-8 aborted for '%s'.\n"),
7680 			    starting_src);
7681 		return (1);
7682 	}
7683 
7684 	*iconv_trg = '\0';	/* Null-terminate iconv output string */
7685 	if (strcmp(starting_src, target) != 0) {
7686 		*Xhdr_ptrptr = target;
7687 		xhdr_flgs |= xhdrflg;
7688 #ifdef ICONV_DEBUG
7689 		(void) fprintf(stderr, "***  inlen: %d %d; outlen: %d %d\n",
7690 		    strlen(starting_src), inlen, max_val, outlen);
7691 		(void) fprintf(stderr, "Input string:\n  ");
7692 		for (inlen = 0; inlen < strlen(starting_src); inlen++) {
7693 			c_to_hex = (unsigned char)starting_src[inlen];
7694 			(void) fprintf(stderr, " %2.2x", c_to_hex);
7695 			if (inlen % 20 == 19)
7696 				(void) fprintf(stderr, "\n  ");
7697 		}
7698 		(void) fprintf(stderr, "\nOutput string:\n  ");
7699 		for (inlen = 0; inlen < strlen(target); inlen++) {
7700 			c_to_hex = (unsigned char)target[inlen];
7701 			(void) fprintf(stderr, " %2.2x", c_to_hex);
7702 			if (inlen % 20 == 19)
7703 				(void) fprintf(stderr, "\n  ");
7704 		}
7705 		(void) fprintf(stderr, "\n");
7706 #endif
7707 	}
7708 
7709 	return (0);
7710 }
7711 
7712 /*
7713  *	Function to test each byte of the source string to make sure it is
7714  *	in within bounds (value between 0 and 127).
7715  *	If valid, copy source to target.
7716  */
7717 
7718 int
7719 c_utf8(char *target, const char *source)
7720 {
7721 	size_t		len;
7722 	const char	*thischar;
7723 
7724 	len = strlen(source);
7725 	thischar = source;
7726 	while (len-- > 0) {
7727 		if (!isascii((int)(*thischar++)))
7728 			return (1);
7729 	}
7730 
7731 	(void) strcpy(target, source);
7732 	return (0);
7733 }
7734 
7735 
7736 #if defined(O_XATTR)
7737 #define	ROUNDTOTBLOCK(a)	((a + (TBLOCK -1)) & ~(TBLOCK -1))
7738 
7739 static void
7740 prepare_xattr(
7741 	char		**attrbuf,
7742 	char		*filename,
7743 	char		*attrpath,
7744 	char		typeflag,
7745 	struct linkbuf	*linkinfo,
7746 	int		*rlen)
7747 {
7748 	char			*bufhead;	/* ptr to full buffer */
7749 	char			*aptr;
7750 	struct xattr_hdr 	*hptr;		/* ptr to header in bufhead */
7751 	struct xattr_buf	*tptr;		/* ptr to pathing pieces */
7752 	int			totalen;	/* total buffer length */
7753 	int			len;		/* length returned to user */
7754 	int			stringlen;	/* length of filename + attr */
7755 						/*
7756 						 * length of filename + attr
7757 						 * in link section
7758 						 */
7759 	int			linkstringlen;
7760 	int			complen;	/* length of pathing section */
7761 	int			linklen;	/* length of link section */
7762 	int			attrnames_index; /* attrnames starting index */
7763 
7764 	/*
7765 	 * Release previous buffer
7766 	 */
7767 
7768 	if (*attrbuf != (char *)NULL) {
7769 		free(*attrbuf);
7770 		*attrbuf = NULL;
7771 	}
7772 
7773 	/*
7774 	 * First add in fixed size stuff
7775 	 */
7776 	len = sizeof (struct xattr_hdr) + sizeof (struct xattr_buf);
7777 
7778 	/*
7779 	 * Add space for two nulls
7780 	 */
7781 	stringlen = strlen(attrpath) + strlen(filename) + 2;
7782 	complen = stringlen + sizeof (struct xattr_buf);
7783 
7784 	len += stringlen;
7785 
7786 	/*
7787 	 * Now add on space for link info if any
7788 	 */
7789 
7790 	if (linkinfo != NULL) {
7791 		/*
7792 		 * Again add space for two nulls
7793 		 */
7794 		linkstringlen = strlen(linkinfo->pathname) +
7795 		    strlen(linkinfo->attrname) + 2;
7796 		linklen = linkstringlen + sizeof (struct xattr_buf);
7797 		len += linklen;
7798 	} else {
7799 		linklen = 0;
7800 	}
7801 
7802 	/*
7803 	 * Now add padding to end to fill out TBLOCK
7804 	 *
7805 	 * Function returns size of real data and not size + padding.
7806 	 */
7807 
7808 	totalen = ROUNDTOTBLOCK(len);
7809 
7810 	if ((bufhead = calloc(1, totalen)) == NULL) {
7811 		fatal(gettext("Out of memory."));
7812 	}
7813 
7814 
7815 	/*
7816 	 * Now we can fill in the necessary pieces
7817 	 */
7818 
7819 	/*
7820 	 * first fill in the fixed header
7821 	 */
7822 	hptr = (struct xattr_hdr *)bufhead;
7823 	(void) sprintf(hptr->h_version, "%s", XATTR_ARCH_VERS);
7824 	(void) sprintf(hptr->h_component_len, "%0*d",
7825 	    sizeof (hptr->h_component_len) - 1, complen);
7826 	(void) sprintf(hptr->h_link_component_len, "%0*d",
7827 	    sizeof (hptr->h_link_component_len) - 1, linklen);
7828 	(void) sprintf(hptr->h_size, "%0*d", sizeof (hptr->h_size) - 1, len);
7829 
7830 	/*
7831 	 * Now fill in the filename + attrnames section
7832 	 * The filename and attrnames section can be composed of two or more
7833 	 * path segments separated by a null character.  The first segment
7834 	 * is the path to the parent file that roots the entire sequence in
7835 	 * the normal name space. The remaining segments describes a path
7836 	 * rooted at the hidden extended attribute directory of the leaf file of
7837 	 * the previous segment, making it possible to name attributes on
7838 	 * attributes.  Thus, if we are just archiving an extended attribute,
7839 	 * the second segment will contain the attribute name.  If we are
7840 	 * archiving a system attribute of an extended attribute, then the
7841 	 * second segment will contain the attribute name, and a third segment
7842 	 * will contain the system attribute name.  The attribute pathing
7843 	 * information is obtained from 'attrpath'.
7844 	 */
7845 
7846 	tptr = (struct xattr_buf *)(bufhead + sizeof (struct xattr_hdr));
7847 	(void) sprintf(tptr->h_namesz, "%0*d", sizeof (tptr->h_namesz) - 1,
7848 	    stringlen);
7849 	(void) strcpy(tptr->h_names, filename);
7850 	attrnames_index = strlen(filename) + 1;
7851 	(void) strcpy(&tptr->h_names[attrnames_index], attrpath);
7852 	tptr->h_typeflag = typeflag;
7853 
7854 	/*
7855 	 * Split the attrnames section into two segments if 'attrpath'
7856 	 * contains pathing information for a system attribute of an
7857 	 * extended attribute.  We split them by replacing the '/' with
7858 	 * a '\0'.
7859 	 */
7860 	if ((aptr = strpbrk(&tptr->h_names[attrnames_index], "/")) != NULL) {
7861 		*aptr = '\0';
7862 	}
7863 
7864 	/*
7865 	 * Now fill in the optional link section if we have one
7866 	 */
7867 
7868 	if (linkinfo != (struct linkbuf *)NULL) {
7869 		tptr = (struct xattr_buf *)(bufhead +
7870 		    sizeof (struct xattr_hdr) + complen);
7871 
7872 		(void) sprintf(tptr->h_namesz, "%0*d",
7873 		    sizeof (tptr->h_namesz) - 1, linkstringlen);
7874 		(void) strcpy(tptr->h_names, linkinfo->pathname);
7875 		(void) strcpy(
7876 		    &tptr->h_names[strlen(linkinfo->pathname) + 1],
7877 		    linkinfo->attrname);
7878 		tptr->h_typeflag = typeflag;
7879 	}
7880 	*attrbuf = (char *)bufhead;
7881 	*rlen = len;
7882 }
7883 
7884 #else
7885 static void
7886 prepare_xattr(
7887 	char		**attrbuf,
7888 	char		*filename,
7889 	char		*attrname,
7890 	char		typeflag,
7891 	struct linkbuf	*linkinfo,
7892 	int		*rlen)
7893 {
7894 	*attrbuf = NULL;
7895 	*rlen = 0;
7896 }
7897 #endif
7898 
7899 int
7900 getstat(int dirfd, char *longname, char *shortname, char *attrparent)
7901 {
7902 
7903 	int i, j;
7904 	int	printerr;
7905 	int	slnkerr;
7906 	struct stat symlnbuf;
7907 
7908 	if (!hflag)
7909 		i = fstatat(dirfd, shortname, &stbuf, AT_SYMLINK_NOFOLLOW);
7910 	else
7911 		i = fstatat(dirfd, shortname, &stbuf, 0);
7912 
7913 	if (i < 0) {
7914 		/* Initialize flag to print error mesg. */
7915 		printerr = 1;
7916 		/*
7917 		 * If stat is done, then need to do lstat
7918 		 * to determine whether it's a sym link
7919 		 */
7920 		if (hflag) {
7921 			/* Save returned error */
7922 			slnkerr = errno;
7923 
7924 			j = fstatat(dirfd, shortname,
7925 			    &symlnbuf, AT_SYMLINK_NOFOLLOW);
7926 			/*
7927 			 * Suppress error message when file is a symbolic link
7928 			 * and function modifier 'l' is off.  Exception:  when
7929 			 * a symlink points to a symlink points to a
7930 			 * symlink ... and we get past MAXSYMLINKS.  That
7931 			 * error will cause a file not to be archived, and
7932 			 * needs to be printed.
7933 			 */
7934 			if ((j == 0) && (!linkerrok) && (slnkerr != ELOOP) &&
7935 			    (S_ISLNK(symlnbuf.st_mode)))
7936 				printerr = 0;
7937 
7938 			/*
7939 			 * Restore errno in case the lstat
7940 			 * on symbolic link change
7941 			 */
7942 			errno = slnkerr;
7943 		}
7944 
7945 		if (printerr) {
7946 			(void) fprintf(stderr, gettext(
7947 			    "tar: %s%s%s%s: %s\n"),
7948 			    (attrparent == NULL) ? "" : gettext("attribute "),
7949 			    (attrparent == NULL) ? "" : attrparent,
7950 			    (attrparent == NULL) ? "" : gettext(" of "),
7951 			    longname, strerror(errno));
7952 			Errflg = 1;
7953 		}
7954 		return (1);
7955 	}
7956 	return (0);
7957 }
7958 
7959 /*
7960  * Recursively archive the extended attributes and/or extended system attributes
7961  * of the base file, longname.  Note:  extended system attribute files will be
7962  * archived only if the extended system attributes are not transient (i.e. the
7963  * extended system attributes are other than the default values).
7964  *
7965  * If -@ was specified and the underlying file system supports it, archive the
7966  * extended attributes, and if there is a system attribute associated with the
7967  * extended attribute, then recursively call xattrs_put() to archive the
7968  * hidden attribute directory and the extended system attribute.  If -/ was
7969  * specified and the underlying file system supports it, archive the extended
7970  * system attributes.  Read-only extended system attributes are never archived.
7971  *
7972  * Currently, there cannot be attributes on attributes; only system
7973  * attributes on attributes.  In addition, there cannot be attributes on
7974  * system attributes.  A file and it's attribute directory hierarchy looks as
7975  * follows:
7976  *	longname ---->	.	("." is the hidden attribute directory)
7977  *			|
7978  *	     ----------------------------
7979  *	     |				|
7980  *	<sys_attr_name>		   <attr_name> ---->	.
7981  *							|
7982  *						  <sys_attr_name>
7983  *
7984  */
7985 #if defined(O_XATTR)
7986 static void
7987 xattrs_put(char *longname, char *shortname, char *parent, char *attrparent)
7988 {
7989 	char *filename = (attrparent == NULL) ? shortname : attrparent;
7990 	int arc_rwsysattr = 0;
7991 	int dirfd;
7992 	int fd = -1;
7993 	int rw_sysattr = 0;
7994 	int ext_attr = 0;
7995 	int rc;
7996 	DIR *dirp;
7997 	struct dirent *dp;
7998 	attr_data_t *attrinfo = NULL;
7999 
8000 	/*
8001 	 * If the underlying file system supports it, then archive the extended
8002 	 * attributes if -@ was specified, and the extended system attributes
8003 	 * if -/ was specified.
8004 	 */
8005 	if (verify_attr_support(filename, (attrparent == NULL), ARC_CREATE,
8006 	    &ext_attr) != ATTR_OK) {
8007 		return;
8008 	}
8009 
8010 	/*
8011 	 * Only want to archive a read-write extended system attribute file
8012 	 * if it contains extended system attribute settings that are not the
8013 	 * default values.
8014 	 */
8015 #if defined(_PC_SATTR_ENABLED)
8016 	if (saflag) {
8017 		int	filefd;
8018 		nvlist_t *slist = NULL;
8019 
8020 		/* Determine if there are non-transient system attributes */
8021 		errno = 0;
8022 		if ((filefd = open(filename, O_RDONLY)) == -1) {
8023 			if (attrparent == NULL) {
8024 				vperror(0, gettext(
8025 				    "unable to open file %s"), longname);
8026 			}
8027 			return;
8028 		}
8029 		if (((slist = sysattr_list(basename(myname), filefd,
8030 		    filename)) != NULL) || (errno != 0)) {
8031 			arc_rwsysattr = 1;
8032 		}
8033 		if (slist != NULL) {
8034 			(void) nvlist_free(slist);
8035 			slist = NULL;
8036 		}
8037 		(void) close(filefd);
8038 	}
8039 
8040 	/*
8041 	 * If we aren't archiving extended system attributes, and we are
8042 	 * processing an attribute, or if we are archiving extended system
8043 	 * attributes, and there are are no extended attributes, then there's
8044 	 * no need to open up the attribute directory of the file unless the
8045 	 * extended system attributes are not transient (i.e, the system
8046 	 * attributes are not the default values).
8047 	 */
8048 	if ((arc_rwsysattr == 0) && ((attrparent != NULL) ||
8049 	    (saflag && !ext_attr))) {
8050 		return;
8051 	}
8052 #endif	/* _PC_SATTR_ENABLED */
8053 
8054 	/* open the parent attribute directory */
8055 	fd = attropen(filename, ".", O_RDONLY);
8056 	if (fd < 0) {
8057 		vperror(0, gettext(
8058 		    "unable to open attribute directory for %s%s%sfile %s"),
8059 		    (attrparent == NULL) ? "" : gettext("attribute "),
8060 		    (attrparent == NULL) ? "" : attrparent,
8061 		    (attrparent == NULL) ? "" : gettext(" of "),
8062 		    longname);
8063 		return;
8064 	}
8065 
8066 	/*
8067 	 * We need to change into the parent's attribute directory to determine
8068 	 * if each of the attributes should be archived.
8069 	 */
8070 	if (fchdir(fd) < 0) {
8071 		vperror(0, gettext(
8072 		    "cannot change to attribute directory of %s%s%sfile %s"),
8073 		    (attrparent == NULL) ? "" : gettext("attribute "),
8074 		    (attrparent == NULL) ? "" : attrparent,
8075 		    (attrparent == NULL) ? "" : gettext(" of "),
8076 		    longname);
8077 		(void) close(fd);
8078 		return;
8079 	}
8080 
8081 	if (((dirfd = dup(fd)) == -1) ||
8082 	    ((dirp = fdopendir(dirfd)) == NULL)) {
8083 		(void) fprintf(stderr, gettext(
8084 		    "tar: unable to open dir pointer for %s%s%sfile %s\n"),
8085 		    (attrparent == NULL) ? "" : gettext("attribute "),
8086 		    (attrparent == NULL) ? "" : attrparent,
8087 		    (attrparent == NULL) ? "" : gettext(" of "),
8088 		    longname);
8089 		if (fd > 0) {
8090 			(void) close(fd);
8091 		}
8092 		return;
8093 	}
8094 
8095 	while (dp = readdir(dirp)) {
8096 		if (strcmp(dp->d_name, "..") == 0) {
8097 			continue;
8098 		} else if (strcmp(dp->d_name, ".") == 0) {
8099 			Hiddendir = 1;
8100 		} else {
8101 			Hiddendir = 0;
8102 		}
8103 
8104 		/* Determine if this attribute should be archived */
8105 		if (verify_attr(dp->d_name, attrparent, arc_rwsysattr,
8106 		    &rw_sysattr) != ATTR_OK) {
8107 			continue;
8108 		}
8109 
8110 		/* gather the attribute's information to pass to putfile() */
8111 		if ((fill_in_attr_info(dp->d_name, longname, attrparent,
8112 		    fd, rw_sysattr, &attrinfo)) == 1) {
8113 			continue;
8114 		}
8115 
8116 		/* add the attribute to the archive */
8117 		rc = putfile(longname, dp->d_name, parent, attrinfo,
8118 		    XATTR_FILE, LEV0, SYMLINK_LEV0);
8119 
8120 		if (exitflag) {
8121 			break;
8122 		}
8123 
8124 #if defined(_PC_SATTR_ENABLED)
8125 		/*
8126 		 * If both -/ and -@ were specified, then archive the
8127 		 * attribute's extended system attributes and hidden directory
8128 		 * by making a recursive call to xattrs_put().
8129 		 */
8130 		if (!rw_sysattr && saflag && atflag && (rc != PUT_AS_LINK) &&
8131 		    (Hiddendir == 0)) {
8132 
8133 			xattrs_put(longname, shortname, parent, dp->d_name);
8134 
8135 			/*
8136 			 * Change back to the parent's attribute directory
8137 			 * to process any further attributes.
8138 			 */
8139 			if (fchdir(fd) < 0) {
8140 				vperror(0, gettext(
8141 				    "cannot change back to attribute directory "
8142 				    "of file %s"), longname);
8143 				break;
8144 			}
8145 		}
8146 #endif	/* _PC_SATTR_ENABLED */
8147 	}
8148 
8149 	if (attrinfo != NULL) {
8150 		if (attrinfo->attr_parent != NULL) {
8151 			free(attrinfo->attr_parent);
8152 		}
8153 		free(attrinfo->attr_path);
8154 		free(attrinfo);
8155 	}
8156 	(void) closedir(dirp);
8157 	if (fd != -1) {
8158 		(void) close(fd);
8159 	}
8160 
8161 	/* Change back to the parent directory of the base file */
8162 	if (attrparent == NULL) {
8163 		(void) chdir(parent);
8164 	}
8165 	Hiddendir = 0;
8166 }
8167 #else
8168 static void
8169 xattrs_put(char *longname, char *shortname, char *parent, char *attrppath)
8170 {
8171 }
8172 #endif /* O_XATTR */
8173 
8174 static int
8175 put_link(char *name, char *longname, char *component, char *longattrname,
8176     char *prefix, int filetype, char type)
8177 {
8178 
8179 	if (stbuf.st_nlink > 1) {
8180 		struct linkbuf *lp;
8181 		int found = 0;
8182 
8183 		for (lp = ihead; lp != NULL; lp = lp->nextp)
8184 			if (lp->inum == stbuf.st_ino &&
8185 			    lp->devnum == stbuf.st_dev) {
8186 				found++;
8187 				break;
8188 			}
8189 		if (found) {
8190 #if defined(O_XATTR)
8191 			if (filetype == XATTR_FILE)
8192 				if (put_xattr_hdr(longname, component,
8193 				    longattrname, prefix, type, filetype, lp)) {
8194 					goto out;
8195 			}
8196 #endif
8197 			stbuf.st_size = (off_t)0;
8198 			if (filetype != XATTR_FILE) {
8199 				tomodes(&stbuf);
8200 				if (chk_path_build(name, longname, lp->pathname,
8201 				    prefix, type, filetype) > 0) {
8202 					goto out;
8203 				}
8204 			}
8205 
8206 			if (mulvol && tapepos + 1 >= blocklim)
8207 				newvol();
8208 			(void) writetbuf((char *)&dblock, 1);
8209 			/*
8210 			 * write_ancillary() is not needed here.
8211 			 * The first link is handled in the following
8212 			 * else statement. No need to process ACLs
8213 			 * for other hard links since they are the
8214 			 * same file.
8215 			 */
8216 
8217 			if (vflag) {
8218 #ifdef DEBUG
8219 				if (NotTape)
8220 					DEBUG("seek = %" FMT_blkcnt_t
8221 					    "K\t", K(tapepos), 0);
8222 #endif
8223 				if (filetype == XATTR_FILE) {
8224 					(void) fprintf(vfile, gettext(
8225 					    "a %s attribute %s link to "
8226 					    "%s attribute %s\n"),
8227 					    name, component, name,
8228 					    lp->attrname);
8229 				} else {
8230 					(void) fprintf(vfile, gettext(
8231 					    "a %s link to %s\n"),
8232 					    longname, lp->pathname);
8233 				}
8234 			}
8235 			lp->count--;
8236 			return (0);
8237 		} else {
8238 			lp = (struct linkbuf *)getmem(sizeof (*lp));
8239 			if (lp != (struct linkbuf *)NULL) {
8240 				lp->nextp = ihead;
8241 				ihead = lp;
8242 				lp->inum = stbuf.st_ino;
8243 				lp->devnum = stbuf.st_dev;
8244 				lp->count = stbuf.st_nlink - 1;
8245 				if (filetype == XATTR_FILE) {
8246 					(void) strcpy(lp->pathname, longname);
8247 					(void) strcpy(lp->attrname,
8248 					    component);
8249 				} else {
8250 					(void) strcpy(lp->pathname, longname);
8251 					(void) strcpy(lp->attrname, "");
8252 				}
8253 			}
8254 		}
8255 	}
8256 
8257 out:
8258 	return (1);
8259 }
8260 
8261 static int
8262 put_extra_attributes(char *longname, char *shortname, char *longattrname,
8263     char *prefix, int filetype, char typeflag)
8264 {
8265 	static acl_t *aclp = NULL;
8266 	int error;
8267 
8268 	if (aclp != NULL) {
8269 		acl_free(aclp);
8270 		aclp = NULL;
8271 	}
8272 #if defined(O_XATTR)
8273 	if ((atflag || saflag) && (filetype == XATTR_FILE)) {
8274 		if (put_xattr_hdr(longname, shortname, longattrname, prefix,
8275 		    typeflag, filetype, NULL)) {
8276 			return (1);
8277 		}
8278 	}
8279 #endif
8280 
8281 	/* ACL support */
8282 	if (pflag) {
8283 		char	*secinfo = NULL;
8284 		int	len = 0;
8285 
8286 		/* ACL support */
8287 		if (((stbuf.st_mode & S_IFMT) != S_IFLNK)) {
8288 			/*
8289 			 * Get ACL info: dont bother allocating space if
8290 			 * there is only a trivial ACL.
8291 			 */
8292 			if ((error = acl_get(shortname, ACL_NO_TRIVIAL,
8293 			    &aclp)) != 0) {
8294 				(void) fprintf(stderr, gettext(
8295 				    "%s: failed to retrieve acl : %s\n"),
8296 				    longname, acl_strerror(error));
8297 				return (1);
8298 			}
8299 		}
8300 
8301 		/* append security attributes if any */
8302 		if (aclp != NULL) {
8303 			(void) append_secattr(&secinfo, &len, acl_cnt(aclp),
8304 			    acl_totext(aclp, ACL_APPEND_ID | ACL_COMPACT_FMT |
8305 			    ACL_SID_FMT), (acl_type(aclp) == ACLENT_T) ?
8306 			    UFSD_ACL : ACE_ACL);
8307 		}
8308 
8309 		if (Tflag) {
8310 			/* append Trusted Extensions extended attributes */
8311 			append_ext_attr(shortname, &secinfo, &len);
8312 			(void) write_ancillary(&dblock, secinfo, len, ACL_HDR);
8313 
8314 		} else if (aclp != NULL) {
8315 			(void) write_ancillary(&dblock, secinfo, len, ACL_HDR);
8316 		}
8317 	}
8318 	return (0);
8319 }
8320 
8321 #if defined(O_XATTR)
8322 static int
8323 put_xattr_hdr(char *longname, char *shortname, char *longattrname, char *prefix,
8324 	int typeflag, int filetype, struct linkbuf *lp)
8325 {
8326 	char *lname = NULL;
8327 	char *sname = NULL;
8328 	int  error = 0;
8329 	static char *attrbuf = NULL;
8330 	int attrlen;
8331 
8332 	lname = malloc(sizeof (char) * strlen("/dev/null") + 1 +
8333 	    strlen(shortname) + strlen(".hdr") + 1);
8334 
8335 	if (lname == NULL) {
8336 		fatal(gettext("Out of Memory."));
8337 	}
8338 	sname = malloc(sizeof (char) * strlen(shortname) +
8339 	    strlen(".hdr") + 1);
8340 	if (sname == NULL) {
8341 		fatal(gettext("Out of Memory."));
8342 	}
8343 
8344 	(void) sprintf(sname, "%s.hdr", shortname);
8345 	(void) sprintf(lname, "/dev/null/%s", sname);
8346 
8347 	if (strlcpy(dblock.dbuf.name, lname, sizeof (dblock.dbuf.name)) >=
8348 	    sizeof (dblock.dbuf.name)) {
8349 		fatal(gettext(
8350 		    "Buffer overflow writing extended attribute file name"));
8351 	}
8352 
8353 	/*
8354 	 * dump extended attr lookup info
8355 	 */
8356 	prepare_xattr(&attrbuf, longname, longattrname, typeflag, lp, &attrlen);
8357 	write_ancillary(&dblock, attrbuf, attrlen, _XATTR_HDRTYPE);
8358 
8359 	(void) sprintf(lname, "/dev/null/%s", shortname);
8360 	(void) strncpy(dblock.dbuf.name, sname, NAMSIZ);
8361 
8362 	/*
8363 	 * Set up filename for attribute
8364 	 */
8365 
8366 	error = build_dblock(lname, tchar, '0', filetype,
8367 	    &stbuf, stbuf.st_dev, prefix);
8368 	free(lname);
8369 	free(sname);
8370 
8371 	return (error);
8372 }
8373 #endif
8374 
8375 #if defined(O_XATTR)
8376 static int
8377 read_xattr_hdr(attr_data_t **attrinfo)
8378 {
8379 	char		buf[TBLOCK];
8380 	char		*attrparent = NULL;
8381 	blkcnt_t	blocks;
8382 	char		*tp;
8383 	off_t		bytes;
8384 	int		comp_len, link_len;
8385 	int		namelen;
8386 	int		attrparentlen;
8387 	int		parentfilelen;
8388 
8389 	if (dblock.dbuf.typeflag != _XATTR_HDRTYPE)
8390 		return (1);
8391 
8392 	bytes = stbuf.st_size;
8393 	if ((xattrhead = calloc(1, (int)bytes)) == NULL) {
8394 		(void) fprintf(stderr, gettext(
8395 		    "Insufficient memory for extended attribute\n"));
8396 		return (1);
8397 	}
8398 
8399 	tp = (char *)xattrhead;
8400 	blocks = TBLOCKS(bytes);
8401 	while (blocks-- > 0) {
8402 		readtape(buf);
8403 		if (bytes <= TBLOCK) {
8404 			(void) memcpy(tp, buf, (size_t)bytes);
8405 			break;
8406 		} else {
8407 			(void) memcpy(tp, buf, TBLOCK);
8408 			tp += TBLOCK;
8409 		}
8410 		bytes -= TBLOCK;
8411 	}
8412 
8413 	/*
8414 	 * Validate that we can handle header format
8415 	 */
8416 	if (strcmp(xattrhead->h_version, XATTR_ARCH_VERS) != 0) {
8417 		(void) fprintf(stderr,
8418 		    gettext("Unknown extended attribute format encountered\n"));
8419 		(void) fprintf(stderr,
8420 		    gettext("Disabling extended attribute parsing\n"));
8421 		xattrbadhead = 1;
8422 		return (0);
8423 	}
8424 	(void) sscanf(xattrhead->h_component_len, "%10d", &comp_len);
8425 	(void) sscanf(xattrhead->h_link_component_len,	"%10d", &link_len);
8426 	xattrp = (struct xattr_buf *)(((char *)xattrhead) +
8427 	    sizeof (struct xattr_hdr));
8428 	(void) sscanf(xattrp->h_namesz, "%7d", &namelen);
8429 	if (link_len > 0)
8430 		xattr_linkp = (struct xattr_buf *)
8431 		    ((int)xattrp + (int)comp_len);
8432 	else
8433 		xattr_linkp = NULL;
8434 
8435 	/*
8436 	 * Gather the attribute path from the filename and attrnames section.
8437 	 * The filename and attrnames section can be composed of two or more
8438 	 * path segments separated by a null character.  The first segment
8439 	 * is the path to the parent file that roots the entire sequence in
8440 	 * the normal name space. The remaining segments describes a path
8441 	 * rooted at the hidden extended attribute directory of the leaf file of
8442 	 * the previous segment, making it possible to name attributes on
8443 	 * attributes.
8444 	 */
8445 	parentfilelen = strlen(xattrp->h_names);
8446 	xattrapath = xattrp->h_names + parentfilelen + 1;
8447 	if ((strlen(xattrapath) + parentfilelen + 2) < namelen) {
8448 		/*
8449 		 * The attrnames section contains a system attribute on an
8450 		 * attribute.  Save the name of the attribute for use later,
8451 		 * and replace the null separating the attribute name from
8452 		 * the system attribute name with a '/' so that xattrapath can
8453 		 * be used to display messages with the full attribute path name
8454 		 * rooted at the hidden attribute directory of the base file
8455 		 * in normal name space.
8456 		 */
8457 		attrparent = strdup(xattrapath);
8458 		attrparentlen = strlen(attrparent);
8459 		xattrapath[attrparentlen] = '/';
8460 	}
8461 	if ((fill_in_attr_info((attrparent == NULL) ? xattrapath :
8462 	    xattrapath + attrparentlen + 1, xattrapath, attrparent,
8463 	    -1, 0, attrinfo)) == 1) {
8464 		free(attrparent);
8465 		return (1);
8466 	}
8467 
8468 	/* Gather link info */
8469 	if (xattr_linkp) {
8470 		xattr_linkaname = xattr_linkp->h_names +
8471 		    strlen(xattr_linkp->h_names) + 1;
8472 	} else {
8473 		xattr_linkaname = NULL;
8474 	}
8475 
8476 	return (0);
8477 }
8478 #else
8479 static int
8480 read_xattr_hdr(attr_data_t **attrinfo)
8481 {
8482 	return (0);
8483 }
8484 #endif
8485 
8486 /*
8487  * skip over extra slashes in string.
8488  *
8489  * For example:
8490  * /usr/tmp/////
8491  *
8492  * would return pointer at
8493  * /usr/tmp/////
8494  *         ^
8495  */
8496 static char *
8497 skipslashes(char *string, char *start)
8498 {
8499 	while ((string > start) && *(string - 1) == '/') {
8500 		string--;
8501 	}
8502 
8503 	return (string);
8504 }
8505 
8506 /*
8507  * Return the parent directory of a given path.
8508  *
8509  * Examples:
8510  * /usr/tmp return /usr
8511  * /usr/tmp/file return /usr/tmp
8512  * /  returns .
8513  * /usr returns /
8514  * file returns .
8515  *
8516  * dir is assumed to be at least as big as path.
8517  */
8518 static void
8519 get_parent(char *path, char *dir)
8520 {
8521 	char *s;
8522 	char tmpdir[PATH_MAX + 1];
8523 
8524 	if (strlen(path) > PATH_MAX) {
8525 		fatal(gettext("pathname is too long"));
8526 	}
8527 	(void) strcpy(tmpdir, path);
8528 	chop_endslashes(tmpdir);
8529 
8530 	if ((s = strrchr(tmpdir, '/')) == NULL) {
8531 		(void) strcpy(dir, ".");
8532 	} else {
8533 		s = skipslashes(s, tmpdir);
8534 		*s = '\0';
8535 		if (s == tmpdir)
8536 			(void) strcpy(dir, "/");
8537 		else
8538 			(void) strcpy(dir, tmpdir);
8539 	}
8540 }
8541 
8542 #if defined(O_XATTR)
8543 static char *
8544 get_component(char *path)
8545 {
8546 	char *ptr;
8547 
8548 	ptr = strrchr(path, '/');
8549 	if (ptr == NULL) {
8550 		return (path);
8551 	} else {
8552 		/*
8553 		 * Handle trailing slash
8554 		 */
8555 		if (*(ptr + 1) == '\0')
8556 			return (ptr);
8557 		else
8558 			return (ptr + 1);
8559 	}
8560 }
8561 #else
8562 static char *
8563 get_component(char *path)
8564 {
8565 	return (path);
8566 }
8567 #endif
8568 
8569 #if defined(O_XATTR)
8570 static int
8571 retry_open_attr(int pdirfd, int cwd, char *dirp, char *pattr, char *name,
8572     int oflag, mode_t mode)
8573 {
8574 	int dirfd;
8575 	int ofilefd = -1;
8576 	struct timeval times[2];
8577 	mode_t newmode;
8578 	struct stat parentstat;
8579 	acl_t *aclp = NULL;
8580 	int error;
8581 
8582 	/*
8583 	 * We couldn't get to attrdir. See if its
8584 	 * just a mode problem on the parent file.
8585 	 * for example: a mode such as r-xr--r--
8586 	 * on a ufs file system without extended
8587 	 * system attribute support won't let us
8588 	 * create an attribute dir if it doesn't
8589 	 * already exist, and on a ufs file system
8590 	 * with extended system attribute support
8591 	 * won't let us open the attribute for
8592 	 * write.
8593 	 *
8594 	 * If file has a non-trivial ACL, then save it
8595 	 * off so that we can place it back on after doing
8596 	 * chmod's.
8597 	 */
8598 	if ((dirfd = openat(cwd, (pattr == NULL) ? dirp : pattr,
8599 	    O_RDONLY)) == -1) {
8600 		return (-1);
8601 	}
8602 	if (fstat(dirfd, &parentstat) == -1) {
8603 		(void) fprintf(stderr, gettext(
8604 		    "tar: cannot stat %sfile %s: %s\n"),
8605 		    (pdirfd == -1) ? "" : gettext("parent of "),
8606 		    (pdirfd == -1) ? dirp : name, strerror(errno));
8607 			return (-1);
8608 	}
8609 	if ((error = facl_get(dirfd, ACL_NO_TRIVIAL, &aclp)) != 0) {
8610 		(void) fprintf(stderr, gettext(
8611 		    "tar: failed to retrieve ACL on %sfile %s: %s\n"),
8612 		    (pdirfd == -1) ? "" : gettext("parent of "),
8613 		    (pdirfd == -1) ? dirp : name, strerror(errno));
8614 			return (-1);
8615 	}
8616 
8617 	newmode = S_IWUSR | parentstat.st_mode;
8618 	if (fchmod(dirfd, newmode) == -1) {
8619 		(void) fprintf(stderr,
8620 		    gettext(
8621 		    "tar: cannot fchmod %sfile %s to %o: %s\n"),
8622 		    (pdirfd == -1) ? "" : gettext("parent of "),
8623 		    (pdirfd == -1) ? dirp : name, newmode, strerror(errno));
8624 		if (aclp)
8625 			acl_free(aclp);
8626 		return (-1);
8627 	}
8628 
8629 
8630 	if (pdirfd == -1) {
8631 		/*
8632 		 * We weren't able to create the attribute directory before.
8633 		 * Now try again.
8634 		 */
8635 		ofilefd = attropen(dirp, ".", oflag);
8636 	} else {
8637 		/*
8638 		 * We weren't able to create open the attribute before.
8639 		 * Now try again.
8640 		 */
8641 		ofilefd = openat(pdirfd, name, oflag, mode);
8642 	}
8643 
8644 	/*
8645 	 * Put mode back to original
8646 	 */
8647 	if (fchmod(dirfd, parentstat.st_mode) == -1) {
8648 		(void) fprintf(stderr,
8649 		    gettext("tar: cannot chmod %sfile %s to %o: %s\n"),
8650 		    (pdirfd == -1) ? "" : gettext("parent of "),
8651 		    (pdirfd == -1) ? dirp : name, newmode, strerror(errno));
8652 	}
8653 
8654 	if (aclp) {
8655 		error = facl_set(dirfd, aclp);
8656 		if (error) {
8657 			(void) fprintf(stderr,
8658 			    gettext("tar: failed to set acl entries on "
8659 			    "%sfile %s\n"),
8660 			    (pdirfd == -1) ? "" : gettext("parent of "),
8661 			    (pdirfd == -1) ? dirp : name);
8662 		}
8663 		acl_free(aclp);
8664 	}
8665 
8666 	/*
8667 	 * Put back time stamps
8668 	 */
8669 
8670 	times[0].tv_sec = parentstat.st_atime;
8671 	times[0].tv_usec = 0;
8672 	times[1].tv_sec = parentstat.st_mtime;
8673 	times[1].tv_usec = 0;
8674 
8675 	(void) futimesat(cwd, (pattr == NULL) ? dirp : pattr, times);
8676 
8677 	(void) close(dirfd);
8678 
8679 	return (ofilefd);
8680 }
8681 #endif
8682 
8683 #if !defined(O_XATTR)
8684 static int
8685 openat64(int fd, const char *name, int oflag, mode_t cmode)
8686 {
8687 	return (open64(name, oflag, cmode));
8688 }
8689 
8690 static int
8691 openat(int fd, const char *name, int oflag, mode_t cmode)
8692 {
8693 	return (open(name, oflag, cmode));
8694 }
8695 
8696 static int
8697 fchownat(int fd, const char *name, uid_t owner, gid_t group, int flag)
8698 {
8699 	if (flag == AT_SYMLINK_NOFOLLOW)
8700 		return (lchown(name, owner, group));
8701 	else
8702 		return (chown(name, owner, group));
8703 }
8704 
8705 static int
8706 renameat(int fromfd, char *old, int tofd, char *new)
8707 {
8708 	return (rename(old, new));
8709 }
8710 
8711 static int
8712 futimesat(int fd, char *path, struct timeval times[2])
8713 {
8714 	return (utimes(path, times));
8715 }
8716 
8717 static int
8718 unlinkat(int dirfd, char *path, int flag)
8719 {
8720 	if (flag == AT_REMOVEDIR)
8721 		return (rmdir(path));
8722 	else
8723 		return (unlink(path));
8724 }
8725 
8726 static int
8727 fstatat(int fd, char *path, struct stat *buf, int flag)
8728 {
8729 	if (flag == AT_SYMLINK_NOFOLLOW)
8730 		return (lstat(path, buf));
8731 	else
8732 		return (stat(path, buf));
8733 }
8734 
8735 static int
8736 attropen(char *file, char *attr, int omode, mode_t cmode)
8737 {
8738 	errno = ENOTSUP;
8739 	return (-1);
8740 }
8741 #endif
8742 
8743 static void
8744 chop_endslashes(char *path)
8745 {
8746 	char *end, *ptr;
8747 
8748 	/*
8749 	 * Chop of slashes, but not if all we have is slashes
8750 	 * for example: ////
8751 	 * should make no changes, otherwise it will screw up
8752 	 * checkdir
8753 	 */
8754 	end = &path[strlen(path) -1];
8755 	if (*end == '/' && end != path) {
8756 		ptr = skipslashes(end, path);
8757 		if (ptr != NULL && ptr != path) {
8758 			*ptr = '\0';
8759 		}
8760 	}
8761 }
8762 /* Trusted Extensions */
8763 
8764 /*
8765  * append_ext_attr():
8766  *
8767  * Append extended attributes and other information into the buffer
8768  * that gets written to the ancillary file.
8769  *
8770  * With option 'T', we create a tarfile which
8771  * has an ancillary file each corresponding archived file.
8772  * Each ancillary file contains 1 or more of the
8773  * following attributes:
8774  *
8775  *	attribute type        attribute		process procedure
8776  *	----------------      ----------------  --------------------------
8777  *   	DIR_TYPE       = 'D'   directory flag	append if a directory
8778  *    	LBL_TYPE       = 'L'   SL[IL] or SL	append ascii label
8779  *
8780  *
8781  */
8782 static void
8783 append_ext_attr(char *shortname, char **secinfo, int *len)
8784 {
8785 	bslabel_t	b_slabel;	/* binary sensitvity label */
8786 	char		*ascii = NULL;	/* ascii label */
8787 
8788 	/*
8789 	 * For each attribute type, append it if it is
8790 	 * relevant to the file type.
8791 	 */
8792 
8793 	/*
8794 	 * For attribute type DIR_TYPE,
8795 	 * append it to the following file type:
8796 	 *
8797 	 *	S_IFDIR: directories
8798 	 */
8799 
8800 	/*
8801 	 * For attribute type LBL_TYPE,
8802 	 * append it to the following file type:
8803 	 *
8804 	 *	S_IFDIR: directories (including mld, sld)
8805 	 *	S_IFLNK: symbolic link
8806 	 *	S_IFREG: regular file but not hard link
8807 	 *	S_IFIFO: FIFO file but not hard link
8808 	 *	S_IFCHR: char special file but not hard link
8809 	 *	S_IFBLK: block special file but not hard link
8810 	 */
8811 	switch (stbuf.st_mode & S_IFMT) {
8812 
8813 	case S_IFDIR:
8814 
8815 		/*
8816 		 * append DIR_TYPE
8817 		 */
8818 		(void) append_secattr(secinfo, len, 1,
8819 		    "\0", DIR_TYPE);
8820 
8821 		/*
8822 		 * Get and append attribute types LBL_TYPE.
8823 		 * For directories, LBL_TYPE contains SL.
8824 		 */
8825 		/* get binary sensitivity label */
8826 		if (getlabel(shortname, &b_slabel) != 0) {
8827 			(void) fprintf(stderr,
8828 			    gettext("tar: can't get sensitvity label for "
8829 			    " %s, getlabel() error: %s\n"),
8830 			    shortname, strerror(errno));
8831 		} else {
8832 			/* get ascii SL */
8833 			if (bsltos(&b_slabel, &ascii,
8834 			    0, 0) <= 0) {
8835 				(void) fprintf(stderr,
8836 				    gettext("tar: can't get ascii SL for"
8837 				    " %s\n"), shortname);
8838 			} else {
8839 				/* append LBL_TYPE */
8840 				(void) append_secattr(secinfo, len,
8841 				    strlen(ascii) + 1, ascii,
8842 				    LBL_TYPE);
8843 
8844 				/* free storage */
8845 				if (ascii != NULL) {
8846 					free(ascii);
8847 					ascii = (char *)0;
8848 				}
8849 			}
8850 
8851 		}
8852 		break;
8853 
8854 	case S_IFLNK:
8855 	case S_IFREG:
8856 	case S_IFIFO:
8857 	case S_IFCHR:
8858 	case S_IFBLK:
8859 
8860 		/* get binary sensitivity label */
8861 		if (getlabel(shortname, &b_slabel) != 0) {
8862 			(void) fprintf(stderr,
8863 			    gettext("tar: can't get sensitivty label for %s, "
8864 			    "getlabel() error: %s\n"),
8865 			    shortname, strerror(errno));
8866 		} else {
8867 			/* get ascii IL[SL] */
8868 			if (bsltos(&b_slabel, &ascii, 0, 0) <= 0) {
8869 				(void) fprintf(stderr,
8870 				    gettext("tar: can't translate sensitivity "
8871 				    " label for %s\n"), shortname);
8872 			} else {
8873 				char *cmw_label;
8874 				size_t  cmw_length;
8875 
8876 				cmw_length = strlen("ADMIN_LOW [] ") +
8877 				    strlen(ascii);
8878 				if ((cmw_label = malloc(cmw_length)) == NULL) {
8879 					(void) fprintf(stderr, gettext(
8880 					    "Insufficient memory for label\n"));
8881 					exit(1);
8882 				}
8883 				/* append LBL_TYPE */
8884 				(void) snprintf(cmw_label, cmw_length,
8885 				    "ADMIN_LOW [%s]", ascii);
8886 				(void) append_secattr(secinfo, len,
8887 				    strlen(cmw_label) + 1, cmw_label,
8888 				    LBL_TYPE);
8889 
8890 				/* free storage */
8891 				if (ascii != NULL) {
8892 					free(cmw_label);
8893 					free(ascii);
8894 					ascii = (char *)0;
8895 				}
8896 			}
8897 		}
8898 		break;
8899 
8900 	default:
8901 		break;
8902 	} /* end switch for LBL_TYPE */
8903 
8904 
8905 	/* DONE !! */
8906 	return;
8907 
8908 } /* end of append_ext_attr */
8909 
8910 
8911 /*
8912  *	Name: extract_attr()
8913  *
8914  *	Description:
8915  *		Process attributes from the ancillary file due to
8916  *		the T option.
8917  *
8918  *	Call by doxtract() as part of the switch case structure.
8919  *	Making this a separate routine because the nesting are too
8920  *	deep in doxtract, thus, leaving very little space
8921  *	on each line for instructions.
8922  *
8923  * With option 'T', we extract from a TS 8 or TS 2.5 ancillary file
8924  *
8925  * For option 'T', following are possible attributes in
8926  * a TS 8 ancillary file: (NOTE: No IL support)
8927  *
8928  *	attribute type        attribute		process procedure
8929  *	----------------      ----------------  -------------------------
8930  *    #	LBL_TYPE       = 'L'   SL               construct binary label
8931  *    #	APRIV_TYPE     = 'P'   allowed priv    	construct privileges
8932  *    #	FPRIV_TYPE     = 'p'   forced priv	construct privileges
8933  *    #	COMP_TYPE      = 'C'   path component	construct real path
8934  *    #	DIR_TYPE       = 'D'   directory flag	note it is a directory
8935  *    $	UFSD_ACL       = '1'   ACL data		construct ACL entries
8936  *	ATTR_FLAG_TYPE = 'F'   file attr flags  construct binary flags
8937  *	LK_COMP_TYPE   = 'K'   linked path comp construct linked real path
8938  *
8939  * note: # = attribute names common between TS 8 & TS 2.5 ancillary
8940  *           files.
8941  *       $ = ACL attribute is processed for the option 'p', it doesn't
8942  *           need option 'T'.
8943  *
8944  * Trusted Extensions ignores APRIV_TYPE, FPRIV_TYPE, and ATTR_FLAG_TYPE
8945  *
8946  */
8947 static void
8948 extract_attr(char **file_ptr, struct sec_attr *attr)
8949 {
8950 	int	reterr, err;
8951 	char	*dummy_buf;	/* for attribute extract */
8952 
8953 	dummy_buf = attr->attr_info;
8954 
8955 	switch (attr->attr_type) {
8956 
8957 	case DIR_TYPE:
8958 
8959 		dir_flag++;
8960 		break;
8961 
8962 	case LBL_TYPE:
8963 
8964 		/*
8965 		 * LBL_TYPE is used to indicate SL for directory, and
8966 		 * CMW label for other file types.
8967 		 */
8968 
8969 		if (!dir_flag) { /* not directory */
8970 			/* Skip over IL portion */
8971 			char *sl_ptr = strchr(dummy_buf, '[');
8972 
8973 			if (sl_ptr == NULL)
8974 				err = 0;
8975 			else
8976 				err = stobsl(sl_ptr, &bs_label,
8977 				    NEW_LABEL, &reterr);
8978 		} else { /* directory */
8979 			err = stobsl(dummy_buf, &bs_label,
8980 			    NEW_LABEL, &reterr);
8981 		}
8982 		if (err == 0) {
8983 			(void) fprintf(stderr, gettext("tar: "
8984 			    "can't convert %s to binary label\n"),
8985 			    dummy_buf);
8986 			bslundef(&bs_label);
8987 		} else if (!blequal(&bs_label, &admin_low) &&
8988 		    !blequal(&bs_label, &admin_high)) {
8989 			bslabel_t *from_label;
8990 			char *buf;
8991 			char tempbuf[MAXPATHLEN];
8992 
8993 			if (*orig_namep != '/') {
8994 				/* got relative linked to path */
8995 				(void) getcwd(tempbuf, (sizeof (tempbuf)));
8996 				(void) strncat(tempbuf, "/", MAXPATHLEN);
8997 			} else
8998 				*tempbuf = '\0';
8999 
9000 			buf = real_path;
9001 			(void) strncat(tempbuf, orig_namep, MAXPATHLEN);
9002 			from_label = getlabelbypath(tempbuf);
9003 			if (from_label != NULL) {
9004 				if (blequal(from_label, &admin_low)) {
9005 					if ((getpathbylabel(tempbuf, buf,
9006 					    MAXPATHLEN, &bs_label) == NULL)) {
9007 						(void) fprintf(stderr,
9008 						    gettext("tar: "
9009 						"can't get zone root path for "
9010 						"%s\n"), tempbuf);
9011 					} else
9012 						rpath_flag = 1;
9013 				}
9014 				free(from_label);
9015 			}
9016 		}
9017 		break;
9018 
9019 	case COMP_TYPE:
9020 
9021 		rebuild_comp_path(dummy_buf, file_ptr);
9022 		break;
9023 
9024 	case LK_COMP_TYPE:
9025 
9026 		if (rebuild_lk_comp_path(dummy_buf, file_ptr)
9027 		    == 0) {
9028 			lk_rpath_flag = 1;
9029 		} else {
9030 			(void) fprintf(stderr, gettext("tar: warning: link's "
9031 			    "target pathname might be invalid.\n"));
9032 			lk_rpath_flag = 0;
9033 		}
9034 		break;
9035 	case APRIV_TYPE:
9036 		ignored_aprivs++;
9037 		break;
9038 	case FPRIV_TYPE:
9039 		ignored_fprivs++;
9040 		break;
9041 	case ATTR_FLAG_TYPE:
9042 		ignored_fattrs++;
9043 		break;
9044 
9045 	default:
9046 
9047 		break;
9048 	}
9049 
9050 	/* done */
9051 	return;
9052 
9053 }	/* end extract_attr */
9054 
9055 
9056 
9057 /*
9058  *	Name:	rebuild_comp_path()
9059  *
9060  *	Description:
9061  *		Take the string of components passed down by the calling
9062  *		routine and parse the values and rebuild the path.
9063  *		This routine no longer needs to produce a new real_path
9064  *		string because it is produced when the 'L' LABEL_TYPE is
9065  *		interpreted. So the only thing done here is to distinguish
9066  *		between an SLD and an MLD entry. We only want one, so we
9067  *		ignore the MLD entry by setting the mld_flag.
9068  *
9069  *	return value:
9070  *		none
9071  */
9072 static void
9073 rebuild_comp_path(char *str, char **namep)
9074 {
9075 	char		*cp;
9076 
9077 	while (*str != '\0') {
9078 
9079 		switch (*str) {
9080 
9081 		case MLD_TYPE:
9082 
9083 			str++;
9084 			if ((cp = strstr(str, ";;")) != NULL) {
9085 				*cp = '\0';
9086 				str = cp + 2;
9087 				*cp = ';';
9088 			}
9089 			mld_flag = 1;
9090 			break;
9091 
9092 		case SLD_TYPE:
9093 
9094 			str++;
9095 			if ((cp = strstr(str, ";;")) != NULL) {
9096 				*cp = '\0';
9097 				str = cp + 2;
9098 				*cp = ';';
9099 			}
9100 			mld_flag = 0;
9101 			break;
9102 
9103 		case PATH_TYPE:
9104 
9105 			str++;
9106 			if ((cp = strstr(str, ";;")) != NULL) {
9107 				*cp = '\0';
9108 				str = cp + 2;
9109 				*cp = ';';
9110 			}
9111 			break;
9112 		}
9113 	}
9114 	if (rpath_flag)
9115 		*namep = real_path;
9116 	return;
9117 
9118 } /* end rebuild_comp_path() */
9119 
9120 /*
9121  *	Name:	rebuild_lk_comp_path()
9122  *
9123  *	Description:
9124  *		Take the string of components passed down by the calling
9125  *		routine and parse the values and rebuild the path.
9126  *
9127  *	return value:
9128  *		0 = succeeded
9129  *		-1 = failed
9130  */
9131 static int
9132 rebuild_lk_comp_path(char *str, char **namep)
9133 {
9134 	char		*cp;
9135 	int		reterr;
9136 	bslabel_t	bslabel;
9137 	char		*buf;
9138 	char		pbuf[MAXPATHLEN];
9139 	char		*ptr1, *ptr2;
9140 	int		plen;
9141 	int		use_pbuf;
9142 	char		tempbuf[MAXPATHLEN];
9143 	int		mismatch;
9144 	bslabel_t	*from_label;
9145 	char		zonename[ZONENAME_MAX];
9146 	zoneid_t	zoneid;
9147 
9148 	/* init stuff */
9149 	use_pbuf = 0;
9150 	mismatch = 0;
9151 
9152 	/*
9153 	 * For linked to pathname (LK_COMP_TYPE):
9154 	 *  - If the linked to pathname is absolute (start with /), we
9155 	 *    will use it as is.
9156 	 *  - If it is a relative pathname then it is relative to 1 of 2
9157 	 *    directories.  For a hardlink, it is relative to the current
9158 	 *    directory.  For a symbolic link, it is relative to the
9159 	 *    directory the symbolic link is in.  For the symbolic link
9160 	 *    case, set a flag to indicate we need to use the prefix of
9161 	 *    the restored file's pathname with the linked to pathname.
9162 	 *
9163 	 *    NOTE: At this point, we have no way to determine if we have
9164 	 *    a hardlink or a symbolic link.  We will compare the 1st
9165 	 *    component in the prefix portion of the restore file's
9166 	 *    pathname to the 1st component in the attribute data
9167 	 *    (the linked pathname).  If they are the same, we will assume
9168 	 *    the link pathname to reconstruct is relative to the current
9169 	 *    directory.  Otherwise, we will set a flag indicate we need
9170 	 *    to use a prefix with the reconstructed name.  Need to compare
9171 	 *    both the adorned and unadorned version before deciding a
9172 	 *    mismatch.
9173 	 */
9174 
9175 	buf = lk_real_path;
9176 	if (*(str + 1) != '/') { /* got relative linked to path */
9177 		ptr1 = orig_namep;
9178 		ptr2 = strrchr(ptr1, '/');
9179 		plen = ptr2 - ptr1;
9180 		if (plen > 0) {
9181 			pbuf[0] = '\0';
9182 			plen++;		/* include '/' */
9183 			(void) strncpy(pbuf, ptr1, plen);
9184 			*(pbuf + plen) = '\0';
9185 			ptr2 = strchr(pbuf, '/');
9186 			if (strncmp(pbuf, str + 1, ptr2 - pbuf) != 0)
9187 				mismatch = 1;
9188 		}
9189 
9190 		if (mismatch == 1)
9191 			use_pbuf = 1;
9192 	}
9193 
9194 	buf[0] = '\0';
9195 
9196 	while (*str != '\0') {
9197 
9198 		switch (*str) {
9199 
9200 		case MLD_TYPE:
9201 
9202 			str++;
9203 			if ((cp = strstr(str, ";;")) != NULL) {
9204 				*cp = '\0';
9205 
9206 				/*
9207 				 * Ignore attempts to backup over .MLD.
9208 				 */
9209 				if (strcmp(str, "../") != 0)
9210 					(void) strncat(buf, str, MAXPATHLEN);
9211 				str = cp + 2;
9212 				*cp = ';';
9213 			}
9214 			break;
9215 
9216 		case SLD_TYPE:
9217 
9218 			str++;
9219 			if ((cp = strstr(str, ";;")) != NULL) {
9220 				*cp = '\0';
9221 
9222 				/*
9223 				 * Use the path name in the header if
9224 				 * error occurs when processing the
9225 				 * SLD type.
9226 				 */
9227 
9228 				if (!stobsl(str, &bslabel,
9229 				    NO_CORRECTION, &reterr)) {
9230 					(void) fprintf(stderr, gettext(
9231 					    "tar: can't translate to binary"
9232 					    "SL for SLD, stobsl() error:"
9233 					    " %s\n"), strerror(errno));
9234 					return (-1);
9235 				}
9236 
9237 				str = cp + 2;
9238 				*cp = ';';
9239 
9240 				if (use_pbuf == 1) {
9241 					if (*pbuf != '/') {
9242 						/* relative linked to path */
9243 
9244 						(void) getcwd(tempbuf,
9245 						    (sizeof (tempbuf)));
9246 						(void) strncat(tempbuf, "/",
9247 						    MAXPATHLEN);
9248 						(void) strncat(tempbuf, pbuf,
9249 						    MAXPATHLEN);
9250 					}
9251 					else
9252 						(void) strcpy(tempbuf, pbuf);
9253 
9254 				} else if (*buf != '/') {
9255 					/* got relative linked to path */
9256 
9257 					(void) getcwd(tempbuf,
9258 					    (sizeof (tempbuf)));
9259 					(void) strncat(tempbuf, "/",
9260 					    MAXPATHLEN);
9261 				} else
9262 					*tempbuf = '\0';
9263 
9264 				(void) strncat(tempbuf, buf, MAXPATHLEN);
9265 				*buf = '\0';
9266 
9267 				if (blequal(&bslabel, &admin_high)) {
9268 					bslabel = admin_low;
9269 				}
9270 
9271 
9272 				/*
9273 				 * Check for cross-zone symbolic links
9274 				 */
9275 				from_label = getlabelbypath(real_path);
9276 				if (rpath_flag && (from_label != NULL) &&
9277 				    !blequal(&bslabel, from_label)) {
9278 					if ((zoneid =
9279 					    getzoneidbylabel(&bslabel)) == -1) {
9280 						(void) fprintf(stderr,
9281 						    gettext("tar: can't get "
9282 						    "zone ID for %s\n"),
9283 						    tempbuf);
9284 						return (-1);
9285 					}
9286 					if (zone_getattr(zoneid, ZONE_ATTR_NAME,
9287 					    &zonename, ZONENAME_MAX) == -1) {
9288 						/* Badly configured zone info */
9289 						(void) fprintf(stderr,
9290 						    gettext("tar: can't get "
9291 						    "zonename for %s\n"),
9292 						    tempbuf);
9293 						return (-1);
9294 					}
9295 					(void) strncpy(buf, AUTO_ZONE,
9296 					    MAXPATHLEN);
9297 					(void) strncat(buf, "/",
9298 					    MAXPATHLEN);
9299 					(void) strncat(buf, zonename,
9300 					    MAXPATHLEN);
9301 				}
9302 				if (from_label != NULL)
9303 					free(from_label);
9304 				(void) strncat(buf, tempbuf, MAXPATHLEN);
9305 				break;
9306 			}
9307 			mld_flag = 0;
9308 			break;
9309 
9310 		case PATH_TYPE:
9311 
9312 			str++;
9313 			if ((cp = strstr(str, ";;")) != NULL) {
9314 				*cp = '\0';
9315 				(void) strncat(buf, str, MAXPATHLEN);
9316 				str = cp + 2;
9317 				*cp = ';';
9318 			}
9319 			break;
9320 
9321 		default:
9322 
9323 			(void) fprintf(stderr, gettext(
9324 			    "tar: error rebuilding path %s\n"),
9325 			    *namep);
9326 			*buf = '\0';
9327 			str++;
9328 			return (-1);
9329 		}
9330 	}
9331 
9332 	/*
9333 	 * Done for LK_COMP_TYPE
9334 	 */
9335 
9336 	return (0);    /* component path is rebuilt successfully */
9337 
9338 } /* end rebuild_lk_comp_path() */
9339 
9340 /*
9341  *	Name: check_ext_attr()
9342  *
9343  *	Description:
9344  *		Check the extended attributes for a file being extracted.
9345  *		The attributes being checked here are CMW labels.
9346  *		ACLs are not set here because they are set by the
9347  *		pflag in doxtract().
9348  *
9349  *		If the label doesn't match, return 0
9350  *		else return 1
9351  */
9352 static int
9353 check_ext_attr(char *filename)
9354 {
9355 	bslabel_t	currentlabel;	/* label from zone */
9356 
9357 	if (bltype(&bs_label, SUN_SL_UN)) {
9358 		/* No label check possible */
9359 		return (0);
9360 	}
9361 	if (getlabel(filename, &currentlabel) != 0) {
9362 		(void) fprintf(stderr,
9363 		    gettext("tar: can't get label for "
9364 		    " %s, getlabel() error: %s\n"),
9365 		    filename, strerror(errno));
9366 		return (0);
9367 	} else if ((blequal(&currentlabel, &bs_label)) == 0) {
9368 		char	*src_label = NULL;	/* ascii label */
9369 
9370 		/* get current src SL */
9371 		if (bsltos(&bs_label, &src_label, 0, 0) <= 0) {
9372 			(void) fprintf(stderr,
9373 			    gettext("tar: can't interpret requested label for"
9374 			    " %s\n"), filename);
9375 		} else {
9376 			(void) fprintf(stderr,
9377 			    gettext("tar: can't apply label %s to %s\n"),
9378 			    src_label, filename);
9379 			free(src_label);
9380 		}
9381 		(void) fprintf(stderr,
9382 		    gettext("tar: %s not restored\n"), filename);
9383 		return (0);
9384 	}
9385 	return (1);
9386 
9387 }	/* end check_ext_attr */
9388 
9389 /* Compressing a tar file using compression method provided in 'opt' */
9390 
9391 static void
9392 compress_back()
9393 {
9394 	pid_t	pid;
9395 	int status;
9396 	int wret;
9397 	struct	stat statb;
9398 
9399 	if (vflag) {
9400 		(void) fprintf(vfile,
9401 		    gettext("Compressing '%s' with '%s'...\n"),
9402 		    usefile, compress_opt);
9403 	}
9404 	if ((pid = fork()) == 0) {
9405 		(void) execlp(compress_opt, compress_opt,
9406 		    usefile, NULL);
9407 	} else if (pid == -1) {
9408 		vperror(1, "%s", gettext("Could not fork"));
9409 	}
9410 	wait_pid(pid);
9411 	if (suffix == 0) {
9412 		(void) rename(tfname, usefile);
9413 	}
9414 }
9415 
9416 /* The magic numbers from /etc/magic */
9417 
9418 #define	GZIP_MAGIC	"\037\213"
9419 #define	BZIP_MAGIC	"BZh"
9420 #define	COMP_MAGIC	"\037\235"
9421 
9422 void
9423 check_compression()
9424 {
9425 	char 	magic[2];
9426 	char	buf[16];
9427 	FILE	*fp;
9428 
9429 	if ((fp = fopen(usefile, "r")) != NULL) {
9430 		(void) fread(buf, sizeof (char), 6, fp);
9431 		magic[0] = buf[0];
9432 		magic[1] = buf[1];
9433 		(void) fclose(fp);
9434 	}
9435 
9436 	if (memcmp(magic, GZIP_MAGIC, 2) == 0) {
9437 		if (xflag || tflag) {
9438 			compress_opt = compress_malloc(strlen(GZCAT) + 1);
9439 			(void) strcpy(compress_opt, GZCAT);
9440 		} else if (uflag || rflag) {
9441 			compress_opt = compress_malloc(strlen(GZIP) + 1);
9442 			(void) strcpy(compress_opt, GZIP);
9443 		}
9444 	} else if (memcmp(magic, BZIP_MAGIC, 2) == 0) {
9445 		if (xflag || tflag) {
9446 			compress_opt = compress_malloc(strlen(BZCAT) + 1);
9447 			(void) strcpy(compress_opt, BZCAT);
9448 		} else if (uflag || rflag) {
9449 			compress_opt = compress_malloc(strlen(BZIP) + 1);
9450 			(void) strcpy(compress_opt, BZIP);
9451 		}
9452 	} else if (memcmp(magic, COMP_MAGIC, 2) == 0) {
9453 		if (xflag || tflag) {
9454 			compress_opt = compress_malloc(strlen(ZCAT) + 1);
9455 			(void) strcpy(compress_opt, ZCAT);
9456 		} else if (uflag || rflag) {
9457 			compress_opt = compress_malloc(strlen(COMPRESS) + 1);
9458 			(void) strcpy(compress_opt, COMPRESS);
9459 		}
9460 	}
9461 }
9462 
9463 char *
9464 add_suffix()
9465 {
9466 	(void) strcpy(tfname, usefile);
9467 	if (strcmp(compress_opt, GZIP) == 0) {
9468 		if ((suffix = gz_suffix()) == NULL) {
9469 			strlcat(tfname, gsuffix[0], sizeof (tfname));
9470 			return (gsuffix[0]);
9471 		}
9472 	} else if (strcmp(compress_opt, COMPRESS) == 0) {
9473 		if ((suffix = gz_suffix()) == NULL) {
9474 			strlcat(tfname, gsuffix[6], sizeof (tfname));
9475 			return (gsuffix[6]);
9476 		}
9477 	} else if (strcmp(compress_opt, BZIP) == 0) {
9478 		if ((suffix = bz_suffix()) == NULL) {
9479 			strlcat(tfname, bsuffix[0], sizeof (tfname));
9480 			return (bsuffix[0]);
9481 		}
9482 	}
9483 	return (NULL);
9484 }
9485 
9486 /* Decompressing a tar file using compression method from the file type */
9487 void
9488 decompress_file(void)
9489 {
9490 	pid_t 	pid;
9491 	int	status;
9492 	char	cmdstr[PATH_MAX];
9493 	char	fname[PATH_MAX];
9494 	char	*added_suffix;
9495 
9496 
9497 	added_suffix = add_suffix();
9498 	if (added_suffix != NULL)  {
9499 		(void) rename(usefile, tfname);
9500 	}
9501 	if ((pid = fork()) == 0) {
9502 		if (vflag) {
9503 			(void) fprintf(vfile,
9504 			    gettext("Decompressing '%s' with "
9505 			    "'%s'...\n"), usefile, compress_opt);
9506 		}
9507 		(void) execlp(compress_opt, compress_opt, "-df",
9508 		    tfname, NULL);
9509 		vperror(1, gettext("Could not exec %s"), compress_opt);
9510 	} else if (pid == -1) {
9511 		vperror(1, gettext("Could not fork"));
9512 	}
9513 	wait_pid(pid);
9514 	if (suffix != NULL) {
9515 		/* restore the file name - original file was without suffix */
9516 		*(usefile + strlen(usefile) - strlen(suffix)) = '\0';
9517 	}
9518 }
9519 
9520 /* Set the archive for writing and then compress the archive */
9521 pid_t
9522 compress_file(void)
9523 {
9524 	int fd[2];
9525 	pid_t pid;
9526 
9527 	if (vflag) {
9528 		(void) fprintf(vfile, gettext("Compressing '%s' with "
9529 		    "'%s'...\n"), usefile, compress_opt);
9530 	}
9531 
9532 	if (pipe(fd) < 0) {
9533 		vperror(1, gettext("Could not create pipe"));
9534 	}
9535 	if (pid = fork() > 0) {
9536 		mt = fd[1];
9537 		(void) close(fd[0]);
9538 		return (pid);
9539 	}
9540 	/* child */
9541 	(void) dup2(fd[0], STDIN_FILENO);
9542 	(void) close(fd[1]);
9543 	(void) dup2(mt, STDOUT_FILENO);
9544 	(void) execlp(compress_opt, compress_opt, NULL);
9545 	vperror(1, gettext("Could not exec %s"), compress_opt);
9546 	return (0);	/*NOTREACHED*/
9547 }
9548 
9549 pid_t
9550 uncompress_file(void)
9551 {
9552 	int fd[2];
9553 	pid_t pid;
9554 
9555 	if (vflag) {
9556 		(void) fprintf(vfile, gettext("Decompressing '%s' with "
9557 		    "'%s'...\n"), usefile, compress_opt);
9558 	}
9559 
9560 	if (pipe(fd) < 0) {
9561 		vperror(1, gettext("Could not create pipe"));
9562 	}
9563 	if (pid = fork() > 0) {
9564 		mt = fd[0];
9565 		(void) close(fd[1]);
9566 		return (pid);
9567 	}
9568 	/* child */
9569 	(void) dup2(fd[1], STDOUT_FILENO);
9570 	(void) close(fd[0]);
9571 	(void) dup2(mt, STDIN_FILENO);
9572 	(void) execlp(compress_opt, compress_opt, NULL);
9573 	vperror(1, gettext("Could not exec %s"), compress_opt);
9574 	return (0);	/*NOTREACHED*/
9575 }
9576 
9577 /* Checking valid 'bzip2' suffix */
9578 char *
9579 bz_suffix()
9580 {
9581 	int 	i;
9582 	int	slen;
9583 	int	nlen = strlen(usefile);
9584 
9585 	for (i = 0; i < BS; i++) {
9586 		slen = strlen(bsuffix[i]);
9587 		if (nlen < slen)
9588 			return (NULL);
9589 		if (strcmp(usefile + nlen - slen, bsuffix[i]) == 0)
9590 			return (bsuffix[i]);
9591 	}
9592 	return (NULL);
9593 }
9594 
9595 /* Checking valid 'gzip' suffix */
9596 char *
9597 gz_suffix()
9598 {
9599 	int 	i;
9600 	int	slen;
9601 	int	nlen = strlen(usefile);
9602 
9603 	for (i = 0; i < GS; i++) {
9604 		slen = strlen(gsuffix[i]);
9605 		if (nlen < slen)
9606 			return (NULL);
9607 		if (strcmp(usefile + nlen - slen, gsuffix[i]) == 0)
9608 			return (gsuffix[i]);
9609 	}
9610 	return (NULL);
9611 }
9612 
9613 void *
9614 compress_malloc(size_t size)
9615 {
9616 	void *opt;
9617 
9618 	if ((opt = malloc(size)) == NULL) {
9619 		vperror(1, "%s",
9620 		    gettext("Could not allocate compress buffer\n"));
9621 	}
9622 	return (opt);
9623 }
9624 
9625 void
9626 wait_pid(pid_t pid)
9627 {
9628 	int status;
9629 
9630 	while (waitpid(pid, &status, 0) == -1 && errno == EINTR)
9631 		;
9632 }
9633