-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtables.c
1958 lines (1765 loc) · 52.7 KB
/
tables.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* $OpenBSD: tables.c,v 1.53 2017/09/16 07:42:34 otto Exp $ */
/* $NetBSD: tables.c,v 1.4 1995/03/21 09:07:45 cgd Exp $ */
/*-
* Copyright (c) 2005, 2012, 2015, 2016, 2018, 2019
* mirabilos <[email protected]>
* Copyright (c) 2011
* Svante Signell <[email protected]>
* Guillem Jover <[email protected]>
* Copyright (c) 1992 Keith Muller.
* Copyright (c) 1992, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Keith Muller of the University of California, San Diego.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <sys/types.h>
#if HAVE_BOTH_TIME_H
#include <sys/time.h>
#include <time.h>
#elif HAVE_SYS_TIME_H
#include <sys/time.h>
#elif HAVE_TIME_H
#include <time.h>
#endif
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if HAVE_STRINGS_H
#include <strings.h>
#endif
#include <unistd.h>
#include "pax.h"
#include "ftimes.h"
#include "extern.h"
__RCSID("$MirOS: src/bin/pax/tables.c,v 1.33 2024/08/17 23:33:52 tg Exp $");
#if (_POSIX_VERSION >= 200809L) || (defined(MirBSD) && (MirBSD > 0x0AB9))
#define REALPATH_CAN_ALLOCATE
#endif
/*
* Routines for controlling the contents of all the different databases pax
* keeps. Tables are dynamically created only when they are needed. The
* goal was speed and the ability to work with HUGE archives. The databases
* were kept simple, but do have complex rules for when the contents change.
* As of this writing, the posix library functions were more complex than
* needed for this application (pax databases have very short lifetimes and
* do not survive after pax is finished). pax is required to handle very
* large archives. These database routines carefully combine memory usage and
* temporary file storage in ways which will not significantly impact runtime
* performance while allowing the largest possible archives to be handled.
* Trying to force the fit to the posix database routines was not considered
* time well spent.
*/
/*
* data structures and constants used by the different databases kept by pax
*/
/*
* Hash Table Sizes MUST BE PRIME, if set too small performance suffers.
* Probably safe to expect 500000 inodes per tape. Assuming good key
* distribution (inodes) chains of under 50 long (worst case) is ok.
*/
#define L_TAB_SZ 2503 /* hard link hash table size */
#define F_TAB_SZ 50503 /* file time hash table size */
#define N_TAB_SZ 541 /* interactive rename hash table */
#define D_TAB_SZ 317 /* unique device mapping table */
#define A_TAB_SZ 317 /* ftree dir access time reset table */
#define SL_TAB_SZ 317 /* escape symlink tables */
#define MAXKEYLEN 64 /* max number of chars for hash */
#define DIRP_SIZE 64 /* initial size of created dir table */
/*
* file hard link structure (hashed by dev/ino and chained) used to find the
* hard links in a filesystem or with some archive formats (cpio)
*/
typedef struct hrdlnk {
ino_t ino; /* files inode number */
char *name; /* name of first file seen with this ino/dev */
dev_t dev; /* files device number */
u_long nlink; /* expected link count */
struct hrdlnk *fow;
} HRDLNK;
/*
* Archive write update file time table (the -u, -C flag), hashed by filename.
* Filenames are stored in a scratch file at seek offset into the file. The
* file time (mod time) and the file name length (for a quick check) are
* stored in a hash table node. We were forced to use a scratch file because
* with -u, the mtime for every node in the archive must always be available
* to compare against (and this data can get REALLY large with big archives).
* By being careful to read only when we have a good chance of a match, the
* performance loss is not measurable (and the size of the archive we can
* handle is greatly increased).
*/
typedef struct ftm {
off_t seek; /* location in scratch file */
struct ftm *fow;
int namelen; /* file name length */
struct stat sb; /* files last modification time */
} FTM;
/*
* Interactive rename table (-i flag), hashed by orig filename.
* We assume this will not be a large table as this mapping data can only be
* obtained through interactive input by the user. Nobody is going to type in
* changes for 500000 files? We use chaining to resolve collisions.
*/
typedef struct namt {
char *oname; /* old name */
char *nname; /* new name typed in by the user */
struct namt *fow;
} NAMT;
/*
* Unique device mapping tables. Some protocols (e.g. cpio) require that the
* <c_dev,c_ino> pair will uniquely identify a file in an archive unless they
* are links to the same file. Appending to archives can break this. For those
* protocols that have this requirement we map c_dev to a unique value not seen
* in the archive when we append. We also try to handle inode truncation with
* this table. (When the inode field in the archive header are too small, we
* remap the dev on writes to remove accidental collisions).
*
* The list is hashed by device number using chain collision resolution. Off of
* each DEVT are linked the various remaps for this device based on those bits
* in the inode which were truncated. For example if we are just remapping to
* avoid a device number during an update append, off the DEVT we would have
* only a single DLIST that has a truncation id of 0 (no inode bits were
* stripped for this device so far). When we spot inode truncation we create
* a new mapping based on the set of bits in the inode which were stripped off.
* so if the top four bits of the inode are stripped and they have a pattern of
* 0110...... (where . are those bits not truncated) we would have a mapping
* assigned for all inodes that has the same 0110.... pattern (with this dev
* number of course). This keeps the mapping sparse and should be able to store
* close to the limit of files which can be represented by the optimal
* combination of dev and inode bits, and without creating a fouled up archive.
* Note we also remap truncated devs in the same way (an exercise for the
* dedicated reader; always wanted to say that...:)
*/
typedef struct devt {
dev_t dev; /* the orig device number we now have to map */
struct devt *fow; /* new device map list */
struct dlist *list; /* map list based on inode truncation bits */
} DEVT;
typedef struct dlist {
ino_t trunc_bits; /* truncation pattern for a specific map */
dev_t dev; /* the new device id we use */
struct dlist *fow;
} DLIST;
/*
* ftree directory access time reset table. When we are done with a
* subtree we reset the access and mod time of the directory when the tflag is
* set. Not really explicitly specified in the pax spec, but easy and fast to
* do (and this may have even been intended in the spec, it is not clear).
* table is hashed by inode with chaining.
*/
typedef struct atdir {
struct file_times ft;
struct atdir *fow;
} ATDIR;
/*
* created directory time and mode storage entry. After pax is finished during
* extraction or copy, we must reset directory access modes and times that
* may have been modified after creation (they no longer have the specified
* times and/or modes). We must reset time in the reverse order of creation,
* because entries are added from the top of the file tree to the bottom.
* We MUST reset times from leaf to root (it will not work the other
* direction).
*/
typedef struct dirdata {
struct file_times ft;
mode_t tr_mode; /* file mode to restore */
Wahr frc_mode; /* do we force mode settings? */
} DIRDATA;
/*
* file hard link structure (hashed by dev/ino and chained) for anonymisation
*/
typedef struct hrdflnk {
dev_t dev; /* files device number */
ino_t ino; /* files inode number */
u_long nlink; /* expected link count */
ino_t newi; /* new inode number */
struct hrdflnk *fow;
} HRDFLNK;
static HRDLNK **ltab = NULL; /* hard link table for detecting hard links */
static HRDFLNK **fltab = NULL; /* hard link table for anonymisation */
static FTM **ftab = NULL; /* file time table for updating arch */
static NAMT **ntab = NULL; /* interactive rename storage table */
static DEVT **dtab = NULL; /* device/inode mapping tables */
static ATDIR **atab = NULL; /* file tree directory time reset table */
static DIRDATA *dirp = NULL; /* storage for setting created dir time/mode */
static size_t dirsize; /* size of dirp table */
static size_t dircnt = 0; /* entries in dir time/mode storage */
static int ffd = -1; /* tmp file for file time table name storage */
static DEVT *chk_dev(dev_t, int);
#ifndef REALPATH_CAN_ALLOCATE
static char realname[PATH_MAX];
#endif
static char *
xrealpath(const char *path)
{
#ifndef REALPATH_CAN_ALLOCATE
char *rv;
if ((rv = realpath(path, realname)))
rv = strdup(rv);
return (rv);
#else
return (realpath(path, NULL));
#endif
}
/*
* hard link table routines
*
* The hard link table tries to detect hard links to files using the device and
* inode values. We do this when writing an archive, so we can tell the format
* write routine that this file is a hard link to another file. The format
* write routine then can store this file in whatever way it wants (as a hard
* link if the format supports that like tar, or ignore this info like cpio).
* (Actually a field in the format driver table tells us if the format wants
* hard link info. if not, we do not waste time looking for them). We also use
* the same table when reading an archive. In that situation, this table is
* used by the format read routine to detect hard links from stored dev and
* inode numbers (like cpio). This will allow pax to create a link when one
* can be detected by the archive format.
*/
/*
* lnk_start
* Creates the hard link table.
* Return:
* 0 if created, -1 if failure
*/
int
lnk_start(void)
{
if (ltab != NULL)
return (0);
if ((ltab = calloc(L_TAB_SZ, sizeof(HRDLNK *))) == NULL) {
paxwarn(1, "%s for %s", "Out of memory",
"hard link table");
return (-1);
}
return (0);
}
/*
* chk_lnk()
* Looks up entry in hard link hash table. If found, it copies the name
* of the file it is linked to (we already saw that file) into ln_name.
* lnkcnt is decremented and if goes to 1 the node is deleted from the
* database. (We have seen all the links to this file). If not found,
* we add the file to the database if it has the potential for having
* hard links to other files we may process (it has a link count > 1)
* Return:
* if found returns 1; if not found returns 0; -1 on error
*/
int
chk_lnk(ARCHD *arcn)
{
HRDLNK *pt;
HRDLNK **ppt;
unsigned int indx;
if (ltab == NULL)
return(-1);
/*
* ignore those nodes that cannot have hard links
*/
if ((arcn->type == PAX_DIR) || (arcn->sb.st_nlink <= 1))
return(0);
/*
* hash inode number and look for this file
*/
indx = ((unsigned)arcn->sb.st_ino) % L_TAB_SZ;
if ((pt = ltab[indx]) != NULL) {
/*
* its hash chain in not empty, walk down looking for it
*/
ppt = &(ltab[indx]);
while (pt != NULL) {
if ((pt->ino == arcn->sb.st_ino) &&
(pt->dev == arcn->sb.st_dev))
break;
ppt = &(pt->fow);
pt = pt->fow;
}
if (pt != NULL) {
/*
* found a link. set the node type and copy in the
* name of the file it is to link to. we need to
* handle hardlinks to regular files differently than
* other links.
*/
arcn->ln_nlen = strlcpy(arcn->ln_name, pt->name,
sizeof(arcn->ln_name));
/* XXX truncate? */
if ((size_t)arcn->nlen >= sizeof(arcn->name))
arcn->nlen = sizeof(arcn->name) - 1;
if (arcn->type == PAX_REG)
arcn->type = PAX_HRG;
else
arcn->type = PAX_HLK;
/*
* if we have found all the links to this file, remove
* it from the database
*/
if (--pt->nlink <= 1) {
*ppt = pt->fow;
free(pt->name);
free(pt);
}
return(1);
}
}
/*
* we never saw this file before. It has links so we add it to the
* front of this hash chain
*/
if ((pt = malloc(sizeof(HRDLNK))) != NULL) {
if ((pt->name = strdup(arcn->name)) != NULL) {
pt->dev = arcn->sb.st_dev;
pt->ino = arcn->sb.st_ino;
pt->nlink = arcn->sb.st_nlink;
pt->fow = ltab[indx];
ltab[indx] = pt;
return(0);
}
free(pt);
}
paxwarn(1, "%s for %s", "Out of memory", "hard link table");
return (-1);
}
/*
* purg_lnk
* remove reference for a file that we may have added to the data base as
* a potential source for hard links. We ended up not using the file, so
* we do not want to accidently point another file at it later on.
*/
void
purg_lnk(ARCHD *arcn)
{
HRDLNK *pt;
HRDLNK **ppt;
unsigned int indx;
if (ltab == NULL)
return;
/*
* do not bother to look if it could not be in the database
*/
if ((arcn->sb.st_nlink <= 1) || (arcn->type == PAX_DIR) ||
PAX_IS_HARDLINK(arcn->type))
return;
/*
* find the hash chain for this inode value, if empty return
*/
indx = ((unsigned)arcn->sb.st_ino) % L_TAB_SZ;
if ((pt = ltab[indx]) == NULL)
return;
/*
* walk down the list looking for the inode/dev pair, unlink and
* free if found
*/
ppt = &(ltab[indx]);
while (pt != NULL) {
if ((pt->ino == arcn->sb.st_ino) &&
(pt->dev == arcn->sb.st_dev))
break;
ppt = &(pt->fow);
pt = pt->fow;
}
if (pt == NULL)
return;
/*
* remove and free it
*/
*ppt = pt->fow;
free(pt->name);
free(pt);
}
/*
* lnk_end()
* pull apart a existing link table so we can reuse it. We do this between
* read and write phases of append with update. (The format may have
* used the link table, and we need to start with a fresh table for the
* write phase
*/
void
lnk_end(void)
{
int i;
HRDLNK *pt;
HRDLNK *ppt;
if (ltab == NULL)
return;
for (i = 0; i < L_TAB_SZ; ++i) {
if (ltab[i] == NULL)
continue;
pt = ltab[i];
ltab[i] = NULL;
/*
* free up each entry on this chain
*/
while (pt != NULL) {
ppt = pt;
pt = ppt->fow;
free(ppt->name);
free(ppt);
}
}
}
/*
* modification time table routines
*
* The modification time table keeps track of last modification times for all
* files stored in an archive during a write phase when -u is set. We only
* add a file to the archive if it is newer than a file with the same name
* already stored on the archive (if there is no other file with the same
* name on the archive it is added). This applies to writes and appends.
* An append with an -u must read the archive and store the modification time
* for every file on that archive before starting the write phase. It is clear
* that this is one HUGE database. To save memory space, the actual file names
* are stored in a scratch file and indexed by an in-memory hash table. The
* hash table is indexed by hashing the file path. The nodes in the table store
* the length of the filename and the lseek offset within the scratch file
* where the actual name is stored. Since there are never any deletions from
* this table, fragmentation of the scratch file is never a issue. Lookups
* seem to not exhibit any locality at all (files in the database are rarely
* looked up more than once...), so caching is just a waste of memory. The
* only limitation is the amount of scratch file space available to store the
* path names.
*/
/*
* ftime_start()
* create the file time hash table and open for read/write the scratch
* file. (after created it is unlinked, so when we exit we leave
* no witnesses).
* Return:
* 0 if the table and file was created ok, -1 otherwise
*/
int
ftime_start(void)
{
if (ftab != NULL)
return (0);
if ((ftab = calloc(F_TAB_SZ, sizeof(FTM *))) == NULL) {
paxwarn(1, "%s for %s", "Out of memory",
"file time table");
return (-1);
}
/*
* get random name and create temporary scratch file, unlink name
* so it will get removed on exit
*/
memcpy(tempbase, _TFILE_BASE, sizeof(_TFILE_BASE));
if ((ffd = mkstemp(tempfile)) < 0) {
syswarn(1, errno, "Unable to create temporary file %s",
tempfile);
return (-1);
}
(void)unlink(tempfile);
return(0);
}
/*
* chk_ftime()
* looks up entry in file time hash table. If not found, the file is
* added to the hash table and the file named stored in the scratch file.
* If a file with the same name is found, the file times are compared and
* the most recent file time is retained. If the new file was younger (or
* was not in the database) the new file is selected for storage.
* Return:
* 0 if file should be added to the archive, 1 if it should be skipped,
* -1 on error
*/
int
chk_ftime(ARCHD *arcn)
{
FTM *pt;
int namelen;
unsigned int indx;
char ckname[PAXPATHLEN+1];
/*
* no info, go ahead and add to archive
*/
if (ftab == NULL)
return(0);
/*
* hash the pathname and look up in table
*/
namelen = arcn->nlen;
indx = st_hash(arcn->name, namelen, F_TAB_SZ);
if ((pt = ftab[indx]) != NULL) {
/*
* the hash chain is not empty, walk down looking for match
* only read up the path names if the lengths match, speeds
* up the search a lot
*/
while (pt != NULL) {
if (pt->namelen == namelen) {
/*
* potential match, have to read the name
* from the scratch file.
*/
if (lseek(ffd,pt->seek,SEEK_SET) != pt->seek) {
syswarn(1, errno, "Failed %s on %s",
"seek", "file time table");
return (-1);
}
if (read(ffd, ckname, namelen) != namelen) {
syswarn(1, errno, "Failed %s on %s",
"read", "file time table");
return (-1);
}
/*
* if the names match, we are done
*/
if (!strncmp(ckname, arcn->name, namelen))
break;
}
/*
* try the next entry on the chain
*/
pt = pt->fow;
}
if (pt != NULL) {
/*
* found the file, compare the times, save the newer
*/
if (st_timecmp(m, &arcn->sb, &pt->sb, >)) {
/*
* file is newer
*/
st_timecpy(m, &pt->sb, &arcn->sb);
return(0);
}
/*
* file is older
*/
return(1);
}
}
/*
* not in table, add it
*/
if ((pt = malloc(sizeof(FTM))) != NULL) {
/*
* add the name at the end of the scratch file, saving the
* offset. add the file to the head of the hash chain
*/
if ((pt->seek = lseek(ffd, 0, SEEK_END)) >= 0) {
if (write(ffd, arcn->name, namelen) == namelen) {
st_timecpy(m, &pt->sb, &arcn->sb);
pt->namelen = namelen;
pt->fow = ftab[indx];
ftab[indx] = pt;
return(0);
}
syswarn(1, errno, "Failed %s on %s",
"write", "file time table");
} else
syswarn(1, errno, "Failed %s on %s",
"seek", "file time table");
} else
paxwarn(1, "%s for %s", "Out of memory", "file time table");
if (pt != NULL)
free(pt);
return(-1);
}
/*
* escaping (absolute or w/"..") symlink table routines
*
* By default, an archive shouldn't be able extract to outside of the
* current directory. What should we do if the archive contains a symlink
* whose value is either absolute or contains ".." components? What we'll
* do is initially create the path as an empty file (to block attempts to
* reference _through_ it) and instead record its path and desired
* final value and mode. Then once all the other archive
* members are created (but before the pass to set timestamps on
* directories) we'll process those records, replacing the placeholder with
* the correct symlink and setting them to the correct mode, owner, group,
* and timestamps.
*
* Note: we also need to handle hardlinks to symlinks (barf) as well as
* hardlinks whose target is replaced by a later entry in the archive (barf^2).
*
* So we track things by dev+ino of the placeholder file, associating with
* that the value and mode of the final symlink and a list of paths that
* should all be hardlinks of that. We'll 'store' the symlink's desired
* timestamps, owner, and group by setting them on the placeholder file.
*
* The operations are:
* a) create an escaping symlink: create the placeholder file and add an entry
* for the new link
* b) create a hardlink: do the link. If the target turns out to be a
* zero-length file whose dev+ino are in the symlink table, then add this
* path to the list of names for that link
* c) perform deferred processing: for each entry, check each associated path:
* if it's a zero-length file with the correct dev+ino then recreate it as
* the specified symlink or hardlink to the first such
*/
struct slpath {
char *sp_path;
struct slpath *sp_next;
};
struct slinode {
ino_t sli_ino;
char *sli_value;
struct slpath sli_paths;
struct slinode *sli_fow; /* hash table chain */
dev_t sli_dev;
mode_t sli_mode;
};
static struct slinode **slitab = NULL;
/*
* sltab_start()
* create the hash table
* Return:
* 0 if the table and file was created ok, -1 otherwise
*/
int
sltab_start(void)
{
if ((slitab = calloc(SL_TAB_SZ, sizeof *slitab)) == NULL) {
syswarn(1, errno, "symlink table");
return(-1);
}
return(0);
}
/*
* sltab_add_sym()
* Create the placeholder and tracking info for an escaping symlink.
* Return:
* 0 on success, -1 otherwise
*/
int
sltab_add_sym(const char *path0, const char *value0, mode_t mode)
{
struct stat sb;
struct slinode *s;
struct slpath *p;
char *path, *value;
unsigned int indx;
int fd;
/* create the placeholder */
fd = binopen3(BO_CLEXEC, path0, O_WRONLY | O_CREAT | O_EXCL, 0600);
if (fd == -1)
return (-1);
if (fstat(fd, &sb) == -1) {
unlink(path0);
close(fd);
return (-1);
}
close(fd);
if (havechd && *path0 != '/') {
if ((path = xrealpath(path0)) == NULL) {
syswarn(1, errno, "Cannot canonicalise %s", path0);
unlink(path0);
return (-1);
}
} else if ((path = strdup(path0)) == NULL) {
syswarn(1, errno, "%s %s", "deferred symlink", "path");
unlink(path0);
return (-1);
}
if ((value = strdup(value0)) == NULL) {
syswarn(1, errno, "%s value", "deferred symlink");
unlink(path);
free(path);
return (-1);
}
/* now check the hash table for conflicting entry */
indx = (sb.st_ino ^ sb.st_dev) % SL_TAB_SZ;
for (s = slitab[indx]; s != NULL; s = s->sli_fow) {
if (s->sli_ino != sb.st_ino || s->sli_dev != sb.st_dev)
continue;
/*
* One of our placeholders got removed behind our back and
* we've reused the inode. Weird, but clean up the mess.
*/
free(s->sli_value);
free(s->sli_paths.sp_path);
p = s->sli_paths.sp_next;
while (p != NULL) {
struct slpath *next_p = p->sp_next;
free(p->sp_path);
free(p);
p = next_p;
}
goto set_value;
}
/* Normal case: create a new node */
if ((s = malloc(sizeof *s)) == NULL) {
syswarn(1, errno, "deferred symlink");
unlink(path);
free(path);
free(value);
return (-1);
}
s->sli_ino = sb.st_ino;
s->sli_dev = sb.st_dev;
s->sli_fow = slitab[indx];
slitab[indx] = s;
set_value:
s->sli_paths.sp_path = path;
s->sli_paths.sp_next = NULL;
s->sli_value = value;
s->sli_mode = mode;
return (0);
}
/*
* sltab_add_link()
* A hardlink was created; if it looks like a placeholder, handle the
* tracking.
* Return:
* 0 if things are ok, -1 if something went wrong
*/
int
sltab_add_link(const char *path, const struct stat *sb)
{
struct slinode *s;
struct slpath *p;
unsigned int indx;
if (!S_ISREG(sb->st_mode) || sb->st_size != 0)
return (1);
/* find the hash table entry for this hardlink */
indx = (sb->st_ino ^ sb->st_dev) % SL_TAB_SZ;
for (s = slitab[indx]; s != NULL; s = s->sli_fow) {
if (s->sli_ino != sb->st_ino || s->sli_dev != sb->st_dev)
continue;
if ((p = malloc(sizeof *p)) == NULL) {
syswarn(1, errno, "%s hardlink", "deferred symlink");
return (-1);
}
if (havechd && *path != '/') {
if ((p->sp_path = xrealpath(path)) == NULL) {
syswarn(1, errno, "Cannot canonicalise %s",
path);
free(p);
return (-1);
}
} else if ((p->sp_path = strdup(path)) == NULL) {
syswarn(1, errno, "%s hardlink path", "deferred symlink");
free(p);
return (-1);
}
/* link it in */
p->sp_next = s->sli_paths.sp_next;
s->sli_paths.sp_next = p;
return (0);
}
/* not found */
return (1);
}
static int
sltab_process_one(struct slinode *s, struct slpath *p, const char *first,
int in_sig)
{
struct stat sb;
char *path = p->sp_path;
mode_t mode;
int err;
/*
* is it the expected placeholder? This can fail legimately
* if the archive overwrote the link with another, later entry,
* so don't warn.
*/
if (stat(path, &sb) != 0 || !S_ISREG(sb.st_mode) || sb.st_size != 0 ||
sb.st_ino != s->sli_ino || sb.st_dev != s->sli_dev)
return (0);
if (unlink(path) && errno != ENOENT) {
if (!in_sig)
syswarn(1, errno, "%s removal", "deferred symlink");
return (0);
}
err = 0;
if (first != NULL) {
#if HAVE_LINKAT
/* add another hardlink to the existing symlink */
if (linkat(AT_FDCWD, first, AT_FDCWD, path, 0) == 0)
return (0);
/*
* Couldn't hardlink the symlink for some reason, so we'll
* try creating it as its own symlink, but save the error
* for reporting if that fails.
*/
err = errno;
#else
err = EOPNOTSUPP;
#endif
}
if (symlink(s->sli_value, path)) {
if (!in_sig) {
const char *qualifier = "";
if (err)
qualifier = " hardlink";
else
err = errno;
syswarn(1, err, "%s%s: %s",
"deferred symlink", qualifier, path);
}
return (0);
}
/* success, so set the id, mode, and times */
mode = s->sli_mode;
if (pids) {
/* if can't set the ids, force the set[ug]id bits off */
if (set_ids(path, sb.st_uid, sb.st_gid, 1))
mode &= ~(SETBITS);
}
if (pmode)
set_pmode(path, mode, 1);
if (patime || pmtime)
set_ftime(path, &sb, 0, 1);
/*
* If we tried to link to first but failed, then this new symlink
* might be a better one to try in the future. Guess from the errno.
*/
if (err == 0 || err == ENOENT || err == EMLINK || err == EOPNOTSUPP)
return (1);
return (0);
}
/*
* sltab_process()
* Do all the delayed process for escape symlinks
*/
void
sltab_process(int in_sig)
{
struct slinode *s;
struct slpath *p;
char *first;
unsigned int indx;
if (slitab == NULL)
return;
/* walk across the entire hash table */
for (indx = 0; indx < SL_TAB_SZ; indx++) {
while ((s = slitab[indx]) != NULL) {
/* pop this entry */
slitab[indx] = s->sli_fow;
first = NULL;
p = &s->sli_paths;
while (1) {
struct slpath *next_p;
if (sltab_process_one(s, p, first, in_sig)) {
if (!in_sig)
free(first);
first = p->sp_path;
} else if (!in_sig)
free(p->sp_path);
if ((next_p = p->sp_next) == NULL)
break;
*p = *next_p;
if (!in_sig)
free(next_p);
}
if (!in_sig) {
free(first);
free(s->sli_value);
free(s);
}
}
}
if (!in_sig)
free(slitab);
slitab = NULL;
}
/*
* Interactive rename table routines
*
* The interactive rename table keeps track of the new names that the user
* assigns to files from tty input. Since this map is unique for each file
* we must store it in case there is a reference to the file later in archive
* (a link). Otherwise we will be unable to find the file we know was
* extracted. The remapping of these files is stored in a memory based hash
* table (it is assumed since input must come from /dev/tty, it is unlikely to
* be a very large table).
*/