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