xref: /freebsd/bin/pax/tables.c (revision 5b31cc94b10d4bb7109c6b27940a0fc76a44a331)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1992 Keith Muller.
5  * Copyright (c) 1992, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * This code is derived from software contributed to Berkeley by
9  * Keith Muller of the University of California, San Diego.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #ifndef lint
37 #endif /* not lint */
38 #include <sys/cdefs.h>
39 #include <sys/types.h>
40 #include <sys/time.h>
41 #include <sys/stat.h>
42 #include <sys/fcntl.h>
43 #include <errno.h>
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <unistd.h>
48 #include "pax.h"
49 #include "tables.h"
50 #include "extern.h"
51 
52 /*
53  * Routines for controlling the contents of all the different databases pax
54  * keeps. Tables are dynamically created only when they are needed. The
55  * goal was speed and the ability to work with HUGE archives. The databases
56  * were kept simple, but do have complex rules for when the contents change.
57  * As of this writing, the POSIX library functions were more complex than
58  * needed for this application (pax databases have very short lifetimes and
59  * do not survive after pax is finished). Pax is required to handle very
60  * large archives. These database routines carefully combine memory usage and
61  * temporary file storage in ways which will not significantly impact runtime
62  * performance while allowing the largest possible archives to be handled.
63  * Trying to force the fit to the POSIX database routines was not considered
64  * time well spent.
65  */
66 
67 static HRDLNK **ltab = NULL;	/* hard link table for detecting hard links */
68 static FTM **ftab = NULL;	/* file time table for updating arch */
69 static NAMT **ntab = NULL;	/* interactive rename storage table */
70 static DEVT **dtab = NULL;	/* device/inode mapping tables */
71 static ATDIR **atab = NULL;	/* file tree directory time reset table */
72 static int dirfd = -1;		/* storage for setting created dir time/mode */
73 static u_long dircnt;		/* entries in dir time/mode storage */
74 static int ffd = -1;		/* tmp file for file time table name storage */
75 
76 static DEVT *chk_dev(dev_t, int);
77 
78 /*
79  * hard link table routines
80  *
81  * The hard link table tries to detect hard links to files using the device and
82  * inode values. We do this when writing an archive, so we can tell the format
83  * write routine that this file is a hard link to another file. The format
84  * write routine then can store this file in whatever way it wants (as a hard
85  * link if the format supports that like tar, or ignore this info like cpio).
86  * (Actually a field in the format driver table tells us if the format wants
87  * hard link info. if not, we do not waste time looking for them). We also use
88  * the same table when reading an archive. In that situation, this table is
89  * used by the format read routine to detect hard links from stored dev and
90  * inode numbers (like cpio). This will allow pax to create a link when one
91  * can be detected by the archive format.
92  */
93 
94 /*
95  * lnk_start
96  *	Creates the hard link table.
97  * Return:
98  *	0 if created, -1 if failure
99  */
100 
101 int
102 lnk_start(void)
103 {
104 	if (ltab != NULL)
105 		return(0);
106  	if ((ltab = (HRDLNK **)calloc(L_TAB_SZ, sizeof(HRDLNK *))) == NULL) {
107 		paxwarn(1, "Cannot allocate memory for hard link table");
108 		return(-1);
109 	}
110 	return(0);
111 }
112 
113 /*
114  * chk_lnk()
115  *	Looks up entry in hard link hash table. If found, it copies the name
116  *	of the file it is linked to (we already saw that file) into ln_name.
117  *	lnkcnt is decremented and if goes to 1 the node is deleted from the
118  *	database. (We have seen all the links to this file). If not found,
119  *	we add the file to the database if it has the potential for having
120  *	hard links to other files we may process (it has a link count > 1)
121  * Return:
122  *	if found returns 1; if not found returns 0; -1 on error
123  */
124 
125 int
126 chk_lnk(ARCHD *arcn)
127 {
128 	HRDLNK *pt;
129 	HRDLNK **ppt;
130 	u_int indx;
131 
132 	if (ltab == NULL)
133 		return(-1);
134 	/*
135 	 * ignore those nodes that cannot have hard links
136 	 */
137 	if ((arcn->type == PAX_DIR) || (arcn->sb.st_nlink <= 1))
138 		return(0);
139 
140 	/*
141 	 * hash inode number and look for this file
142 	 */
143 	indx = ((unsigned)arcn->sb.st_ino) % L_TAB_SZ;
144 	if ((pt = ltab[indx]) != NULL) {
145 		/*
146 		 * it's hash chain in not empty, walk down looking for it
147 		 */
148 		ppt = &(ltab[indx]);
149 		while (pt != NULL) {
150 			if ((pt->ino == arcn->sb.st_ino) &&
151 			    (pt->dev == arcn->sb.st_dev))
152 				break;
153 			ppt = &(pt->fow);
154 			pt = pt->fow;
155 		}
156 
157 		if (pt != NULL) {
158 			/*
159 			 * found a link. set the node type and copy in the
160 			 * name of the file it is to link to. we need to
161 			 * handle hardlinks to regular files differently than
162 			 * other links.
163 			 */
164 			arcn->ln_nlen = l_strncpy(arcn->ln_name, pt->name,
165 				sizeof(arcn->ln_name) - 1);
166 			arcn->ln_name[arcn->ln_nlen] = '\0';
167 			if (arcn->type == PAX_REG)
168 				arcn->type = PAX_HRG;
169 			else
170 				arcn->type = PAX_HLK;
171 
172 			/*
173 			 * if we have found all the links to this file, remove
174 			 * it from the database
175 			 */
176 			if (--pt->nlink <= 1) {
177 				*ppt = pt->fow;
178 				free(pt->name);
179 				free(pt);
180 			}
181 			return(1);
182 		}
183 	}
184 
185 	/*
186 	 * we never saw this file before. It has links so we add it to the
187 	 * front of this hash chain
188 	 */
189 	if ((pt = (HRDLNK *)malloc(sizeof(HRDLNK))) != NULL) {
190 		if ((pt->name = strdup(arcn->name)) != NULL) {
191 			pt->dev = arcn->sb.st_dev;
192 			pt->ino = arcn->sb.st_ino;
193 			pt->nlink = arcn->sb.st_nlink;
194 			pt->fow = ltab[indx];
195 			ltab[indx] = pt;
196 			return(0);
197 		}
198 		free(pt);
199 	}
200 
201 	paxwarn(1, "Hard link table out of memory");
202 	return(-1);
203 }
204 
205 /*
206  * purg_lnk
207  *	remove reference for a file that we may have added to the data base as
208  *	a potential source for hard links. We ended up not using the file, so
209  *	we do not want to accidentally point another file at it later on.
210  */
211 
212 void
213 purg_lnk(ARCHD *arcn)
214 {
215 	HRDLNK *pt;
216 	HRDLNK **ppt;
217 	u_int indx;
218 
219 	if (ltab == NULL)
220 		return;
221 	/*
222 	 * do not bother to look if it could not be in the database
223 	 */
224 	if ((arcn->sb.st_nlink <= 1) || (arcn->type == PAX_DIR) ||
225 	    (arcn->type == PAX_HLK) || (arcn->type == PAX_HRG))
226 		return;
227 
228 	/*
229 	 * find the hash chain for this inode value, if empty return
230 	 */
231 	indx = ((unsigned)arcn->sb.st_ino) % L_TAB_SZ;
232 	if ((pt = ltab[indx]) == NULL)
233 		return;
234 
235 	/*
236 	 * walk down the list looking for the inode/dev pair, unlink and
237 	 * free if found
238 	 */
239 	ppt = &(ltab[indx]);
240 	while (pt != NULL) {
241 		if ((pt->ino == arcn->sb.st_ino) &&
242 		    (pt->dev == arcn->sb.st_dev))
243 			break;
244 		ppt = &(pt->fow);
245 		pt = pt->fow;
246 	}
247 	if (pt == NULL)
248 		return;
249 
250 	/*
251 	 * remove and free it
252 	 */
253 	*ppt = pt->fow;
254 	free(pt->name);
255 	free(pt);
256 }
257 
258 /*
259  * lnk_end()
260  *	Pull apart an existing link table so we can reuse it. We do this between
261  *	read and write phases of append with update. (The format may have
262  *	used the link table, and we need to start with a fresh table for the
263  *	write phase).
264  */
265 
266 void
267 lnk_end(void)
268 {
269 	int i;
270 	HRDLNK *pt;
271 	HRDLNK *ppt;
272 
273 	if (ltab == NULL)
274 		return;
275 
276 	for (i = 0; i < L_TAB_SZ; ++i) {
277 		if (ltab[i] == NULL)
278 			continue;
279 		pt = ltab[i];
280 		ltab[i] = NULL;
281 
282 		/*
283 		 * free up each entry on this chain
284 		 */
285 		while (pt != NULL) {
286 			ppt = pt;
287 			pt = ppt->fow;
288 			free(ppt->name);
289 			free(ppt);
290 		}
291 	}
292 	return;
293 }
294 
295 /*
296  * modification time table routines
297  *
298  * The modification time table keeps track of last modification times for all
299  * files stored in an archive during a write phase when -u is set. We only
300  * add a file to the archive if it is newer than a file with the same name
301  * already stored on the archive (if there is no other file with the same
302  * name on the archive it is added). This applies to writes and appends.
303  * An append with an -u must read the archive and store the modification time
304  * for every file on that archive before starting the write phase. It is clear
305  * that this is one HUGE database. To save memory space, the actual file names
306  * are stored in a scratch file and indexed by an in memory hash table. The
307  * hash table is indexed by hashing the file path. The nodes in the table store
308  * the length of the filename and the lseek offset within the scratch file
309  * where the actual name is stored. Since there are never any deletions from
310  * this table, fragmentation of the scratch file is never an issue. Lookups
311  * seem to not exhibit any locality at all (files in the database are rarely
312  * looked up more than once...). So caching is just a waste of memory. The
313  * only limitation is the amount of scratch file space available to store the
314  * path names.
315  */
316 
317 /*
318  * ftime_start()
319  *	create the file time hash table and open for read/write the scratch
320  *	file. (after created it is unlinked, so when we exit we leave
321  *	no witnesses).
322  * Return:
323  *	0 if the table and file was created ok, -1 otherwise
324  */
325 
326 int
327 ftime_start(void)
328 {
329 
330 	if (ftab != NULL)
331 		return(0);
332  	if ((ftab = (FTM **)calloc(F_TAB_SZ, sizeof(FTM *))) == NULL) {
333 		paxwarn(1, "Cannot allocate memory for file time table");
334 		return(-1);
335 	}
336 
337 	/*
338 	 * get random name and create temporary scratch file, unlink name
339 	 * so it will get removed on exit
340 	 */
341 	memcpy(tempbase, _TFILE_BASE, sizeof(_TFILE_BASE));
342 	if ((ffd = mkstemp(tempfile)) < 0) {
343 		syswarn(1, errno, "Unable to create temporary file: %s",
344 		    tempfile);
345 		return(-1);
346 	}
347 	(void)unlink(tempfile);
348 
349 	return(0);
350 }
351 
352 /*
353  * chk_ftime()
354  *	looks up entry in file time hash table. If not found, the file is
355  *	added to the hash table and the file named stored in the scratch file.
356  *	If a file with the same name is found, the file times are compared and
357  *	the most recent file time is retained. If the new file was younger (or
358  *	was not in the database) the new file is selected for storage.
359  * Return:
360  *	0 if file should be added to the archive, 1 if it should be skipped,
361  *	-1 on error
362  */
363 
364 int
365 chk_ftime(ARCHD *arcn)
366 {
367 	FTM *pt;
368 	int namelen;
369 	u_int indx;
370 	char ckname[PAXPATHLEN+1];
371 
372 	/*
373 	 * no info, go ahead and add to archive
374 	 */
375 	if (ftab == NULL)
376 		return(0);
377 
378 	/*
379 	 * hash the pathname and look up in table
380 	 */
381 	namelen = arcn->nlen;
382 	indx = st_hash(arcn->name, namelen, F_TAB_SZ);
383 	if ((pt = ftab[indx]) != NULL) {
384 		/*
385 		 * the hash chain is not empty, walk down looking for match
386 		 * only read up the path names if the lengths match, speeds
387 		 * up the search a lot
388 		 */
389 		while (pt != NULL) {
390 			if (pt->namelen == namelen) {
391 				/*
392 				 * potential match, have to read the name
393 				 * from the scratch file.
394 				 */
395 				if (lseek(ffd,pt->seek,SEEK_SET) != pt->seek) {
396 					syswarn(1, errno,
397 					    "Failed ftime table seek");
398 					return(-1);
399 				}
400 				if (read(ffd, ckname, namelen) != namelen) {
401 					syswarn(1, errno,
402 					    "Failed ftime table read");
403 					return(-1);
404 				}
405 
406 				/*
407 				 * if the names match, we are done
408 				 */
409 				if (!strncmp(ckname, arcn->name, namelen))
410 					break;
411 			}
412 
413 			/*
414 			 * try the next entry on the chain
415 			 */
416 			pt = pt->fow;
417 		}
418 
419 		if (pt != NULL) {
420 			/*
421 			 * found the file, compare the times, save the newer
422 			 */
423 			if (arcn->sb.st_mtime > pt->mtime) {
424 				/*
425 				 * file is newer
426 				 */
427 				pt->mtime = arcn->sb.st_mtime;
428 				return(0);
429 			}
430 			/*
431 			 * file is older
432 			 */
433 			return(1);
434 		}
435 	}
436 
437 	/*
438 	 * not in table, add it
439 	 */
440 	if ((pt = (FTM *)malloc(sizeof(FTM))) != NULL) {
441 		/*
442 		 * add the name at the end of the scratch file, saving the
443 		 * offset. add the file to the head of the hash chain
444 		 */
445 		if ((pt->seek = lseek(ffd, (off_t)0, SEEK_END)) >= 0) {
446 			if (write(ffd, arcn->name, namelen) == namelen) {
447 				pt->mtime = arcn->sb.st_mtime;
448 				pt->namelen = namelen;
449 				pt->fow = ftab[indx];
450 				ftab[indx] = pt;
451 				return(0);
452 			}
453 			syswarn(1, errno, "Failed write to file time table");
454 		} else
455 			syswarn(1, errno, "Failed seek on file time table");
456 	} else
457 		paxwarn(1, "File time table ran out of memory");
458 
459 	if (pt != NULL)
460 		free(pt);
461 	return(-1);
462 }
463 
464 /*
465  * Interactive rename table routines
466  *
467  * The interactive rename table keeps track of the new names that the user
468  * assigns to files from tty input. Since this map is unique for each file
469  * we must store it in case there is a reference to the file later in archive
470  * (a link). Otherwise we will be unable to find the file we know was
471  * extracted. The remapping of these files is stored in a memory based hash
472  * table (it is assumed since input must come from /dev/tty, it is unlikely to
473  * be a very large table).
474  */
475 
476 /*
477  * name_start()
478  *	create the interactive rename table
479  * Return:
480  *	0 if successful, -1 otherwise
481  */
482 
483 int
484 name_start(void)
485 {
486 	if (ntab != NULL)
487 		return(0);
488  	if ((ntab = (NAMT **)calloc(N_TAB_SZ, sizeof(NAMT *))) == NULL) {
489 		paxwarn(1, "Cannot allocate memory for interactive rename table");
490 		return(-1);
491 	}
492 	return(0);
493 }
494 
495 /*
496  * add_name()
497  *	add the new name to old name mapping just created by the user.
498  *	If an old name mapping is found (there may be duplicate names on an
499  *	archive) only the most recent is kept.
500  * Return:
501  *	0 if added, -1 otherwise
502  */
503 
504 int
505 add_name(char *oname, int onamelen, char *nname)
506 {
507 	NAMT *pt;
508 	u_int indx;
509 
510 	if (ntab == NULL) {
511 		/*
512 		 * should never happen
513 		 */
514 		paxwarn(0, "No interactive rename table, links may fail\n");
515 		return(0);
516 	}
517 
518 	/*
519 	 * look to see if we have already mapped this file, if so we
520 	 * will update it
521 	 */
522 	indx = st_hash(oname, onamelen, N_TAB_SZ);
523 	if ((pt = ntab[indx]) != NULL) {
524 		/*
525 		 * look down the has chain for the file
526 		 */
527 		while ((pt != NULL) && (strcmp(oname, pt->oname) != 0))
528 			pt = pt->fow;
529 
530 		if (pt != NULL) {
531 			/*
532 			 * found an old mapping, replace it with the new one
533 			 * the user just input (if it is different)
534 			 */
535 			if (strcmp(nname, pt->nname) == 0)
536 				return(0);
537 
538 			free(pt->nname);
539 			if ((pt->nname = strdup(nname)) == NULL) {
540 				paxwarn(1, "Cannot update rename table");
541 				return(-1);
542 			}
543 			return(0);
544 		}
545 	}
546 
547 	/*
548 	 * this is a new mapping, add it to the table
549 	 */
550 	if ((pt = (NAMT *)malloc(sizeof(NAMT))) != NULL) {
551 		if ((pt->oname = strdup(oname)) != NULL) {
552 			if ((pt->nname = strdup(nname)) != NULL) {
553 				pt->fow = ntab[indx];
554 				ntab[indx] = pt;
555 				return(0);
556 			}
557 			free(pt->oname);
558 		}
559 		free(pt);
560 	}
561 	paxwarn(1, "Interactive rename table out of memory");
562 	return(-1);
563 }
564 
565 /*
566  * sub_name()
567  *	look up a link name to see if it points at a file that has been
568  *	remapped by the user. If found, the link is adjusted to contain the
569  *	new name (oname is the link to name)
570  */
571 
572 void
573 sub_name(char *oname, int *onamelen, size_t onamesize)
574 {
575 	NAMT *pt;
576 	u_int indx;
577 
578 	if (ntab == NULL)
579 		return;
580 	/*
581 	 * look the name up in the hash table
582 	 */
583 	indx = st_hash(oname, *onamelen, N_TAB_SZ);
584 	if ((pt = ntab[indx]) == NULL)
585 		return;
586 
587 	while (pt != NULL) {
588 		/*
589 		 * walk down the hash chain looking for a match
590 		 */
591 		if (strcmp(oname, pt->oname) == 0) {
592 			/*
593 			 * found it, replace it with the new name
594 			 * and return (we know that oname has enough space)
595 			 */
596 			*onamelen = l_strncpy(oname, pt->nname, onamesize - 1);
597 			oname[*onamelen] = '\0';
598 			return;
599 		}
600 		pt = pt->fow;
601 	}
602 
603 	/*
604 	 * no match, just return
605 	 */
606 	return;
607 }
608 
609 /*
610  * device/inode mapping table routines
611  * (used with formats that store device and inodes fields)
612  *
613  * device/inode mapping tables remap the device field in an archive header. The
614  * device/inode fields are used to determine when files are hard links to each
615  * other. However these values have very little meaning outside of that. This
616  * database is used to solve one of two different problems.
617  *
618  * 1) when files are appended to an archive, while the new files may have hard
619  * links to each other, you cannot determine if they have hard links to any
620  * file already stored on the archive from a prior run of pax. We must assume
621  * that these inode/device pairs are unique only within a SINGLE run of pax
622  * (which adds a set of files to an archive). So we have to make sure the
623  * inode/dev pairs we add each time are always unique. We do this by observing
624  * while the inode field is very dense, the use of the dev field is fairly
625  * sparse. Within each run of pax, we remap any device number of a new archive
626  * member that has a device number used in a prior run and already stored in a
627  * file on the archive. During the read phase of the append, we store the
628  * device numbers used and mark them to not be used by any file during the
629  * write phase. If during write we go to use one of those old device numbers,
630  * we remap it to a new value.
631  *
632  * 2) Often the fields in the archive header used to store these values are
633  * too small to store the entire value. The result is an inode or device value
634  * which can be truncated. This really can foul up an archive. With truncation
635  * we end up creating links between files that are really not links (after
636  * truncation the inodes are the same value). We address that by detecting
637  * truncation and forcing a remap of the device field to split truncated
638  * inodes away from each other. Each truncation creates a pattern of bits that
639  * are removed. We use this pattern of truncated bits to partition the inodes
640  * on a single device to many different devices (each one represented by the
641  * truncated bit pattern). All inodes on the same device that have the same
642  * truncation pattern are mapped to the same new device. Two inodes that
643  * truncate to the same value clearly will always have different truncation
644  * bit patterns, so they will be split from away each other. When we spot
645  * device truncation we remap the device number to a non truncated value.
646  * (for more info see table.h for the data structures involved).
647  */
648 
649 /*
650  * dev_start()
651  *	create the device mapping table
652  * Return:
653  *	0 if successful, -1 otherwise
654  */
655 
656 int
657 dev_start(void)
658 {
659 	if (dtab != NULL)
660 		return(0);
661  	if ((dtab = (DEVT **)calloc(D_TAB_SZ, sizeof(DEVT *))) == NULL) {
662 		paxwarn(1, "Cannot allocate memory for device mapping table");
663 		return(-1);
664 	}
665 	return(0);
666 }
667 
668 /*
669  * add_dev()
670  *	add a device number to the table. this will force the device to be
671  *	remapped to a new value if it be used during a write phase. This
672  *	function is called during the read phase of an append to prohibit the
673  *	use of any device number already in the archive.
674  * Return:
675  *	0 if added ok, -1 otherwise
676  */
677 
678 int
679 add_dev(ARCHD *arcn)
680 {
681 	if (chk_dev(arcn->sb.st_dev, 1) == NULL)
682 		return(-1);
683 	return(0);
684 }
685 
686 /*
687  * chk_dev()
688  *	check for a device value in the device table. If not found and the add
689  *	flag is set, it is added. This does NOT assign any mapping values, just
690  *	adds the device number as one that need to be remapped. If this device
691  *	is already mapped, just return with a pointer to that entry.
692  * Return:
693  *	pointer to the entry for this device in the device map table. Null
694  *	if the add flag is not set and the device is not in the table (it is
695  *	not been seen yet). If add is set and the device cannot be added, null
696  *	is returned (indicates an error).
697  */
698 
699 static DEVT *
700 chk_dev(dev_t dev, int add)
701 {
702 	DEVT *pt;
703 	u_int indx;
704 
705 	if (dtab == NULL)
706 		return(NULL);
707 	/*
708 	 * look to see if this device is already in the table
709 	 */
710 	indx = ((unsigned)dev) % D_TAB_SZ;
711 	if ((pt = dtab[indx]) != NULL) {
712 		while ((pt != NULL) && (pt->dev != dev))
713 			pt = pt->fow;
714 
715 		/*
716 		 * found it, return a pointer to it
717 		 */
718 		if (pt != NULL)
719 			return(pt);
720 	}
721 
722 	/*
723 	 * not in table, we add it only if told to as this may just be a check
724 	 * to see if a device number is being used.
725 	 */
726 	if (add == 0)
727 		return(NULL);
728 
729 	/*
730 	 * allocate a node for this device and add it to the front of the hash
731 	 * chain. Note we do not assign remaps values here, so the pt->list
732 	 * list must be NULL.
733 	 */
734 	if ((pt = (DEVT *)malloc(sizeof(DEVT))) == NULL) {
735 		paxwarn(1, "Device map table out of memory");
736 		return(NULL);
737 	}
738 	pt->dev = dev;
739 	pt->list = NULL;
740 	pt->fow = dtab[indx];
741 	dtab[indx] = pt;
742 	return(pt);
743 }
744 /*
745  * map_dev()
746  *	given an inode and device storage mask (the mask has a 1 for each bit
747  *	the archive format is able to store in a header), we check for inode
748  *	and device truncation and remap the device as required. Device mapping
749  *	can also occur when during the read phase of append a device number was
750  *	seen (and was marked as do not use during the write phase). WE ASSUME
751  *	that unsigned longs are the same size or bigger than the fields used
752  *	for ino_t and dev_t. If not the types will have to be changed.
753  * Return:
754  *	0 if all ok, -1 otherwise.
755  */
756 
757 int
758 map_dev(ARCHD *arcn, u_long dev_mask, u_long ino_mask)
759 {
760 	DEVT *pt;
761 	DLIST *dpt;
762 	static dev_t lastdev = 0;	/* next device number to try */
763 	int trc_ino = 0;
764 	int trc_dev = 0;
765 	ino_t trunc_bits = 0;
766 	ino_t nino;
767 
768 	if (dtab == NULL)
769 		return(0);
770 	/*
771 	 * check for device and inode truncation, and extract the truncated
772 	 * bit pattern.
773 	 */
774 	if ((arcn->sb.st_dev & (dev_t)dev_mask) != arcn->sb.st_dev)
775 		++trc_dev;
776 	if ((nino = arcn->sb.st_ino & (ino_t)ino_mask) != arcn->sb.st_ino) {
777 		++trc_ino;
778 		trunc_bits = arcn->sb.st_ino & (ino_t)(~ino_mask);
779 	}
780 
781 	/*
782 	 * see if this device is already being mapped, look up the device
783 	 * then find the truncation bit pattern which applies
784 	 */
785 	if ((pt = chk_dev(arcn->sb.st_dev, 0)) != NULL) {
786 		/*
787 		 * this device is already marked to be remapped
788 		 */
789 		for (dpt = pt->list; dpt != NULL; dpt = dpt->fow)
790 			if (dpt->trunc_bits == trunc_bits)
791 				break;
792 
793 		if (dpt != NULL) {
794 			/*
795 			 * we are being remapped for this device and pattern
796 			 * change the device number to be stored and return
797 			 */
798 			arcn->sb.st_dev = dpt->dev;
799 			arcn->sb.st_ino = nino;
800 			return(0);
801 		}
802 	} else {
803 		/*
804 		 * this device is not being remapped YET. if we do not have any
805 		 * form of truncation, we do not need a remap
806 		 */
807 		if (!trc_ino && !trc_dev)
808 			return(0);
809 
810 		/*
811 		 * we have truncation, have to add this as a device to remap
812 		 */
813 		if ((pt = chk_dev(arcn->sb.st_dev, 1)) == NULL)
814 			goto bad;
815 
816 		/*
817 		 * if we just have a truncated inode, we have to make sure that
818 		 * all future inodes that do not truncate (they have the
819 		 * truncation pattern of all 0's) continue to map to the same
820 		 * device number. We probably have already written inodes with
821 		 * this device number to the archive with the truncation
822 		 * pattern of all 0's. So we add the mapping for all 0's to the
823 		 * same device number.
824 		 */
825 		if (!trc_dev && (trunc_bits != 0)) {
826 			if ((dpt = (DLIST *)malloc(sizeof(DLIST))) == NULL)
827 				goto bad;
828 			dpt->trunc_bits = 0;
829 			dpt->dev = arcn->sb.st_dev;
830 			dpt->fow = pt->list;
831 			pt->list = dpt;
832 		}
833 	}
834 
835 	/*
836 	 * look for a device number not being used. We must watch for wrap
837 	 * around on lastdev (so we do not get stuck looking forever!)
838 	 */
839 	while (++lastdev > 0) {
840 		if (chk_dev(lastdev, 0) != NULL)
841 			continue;
842 		/*
843 		 * found an unused value. If we have reached truncation point
844 		 * for this format we are hosed, so we give up. Otherwise we
845 		 * mark it as being used.
846 		 */
847 		if (((lastdev & ((dev_t)dev_mask)) != lastdev) ||
848 		    (chk_dev(lastdev, 1) == NULL))
849 			goto bad;
850 		break;
851 	}
852 
853 	if ((lastdev <= 0) || ((dpt = (DLIST *)malloc(sizeof(DLIST))) == NULL))
854 		goto bad;
855 
856 	/*
857 	 * got a new device number, store it under this truncation pattern.
858 	 * change the device number this file is being stored with.
859 	 */
860 	dpt->trunc_bits = trunc_bits;
861 	dpt->dev = lastdev;
862 	dpt->fow = pt->list;
863 	pt->list = dpt;
864 	arcn->sb.st_dev = lastdev;
865 	arcn->sb.st_ino = nino;
866 	return(0);
867 
868     bad:
869 	paxwarn(1, "Unable to fix truncated inode/device field when storing %s",
870 	    arcn->name);
871 	paxwarn(0, "Archive may create improper hard links when extracted");
872 	return(0);
873 }
874 
875 /*
876  * directory access/mod time reset table routines (for directories READ by pax)
877  *
878  * The pax -t flag requires that access times of archive files be the same
879  * before being read by pax. For regular files, access time is restored after
880  * the file has been copied. This database provides the same functionality for
881  * directories read during file tree traversal. Restoring directory access time
882  * is more complex than files since directories may be read several times until
883  * all the descendants in their subtree are visited by fts. Directory access
884  * and modification times are stored during the fts pre-order visit (done
885  * before any descendants in the subtree are visited) and restored after the
886  * fts post-order visit (after all the descendants have been visited). In the
887  * case of premature exit from a subtree (like from the effects of -n), any
888  * directory entries left in this database are reset during final cleanup
889  * operations of pax. Entries are hashed by inode number for fast lookup.
890  */
891 
892 /*
893  * atdir_start()
894  *	create the directory access time database for directories READ by pax.
895  * Return:
896  *	0 is created ok, -1 otherwise.
897  */
898 
899 int
900 atdir_start(void)
901 {
902 	if (atab != NULL)
903 		return(0);
904  	if ((atab = (ATDIR **)calloc(A_TAB_SZ, sizeof(ATDIR *))) == NULL) {
905 		paxwarn(1,"Cannot allocate space for directory access time table");
906 		return(-1);
907 	}
908 	return(0);
909 }
910 
911 
912 /*
913  * atdir_end()
914  *	walk through the directory access time table and reset the access time
915  *	of any directory who still has an entry left in the database. These
916  *	entries are for directories READ by pax
917  */
918 
919 void
920 atdir_end(void)
921 {
922 	ATDIR *pt;
923 	int i;
924 
925 	if (atab == NULL)
926 		return;
927 	/*
928 	 * for each non-empty hash table entry reset all the directories
929 	 * chained there.
930 	 */
931 	for (i = 0; i < A_TAB_SZ; ++i) {
932 		if ((pt = atab[i]) == NULL)
933 			continue;
934 		/*
935 		 * remember to force the times, set_ftime() looks at pmtime
936 		 * and patime, which only applies to things CREATED by pax,
937 		 * not read by pax. Read time reset is controlled by -t.
938 		 */
939 		for (; pt != NULL; pt = pt->fow)
940 			set_ftime(pt->name, pt->mtime, pt->atime, 1);
941 	}
942 }
943 
944 /*
945  * add_atdir()
946  *	add a directory to the directory access time table. Table is hashed
947  *	and chained by inode number. This is for directories READ by pax
948  */
949 
950 void
951 add_atdir(char *fname, dev_t dev, ino_t ino, time_t mtime, time_t atime)
952 {
953 	ATDIR *pt;
954 	u_int indx;
955 
956 	if (atab == NULL)
957 		return;
958 
959 	/*
960 	 * make sure this directory is not already in the table, if so just
961 	 * return (the older entry always has the correct time). The only
962 	 * way this will happen is when the same subtree can be traversed by
963 	 * different args to pax and the -n option is aborting fts out of a
964 	 * subtree before all the post-order visits have been made.
965 	 */
966 	indx = ((unsigned)ino) % A_TAB_SZ;
967 	if ((pt = atab[indx]) != NULL) {
968 		while (pt != NULL) {
969 			if ((pt->ino == ino) && (pt->dev == dev))
970 				break;
971 			pt = pt->fow;
972 		}
973 
974 		/*
975 		 * oops, already there. Leave it alone.
976 		 */
977 		if (pt != NULL)
978 			return;
979 	}
980 
981 	/*
982 	 * add it to the front of the hash chain
983 	 */
984 	if ((pt = (ATDIR *)malloc(sizeof(ATDIR))) != NULL) {
985 		if ((pt->name = strdup(fname)) != NULL) {
986 			pt->dev = dev;
987 			pt->ino = ino;
988 			pt->mtime = mtime;
989 			pt->atime = atime;
990 			pt->fow = atab[indx];
991 			atab[indx] = pt;
992 			return;
993 		}
994 		free(pt);
995 	}
996 
997 	paxwarn(1, "Directory access time reset table ran out of memory");
998 	return;
999 }
1000 
1001 /*
1002  * get_atdir()
1003  *	look up a directory by inode and device number to obtain the access
1004  *	and modification time you want to set to. If found, the modification
1005  *	and access time parameters are set and the entry is removed from the
1006  *	table (as it is no longer needed). These are for directories READ by
1007  *	pax
1008  * Return:
1009  *	0 if found, -1 if not found.
1010  */
1011 
1012 int
1013 get_atdir(dev_t dev, ino_t ino, time_t *mtime, time_t *atime)
1014 {
1015 	ATDIR *pt;
1016 	ATDIR **ppt;
1017 	u_int indx;
1018 
1019 	if (atab == NULL)
1020 		return(-1);
1021 	/*
1022 	 * hash by inode and search the chain for an inode and device match
1023 	 */
1024 	indx = ((unsigned)ino) % A_TAB_SZ;
1025 	if ((pt = atab[indx]) == NULL)
1026 		return(-1);
1027 
1028 	ppt = &(atab[indx]);
1029 	while (pt != NULL) {
1030 		if ((pt->ino == ino) && (pt->dev == dev))
1031 			break;
1032 		/*
1033 		 * no match, go to next one
1034 		 */
1035 		ppt = &(pt->fow);
1036 		pt = pt->fow;
1037 	}
1038 
1039 	/*
1040 	 * return if we did not find it.
1041 	 */
1042 	if (pt == NULL)
1043 		return(-1);
1044 
1045 	/*
1046 	 * found it. return the times and remove the entry from the table.
1047 	 */
1048 	*ppt = pt->fow;
1049 	*mtime = pt->mtime;
1050 	*atime = pt->atime;
1051 	free(pt->name);
1052 	free(pt);
1053 	return(0);
1054 }
1055 
1056 /*
1057  * directory access mode and time storage routines (for directories CREATED
1058  * by pax).
1059  *
1060  * Pax requires that extracted directories, by default, have their access/mod
1061  * times and permissions set to the values specified in the archive. During the
1062  * actions of extracting (and creating the destination subtree during -rw copy)
1063  * directories extracted may be modified after being created. Even worse is
1064  * that these directories may have been created with file permissions which
1065  * prohibits any descendants of these directories from being extracted. When
1066  * directories are created by pax, access rights may be added to permit the
1067  * creation of files in their subtree. Every time pax creates a directory, the
1068  * times and file permissions specified by the archive are stored. After all
1069  * files have been extracted (or copied), these directories have their times
1070  * and file modes reset to the stored values. The directory info is restored in
1071  * reverse order as entries were added to the data file from root to leaf. To
1072  * restore atime properly, we must go backwards. The data file consists of
1073  * records with two parts, the file name followed by a DIRDATA trailer. The
1074  * fixed sized trailer contains the size of the name plus the off_t location in
1075  * the file. To restore we work backwards through the file reading the trailer
1076  * then the file name.
1077  */
1078 
1079 /*
1080  * dir_start()
1081  *	set up the directory time and file mode storage for directories CREATED
1082  *	by pax.
1083  * Return:
1084  *	0 if ok, -1 otherwise
1085  */
1086 
1087 int
1088 dir_start(void)
1089 {
1090 
1091 	if (dirfd != -1)
1092 		return(0);
1093 
1094 	/*
1095 	 * unlink the file so it goes away at termination by itself
1096 	 */
1097 	memcpy(tempbase, _TFILE_BASE, sizeof(_TFILE_BASE));
1098 	if ((dirfd = mkstemp(tempfile)) >= 0) {
1099 		(void)unlink(tempfile);
1100 		return(0);
1101 	}
1102 	paxwarn(1, "Unable to create temporary file for directory times: %s",
1103 	    tempfile);
1104 	return(-1);
1105 }
1106 
1107 /*
1108  * add_dir()
1109  *	add the mode and times for a newly CREATED directory
1110  *	name is name of the directory, psb the stat buffer with the data in it,
1111  *	frc_mode is a flag that says whether to force the setting of the mode
1112  *	(ignoring the user set values for preserving file mode). Frc_mode is
1113  *	for the case where we created a file and found that the resulting
1114  *	directory was not writeable and the user asked for file modes to NOT
1115  *	be preserved. (we have to preserve what was created by default, so we
1116  *	have to force the setting at the end. this is stated explicitly in the
1117  *	pax spec)
1118  */
1119 
1120 void
1121 add_dir(char *name, int nlen, struct stat *psb, int frc_mode)
1122 {
1123 	DIRDATA dblk;
1124 
1125 	if (dirfd < 0)
1126 		return;
1127 
1128 	/*
1129 	 * get current position (where file name will start) so we can store it
1130 	 * in the trailer
1131 	 */
1132 	if ((dblk.npos = lseek(dirfd, 0L, SEEK_CUR)) < 0) {
1133 		paxwarn(1,"Unable to store mode and times for directory: %s",name);
1134 		return;
1135 	}
1136 
1137 	/*
1138 	 * write the file name followed by the trailer
1139 	 */
1140 	dblk.nlen = nlen + 1;
1141 	dblk.mode = psb->st_mode & 0xffff;
1142 	dblk.mtime = psb->st_mtime;
1143 	dblk.atime = psb->st_atime;
1144 	dblk.frc_mode = frc_mode;
1145 	if ((write(dirfd, name, dblk.nlen) == dblk.nlen) &&
1146 	    (write(dirfd, (char *)&dblk, sizeof(dblk)) == sizeof(dblk))) {
1147 		++dircnt;
1148 		return;
1149 	}
1150 
1151 	paxwarn(1,"Unable to store mode and times for created directory: %s",name);
1152 	return;
1153 }
1154 
1155 /*
1156  * proc_dir()
1157  *	process all file modes and times stored for directories CREATED
1158  *	by pax
1159  */
1160 
1161 void
1162 proc_dir(void)
1163 {
1164 	char name[PAXPATHLEN+1];
1165 	DIRDATA dblk;
1166 	u_long cnt;
1167 
1168 	if (dirfd < 0)
1169 		return;
1170 	/*
1171 	 * read backwards through the file and process each directory
1172 	 */
1173 	for (cnt = 0; cnt < dircnt; ++cnt) {
1174 		/*
1175 		 * read the trailer, then the file name, if this fails
1176 		 * just give up.
1177 		 */
1178 		if (lseek(dirfd, -((off_t)sizeof(dblk)), SEEK_CUR) < 0)
1179 			break;
1180 		if (read(dirfd,(char *)&dblk, sizeof(dblk)) != sizeof(dblk))
1181 			break;
1182 		if (lseek(dirfd, dblk.npos, SEEK_SET) < 0)
1183 			break;
1184 		if (read(dirfd, name, dblk.nlen) != dblk.nlen)
1185 			break;
1186 		if (lseek(dirfd, dblk.npos, SEEK_SET) < 0)
1187 			break;
1188 
1189 		/*
1190 		 * frc_mode set, make sure we set the file modes even if
1191 		 * the user didn't ask for it (see file_subs.c for more info)
1192 		 */
1193 		if (pmode || dblk.frc_mode)
1194 			set_pmode(name, dblk.mode);
1195 		if (patime || pmtime)
1196 			set_ftime(name, dblk.mtime, dblk.atime, 0);
1197 	}
1198 
1199 	(void)close(dirfd);
1200 	dirfd = -1;
1201 	if (cnt != dircnt)
1202 		paxwarn(1,"Unable to set mode and times for created directories");
1203 	return;
1204 }
1205 
1206 /*
1207  * database independent routines
1208  */
1209 
1210 /*
1211  * st_hash()
1212  *	hashes filenames to a u_int for hashing into a table. Looks at the tail
1213  *	end of file, as this provides far better distribution than any other
1214  *	part of the name. For performance reasons we only care about the last
1215  *	MAXKEYLEN chars (should be at LEAST large enough to pick off the file
1216  *	name). Was tested on 500,000 name file tree traversal from the root
1217  *	and gave almost a perfectly uniform distribution of keys when used with
1218  *	prime sized tables (MAXKEYLEN was 128 in test). Hashes (sizeof int)
1219  *	chars at a time and pads with 0 for last addition.
1220  * Return:
1221  *	the hash value of the string MOD (%) the table size.
1222  */
1223 
1224 u_int
1225 st_hash(char *name, int len, int tabsz)
1226 {
1227 	char *pt;
1228 	char *dest;
1229 	char *end;
1230 	int i;
1231 	u_int key = 0;
1232 	int steps;
1233 	int res;
1234 	u_int val;
1235 
1236 	/*
1237 	 * only look at the tail up to MAXKEYLEN, we do not need to waste
1238 	 * time here (remember these are pathnames, the tail is what will
1239 	 * spread out the keys)
1240 	 */
1241 	if (len > MAXKEYLEN) {
1242 		pt = &(name[len - MAXKEYLEN]);
1243 		len = MAXKEYLEN;
1244 	} else
1245 		pt = name;
1246 
1247 	/*
1248 	 * calculate the number of u_int size steps in the string and if
1249 	 * there is a runt to deal with
1250 	 */
1251 	steps = len/sizeof(u_int);
1252 	res = len % sizeof(u_int);
1253 
1254 	/*
1255 	 * add up the value of the string in unsigned integer sized pieces
1256 	 * too bad we cannot have unsigned int aligned strings, then we
1257 	 * could avoid the expensive copy.
1258 	 */
1259 	for (i = 0; i < steps; ++i) {
1260 		end = pt + sizeof(u_int);
1261 		dest = (char *)&val;
1262 		while (pt < end)
1263 			*dest++ = *pt++;
1264 		key += val;
1265 	}
1266 
1267 	/*
1268 	 * add in the runt padded with zero to the right
1269 	 */
1270 	if (res) {
1271 		val = 0;
1272 		end = pt + res;
1273 		dest = (char *)&val;
1274 		while (pt < end)
1275 			*dest++ = *pt++;
1276 		key += val;
1277 	}
1278 
1279 	/*
1280 	 * return the result mod the table size
1281 	 */
1282 	return(key % tabsz);
1283 }
1284