summaryrefslogtreecommitdiff
path: root/lib/rpmdb.c
blob: 1a817f18c8076819652dd2a93b1591aeac31cd6f (plain)
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
#include "system.h"

#include <sys/file.h>
#include <signal.h>
#include <sys/signal.h>

#include <rpmlib.h>
#include <rpmmacro.h>	/* XXX for rpmGetPath */

#include "falloc.h"
#include "fprint.h"
#include "misc.h"
#include "rpmdb.h"

/*@access dbiIndexSet@*/
/*@access dbiIndexRecord@*/

const char *rpmdb_filenames[] = {
    "packages.rpm",
    "nameindex.rpm",
    "fileindex.rpm",
    "groupindex.rpm",
    "requiredby.rpm",
    "providesindex.rpm",
    "conflictsindex.rpm",
    "triggerindex.rpm",
    NULL
};

/* XXX the signal handling in here is not thread safe */

/* the requiredbyIndex isn't stricly necessary. In a perfect world, we could
   have each header keep a list of packages that need it. However, we
   can't reserve space in the header for extra information so all of the
   required packages would move in the database every time a package was
   added or removed. Instead, each package (or virtual package) name
   keeps a list of package offsets of packages that might depend on this
   one. Version numbers still need verification, but it gets us in the
   right area w/o a linear search through the database. */

struct rpmdb_s {
    faFile pkgs;
    dbiIndex * nameIndex, * fileIndex, * groupIndex, * providesIndex;
    dbiIndex * requiredbyIndex, * conflictsIndex, * triggerIndex;
};

static sigset_t signalMask;

static void blockSignals(void)
{
    sigset_t newMask;

    sigfillset(&newMask);		/* block all signals */
    sigprocmask(SIG_BLOCK, &newMask, &signalMask);
}

static void unblockSignals(void)
{
    sigprocmask(SIG_SETMASK, &signalMask, NULL);
}

int rpmdbOpenForTraversal(const char * prefix, rpmdb * rpmdbp)
{
    const char * dbpath;
    int rc = 0;

    dbpath = rpmGetPath("%{_dbpath}", NULL);
    if (dbpath == NULL || dbpath[0] == '%') {
	rpmMessage(RPMMESS_DEBUG, _("no dbpath has been set"));
	return 1;
    }

    if (openDatabase(prefix, dbpath, rpmdbp, O_RDONLY, 0644, 
		     RPMDB_FLAG_MINIMAL)) {
	rc = 1;
    }
    xfree(dbpath);
    return rc;
}

int rpmdbOpen (const char * prefix, rpmdb *rpmdbp, int mode, int perms)
{
    const char * dbpath;
    int rc;

    dbpath = rpmGetPath("%{_dbpath}", NULL);
    if (dbpath == NULL || dbpath[0] == '%') {
	rpmMessage(RPMMESS_DEBUG, _("no dbpath has been set"));
	return 1;
    }

    rc = openDatabase(prefix, dbpath, rpmdbp, mode, perms, 0);
    xfree(dbpath);
    return rc;
}

int rpmdbInit (const char * prefix, int perms)
{
    rpmdb db;
    const char * dbpath;
    int rc;

    dbpath = rpmGetPath("%{_dbpath}", NULL);
    if (dbpath == NULL || dbpath[0] == '%') {
	rpmMessage(RPMMESS_DEBUG, _("no dbpath has been set"));
	return 1;
    }

    rc = openDatabase(prefix, dbpath, &db, O_CREAT | O_RDWR, perms, 
			RPMDB_FLAG_JUSTCHECK);
    xfree(dbpath);
    return rc;
}

static int openDbFile(const char * prefix, const char * dbpath, const char * shortName, 
	 int justCheck, int mode, int perms, dbiIndex ** db, DBTYPE type)
{
    int len = (prefix ? strlen(prefix) : 0) + strlen(dbpath) + strlen(shortName) + 1;
    char * filename = alloca(len);

    *filename = '\0';
    if (prefix && *prefix) strcat(filename, prefix); 
    strcat(filename, dbpath);
    strcat(filename, shortName);

    if (!justCheck || !rpmfileexists(filename)) {
	*db = dbiOpenIndex(filename, mode, perms, type);
	if (!*db) {
	    return 1;
	}
    }

    return 0;
}

static /*@only@*/ rpmdb newRpmdb(void)
{
    rpmdb db = xmalloc(sizeof(*db));
    db->pkgs = NULL;
    db->nameIndex = NULL;
    db->fileIndex = NULL;
    db->groupIndex = NULL;
    db->providesIndex = NULL;
    db->requiredbyIndex = NULL;
    db->conflictsIndex = NULL;
    db->triggerIndex = NULL;
    return db;
}

int openDatabase(const char * prefix, const char * dbpath, rpmdb *rpmdbp, int mode, 
		 int perms, int flags)
{
    char * filename;
    rpmdb db;
    int i, rc;
    struct flock lockinfo;
    int justcheck = flags & RPMDB_FLAG_JUSTCHECK;
    int minimal = flags & RPMDB_FLAG_MINIMAL;
    const char * akey;

    if (mode & O_WRONLY) 
	return 1;

    if (!(perms & 0600))	/* XXX sanity */
	perms = 0644;

    /* we should accept NULL as a valid prefix */
    if (!prefix) prefix="";

    i = strlen(dbpath);
    if (dbpath[i - 1] != '/') {
	filename = alloca(i + 2);
	strcpy(filename, dbpath);
	filename[i] = '/';
	filename[i + 1] = '\0';
	dbpath = filename;
    }
    
    filename = alloca(strlen(prefix) + strlen(dbpath) + 40);

    strcpy(filename, prefix); 
    strcat(filename, dbpath);

    rpmMessage(RPMMESS_DEBUG, _("opening database mode 0x%x in %s\n"),
	mode, filename);

    strcat(filename, "packages.rpm");

    db = newRpmdb();

    if (!justcheck || !rpmfileexists(filename)) {
	if ((db->pkgs = faOpen(filename, mode, perms)) == NULL) {
	    rpmError(RPMERR_DBOPEN, _("failed to open %s\n"), filename);
	    return 1;
	}

	/* try and get a lock - this is released by the kernel when we close
	   the file */
	lockinfo.l_whence = 0;
	lockinfo.l_start = 0;
	lockinfo.l_len = 0;
	
	if (mode & O_RDWR) {
	    lockinfo.l_type = F_WRLCK;
	    if (faFcntl(db->pkgs, F_SETLK, (void *) &lockinfo)) {
		rpmError(RPMERR_FLOCK, _("cannot get %s lock on database"), 
			 _("exclusive"));
		rpmdbClose(db);
		return 1;
	    } 
	} else {
	    lockinfo.l_type = F_RDLCK;
	    if (faFcntl(db->pkgs, F_SETLK, (void *) &lockinfo)) {
		rpmError(RPMERR_FLOCK, _("cannot get %s lock on database"), 
			 _("shared"));
		rpmdbClose(db);
		return 1;
	    } 
	}
    }

    rc = openDbFile(prefix, dbpath, "nameindex.rpm", justcheck, mode, perms,
		    &db->nameIndex, DB_HASH);

    if (minimal) {
	*rpmdbp = xmalloc(sizeof(struct rpmdb_s));
	if (rpmdbp)
	    *rpmdbp = db;	/* structure assignment */
	else
	    rpmdbClose(db);
	return 0;
    }

    if (!rc)
	rc = openDbFile(prefix, dbpath, "fileindex.rpm", justcheck, mode, perms,
			&db->fileIndex, DB_HASH);

    /* We used to store the fileindexes as complete paths, rather then
       plain basenames. Let's see which version we are... */
    /*
     * XXX FIXME: db->fileindex can be NULL under pathological (e.g. mixed
     * XXX db1/db2 linkage) conditions.
     */
    if (!justcheck && !dbiGetFirstKey(db->fileIndex, &akey)) {
	if (strchr(akey, '/')) {
	    rpmError(RPMERR_OLDDB, _("old format database is present; "
			"use --rebuilddb to generate a new format database"));
	    rc |= 1;
	}
	xfree(akey);
    }

    if (!rc)
	rc = openDbFile(prefix, dbpath, "providesindex.rpm", justcheck, mode, perms,
			&db->providesIndex, DB_HASH);
    if (!rc)
	rc = openDbFile(prefix, dbpath, "requiredby.rpm", justcheck, mode, perms,
			&db->requiredbyIndex, DB_HASH);
    if (!rc)
	rc = openDbFile(prefix, dbpath, "conflictsindex.rpm", justcheck, mode, perms,
			&db->conflictsIndex, DB_HASH);
    if (!rc)
	rc = openDbFile(prefix, dbpath, "groupindex.rpm", justcheck, mode, perms,
			&db->groupIndex, DB_HASH);
    if (!rc)
	rc = openDbFile(prefix, dbpath, "triggerindex.rpm", justcheck, mode, perms,
			&db->triggerIndex, DB_HASH);

    if (rc || justcheck || rpmdbp == NULL)
	rpmdbClose(db);
     else
	*rpmdbp = db;

     return rc;
}

void rpmdbClose (rpmdb db)
{
    if (db->pkgs != NULL) faClose(db->pkgs);
    if (db->fileIndex) dbiCloseIndex(db->fileIndex);
    if (db->groupIndex) dbiCloseIndex(db->groupIndex);
    if (db->nameIndex) dbiCloseIndex(db->nameIndex);
    if (db->providesIndex) dbiCloseIndex(db->providesIndex);
    if (db->requiredbyIndex) dbiCloseIndex(db->requiredbyIndex);
    if (db->conflictsIndex) dbiCloseIndex(db->conflictsIndex);
    if (db->triggerIndex) dbiCloseIndex(db->triggerIndex);
    free(db);
}

int rpmdbFirstRecNum(rpmdb db) {
    return faFirstOffset(db->pkgs);
}

int rpmdbNextRecNum(rpmdb db, unsigned int lastOffset) {
    /* 0 at end */
    return faNextOffset(db->pkgs, lastOffset);
}

static Header doGetRecord(rpmdb db, unsigned int offset, int pristine) {
    Header h;
    char ** fileList;
    char ** newList;
    int fileCount = 0;
    int i;

    (void)faLseek(db->pkgs, offset, SEEK_SET);

    h = headerRead(faFileno(db->pkgs), HEADER_MAGIC_NO);

    if (pristine) return h;

    /* the RPM used to build much of RH 5.1 could produce packages whose
       file lists did not have leading /'s. Now is a good time to fix
       that */

    /* If this tag isn't present, either no files are in the package or
       we're dealing with a package that has just the compressed file name
       list */
    if (!headerGetEntryMinMemory(h, RPMTAG_OLDFILENAMES, NULL, 
			   (void **) &fileList, &fileCount)) return h;

    for (i = 0; i < fileCount; i++) 
	if (*fileList[i] != '/') break;

    if (i == fileCount) {
	free(fileList);
    } else {
	/* bad header -- let's clean it up */
	newList = alloca(sizeof(*newList) * fileCount);
	for (i = 0; i < fileCount; i++) {
	    newList[i] = alloca(strlen(fileList[i]) + 2);
	    if (*fileList[i] == '/')
		strcpy(newList[i], fileList[i]);
	    else
		sprintf(newList[i], "/%s", fileList[i]);
	}

	free(fileList);

	headerModifyEntry(h, RPMTAG_OLDFILENAMES, RPM_STRING_ARRAY_TYPE, 
			  newList, fileCount);
    }

    /* The file list was moved to a more compressed format which not
       only saves memory (nice), but gives fingerprinting a nice, fat
       speed boost (very nice). Go ahead and convert old headers to
       the new style (this is a noop for new headers) */
    compressFilelist(h);

    return h;
}

Header rpmdbGetRecord(rpmdb db, unsigned int offset)
{
    return doGetRecord(db, offset, 0);
}

int rpmdbFindByFile(rpmdb db, const char * filespec, dbiIndexSet * matches)
{
    const char * basename;
    fingerPrint fp1, fp2;
    dbiIndexSet allMatches;
    int i, rc, num;
    Header h;
    char ** baseNames, ** dirNames;
    int_32 * dirIndexes;
    char * otherFile;

    fp1 = fpLookup(filespec, 0);

    basename = strrchr(filespec, '/');
    if (!basename) 
	basename = filespec;
    else
	basename++;

    rc = dbiSearchIndex(db->fileIndex, basename, &allMatches);
    if (rc) return rc;

    *matches = dbiCreateIndexRecord();
    i = 0;
    while (i < allMatches.count) {
	if ((h = rpmdbGetRecord(db, allMatches.recs[i].recOffset)) == NULL) {
	    i++;
	    continue;
	}

	headerGetEntryMinMemory(h, RPMTAG_COMPFILELIST, NULL, 
				(void **) &baseNames, NULL);
	headerGetEntryMinMemory(h, RPMTAG_COMPFILEDIRS, NULL, 
				(void **) &dirIndexes, NULL);
	headerGetEntryMinMemory(h, RPMTAG_COMPDIRLIST, NULL, 
				(void **) &dirNames, NULL);

	do {
	    num = allMatches.recs[i].fileNumber;
	    otherFile = xmalloc(strlen(dirNames[dirIndexes[num]]) + 
			      strlen(baseNames[num]) + 1);
	    strcpy(otherFile, dirNames[dirIndexes[num]]);
	    strcat(otherFile, baseNames[num]);

	    fp2 = fpLookup(otherFile, 1);
	    if (FP_EQUAL(fp1, fp2)) 
		dbiAppendIndexRecord(matches, allMatches.recs[i]);

	    free(otherFile);
	    i++;
	} while ((i < allMatches.count) && 
			((i == 0) || (allMatches.recs[i].recOffset == 
				allMatches.recs[i - 1].recOffset)));

	free(baseNames);
	free(dirNames);
	headerFree(h);
    }

    dbiFreeIndexRecord(allMatches);

    if (!matches->count) {
	dbiFreeIndexRecord(*matches);
	return 1;
    }

    return 0;
}

int rpmdbFindByProvides(rpmdb db, const char * filespec, dbiIndexSet * matches) {
    return dbiSearchIndex(db->providesIndex, filespec, matches);
}

int rpmdbFindByRequiredBy(rpmdb db, const char * filespec, dbiIndexSet * matches) {
    return dbiSearchIndex(db->requiredbyIndex, filespec, matches);
}

int rpmdbFindByConflicts(rpmdb db, const char * filespec, dbiIndexSet * matches) {
    return dbiSearchIndex(db->conflictsIndex, filespec, matches);
}

int rpmdbFindByTriggeredBy(rpmdb db, const char * filespec, dbiIndexSet * matches) {
    return dbiSearchIndex(db->triggerIndex, filespec, matches);
}

int rpmdbFindByGroup(rpmdb db, const char * group, dbiIndexSet * matches) {
    return dbiSearchIndex(db->groupIndex, group, matches);
}

int rpmdbFindPackage(rpmdb db, const char * name, dbiIndexSet * matches) {
    return dbiSearchIndex(db->nameIndex, name, matches);
}

static void removeIndexEntry(dbiIndex * dbi, char * key, dbiIndexRecord rec,
		             int tolerant, char * idxName)
{
    int rc;
    dbiIndexSet matches;
    
    rc = dbiSearchIndex(dbi, key, &matches);
    switch (rc) {
      case 0:
	if (dbiRemoveIndexRecord(&matches, rec) && !tolerant) {
	    rpmError(RPMERR_DBCORRUPT, _("package %s not listed in %s"),
		  key, idxName);
	} else {
	    dbiUpdateIndex(dbi, key, &matches);
	       /* errors from above will be reported from dbindex.c */
	}

	dbiFreeIndexRecord(matches);
	break;
      case 1:
	if (!tolerant) 
	    rpmError(RPMERR_DBCORRUPT, _("package %s not found in %s"), 
			key, idxName);
	break;
      case 2:
	break;   /* error message already generated from dbindex.c */
    }
}

int rpmdbRemove(rpmdb db, unsigned int offset, int tolerant)
{
    Header h;
    char * name, * group;
    int type;
    unsigned int count;
    dbiIndexRecord rec;
    char ** fileList, ** providesList, ** requiredbyList;
    char ** conflictList, ** triggerList;
    int i;
    char * basename;

    /* structure assignment */
    rec = dbiReturnIndexRecordInstance(offset, 0);

    h = rpmdbGetRecord(db, offset);
    if (h == NULL) {
	rpmError(RPMERR_DBCORRUPT, _("cannot read header at %d for uninstall"),
	      offset);
	return 1;
    }

    blockSignals();

    if (!headerGetEntry(h, RPMTAG_NAME, &type, (void **) &name, &count)) {
	rpmError(RPMERR_DBCORRUPT, _("package has no name"));
    } else {
	rpmMessage(RPMMESS_DEBUG, _("removing name index\n"));
	removeIndexEntry(db->nameIndex, name, rec, tolerant, "name index");
    }

    if (!headerGetEntry(h, RPMTAG_GROUP, &type, (void **) &group, &count)) {
	rpmMessage(RPMMESS_DEBUG, _("package has no group\n"));
    } else {
	rpmMessage(RPMMESS_DEBUG, _("removing group index\n"));
	removeIndexEntry(db->groupIndex, group, rec, tolerant, "group index");
    }

    if (headerGetEntry(h, RPMTAG_PROVIDENAME, &type, (void **) &providesList, 
	 &count)) {
	for (i = 0; i < count; i++) {
	    rpmMessage(RPMMESS_DEBUG, _("removing provides index for %s\n"), 
		    providesList[i]);
	    removeIndexEntry(db->providesIndex, providesList[i], rec, tolerant, 
			     "providesfile index");
	}
	free(providesList);
    }

    if (headerGetEntry(h, RPMTAG_REQUIRENAME, &type, (void **) &requiredbyList, 
	 &count)) {
	/* There could be dups in requiredByLIst, and the list is sorted.
	   Rather then sort the list, be tolerant of missing entries
	   as they should just indicate duplicated requirements. */

	for (i = 0; i < count; i++) {
	    rpmMessage(RPMMESS_DEBUG, _("removing requiredby index for %s\n"), 
		    requiredbyList[i]);
	    removeIndexEntry(db->requiredbyIndex, requiredbyList[i], rec, 
			     1, "requiredby index");
	}
	free(requiredbyList);
    }

    if (headerGetEntry(h, RPMTAG_TRIGGERNAME, &type, (void **) &triggerList, 
	 &count)) {
	/* triggerList often contains duplicates */
	for (i = 0; i < count; i++) {
	    rpmMessage(RPMMESS_DEBUG, _("removing trigger index for %s\n"), 
		       triggerList[i]);
	    removeIndexEntry(db->triggerIndex, triggerList[i], rec, 
			     1, "trigger index");
	}
	free(triggerList);
    }

    if (headerGetEntry(h, RPMTAG_CONFLICTNAME, &type, (void **) &conflictList, 
	 &count)) {
	for (i = 0; i < count; i++) {
	    rpmMessage(RPMMESS_DEBUG, _("removing conflict index for %s\n"), 
		    conflictList[i]);
	    removeIndexEntry(db->conflictsIndex, conflictList[i], rec, 
			     tolerant, "conflict index");
	}
	free(conflictList);
    }

    if (headerGetEntry(h, RPMTAG_OLDFILENAMES, &type, (void **) &fileList, 
	 &count)) {
	for (i = 0; i < count; i++) {
	    basename = strrchr(fileList[i], '/');
	    if (!basename) 
		basename = fileList[i];
	    else
		basename++;

	    rpmMessage(RPMMESS_DEBUG, _("removing file index for %s\n"), 
			basename);
	    /* structure assignment */
	    rec = dbiReturnIndexRecordInstance(offset, i);
	    removeIndexEntry(db->fileIndex, basename, rec, tolerant, 
			     "file index");
	}
	free(fileList);
    } else {
	rpmMessage(RPMMESS_DEBUG, _("package has no files\n"));
    }

    faFree(db->pkgs, offset);

    dbiSyncIndex(db->nameIndex);
    dbiSyncIndex(db->groupIndex);
    dbiSyncIndex(db->fileIndex);

    unblockSignals();

    headerFree(h);

    return 0;
}

static int addIndexEntry(dbiIndex *idx, const char *index, unsigned int offset,
		         unsigned int fileNumber)
{
    dbiIndexSet set;
    dbiIndexRecord irec;   
    int rc;

    irec = dbiReturnIndexRecordInstance(offset, fileNumber);

    rc = dbiSearchIndex(idx, index, &set);
    if (rc == -1)  		/* error */
	return 1;

    if (rc == 1)  		/* new item */
	set = dbiCreateIndexRecord();
    dbiAppendIndexRecord(&set, irec);
    if (dbiUpdateIndex(idx, index, &set))
	exit(EXIT_FAILURE);
    dbiFreeIndexRecord(set);
    return 0;
}

int rpmdbAdd(rpmdb db, Header dbentry)
{
    unsigned int dboffset;
    unsigned int i, j;
    const char ** fileList;
    const char ** providesList;
    const char ** requiredbyList;
    const char ** conflictList;
    const char ** triggerList;
    const char * name;
    const char * group;
    int count = 0, providesCount = 0, requiredbyCount = 0, conflictCount = 0;
    int triggerCount = 0;
    int type;
    int rc = 0;

    headerGetEntry(dbentry, RPMTAG_NAME, &type, (void **) &name, &count);
    headerGetEntry(dbentry, RPMTAG_GROUP, &type, (void **) &group, &count);

    if (!group) group = "Unknown";

    count = 0;
    headerGetEntry(dbentry, RPMTAG_OLDFILENAMES, &type, (void **) &fileList, 
	           &count);
    headerGetEntry(dbentry, RPMTAG_PROVIDENAME, &type, (void **) &providesList, 
	           &providesCount);
    headerGetEntry(dbentry, RPMTAG_REQUIRENAME, &type, 
		   (void **) &requiredbyList, &requiredbyCount);
    headerGetEntry(dbentry, RPMTAG_CONFLICTNAME, &type, 
		   (void **) &conflictList, &conflictCount);
    headerGetEntry(dbentry, RPMTAG_TRIGGERNAME, &type, 
		   (void **) &triggerList, &triggerCount);

    blockSignals();

    dboffset = faAlloc(db->pkgs, headerSizeof(dbentry, HEADER_MAGIC_NO));
    if (!dboffset) {
	rc = 1;
    } else {
	(void)faLseek(db->pkgs, dboffset, SEEK_SET);
	rc = headerWrite(faFileno(db->pkgs), dbentry, HEADER_MAGIC_NO);
    }

    if (rc) {
	rpmError(RPMERR_DBCORRUPT, _("cannot allocate space for database"));
	goto exit;
    }

    /* Now update the appropriate indexes */
    if (addIndexEntry(db->nameIndex, name, dboffset, 0))
	rc = 1;
    if (addIndexEntry(db->groupIndex, group, dboffset, 0))
	rc = 1;

    for (i = 0; i < triggerCount; i++) {
	/* don't add duplicates */
	for (j = 0; j < i; j++)
	    if (!strcmp(triggerList[i], triggerList[j])) break;
	if (j == i)
	    rc += addIndexEntry(db->triggerIndex, triggerList[i], dboffset, 0);
    }

    for (i = 0; i < conflictCount; i++)
	rc += addIndexEntry(db->conflictsIndex, conflictList[i], dboffset, 0);

    for (i = 0; i < requiredbyCount; i++)
	rc += addIndexEntry(db->requiredbyIndex, requiredbyList[i], 
			    dboffset, 0);

    for (i = 0; i < providesCount; i++)
	rc += addIndexEntry(db->providesIndex, providesList[i], dboffset, 0);

    for (i = 0; i < count; i++) {
	const char * basename;
	basename = strrchr(fileList[i], '/');
	if (!basename) 
	    basename = fileList[i];
	else
	    basename++;
	if (*basename)
	    rc += addIndexEntry(db->fileIndex, basename, dboffset, i);
    }

    dbiSyncIndex(db->nameIndex);
    dbiSyncIndex(db->groupIndex);
    dbiSyncIndex(db->fileIndex);
    dbiSyncIndex(db->providesIndex);
    dbiSyncIndex(db->requiredbyIndex);
    dbiSyncIndex(db->triggerIndex);

exit:
    unblockSignals();

    if (requiredbyCount) free(requiredbyList);
    if (providesCount) free(providesList);
    if (conflictCount) free(conflictList);
    if (triggerCount) free(triggerList);
    if (count) free(fileList);

    return rc;
}

int rpmdbUpdateRecord(rpmdb db, int offset, Header newHeader)
{
    Header oldHeader;
    int oldSize;
    int rc = 0;

    oldHeader = doGetRecord(db, offset, 1);
    if (oldHeader == NULL) {
	rpmError(RPMERR_DBCORRUPT, _("cannot read header at %d for update"),
		offset);
	return 1;
    }

    oldSize = headerSizeof(oldHeader, HEADER_MAGIC_NO);
    headerFree(oldHeader);

    if (oldSize != headerSizeof(newHeader, HEADER_MAGIC_NO)) {
	rpmMessage(RPMMESS_DEBUG, _("header changed size!"));
	if (rpmdbRemove(db, offset, 1))
	    return 1;

	if (rpmdbAdd(db, newHeader)) 
	    return 1;
    } else {
	blockSignals();

	(void)faLseek(db->pkgs, offset, SEEK_SET);

	rc = headerWrite(faFileno(db->pkgs), newHeader, HEADER_MAGIC_NO);

	unblockSignals();
    }

    return rc;
}

void rpmdbRemoveDatabase(const char * rootdir, const char * dbpath)
{ 
    int i;
    const char **rpmdbfnp;
    char * filename;

    i = strlen(dbpath);
    if (dbpath[i - 1] != '/') {
	filename = alloca(i);
	strcpy(filename, dbpath);
	filename[i] = '/';
	filename[i + 1] = '\0';
	dbpath = filename;
    }
    
    filename = alloca(strlen(rootdir) + strlen(dbpath) + 40);

    for (rpmdbfnp = rpmdb_filenames; *rpmdbfnp; rpmdbfnp++) {
	sprintf(filename, "%s/%s/%s", rootdir, dbpath, *rpmdbfnp);
	unlink(filename);
    }

    sprintf(filename, "%s/%s", rootdir, dbpath);
    rmdir(filename);

}

int rpmdbMoveDatabase(const char * rootdir, const char * olddbpath, const char * newdbpath)
{
    int i;
    const char **rpmdbfnp;
    char * ofilename, * nfilename;
    int rc = 0;
 
    i = strlen(olddbpath);
    if (olddbpath[i - 1] != '/') {
	ofilename = alloca(i + 2);
	strcpy(ofilename, olddbpath);
	ofilename[i] = '/';
	ofilename[i + 1] = '\0';
	olddbpath = ofilename;
    }
    
    i = strlen(newdbpath);
    if (newdbpath[i - 1] != '/') {
	nfilename = alloca(i + 2);
	strcpy(nfilename, newdbpath);
	nfilename[i] = '/';
	nfilename[i + 1] = '\0';
	newdbpath = nfilename;
    }
    
    ofilename = alloca(strlen(rootdir) + strlen(olddbpath) + 40);
    nfilename = alloca(strlen(rootdir) + strlen(newdbpath) + 40);

    for (rpmdbfnp = rpmdb_filenames; *rpmdbfnp; rpmdbfnp++) {
	sprintf(ofilename, "%s/%s/%s", rootdir, olddbpath, *rpmdbfnp);
	sprintf(nfilename, "%s/%s/%s", rootdir, newdbpath, *rpmdbfnp);
	if (rename(ofilename, nfilename)) rc = 1;
    }

    return rc;
}

struct intMatch {
    dbiIndexRecord rec;
    int fpNum;
};

static int intMatchCmp(const void * one, const void * two)
{
    const struct intMatch * a = one;
    const struct intMatch * b = two;

    if (a->rec.recOffset < b->rec.recOffset)
	return -1;
    else if (a->rec.recOffset > b->rec.recOffset)
	return 1;

    return 0;
}

int rpmdbFindFpList(rpmdb db, fingerPrint * fpList, dbiIndexSet * matchList, 
		    int numItems)
{
    int numIntMatches = 0;
    int intMatchesAlloced = numItems;
    struct intMatch * intMatches;
    int i, j;
    int start, end;
    int num;

    /* this may be worth batching by basename, but probably not as
       basenames are quite unique as it is */

    intMatches = xcalloc(intMatchesAlloced, sizeof(*intMatches));

    /* Gather all matches from the database */
    for (i = 0; i < numItems; i++) {
	dbiIndexSet matches;
	switch (dbiSearchIndex(db->fileIndex, fpList[i].basename, &matches)) {
	default:
	    break;
	case 2:
	    free(intMatches);
	    return 1;
	    /*@notreached@*/ break;
	case 0:
	    if ((numIntMatches + dbiIndexSetCount(matches)) >= intMatchesAlloced) {
		intMatchesAlloced += dbiIndexSetCount(matches);
		intMatchesAlloced += intMatchesAlloced / 5;
		intMatches = xrealloc(intMatches, 
				     sizeof(*intMatches) * intMatchesAlloced);
	    }

	    for (j = 0; j < dbiIndexSetCount(matches); j++) {
		/* structure assignment */
		intMatches[numIntMatches].rec = matches.recs[j];
		intMatches[numIntMatches++].fpNum = i;
	    }

	    dbiFreeIndexRecord(matches);
	    break;
	}
    }

    qsort(intMatches, numIntMatches, sizeof(*intMatches), intMatchCmp);
    /* intMatches is now sorted by (recnum, filenum) */

    for (i = 0; i < numItems; i++)
	matchList[i] = dbiCreateIndexRecord();

    /* For each set of files matched in a package ... */
    for (start = 0; start < numIntMatches; start = end) {
	struct intMatch * im;
	Header h;
	fingerPrint * fps;

	im = intMatches + start;

	/* Find the end of the set of matched files in this package. */
	for (end = start + 1; end < numIntMatches; end++) {
	    if (im->rec.recOffset != intMatches[end].rec.recOffset)
		break;
	}
	num = end - start;

	/* Compute fingerprints for each file match in this package. */
	h = rpmdbGetRecord(db, im->rec.recOffset);
	if (h == NULL) {
	    free(intMatches);
	    return 1;
	}

	{   const char ** fullfl, **fl;
	    int_32 fc;
	   
	    headerGetEntryMinMemory(h, RPMTAG_OLDFILENAMES, NULL, 
				(void **) &fullfl, &fc);

	    fl = xcalloc(num, sizeof(*fl));
	    for (i = 0; i < num; i++)
		fl[i] = fullfl[im[i].rec.fileNumber];
	    free(fullfl);
	    fps = xcalloc(num, sizeof(*fps));
	    fpLookupList(fl, fps, num, 1);
	    free(fl);
	}

	/* Add db (recnum,filenum) to list for fingerprint matches. */
	for (i = 0; i < num; i++) {
	    j = im[i].fpNum;
	    if (FP_EQUAL(fps[i], fpList[j]))
		dbiAppendIndexRecord(&matchList[j], im[i].rec);
	}

	headerFree(h);

	free(fps);

    }

    free(intMatches);

    return 0;
}