Debian Codegraph @

tables.c

raw symbols SCIP
1 /* $OpenBSD: tables.c,v 1.53 2017/09/16 07:42:34 otto Exp $ */
2 /* $NetBSD: tables.c,v 1.4 1995/03/21 09:07:45 cgd Exp $ */
3
4 /*-
5 * Copyright (c) 2005, 2012, 2015, 2016, 2018, 2019
6 * mirabilos <[email protected]>
7 * Copyright (c) 2011
8 * Svante Signell <[email protected]>
9 * Guillem Jover <[email protected]>
10 * Copyright (c) 1992 Keith Muller.
11 * Copyright (c) 1992, 1993
12 * The Regents of the University of California. All rights reserved.
13 *
14 * This code is derived from software contributed to Berkeley by
15 * Keith Muller of the University of California, San Diego.
16 *
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions
19 * are met:
20 * 1. Redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution.
25 * 3. Neither the name of the University nor the names of its contributors
26 * may be used to endorse or promote products derived from this software
27 * without specific prior written permission.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
30 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
31 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
32 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
33 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
35 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
37 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
38 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39 * SUCH DAMAGE.
40 */
41
42 #include <sys/types.h>
43 #if HAVE_BOTH_TIME_H
44 #include <sys/time.h>
45 #include <time.h>
46 #elif HAVE_SYS_TIME_H
47 #include <sys/time.h>
48 #elif HAVE_TIME_H
49 #include <time.h>
50 #endif
51 #include <sys/stat.h>
52 #include <errno.h>
53 #include <fcntl.h>
54 #include <limits.h>
55 #include <signal.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #if HAVE_STRINGS_H
60 #include <strings.h>
61 #endif
62 #include <unistd.h>
63
64 #include "pax.h"
65 #include "ftimes.h"
66 #include "extern.h"
67
68 __RCSID("$MirOS: src/bin/pax/tables.c,v 1.33 2024/08/17 23:33:52 tg Exp $");
69
70 #if (_POSIX_VERSION >= 200809L) || (defined(MirBSD) && (MirBSD > 0x0AB9))
71 #define REALPATH_CAN_ALLOCATE
72 #endif
73
74 /*
75 * Routines for controlling the contents of all the different databases pax
76 * keeps. Tables are dynamically created only when they are needed. The
77 * goal was speed and the ability to work with HUGE archives. The databases
78 * were kept simple, but do have complex rules for when the contents change.
79 * As of this writing, the posix library functions were more complex than
80 * needed for this application (pax databases have very short lifetimes and
81 * do not survive after pax is finished). pax is required to handle very
82 * large archives. These database routines carefully combine memory usage and
83 * temporary file storage in ways which will not significantly impact runtime
84 * performance while allowing the largest possible archives to be handled.
85 * Trying to force the fit to the posix database routines was not considered
86 * time well spent.
87 */
88
89 /*
90 * data structures and constants used by the different databases kept by pax
91 */
92
93 /*
94 * Hash Table Sizes MUST BE PRIME, if set too small performance suffers.
95 * Probably safe to expect 500000 inodes per tape. Assuming good key
96 * distribution (inodes) chains of under 50 long (worst case) is ok.
97 */
98 #define L_TAB_SZ 2503 /* hard link hash table size */
99 #define F_TAB_SZ 50503 /* file time hash table size */
100 #define N_TAB_SZ 541 /* interactive rename hash table */
101 #define D_TAB_SZ 317 /* unique device mapping table */
102 #define A_TAB_SZ 317 /* ftree dir access time reset table */
103 #define SL_TAB_SZ 317 /* escape symlink tables */
104 #define MAXKEYLEN 64 /* max number of chars for hash */
105 #define DIRP_SIZE 64 /* initial size of created dir table */
106
107 /*
108 * file hard link structure (hashed by dev/ino and chained) used to find the
109 * hard links in a filesystem or with some archive formats (cpio)
110 */
111 typedef struct hrdlnk {
112 ino_t ino; /* files inode number */
113 char *name; /* name of first file seen with this ino/dev */
114 dev_t dev; /* files device number */
115 u_long nlink; /* expected link count */
116 struct hrdlnk *fow;
117 } HRDLNK;
118
119 /*
120 * Archive write update file time table (the -u, -C flag), hashed by filename.
121 * Filenames are stored in a scratch file at seek offset into the file. The
122 * file time (mod time) and the file name length (for a quick check) are
123 * stored in a hash table node. We were forced to use a scratch file because
124 * with -u, the mtime for every node in the archive must always be available
125 * to compare against (and this data can get REALLY large with big archives).
126 * By being careful to read only when we have a good chance of a match, the
127 * performance loss is not measurable (and the size of the archive we can
128 * handle is greatly increased).
129 */
130 typedef struct ftm {
131 off_t seek; /* location in scratch file */
132 struct ftm *fow;
133 int namelen; /* file name length */
134 struct stat sb; /* files last modification time */
135 } FTM;
136
137 /*
138 * Interactive rename table (-i flag), hashed by orig filename.
139 * We assume this will not be a large table as this mapping data can only be
140 * obtained through interactive input by the user. Nobody is going to type in
141 * changes for 500000 files? We use chaining to resolve collisions.
142 */
143
144 typedef struct namt {
145 char *oname; /* old name */
146 char *nname; /* new name typed in by the user */
147 struct namt *fow;
148 } NAMT;
149
150 /*
151 * Unique device mapping tables. Some protocols (e.g. cpio) require that the
152 * <c_dev,c_ino> pair will uniquely identify a file in an archive unless they
153 * are links to the same file. Appending to archives can break this. For those
154 * protocols that have this requirement we map c_dev to a unique value not seen
155 * in the archive when we append. We also try to handle inode truncation with
156 * this table. (When the inode field in the archive header are too small, we
157 * remap the dev on writes to remove accidental collisions).
158 *
159 * The list is hashed by device number using chain collision resolution. Off of
160 * each DEVT are linked the various remaps for this device based on those bits
161 * in the inode which were truncated. For example if we are just remapping to
162 * avoid a device number during an update append, off the DEVT we would have
163 * only a single DLIST that has a truncation id of 0 (no inode bits were
164 * stripped for this device so far). When we spot inode truncation we create
165 * a new mapping based on the set of bits in the inode which were stripped off.
166 * so if the top four bits of the inode are stripped and they have a pattern of
167 * 0110...... (where . are those bits not truncated) we would have a mapping
168 * assigned for all inodes that has the same 0110.... pattern (with this dev
169 * number of course). This keeps the mapping sparse and should be able to store
170 * close to the limit of files which can be represented by the optimal
171 * combination of dev and inode bits, and without creating a fouled up archive.
172 * Note we also remap truncated devs in the same way (an exercise for the
173 * dedicated reader; always wanted to say that...:)
174 */
175
176 typedef struct devt {
177 dev_t dev; /* the orig device number we now have to map */
178 struct devt *fow; /* new device map list */
179 struct dlist *list; /* map list based on inode truncation bits */
180 } DEVT;
181
182 typedef struct dlist {
183 ino_t trunc_bits; /* truncation pattern for a specific map */
184 dev_t dev; /* the new device id we use */
185 struct dlist *fow;
186 } DLIST;
187
188 /*
189 * ftree directory access time reset table. When we are done with a
190 * subtree we reset the access and mod time of the directory when the tflag is
191 * set. Not really explicitly specified in the pax spec, but easy and fast to
192 * do (and this may have even been intended in the spec, it is not clear).
193 * table is hashed by inode with chaining.
194 */
195
196 typedef struct atdir {
197 struct file_times ft;
198 struct atdir *fow;
199 } ATDIR;
200
201 /*
202 * created directory time and mode storage entry. After pax is finished during
203 * extraction or copy, we must reset directory access modes and times that
204 * may have been modified after creation (they no longer have the specified
205 * times and/or modes). We must reset time in the reverse order of creation,
206 * because entries are added from the top of the file tree to the bottom.
207 * We MUST reset times from leaf to root (it will not work the other
208 * direction).
209 */
210
211 typedef struct dirdata {
212 struct file_times ft;
213 mode_t tr_mode; /* file mode to restore */
214 Wahr frc_mode; /* do we force mode settings? */
215 } DIRDATA;
216
217 /*
218 * file hard link structure (hashed by dev/ino and chained) for anonymisation
219 */
220 typedef struct hrdflnk {
221 dev_t dev; /* files device number */
222 ino_t ino; /* files inode number */
223 u_long nlink; /* expected link count */
224 ino_t newi; /* new inode number */
225 struct hrdflnk *fow;
226 } HRDFLNK;
227
228 static HRDLNK **ltab = NULL; /* hard link table for detecting hard links */
229 static HRDFLNK **fltab = NULL; /* hard link table for anonymisation */
230 static FTM **ftab = NULL; /* file time table for updating arch */
231 static NAMT **ntab = NULL; /* interactive rename storage table */
232 static DEVT **dtab = NULL; /* device/inode mapping tables */
233 static ATDIR **atab = NULL; /* file tree directory time reset table */
234 static DIRDATA *dirp = NULL; /* storage for setting created dir time/mode */
235 static size_t dirsize; /* size of dirp table */
236 static size_t dircnt = 0; /* entries in dir time/mode storage */
237 static int ffd = -1; /* tmp file for file time table name storage */
238
239 static DEVT *chk_dev(dev_t, int);
240
241 #ifndef REALPATH_CAN_ALLOCATE
242 static char realname[PATH_MAX];
243 #endif
244
245 static char *
246 xrealpath(const char *path)
247 {
248 #ifndef REALPATH_CAN_ALLOCATE
249 char *rv;
250
251 if ((rv = realpath(path, realname)))
252 rv = strdup(rv);
253 return (rv);
254 #else
255 return (realpath(path, NULL));
256 #endif
257 }
258
259 /*
260 * hard link table routines
261 *
262 * The hard link table tries to detect hard links to files using the device and
263 * inode values. We do this when writing an archive, so we can tell the format
264 * write routine that this file is a hard link to another file. The format
265 * write routine then can store this file in whatever way it wants (as a hard
266 * link if the format supports that like tar, or ignore this info like cpio).
267 * (Actually a field in the format driver table tells us if the format wants
268 * hard link info. if not, we do not waste time looking for them). We also use
269 * the same table when reading an archive. In that situation, this table is
270 * used by the format read routine to detect hard links from stored dev and
271 * inode numbers (like cpio). This will allow pax to create a link when one
272 * can be detected by the archive format.
273 */
274
275 /*
276 * lnk_start
277 * Creates the hard link table.
278 * Return:
279 * 0 if created, -1 if failure
280 */
281
282 int
283 lnk_start(void)
284 {
285 if (ltab != NULL)
286 return (0);
287 if ((ltab = calloc(L_TAB_SZ, sizeof(HRDLNK *))) == NULL) {
288 paxwarn(1, "%s for %s", "Out of memory",
289 "hard link table");
290 return (-1);
291 }
292 return (0);
293 }
294
295 /*
296 * chk_lnk()
297 * Looks up entry in hard link hash table. If found, it copies the name
298 * of the file it is linked to (we already saw that file) into ln_name.
299 * lnkcnt is decremented and if goes to 1 the node is deleted from the
300 * database. (We have seen all the links to this file). If not found,
301 * we add the file to the database if it has the potential for having
302 * hard links to other files we may process (it has a link count > 1)
303 * Return:
304 * if found returns 1; if not found returns 0; -1 on error
305 */
306
307 int
308 chk_lnk(ARCHD *arcn)
309 {
310 HRDLNK *pt;
311 HRDLNK **ppt;
312 unsigned int indx;
313
314 if (ltab == NULL)
315 return(-1);
316 /*
317 * ignore those nodes that cannot have hard links
318 */
319 if ((arcn->type == PAX_DIR) || (arcn->sb.st_nlink <= 1))
320 return(0);
321
322 /*
323 * hash inode number and look for this file
324 */
325 indx = ((unsigned)arcn->sb.st_ino) % L_TAB_SZ;
326 if ((pt = ltab[indx]) != NULL) {
327 /*
328 * its hash chain in not empty, walk down looking for it
329 */
330 ppt = &(ltab[indx]);
331 while (pt != NULL) {
332 if ((pt->ino == arcn->sb.st_ino) &&
333 (pt->dev == arcn->sb.st_dev))
334 break;
335 ppt = &(pt->fow);
336 pt = pt->fow;
337 }
338
339 if (pt != NULL) {
340 /*
341 * found a link. set the node type and copy in the
342 * name of the file it is to link to. we need to
343 * handle hardlinks to regular files differently than
344 * other links.
345 */
346 arcn->ln_nlen = strlcpy(arcn->ln_name, pt->name,
347 sizeof(arcn->ln_name));
348 /* XXX truncate? */
349 if ((size_t)arcn->nlen >= sizeof(arcn->name))
350 arcn->nlen = sizeof(arcn->name) - 1;
351 if (arcn->type == PAX_REG)
352 arcn->type = PAX_HRG;
353 else
354 arcn->type = PAX_HLK;
355
356 /*
357 * if we have found all the links to this file, remove
358 * it from the database
359 */
360 if (--pt->nlink <= 1) {
361 *ppt = pt->fow;
362 free(pt->name);
363 free(pt);
364 }
365 return(1);
366 }
367 }
368
369 /*
370 * we never saw this file before. It has links so we add it to the
371 * front of this hash chain
372 */
373 if ((pt = malloc(sizeof(HRDLNK))) != NULL) {
374 if ((pt->name = strdup(arcn->name)) != NULL) {
375 pt->dev = arcn->sb.st_dev;
376 pt->ino = arcn->sb.st_ino;
377 pt->nlink = arcn->sb.st_nlink;
378 pt->fow = ltab[indx];
379 ltab[indx] = pt;
380 return(0);
381 }
382 free(pt);
383 }
384
385 paxwarn(1, "%s for %s", "Out of memory", "hard link table");
386 return (-1);
387 }
388
389 /*
390 * purg_lnk
391 * remove reference for a file that we may have added to the data base as
392 * a potential source for hard links. We ended up not using the file, so
393 * we do not want to accidently point another file at it later on.
394 */
395
396 void
397 purg_lnk(ARCHD *arcn)
398 {
399 HRDLNK *pt;
400 HRDLNK **ppt;
401 unsigned int indx;
402
403 if (ltab == NULL)
404 return;
405 /*
406 * do not bother to look if it could not be in the database
407 */
408 if ((arcn->sb.st_nlink <= 1) || (arcn->type == PAX_DIR) ||
409 PAX_IS_HARDLINK(arcn->type))
410 return;
411
412 /*
413 * find the hash chain for this inode value, if empty return
414 */
415 indx = ((unsigned)arcn->sb.st_ino) % L_TAB_SZ;
416 if ((pt = ltab[indx]) == NULL)
417 return;
418
419 /*
420 * walk down the list looking for the inode/dev pair, unlink and
421 * free if found
422 */
423 ppt = &(ltab[indx]);
424 while (pt != NULL) {
425 if ((pt->ino == arcn->sb.st_ino) &&
426 (pt->dev == arcn->sb.st_dev))
427 break;
428 ppt = &(pt->fow);
429 pt = pt->fow;
430 }
431 if (pt == NULL)
432 return;
433
434 /*
435 * remove and free it
436 */
437 *ppt = pt->fow;
438 free(pt->name);
439 free(pt);
440 }
441
442 /*
443 * lnk_end()
444 * pull apart a existing link table so we can reuse it. We do this between
445 * read and write phases of append with update. (The format may have
446 * used the link table, and we need to start with a fresh table for the
447 * write phase
448 */
449
450 void
451 lnk_end(void)
452 {
453 int i;
454 HRDLNK *pt;
455 HRDLNK *ppt;
456
457 if (ltab == NULL)
458 return;
459
460 for (i = 0; i < L_TAB_SZ; ++i) {
461 if (ltab[i] == NULL)
462 continue;
463 pt = ltab[i];
464 ltab[i] = NULL;
465
466 /*
467 * free up each entry on this chain
468 */
469 while (pt != NULL) {
470 ppt = pt;
471 pt = ppt->fow;
472 free(ppt->name);
473 free(ppt);
474 }
475 }
476 }
477
478 /*
479 * modification time table routines
480 *
481 * The modification time table keeps track of last modification times for all
482 * files stored in an archive during a write phase when -u is set. We only
483 * add a file to the archive if it is newer than a file with the same name
484 * already stored on the archive (if there is no other file with the same
485 * name on the archive it is added). This applies to writes and appends.
486 * An append with an -u must read the archive and store the modification time
487 * for every file on that archive before starting the write phase. It is clear
488 * that this is one HUGE database. To save memory space, the actual file names
489 * are stored in a scratch file and indexed by an in-memory hash table. The
490 * hash table is indexed by hashing the file path. The nodes in the table store
491 * the length of the filename and the lseek offset within the scratch file
492 * where the actual name is stored. Since there are never any deletions from
493 * this table, fragmentation of the scratch file is never a issue. Lookups
494 * seem to not exhibit any locality at all (files in the database are rarely
495 * looked up more than once...), so caching is just a waste of memory. The
496 * only limitation is the amount of scratch file space available to store the
497 * path names.
498 */
499
500 /*
501 * ftime_start()
502 * create the file time hash table and open for read/write the scratch
503 * file. (after created it is unlinked, so when we exit we leave
504 * no witnesses).
505 * Return:
506 * 0 if the table and file was created ok, -1 otherwise
507 */
508
509 int
510 ftime_start(void)
511 {
512
513 if (ftab != NULL)
514 return (0);
515 if ((ftab = calloc(F_TAB_SZ, sizeof(FTM *))) == NULL) {
516 paxwarn(1, "%s for %s", "Out of memory",
517 "file time table");
518 return (-1);
519 }
520
521 /*
522 * get random name and create temporary scratch file, unlink name
523 * so it will get removed on exit
524 */
525 memcpy(tempbase, _TFILE_BASE, sizeof(_TFILE_BASE));
526 if ((ffd = mkstemp(tempfile)) < 0) {
527 syswarn(1, errno, "Unable to create temporary file %s",
528 tempfile);
529 return (-1);
530 }
531 (void)unlink(tempfile);
532
533 return(0);
534 }
535
536 /*
537 * chk_ftime()
538 * looks up entry in file time hash table. If not found, the file is
539 * added to the hash table and the file named stored in the scratch file.
540 * If a file with the same name is found, the file times are compared and
541 * the most recent file time is retained. If the new file was younger (or
542 * was not in the database) the new file is selected for storage.
543 * Return:
544 * 0 if file should be added to the archive, 1 if it should be skipped,
545 * -1 on error
546 */
547
548 int
549 chk_ftime(ARCHD *arcn)
550 {
551 FTM *pt;
552 int namelen;
553 unsigned int indx;
554 char ckname[PAXPATHLEN+1];
555
556 /*
557 * no info, go ahead and add to archive
558 */
559 if (ftab == NULL)
560 return(0);
561
562 /*
563 * hash the pathname and look up in table
564 */
565 namelen = arcn->nlen;
566 indx = st_hash(arcn->name, namelen, F_TAB_SZ);
567 if ((pt = ftab[indx]) != NULL) {
568 /*
569 * the hash chain is not empty, walk down looking for match
570 * only read up the path names if the lengths match, speeds
571 * up the search a lot
572 */
573 while (pt != NULL) {
574 if (pt->namelen == namelen) {
575 /*
576 * potential match, have to read the name
577 * from the scratch file.
578 */
579 if (lseek(ffd,pt->seek,SEEK_SET) != pt->seek) {
580 syswarn(1, errno, "Failed %s on %s",
581 "seek", "file time table");
582 return (-1);
583 }
584 if (read(ffd, ckname, namelen) != namelen) {
585 syswarn(1, errno, "Failed %s on %s",
586 "read", "file time table");
587 return (-1);
588 }
589
590 /*
591 * if the names match, we are done
592 */
593 if (!strncmp(ckname, arcn->name, namelen))
594 break;
595 }
596
597 /*
598 * try the next entry on the chain
599 */
600 pt = pt->fow;
601 }
602
603 if (pt != NULL) {
604 /*
605 * found the file, compare the times, save the newer
606 */
607 if (st_timecmp(m, &arcn->sb, &pt->sb, >)) {
608 /*
609 * file is newer
610 */
611 st_timecpy(m, &pt->sb, &arcn->sb);
612 return(0);
613 }
614 /*
615 * file is older
616 */
617 return(1);
618 }
619 }
620
621 /*
622 * not in table, add it
623 */
624 if ((pt = malloc(sizeof(FTM))) != NULL) {
625 /*
626 * add the name at the end of the scratch file, saving the
627 * offset. add the file to the head of the hash chain
628 */
629 if ((pt->seek = lseek(ffd, 0, SEEK_END)) >= 0) {
630 if (write(ffd, arcn->name, namelen) == namelen) {
631 st_timecpy(m, &pt->sb, &arcn->sb);
632 pt->namelen = namelen;
633 pt->fow = ftab[indx];
634 ftab[indx] = pt;
635 return(0);
636 }
637 syswarn(1, errno, "Failed %s on %s",
638 "write", "file time table");
639 } else
640 syswarn(1, errno, "Failed %s on %s",
641 "seek", "file time table");
642 } else
643 paxwarn(1, "%s for %s", "Out of memory", "file time table");
644
645 if (pt != NULL)
646 free(pt);
647 return(-1);
648 }
649
650 /*
651 * escaping (absolute or w/"..") symlink table routines
652 *
653 * By default, an archive shouldn't be able extract to outside of the
654 * current directory. What should we do if the archive contains a symlink
655 * whose value is either absolute or contains ".." components? What we'll
656 * do is initially create the path as an empty file (to block attempts to
657 * reference _through_ it) and instead record its path and desired
658 * final value and mode. Then once all the other archive
659 * members are created (but before the pass to set timestamps on
660 * directories) we'll process those records, replacing the placeholder with
661 * the correct symlink and setting them to the correct mode, owner, group,
662 * and timestamps.
663 *
664 * Note: we also need to handle hardlinks to symlinks (barf) as well as
665 * hardlinks whose target is replaced by a later entry in the archive (barf^2).
666 *
667 * So we track things by dev+ino of the placeholder file, associating with
668 * that the value and mode of the final symlink and a list of paths that
669 * should all be hardlinks of that. We'll 'store' the symlink's desired
670 * timestamps, owner, and group by setting them on the placeholder file.
671 *
672 * The operations are:
673 * a) create an escaping symlink: create the placeholder file and add an entry
674 * for the new link
675 * b) create a hardlink: do the link. If the target turns out to be a
676 * zero-length file whose dev+ino are in the symlink table, then add this
677 * path to the list of names for that link
678 * c) perform deferred processing: for each entry, check each associated path:
679 * if it's a zero-length file with the correct dev+ino then recreate it as
680 * the specified symlink or hardlink to the first such
681 */
682
683 struct slpath {
684 char *sp_path;
685 struct slpath *sp_next;
686 };
687 struct slinode {
688 ino_t sli_ino;
689 char *sli_value;
690 struct slpath sli_paths;
691 struct slinode *sli_fow; /* hash table chain */
692 dev_t sli_dev;
693 mode_t sli_mode;
694 };
695
696 static struct slinode **slitab = NULL;
697
698 /*
699 * sltab_start()
700 * create the hash table
701 * Return:
702 * 0 if the table and file was created ok, -1 otherwise
703 */
704
705 int
706 sltab_start(void)
707 {
708
709 if ((slitab = calloc(SL_TAB_SZ, sizeof *slitab)) == NULL) {
710 syswarn(1, errno, "symlink table");
711 return(-1);
712 }
713
714 return(0);
715 }
716
717 /*
718 * sltab_add_sym()
719 * Create the placeholder and tracking info for an escaping symlink.
720 * Return:
721 * 0 on success, -1 otherwise
722 */
723
724 int
725 sltab_add_sym(const char *path0, const char *value0, mode_t mode)
726 {
727 struct stat sb;
728 struct slinode *s;
729 struct slpath *p;
730 char *path, *value;
731 unsigned int indx;
732 int fd;
733
734 /* create the placeholder */
735 fd = binopen3(BO_CLEXEC, path0, O_WRONLY | O_CREAT | O_EXCL, 0600);
736 if (fd == -1)
737 return (-1);
738 if (fstat(fd, &sb) == -1) {
739 unlink(path0);
740 close(fd);
741 return (-1);
742 }
743 close(fd);
744
745 if (havechd && *path0 != '/') {
746 if ((path = xrealpath(path0)) == NULL) {
747 syswarn(1, errno, "Cannot canonicalise %s", path0);
748 unlink(path0);
749 return (-1);
750 }
751 } else if ((path = strdup(path0)) == NULL) {
752 syswarn(1, errno, "%s %s", "deferred symlink", "path");
753 unlink(path0);
754 return (-1);
755 }
756 if ((value = strdup(value0)) == NULL) {
757 syswarn(1, errno, "%s value", "deferred symlink");
758 unlink(path);
759 free(path);
760 return (-1);
761 }
762
763 /* now check the hash table for conflicting entry */
764 indx = (sb.st_ino ^ sb.st_dev) % SL_TAB_SZ;
765 for (s = slitab[indx]; s != NULL; s = s->sli_fow) {
766 if (s->sli_ino != sb.st_ino || s->sli_dev != sb.st_dev)
767 continue;
768
769 /*
770 * One of our placeholders got removed behind our back and
771 * we've reused the inode. Weird, but clean up the mess.
772 */
773 free(s->sli_value);
774 free(s->sli_paths.sp_path);
775 p = s->sli_paths.sp_next;
776 while (p != NULL) {
777 struct slpath *next_p = p->sp_next;
778
779 free(p->sp_path);
780 free(p);
781 p = next_p;
782 }
783 goto set_value;
784 }
785
786 /* Normal case: create a new node */
787 if ((s = malloc(sizeof *s)) == NULL) {
788 syswarn(1, errno, "deferred symlink");
789 unlink(path);
790 free(path);
791 free(value);
792 return (-1);
793 }
794 s->sli_ino = sb.st_ino;
795 s->sli_dev = sb.st_dev;
796 s->sli_fow = slitab[indx];
797 slitab[indx] = s;
798
799 set_value:
800 s->sli_paths.sp_path = path;
801 s->sli_paths.sp_next = NULL;
802 s->sli_value = value;
803 s->sli_mode = mode;
804 return (0);
805 }
806
807 /*
808 * sltab_add_link()
809 * A hardlink was created; if it looks like a placeholder, handle the
810 * tracking.
811 * Return:
812 * 0 if things are ok, -1 if something went wrong
813 */
814
815 int
816 sltab_add_link(const char *path, const struct stat *sb)
817 {
818 struct slinode *s;
819 struct slpath *p;
820 unsigned int indx;
821
822 if (!S_ISREG(sb->st_mode) || sb->st_size != 0)
823 return (1);
824
825 /* find the hash table entry for this hardlink */
826 indx = (sb->st_ino ^ sb->st_dev) % SL_TAB_SZ;
827 for (s = slitab[indx]; s != NULL; s = s->sli_fow) {
828 if (s->sli_ino != sb->st_ino || s->sli_dev != sb->st_dev)
829 continue;
830
831 if ((p = malloc(sizeof *p)) == NULL) {
832 syswarn(1, errno, "%s hardlink", "deferred symlink");
833 return (-1);
834 }
835 if (havechd && *path != '/') {
836 if ((p->sp_path = xrealpath(path)) == NULL) {
837 syswarn(1, errno, "Cannot canonicalise %s",
838 path);
839 free(p);
840 return (-1);
841 }
842 } else if ((p->sp_path = strdup(path)) == NULL) {
843 syswarn(1, errno, "%s hardlink path", "deferred symlink");
844 free(p);
845 return (-1);
846 }
847
848 /* link it in */
849 p->sp_next = s->sli_paths.sp_next;
850 s->sli_paths.sp_next = p;
851 return (0);
852 }
853
854 /* not found */
855 return (1);
856 }
857
858 static int
859 sltab_process_one(struct slinode *s, struct slpath *p, const char *first,
860 int in_sig)
861 {
862 struct stat sb;
863 char *path = p->sp_path;
864 mode_t mode;
865 int err;
866
867 /*
868 * is it the expected placeholder? This can fail legimately
869 * if the archive overwrote the link with another, later entry,
870 * so don't warn.
871 */
872 if (stat(path, &sb) != 0 || !S_ISREG(sb.st_mode) || sb.st_size != 0 ||
873 sb.st_ino != s->sli_ino || sb.st_dev != s->sli_dev)
874 return (0);
875
876 if (unlink(path) && errno != ENOENT) {
877 if (!in_sig)
878 syswarn(1, errno, "%s removal", "deferred symlink");
879 return (0);
880 }
881
882 err = 0;
883 if (first != NULL) {
884 #if HAVE_LINKAT
885 /* add another hardlink to the existing symlink */
886 if (linkat(AT_FDCWD, first, AT_FDCWD, path, 0) == 0)
887 return (0);
888
889 /*
890 * Couldn't hardlink the symlink for some reason, so we'll
891 * try creating it as its own symlink, but save the error
892 * for reporting if that fails.
893 */
894 err = errno;
895 #else
896 err = EOPNOTSUPP;
897 #endif
898 }
899
900 if (symlink(s->sli_value, path)) {
901 if (!in_sig) {
902 const char *qualifier = "";
903 if (err)
904 qualifier = " hardlink";
905 else
906 err = errno;
907
908 syswarn(1, err, "%s%s: %s",
909 "deferred symlink", qualifier, path);
910 }
911 return (0);
912 }
913
914 /* success, so set the id, mode, and times */
915 mode = s->sli_mode;
916 if (pids) {
917 /* if can't set the ids, force the set[ug]id bits off */
918 if (set_ids(path, sb.st_uid, sb.st_gid, 1))
919 mode &= ~(SETBITS);
920 }
921
922 if (pmode)
923 set_pmode(path, mode, 1);
924
925 if (patime || pmtime)
926 set_ftime(path, &sb, 0, 1);
927
928 /*
929 * If we tried to link to first but failed, then this new symlink
930 * might be a better one to try in the future. Guess from the errno.
931 */
932 if (err == 0 || err == ENOENT || err == EMLINK || err == EOPNOTSUPP)
933 return (1);
934 return (0);
935 }
936
937 /*
938 * sltab_process()
939 * Do all the delayed process for escape symlinks
940 */
941
942 void
943 sltab_process(int in_sig)
944 {
945 struct slinode *s;
946 struct slpath *p;
947 char *first;
948 unsigned int indx;
949
950 if (slitab == NULL)
951 return;
952
953 /* walk across the entire hash table */
954 for (indx = 0; indx < SL_TAB_SZ; indx++) {
955 while ((s = slitab[indx]) != NULL) {
956 /* pop this entry */
957 slitab[indx] = s->sli_fow;
958
959 first = NULL;
960 p = &s->sli_paths;
961 while (1) {
962 struct slpath *next_p;
963
964 if (sltab_process_one(s, p, first, in_sig)) {
965 if (!in_sig)
966 free(first);
967 first = p->sp_path;
968 } else if (!in_sig)
969 free(p->sp_path);
970
971 if ((next_p = p->sp_next) == NULL)
972 break;
973 *p = *next_p;
974 if (!in_sig)
975 free(next_p);
976 }
977 if (!in_sig) {
978 free(first);
979 free(s->sli_value);
980 free(s);
981 }
982 }
983 }
984 if (!in_sig)
985 free(slitab);
986 slitab = NULL;
987 }
988
989 /*
990 * Interactive rename table routines
991 *
992 * The interactive rename table keeps track of the new names that the user
993 * assigns to files from tty input. Since this map is unique for each file
994 * we must store it in case there is a reference to the file later in archive
995 * (a link). Otherwise we will be unable to find the file we know was
996 * extracted. The remapping of these files is stored in a memory based hash
997 * table (it is assumed since input must come from /dev/tty, it is unlikely to
998 * be a very large table).
999 */
1000
1001 /*
1002 * name_start()
1003 * create the interactive rename table
1004 * Return:
1005 * 0 if successful, -1 otherwise
1006 */
1007
1008 int
1009 name_start(void)
1010 {
1011 if (ntab != NULL)
1012 return (0);
1013 if ((ntab = calloc(N_TAB_SZ, sizeof(NAMT *))) == NULL) {
1014 paxwarn(1, "%s for %s", "Out of memory",
1015 "interactive rename table");
1016 return (-1);
1017 }
1018 return (0);
1019 }
1020
1021 /*
1022 * add_name()
1023 * add the new name to old name mapping just created by the user.
1024 * If an old name mapping is found (there may be duplicate names on an
1025 * archive) only the most recent is kept.
1026 * Return:
1027 * 0 if added, -1 otherwise
1028 */
1029
1030 int
1031 add_name(char *oname, int onamelen, char *nname)
1032 {
1033 NAMT *pt;
1034 unsigned int indx;
1035
1036 if (ntab == NULL) {
1037 /*
1038 * should never happen
1039 */
1040 paxwarn(0, "No interactive rename table, links may fail");
1041 return(0);
1042 }
1043
1044 /*
1045 * look to see if we have already mapped this file, if so we
1046 * will update it
1047 */
1048 indx = st_hash(oname, onamelen, N_TAB_SZ);
1049 if ((pt = ntab[indx]) != NULL) {
1050 /*
1051 * look down the has chain for the file
1052 */
1053 while ((pt != NULL) && (strcmp(oname, pt->oname) != 0))
1054 pt = pt->fow;
1055
1056 if (pt != NULL) {
1057 /*
1058 * found an old mapping, replace it with the new one
1059 * the user just input (if it is different)
1060 */
1061 if (strcmp(nname, pt->nname) == 0)
1062 return(0);
1063
1064 free(pt->nname);
1065 if ((pt->nname = strdup(nname)) == NULL) {
1066 paxwarn(1, "Cannot update rename table");
1067 return(-1);
1068 }
1069 return(0);
1070 }
1071 }
1072
1073 /*
1074 * this is a new mapping, add it to the table
1075 */
1076 if ((pt = malloc(sizeof(NAMT))) != NULL) {
1077 if ((pt->oname = strdup(oname)) != NULL) {
1078 if ((pt->nname = strdup(nname)) != NULL) {
1079 pt->fow = ntab[indx];
1080 ntab[indx] = pt;
1081 return(0);
1082 }
1083 free(pt->oname);
1084 }
1085 free(pt);
1086 }
1087 paxwarn(1, "%s for %s", "Out of memory", "interactive rename table");
1088 return (-1);
1089 }
1090
1091 /*
1092 * sub_name()
1093 * look up a link name to see if it points at a file that has been
1094 * remapped by the user. If found, the link is adjusted to contain the
1095 * new name (oname is the link to name)
1096 */
1097
1098 void
1099 sub_name(char *oname, int *onamelen, int onamesize)
1100 {
1101 NAMT *pt;
1102 unsigned int indx;
1103
1104 if (ntab == NULL)
1105 return;
1106 /*
1107 * look the name up in the hash table
1108 */
1109 indx = st_hash(oname, *onamelen, N_TAB_SZ);
1110 if ((pt = ntab[indx]) == NULL)
1111 return;
1112
1113 while (pt != NULL) {
1114 /*
1115 * walk down the hash chain looking for a match
1116 */
1117 if (strcmp(oname, pt->oname) == 0) {
1118 /*
1119 * found it, replace it with the new name
1120 * and return (we know that oname has enough space)
1121 */
1122 *onamelen = strlcpy(oname, pt->nname, onamesize);
1123 if (*onamelen >= onamesize)
1124 *onamelen = onamesize - 1; /* XXX truncate? */
1125 return;
1126 }
1127 pt = pt->fow;
1128 }
1129
1130 /*
1131 * no match, just return
1132 */
1133 }
1134
1135 /*
1136 * device/inode mapping table routines
1137 * (used with formats that store device and inodes fields)
1138 *
1139 * device/inode mapping tables remap the device field in a archive header. The
1140 * device/inode fields are used to determine when files are hard links to each
1141 * other. However these values have very little meaning outside of that. This
1142 * database is used to solve one of two different problems.
1143 *
1144 * 1) when files are appended to an archive, while the new files may have hard
1145 * links to each other, you cannot determine if they have hard links to any
1146 * file already stored on the archive from a prior run of pax. We must assume
1147 * that these inode/device pairs are unique only within a SINGLE run of pax
1148 * (which adds a set of files to an archive). So we have to make sure the
1149 * inode/dev pairs we add each time are always unique. We do this by observing
1150 * while the inode field is very dense, the use of the dev field is fairly
1151 * sparse. Within each run of pax, we remap any device number of a new archive
1152 * member that has a device number used in a prior run and already stored in a
1153 * file on the archive. During the read phase of the append, we store the
1154 * device numbers used and mark them to not be used by any file during the
1155 * write phase. If during write we go to use one of those old device numbers,
1156 * we remap it to a new value.
1157 *
1158 * 2) Often the fields in the archive header used to store these values are
1159 * too small to store the entire value. The result is an inode or device value
1160 * which can be truncated. This really can foul up an archive. With truncation
1161 * we end up creating links between files that are really not links (after
1162 * truncation the inodes are the same value). We address that by detecting
1163 * truncation and forcing a remap of the device field to split truncated
1164 * inodes away from each other. Each truncation creates a pattern of bits that
1165 * are removed. We use this pattern of truncated bits to partition the inodes
1166 * on a single device to many different devices (each one represented by the
1167 * truncated bit pattern). All inodes on the same device that have the same
1168 * truncation pattern are mapped to the same new device. Two inodes that
1169 * truncate to the same value clearly will always have different truncation
1170 * bit patterns, so they will be split from away each other. When we spot
1171 * device truncation we remap the device number to a non truncated value.
1172 * (for more info see table.h for the data structures involved).
1173 */
1174
1175 /*
1176 * dev_start()
1177 * create the device mapping table
1178 * Return:
1179 * 0 if successful, -1 otherwise
1180 */
1181
1182 int
1183 dev_start(void)
1184 {
1185 if (dtab != NULL)
1186 return (0);
1187 if ((dtab = calloc(D_TAB_SZ, sizeof(DEVT *))) == NULL) {
1188 paxwarn(1, "%s for %s", "Out of memory",
1189 "device mapping table");
1190 return (-1);
1191 }
1192 return (0);
1193 }
1194
1195 /*
1196 * add_dev()
1197 * add a device number to the table. this will force the device to be
1198 * remapped to a new value if it be used during a write phase. This
1199 * function is called during the read phase of an append to prohibit the
1200 * use of any device number already in the archive.
1201 * Return:
1202 * 0 if added ok, -1 otherwise
1203 */
1204
1205 int
1206 add_dev(ARCHD *arcn)
1207 {
1208 if (chk_dev(arcn->sb.st_dev, 1) == NULL)
1209 return(-1);
1210 return(0);
1211 }
1212
1213 /*
1214 * chk_dev()
1215 * check for a device value in the device table. If not found and the add
1216 * flag is set, it is added. This does NOT assign any mapping values, just
1217 * adds the device number as one that need to be remapped. If this device
1218 * is already mapped, just return with a pointer to that entry.
1219 * Return:
1220 * pointer to the entry for this device in the device map table. Null
1221 * if the add flag is not set and the device is not in the table (it is
1222 * not been seen yet). If add is set and the device cannot be added, null
1223 * is returned (indicates an error).
1224 */
1225
1226 static DEVT *
1227 chk_dev(dev_t dev, int add)
1228 {
1229 DEVT *pt;
1230 unsigned int indx;
1231
1232 if (dtab == NULL)
1233 return(NULL);
1234 /*
1235 * look to see if this device is already in the table
1236 */
1237 indx = ((unsigned)dev) % D_TAB_SZ;
1238 if ((pt = dtab[indx]) != NULL) {
1239 while ((pt != NULL) && (pt->dev != dev))
1240 pt = pt->fow;
1241
1242 /*
1243 * found it, return a pointer to it
1244 */
1245 if (pt != NULL)
1246 return(pt);
1247 }
1248
1249 /*
1250 * not in table, we add it only if told to as this may just be a check
1251 * to see if a device number is being used.
1252 */
1253 if (add == 0)
1254 return(NULL);
1255
1256 /*
1257 * allocate a node for this device and add it to the front of the hash
1258 * chain. Note we do not assign remaps values here, so the pt->list
1259 * list must be NULL.
1260 */
1261 if ((pt = malloc(sizeof(DEVT))) == NULL) {
1262 paxwarn(1, "%s for %s", "Out of memory", "device mapping table");
1263 return (NULL);
1264 }
1265 pt->dev = dev;
1266 pt->list = NULL;
1267 pt->fow = dtab[indx];
1268 dtab[indx] = pt;
1269 return(pt);
1270 }
1271 /*
1272 * map_dev()
1273 * given an inode and device storage mask (the mask has a 1 for each bit
1274 * the archive format is able to store in a header), we check for inode
1275 * and device truncation and remap the device as required. Device mapping
1276 * can also occur when during the read phase of append a device number was
1277 * seen (and was marked as do not use during the write phase). WE ASSUME
1278 * that unsigned longs are the same size or bigger than the fields used
1279 * for ino_t and dev_t. If not the types will have to be changed.
1280 * Return:
1281 * 0 if all ok, -1 otherwise.
1282 */
1283
1284 int
1285 map_dev(ARCHD *arcn, u_long dev_mask, u_long ino_mask)
1286 {
1287 DEVT *pt;
1288 DLIST *dpt;
1289 static dev_t lastdev = 0; /* next device number to try */
1290 int trc_ino = 0;
1291 int trc_dev = 0;
1292 ino_t trunc_bits = 0;
1293 ino_t nino;
1294
1295 if (dtab == NULL)
1296 return(0);
1297 /*
1298 * check for device and inode truncation, and extract the truncated
1299 * bit pattern.
1300 */
1301 if ((arcn->sb.st_dev & (dev_t)dev_mask) != arcn->sb.st_dev)
1302 ++trc_dev;
1303 if ((nino = arcn->sb.st_ino & (ino_t)ino_mask) != arcn->sb.st_ino) {
1304 ++trc_ino;
1305 trunc_bits = arcn->sb.st_ino & (ino_t)(~ino_mask);
1306 }
1307
1308 /*
1309 * see if this device is already being mapped, look up the device
1310 * then find the truncation bit pattern which applies
1311 */
1312 if ((pt = chk_dev(arcn->sb.st_dev, 0)) != NULL) {
1313 /*
1314 * this device is already marked to be remapped
1315 */
1316 for (dpt = pt->list; dpt != NULL; dpt = dpt->fow)
1317 if (dpt->trunc_bits == trunc_bits)
1318 break;
1319
1320 if (dpt != NULL) {
1321 /*
1322 * we are being remapped for this device and pattern
1323 * change the device number to be stored and return
1324 */
1325 arcn->sb.st_dev = dpt->dev;
1326 arcn->sb.st_ino = nino;
1327 return(0);
1328 }
1329 } else {
1330 /*
1331 * this device is not being remapped YET. if we do not have any
1332 * form of truncation, we do not need a remap
1333 */
1334 if (!trc_ino && !trc_dev)
1335 return(0);
1336
1337 /*
1338 * we have truncation, have to add this as a device to remap
1339 */
1340 if ((pt = chk_dev(arcn->sb.st_dev, 1)) == NULL)
1341 goto bad;
1342
1343 /*
1344 * if we just have a truncated inode, we have to make sure that
1345 * all future inodes that do not truncate (they have the
1346 * truncation pattern of all 0's) continue to map to the same
1347 * device number. We probably have already written inodes with
1348 * this device number to the archive with the truncation
1349 * pattern of all 0's. So we add the mapping for all 0's to the
1350 * same device number.
1351 */
1352 if (!trc_dev && (trunc_bits != 0)) {
1353 if ((dpt = malloc(sizeof(DLIST))) == NULL)
1354 goto bad;
1355 dpt->trunc_bits = 0;
1356 dpt->dev = arcn->sb.st_dev;
1357 dpt->fow = pt->list;
1358 pt->list = dpt;
1359 }
1360 }
1361
1362 /*
1363 * look for a device number not being used. We must watch for wrap
1364 * around on lastdev (so we do not get stuck looking forever!)
1365 */
1366 while (++lastdev > 0) {
1367 if (chk_dev(lastdev, 0) != NULL)
1368 continue;
1369 /*
1370 * found an unused value. If we have reached truncation point
1371 * for this format we are hosed, so we give up. Otherwise we
1372 * mark it as being used.
1373 */
1374 if (((lastdev & ((dev_t)dev_mask)) != lastdev) ||
1375 (chk_dev(lastdev, 1) == NULL))
1376 goto bad;
1377 break;
1378 }
1379
1380 if ((lastdev <= 0) || ((dpt = malloc(sizeof(DLIST))) == NULL))
1381 goto bad;
1382
1383 /*
1384 * got a new device number, store it under this truncation pattern.
1385 * change the device number this file is being stored with.
1386 */
1387 dpt->trunc_bits = trunc_bits;
1388 dpt->dev = lastdev;
1389 dpt->fow = pt->list;
1390 pt->list = dpt;
1391 arcn->sb.st_dev = lastdev;
1392 arcn->sb.st_ino = nino;
1393 return(0);
1394
1395 bad:
1396 paxwarn(1, "Unable to fix truncated inode/device field when storing %s",
1397 arcn->name);
1398 paxwarn(0, "Archive may create improper hard links when extracted");
1399 return(0);
1400 }
1401
1402 /*
1403 * directory access/mod time reset table routines (for directories READ by pax)
1404 *
1405 * The pax -t flag requires that access times of archive files be the same
1406 * before being read by pax. For regular files, access time is restored after
1407 * the file has been copied. This database provides the same functionality for
1408 * directories read during file tree traversal. Restoring directory access time
1409 * is more complex than files since directories may be read several times until
1410 * all the descendants in their subtree are visited by fts. Directory access
1411 * and modification times are stored during the fts pre-order visit (done
1412 * before any descendants in the subtree are visited) and restored after the
1413 * fts post-order visit (after all the descendants have been visited). In the
1414 * case of premature exit from a subtree (like from the effects of -n), any
1415 * directory entries left in this database are reset during final cleanup
1416 * operations of pax. Entries are hashed by inode number for fast lookup.
1417 */
1418
1419 /*
1420 * atdir_start()
1421 * create the directory access time database for directories READ by pax.
1422 * Return:
1423 * 0 is created ok, -1 otherwise.
1424 */
1425
1426 int
1427 atdir_start(void)
1428 {
1429 if (atab != NULL)
1430 return (0);
1431 if ((atab = calloc(A_TAB_SZ, sizeof(ATDIR *))) == NULL) {
1432 paxwarn(1, "%s for %s", "Out of memory",
1433 "directory access time reset table");
1434 return (-1);
1435 }
1436 return (0);
1437 }
1438
1439 /*
1440 * atdir_end()
1441 * walk through the directory access time table and reset the access time
1442 * of any directory who still has an entry left in the database. These
1443 * entries are for directories READ by pax
1444 */
1445
1446 void
1447 atdir_end(void)
1448 {
1449 ATDIR *pt;
1450 int i;
1451
1452 if (atab == NULL)
1453 return;
1454 /*
1455 * for each non-empty hash table entry reset all the directories
1456 * chained there.
1457 */
1458 for (i = 0; i < A_TAB_SZ; ++i) {
1459 if ((pt = atab[i]) == NULL)
1460 continue;
1461 /*
1462 * remember to force the times, set_ftime() looks at pmtime
1463 * and patime, which only applies to things CREATED by pax,
1464 * not read by pax. Read time reset is controlled by -t.
1465 */
1466 for (; pt != NULL; pt = pt->fow)
1467 set_attr(&pt->ft, 1, 0, 0, 0);
1468 }
1469 }
1470
1471 /*
1472 * add_atdir()
1473 * add a directory to the directory access time table. Table is hashed
1474 * and chained by inode number. This is for directories READ by pax
1475 */
1476
1477 void
1478 add_atdir(const char *fname, const struct stat *sbp)
1479 {
1480 ATDIR *pt;
1481 sigset_t allsigs, savedsigs;
1482 unsigned int indx;
1483
1484 if (atab == NULL)
1485 return;
1486
1487 /*
1488 * make sure this directory is not already in the table, if so just
1489 * return (the older entry always has the correct time). The only
1490 * way this will happen is when the same subtree can be traversed by
1491 * different args to pax and the -n option is aborting fts out of a
1492 * subtree before all the post-order visits have been made.
1493 */
1494 indx = ((unsigned)sbp->st_ino) % A_TAB_SZ;
1495 if ((pt = atab[indx]) != NULL) {
1496 while (pt != NULL) {
1497 if ((pt->ft.ft_ino == sbp->st_ino) && (pt->ft.ft_dev == sbp->st_dev))
1498 break;
1499 pt = pt->fow;
1500 }
1501
1502 /*
1503 * oops, already there. Leave it alone.
1504 */
1505 if (pt != NULL)
1506 return;
1507 }
1508
1509 /*
1510 * add it to the front of the hash chain
1511 */
1512 sigfillset(&allsigs);
1513 sigprocmask(SIG_BLOCK, &allsigs, &savedsigs);
1514 if ((pt = malloc(sizeof *pt)) != NULL) {
1515 if ((pt->ft.ft_name = strdup(fname)) != NULL) {
1516 pt->ft.ft_dev = sbp->st_dev;
1517 pt->ft.ft_ino = sbp->st_ino;
1518 st_timecpy(m, &pt->ft.sb, sbp);
1519 st_timecpy(a, &pt->ft.sb, sbp);
1520 pt->fow = atab[indx];
1521 atab[indx] = pt;
1522 sigprocmask(SIG_SETMASK, &savedsigs, NULL);
1523 return;
1524 }
1525 free(pt);
1526 }
1527
1528 sigprocmask(SIG_SETMASK, &savedsigs, NULL);
1529 paxwarn(1, "%s for %s", "Out of memory", "directory access time reset table");
1530 }
1531
1532 /*
1533 * get_atdir()
1534 * look up a directory by inode and device number to obtain the access
1535 * and modification time you want to set to. If found, the modification
1536 * and access time parameters are set and the entry is removed from the
1537 * table (as it is no longer needed). These are for directories READ by
1538 * pax
1539 * Return:
1540 * 0 if found, -1 if not found.
1541 */
1542
1543 int
1544 do_atdir(const char *name, dev_t dev, ino_t ino)
1545 {
1546 ATDIR *pt;
1547 ATDIR **ppt;
1548 sigset_t allsigs, savedsigs;
1549 unsigned int indx;
1550
1551 if (atab == NULL)
1552 return(-1);
1553 /*
1554 * hash by inode and search the chain for an inode and device match
1555 */
1556 indx = ((unsigned)ino) % A_TAB_SZ;
1557 if ((pt = atab[indx]) == NULL)
1558 return(-1);
1559
1560 ppt = &(atab[indx]);
1561 while (pt != NULL) {
1562 if ((pt->ft.ft_ino == ino) && (pt->ft.ft_dev == dev))
1563 break;
1564 /*
1565 * no match, go to next one
1566 */
1567 ppt = &(pt->fow);
1568 pt = pt->fow;
1569 }
1570
1571 /*
1572 * return if we did not find it.
1573 */
1574 if (pt == NULL || pt->ft.ft_name == NULL ||
1575 strcmp(name, pt->ft.ft_name) == 0)
1576 return(-1);
1577
1578 /*
1579 * found it. set the times and remove the entry from the table.
1580 */
1581 set_attr(&pt->ft, 1, 0, 0, 0);
1582 sigfillset(&allsigs);
1583 sigprocmask(SIG_BLOCK, &allsigs, &savedsigs);
1584 *ppt = pt->fow;
1585 sigprocmask(SIG_SETMASK, &savedsigs, NULL);
1586 free(pt->ft.ft_name);
1587 free(pt);
1588 return(0);
1589 }
1590
1591 /*
1592 * directory access mode and time storage routines (for directories CREATED
1593 * by pax).
1594 *
1595 * pax requires that extracted directories, by default, have their access/mod
1596 * times and permissions set to the values specified in the archive. During the
1597 * actions of extracting (and creating the destination subtree during -rw copy)
1598 * directories extracted may be modified after being created. Even worse is
1599 * that these directories may have been created with file permissions which
1600 * prohibits any descendants of these directories from being extracted. When
1601 * directories are created by pax, access rights may be added to permit the
1602 * creation of files in their subtree. Every time pax creates a directory, the
1603 * times and file permissions specified by the archive are stored. After all
1604 * files have been extracted (or copied), these directories have their times
1605 * and file modes reset to the stored values. The directory info is restored in
1606 * reverse order as entries were added from root to leaf: to restore atime
1607 * properly, we must go backwards.
1608 */
1609
1610 /*
1611 * dir_start()
1612 * set up the directory time and file mode storage for directories CREATED
1613 * by pax.
1614 * Return:
1615 * 0 if ok, -1 otherwise
1616 */
1617
1618 int
1619 dir_start(void)
1620 {
1621 if (dirp != NULL)
1622 return(0);
1623
1624 dirsize = DIRP_SIZE;
1625 if ((dirp = reallocarray(NULL, dirsize, sizeof(DIRDATA))) == NULL) {
1626 paxwarn(1, "%s for %s", "Out of memory",
1627 "directory times");
1628 return (-1);
1629 }
1630 return(0);
1631 }
1632
1633 /*
1634 * add_dir()
1635 * add the mode and times for a newly CREATED directory
1636 * name is name of the directory, psb the stat buffer with the data in it,
1637 * frc_mode is a bool that says whether to force the setting of the mode
1638 * (ignoring the user-set values for preserving file mode). frc_mode is
1639 * for the case where we created a file and found that the resulting
1640 * directory was not writeable and the user asked for file modes to NOT
1641 * be preserved. (We have to preserve what was created by default, so we
1642 * have to force the setting at the end. This is stated explicitly in the
1643 * pax spec.)
1644 */
1645
1646 void
1647 add_dir(char *name, struct stat *psb, int frc_mode)
1648 {
1649 DIRDATA *dblk;
1650 sigset_t allsigs, savedsigs;
1651 char *rp = NULL;
1652
1653 if (dirp == NULL)
1654 return;
1655
1656 if (havechd && *name != '/') {
1657 #ifdef REALPATH_CAN_ALLOCATE
1658 if ((rp = realpath(name, NULL)) == NULL)
1659 #else
1660 if ((rp = realpath(name, realname)) == NULL)
1661 #endif
1662 {
1663 paxwarn(1, "Cannot canonicalise %s", name);
1664 return;
1665 }
1666 name = rp;
1667 }
1668 if (dircnt == dirsize) {
1669 dblk = reallocarray(dirp, dirsize * 2, sizeof(DIRDATA));
1670 if (dblk == NULL) {
1671 paxwarn(1, "Unable to store mode and times for created"
1672 " directory %s", name);
1673 #ifdef REALPATH_CAN_ALLOCATE
1674 free(rp);
1675 #endif
1676 return;
1677 }
1678 sigprocmask(SIG_BLOCK, &allsigs, &savedsigs);
1679 dirp = dblk;
1680 dirsize *= 2;
1681 sigprocmask(SIG_SETMASK, &savedsigs, NULL);
1682 }
1683 dblk = &dirp[dircnt];
1684 if ((dblk->ft.ft_name = strdup(name)) == NULL) {
1685 paxwarn(1, "Unable to store mode and times for created"
1686 " directory %s", name);
1687 #ifdef REALPATH_CAN_ALLOCATE
1688 free(rp);
1689 #endif
1690 return;
1691 }
1692 st_timecpy(m, &dblk->ft.sb, psb);
1693 st_timecpy(a, &dblk->ft.sb, psb);
1694 dblk->ft.ft_ino = psb->st_ino;
1695 dblk->ft.ft_dev = psb->st_dev;
1696 dblk->tr_mode = psb->st_mode & ABITS;
1697 dblk->frc_mode = isWahr(frc_mode);
1698 sigprocmask(SIG_BLOCK, &allsigs, &savedsigs);
1699 ++dircnt;
1700 sigprocmask(SIG_SETMASK, &savedsigs, NULL);
1701 #ifdef REALPATH_CAN_ALLOCATE
1702 free(rp);
1703 #endif
1704 }
1705
1706 /*
1707 * delete_dir()
1708 * When we rmdir a directory, we may want to make sure we don't
1709 * later warn about being unable to set its mode and times.
1710 */
1711
1712 void
1713 delete_dir(dev_t dev, ino_t ino)
1714 {
1715 DIRDATA *dblk;
1716 char *name;
1717 size_t i;
1718
1719 if (dirp == NULL)
1720 return;
1721 for (i = 0; i < dircnt; i++) {
1722 dblk = &dirp[i];
1723
1724 if (dblk->ft.ft_name == NULL)
1725 continue;
1726 if (dblk->ft.ft_dev == dev && dblk->ft.ft_ino == ino) {
1727 name = dblk->ft.ft_name;
1728 dblk->ft.ft_name = NULL;
1729 free(name);
1730 break;
1731 }
1732 }
1733 }
1734
1735 /*
1736 * proc_dir(int in_sig)
1737 * process all file modes and times stored for directories CREATED
1738 * by pax. If in_sig is set, we're in a signal handler and can't
1739 * free stuff.
1740 */
1741
1742 void
1743 proc_dir(int in_sig)
1744 {
1745 DIRDATA *dblk;
1746 size_t cnt;
1747
1748 if (dirp == NULL)
1749 return;
1750 /*
1751 * read backwards through the file and process each directory
1752 */
1753 cnt = dircnt;
1754 while (cnt-- > 0) {
1755 dblk = &dirp[cnt];
1756 /*
1757 * If we remove a directory we created, we replace the
1758 * ft_name with NULL. Ignore those.
1759 */
1760 if (dblk->ft.ft_name == NULL)
1761 continue;
1762
1763 /*
1764 * frc_mode set, make sure we set the file modes even if
1765 * the user didn't ask for it (see file_subs.c for more info)
1766 */
1767 set_attr(&dblk->ft, 0, dblk->tr_mode, pmode || dblk->frc_mode,
1768 in_sig);
1769 if (!in_sig)
1770 free(dblk->ft.ft_name);
1771 }
1772
1773 if (!in_sig)
1774 free(dirp);
1775 dirp = NULL;
1776 dircnt = 0;
1777 }
1778
1779 /*
1780 * database independent routines
1781 */
1782
1783 /*
1784 * st_hash()
1785 * hashes filenames to an unsigned int for hashing into a table. It looks
1786 * at the tail end of the file, as this provides far better distribution
1787 * than any other part of the name. For performance reasons we only care
1788 * about the last MAXKEYLEN chars (should be at LEAST large enough to pick
1789 * off the filename). It was tested on a 500'000 name file tree traversal
1790 * from the root and gave almost a perfectly uniform distribution of keys
1791 * when used with prime-sized tables (MAXKEYLEN was 128 in the test).
1792 * Hashes sizeof(int) chars at a time and pads with 0 for last addition.
1793 * Return:
1794 * the hash value of the string MOD (%) the table size.
1795 */
1796
1797 unsigned int
1798 st_hash(const char *name, int len, int tabsz)
1799 {
1800 const char *pt;
1801 char *dest;
1802 const char *end;
1803 int i;
1804 unsigned int key = 0;
1805 int steps;
1806 int res;
1807 unsigned int val;
1808
1809 /*
1810 * only look at the tail up to MAXKEYLEN, we do not need to waste
1811 * time here (remember these are pathnames, the tail is what will
1812 * spread out the keys)
1813 */
1814 if (len > MAXKEYLEN) {
1815 pt = &(name[len - MAXKEYLEN]);
1816 len = MAXKEYLEN;
1817 } else
1818 pt = name;
1819
1820 /*
1821 * calculate the number of unsigned int size steps in the string
1822 * and if there is a runt to deal with
1823 */
1824 steps = len / sizeof(unsigned int);
1825 res = len % sizeof(unsigned int);
1826
1827 /*
1828 * add up the value of the string in unsigned integer sized pieces
1829 * too bad we cannot have unsigned int aligned strings, then we
1830 * could avoid the expensive copy.
1831 */
1832 for (i = 0; i < steps; ++i) {
1833 end = pt + sizeof(unsigned int);
1834 dest = (char *)&val;
1835 while (pt < end)
1836 *dest++ = *pt++;
1837 key += val;
1838 }
1839
1840 /*
1841 * add in the runt padded with zero to the right
1842 */
1843 if (res) {
1844 val = 0;
1845 end = pt + res;
1846 dest = (char *)&val;
1847 while (pt < end)
1848 *dest++ = *pt++;
1849 key += val;
1850 }
1851
1852 /*
1853 * return the result mod the table size
1854 */
1855 return(key % tabsz);
1856 }
1857
1858 /* Forward hard link anonymisation routines */
1859
1860 /*
1861 * flnk_start
1862 * Creates the hard link table.
1863 * Return:
1864 * 0 if created, -1 if failure
1865 */
1866
1867 int
1868 flnk_start(void)
1869 {
1870 if (fltab != NULL)
1871 return (0);
1872 if ((fltab = (HRDFLNK **)calloc(L_TAB_SZ, sizeof(HRDFLNK *))) == NULL) {
1873 paxwarn(1, "%s for %s", "Out of memory",
1874 "hard link anonymisation table");
1875 return (-1);
1876 }
1877 return (0);
1878 }
1879
1880 /*
1881 * chk_flnk()
1882 * Looks up entry in hard link hash table. If found, it copies the name
1883 * of the file it is linked to (we already saw that file) into ln_name.
1884 * lnkcnt is decremented and if goes to 1 the node is deleted from the
1885 * database. (We have seen all the links to this file). If not found,
1886 * we add the file to the database if it has the potential for having
1887 * hard links to other files we may process (it has a link count > 1)
1888 * Return:
1889 * if found returns the new inode number; -1 on error
1890 */
1891
1892 int
1893 chk_flnk(ARCHD *arcn)
1894 {
1895 HRDFLNK *pt;
1896 HRDFLNK **ppt;
1897 unsigned int indx;
1898 static ino_t running = 3;
1899
1900 if (fltab == NULL)
1901 return (-1);
1902 /*
1903 * ignore those nodes that cannot have hard links
1904 */
1905 if ((arcn->type == PAX_DIR) || (arcn->sb.st_nlink <= 1))
1906 return (running++);
1907
1908 /*
1909 * hash inode number and look for this file
1910 */
1911 indx = ((unsigned)arcn->sb.st_ino) % L_TAB_SZ;
1912 if ((pt = fltab[indx]) != NULL) {
1913 /*
1914 * it's hash chain in not empty, walk down looking for it
1915 */
1916 ppt = &(fltab[indx]);
1917 while (pt != NULL) {
1918 if ((pt->ino == arcn->sb.st_ino) &&
1919 (pt->dev == arcn->sb.st_dev))
1920 break;
1921 ppt = &(pt->fow);
1922 pt = pt->fow;
1923 }
1924
1925 if (pt != NULL) {
1926 /* found a link */
1927 ino_t rv = pt->newi;
1928 /* so cpio doesn't write file data twice */
1929 arcn->type |= PAX_LINKOR;
1930 /*
1931 * if we have found all the links to this file, remove
1932 * it from the database
1933 */
1934 if (--pt->nlink <= 1) {
1935 *ppt = pt->fow;
1936 (void)free((char *)pt);
1937 }
1938 return (rv);
1939 }
1940 }
1941
1942 /*
1943 * we never saw this file before. It has links so we add it to the
1944 * front of this hash chain
1945 */
1946 if ((pt = (HRDFLNK *)malloc(sizeof(HRDFLNK))) != NULL) {
1947 pt->dev = arcn->sb.st_dev;
1948 pt->ino = arcn->sb.st_ino;
1949 pt->nlink = arcn->sb.st_nlink;
1950 pt->fow = fltab[indx];
1951 pt->newi = running++;
1952 fltab[indx] = pt;
1953 return (pt->newi);
1954 }
1955
1956 paxwarn(1, "%s for %s", "Out of memory", "hard link anonymisation table");
1957 return (-1);
1958 }