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