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