summaryrefslogtreecommitdiffstats
path: root/src/kadmin/dbutil/dump.c
blob: 8fcb56e5acc1e76af09c00ebeeaa01bd60f2e5ed (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
/*
 * kadmin/dbutil/dump.c
 *
 * Copyright 1990,1991,2001,2006,2008 by the Massachusetts Institute of Technology.
 * All Rights Reserved.
 *
 * Export of this software from the United States of America may
 *   require a specific license from the United States Government.
 *   It is the responsibility of any person or organization contemplating
 *   export to obtain such a license before exporting.
 * 
 * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
 * distribute this software and its documentation for any purpose and
 * without fee is hereby granted, provided that the above copyright
 * notice appear in all copies and that both that copyright notice and
 * this permission notice appear in supporting documentation, and that
 * the name of M.I.T. not be used in advertising or publicity pertaining
 * to distribution of the software without specific, written prior
 * permission.  Furthermore if you modify this software you must label
 * your software as modified software and not distribute it in such a
 * fashion that it might be confused with the original M.I.T. software.
 * M.I.T. makes no representations about the suitability of
 * this software for any purpose.  It is provided "as is" without express
 * or implied warranty.
 * 
 *
 * Dump a KDC database
 */
/*
 * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#include <stdio.h>
#include <k5-int.h>
#include <kadm5/admin.h>
#include <kadm5/server_internal.h>
#include <kdb.h>
#include <com_err.h>
#include "kdb5_util.h"
#if defined(HAVE_REGEX_H) && defined(HAVE_REGCOMP)
#include <regex.h>
#endif	/* HAVE_REGEX_H */

/*
 * Needed for master key conversion.
 */
static int			mkey_convert;
static krb5_keyblock		new_master_keyblock;

static int	backwards;
static int	recursive;

/*
 * Use compile(3) if no regcomp present.
 */
#if	!defined(HAVE_REGCOMP) && defined(HAVE_REGEXP_H)
#define	INIT		char *sp = instring;
#define	GETC()		(*sp++)
#define	PEEKC()		(*sp)
#define	UNGETC(c)	(--sp)
#define	RETURN(c)	return(c)
#define	ERROR(c)	
#define	RE_BUF_SIZE	1024
#include <regexp.h>
#endif	/* !HAVE_REGCOMP && HAVE_REGEXP_H */

struct dump_args {
    char		*programname;
    FILE		*ofile;
    krb5_context	kcontext;
    char		**names;
    int			nnames;
    int			verbose;
};

static krb5_error_code dump_k5beta_iterator (krb5_pointer,
					     krb5_db_entry *);
static krb5_error_code dump_k5beta6_iterator (krb5_pointer,
					      krb5_db_entry *);
static krb5_error_code dump_k5beta6_iterator_ext (krb5_pointer,
						  krb5_db_entry *,
						  int);
static krb5_error_code dump_iprop_iterator (krb5_pointer,
					    krb5_db_entry *);
static krb5_error_code dump_k5beta7_princ (krb5_pointer,
					   krb5_db_entry *);
static krb5_error_code dump_k5beta7_princ_ext (krb5_pointer,
					       krb5_db_entry *,
					       int);
static krb5_error_code dump_k5beta7_princ_withpolicy
			(krb5_pointer, krb5_db_entry *);
static krb5_error_code dump_iprop_princ (krb5_pointer,
					 krb5_db_entry *);
static krb5_error_code dump_ov_princ (krb5_pointer,
				      krb5_db_entry *);
static void dump_k5beta7_policy (void *, osa_policy_ent_t);

typedef krb5_error_code (*dump_func)(krb5_pointer,
				     krb5_db_entry *);

static int process_k5beta_record (char *, krb5_context,
				  FILE *, int, int *);
static int process_k5beta6_record (char *, krb5_context,
				   FILE *, int, int *);
static int process_k5beta7_record (char *, krb5_context,
				   FILE *, int, int *);
static int process_ov_record (char *, krb5_context,
			      FILE *, int, int *);
typedef krb5_error_code (*load_func)(char *, krb5_context,
				     FILE *, int, int *);

typedef struct _dump_version {
     char *name;
     char *header;
     int updateonly;
     int create_kadm5;
     dump_func dump_princ;
     osa_adb_iter_policy_func dump_policy;
     load_func load_record;
} dump_version;

dump_version old_version = {
     "Kerberos version 5 old format",
     "kdb5_edit load_dump version 2.0\n",
     0,
     1,
     dump_k5beta_iterator,
     NULL,
     process_k5beta_record,
};
dump_version beta6_version = {
     "Kerberos version 5 beta 6 format",
     "kdb5_edit load_dump version 3.0\n",
     0,
     1,
     dump_k5beta6_iterator,
     NULL,
     process_k5beta6_record,
};
dump_version beta7_version = {
     "Kerberos version 5",
     "kdb5_util load_dump version 4\n",
     0,
     0,
     dump_k5beta7_princ,
     dump_k5beta7_policy,
     process_k5beta7_record,
};
dump_version iprop_version = {
     "Kerberos iprop version",
     "iprop",
     0,
     0,
     dump_iprop_princ,
     dump_k5beta7_policy,
     process_k5beta7_record,
};
dump_version ov_version = {
     "OpenV*Secure V1.0",
     "OpenV*Secure V1.0\t",
     1,
     1,
     dump_ov_princ,
     dump_k5beta7_policy,
     process_ov_record
};

dump_version r1_3_version = {
     "Kerberos version 5 release 1.3",
     "kdb5_util load_dump version 5\n",
     0,
     0,
     dump_k5beta7_princ_withpolicy,
     dump_k5beta7_policy,
     process_k5beta7_record,
};

/* External data */
extern char		*current_dbname;
extern krb5_boolean	dbactive;
extern int		exit_status;
extern krb5_context	util_context;
extern kadm5_config_params global_params;

/* Strings */

#define k5beta_dump_header	"kdb5_edit load_dump version 2.0\n"

static const char null_mprinc_name[] = "kdb5_dump@MISSING";

/* Message strings */
#define regex_err		"%s: regular expression error - %s\n"
#define regex_merr		"%s: regular expression match error - %s\n"
#define pname_unp_err		"%s: cannot unparse principal name (%s)\n"
#define mname_unp_err		"%s: cannot unparse modifier name (%s)\n"
#define nokeys_err		"%s: cannot find any standard key for %s\n"
#define sdump_tl_inc_err	"%s: tagged data list inconsistency for %s (counted %d, stored %d)\n"
#define stand_fmt_name		"Kerberos version 5"
#define old_fmt_name		"Kerberos version 5 old format"
#define b6_fmt_name		"Kerberos version 5 beta 6 format"
#define ofopen_error		"%s: cannot open %s for writing (%s)\n"
#define oflock_error		"%s: cannot lock %s (%s)\n"
#define dumprec_err		"%s: error performing %s dump (%s)\n"
#define dumphdr_err		"%s: error dumping %s header (%s)\n"
#define trash_end_fmt		"%s(%d): ignoring trash at end of line: "
#define read_name_string	"name string"
#define read_key_type		"key type"
#define read_key_data		"key data"
#define read_pr_data1		"first set of principal attributes"
#define read_mod_name		"modifier name"
#define read_pr_data2		"second set of principal attributes"
#define read_salt_data		"salt data"
#define read_akey_type		"alternate key type"
#define read_akey_data		"alternate key data"
#define read_asalt_type		"alternate salt type"
#define read_asalt_data		"alternate salt data"
#define read_exp_data		"expansion data"
#define store_err_fmt		"%s(%d): cannot store %s(%s)\n"
#define add_princ_fmt		"%s\n"
#define parse_err_fmt		"%s(%d): cannot parse %s (%s)\n"
#define read_err_fmt		"%s(%d): cannot read %s\n"
#define no_mem_fmt		"%s(%d): no memory for buffers\n"
#define rhead_err_fmt		"%s(%d): cannot match size tokens\n"
#define err_line_fmt		"%s: error processing line %d of %s\n"
#define head_bad_fmt		"%s: dump header bad in %s\n"
#define read_bytecnt		"record byte count"
#define read_encdata		"encoded data"
#define n_name_unp_fmt		"%s(%s): cannot unparse name\n"
#define n_dec_cont_fmt		"%s(%s): cannot decode contents\n"
#define read_nint_data		"principal static attributes"
#define read_tcontents		"tagged data contents"
#define read_ttypelen		"tagged data type and length"
#define read_kcontents		"key data contents"
#define read_ktypelen		"key data type and length"
#define read_econtents		"extra data contents"
#define k5beta_fmt_name		"Kerberos version 5 old format"
#define standard_fmt_name	"Kerberos version 5 format"
#define no_name_mem_fmt		"%s: cannot get memory for temporary name\n"
#define ctx_err_fmt		"%s: cannot initialize Kerberos context\n"
#define stdin_name		"standard input"
#define remaster_err_fmt	"while re-encoding keys for principal %s with new master key"
#define restfail_fmt		"%s: %s restore failed\n"
#define close_err_fmt		"%s: cannot close database (%s)\n"
#define dbinit_err_fmt		"%s: cannot initialize database (%s)\n"
#define dblock_err_fmt		"%s: cannot initialize database lock (%s)\n"
#define dbname_err_fmt		"%s: cannot set database name to %s (%s)\n"
#define dbdelerr_fmt		"%s: cannot delete bad database %s (%s)\n"
#define dbunlockerr_fmt		"%s: cannot unlock database %s (%s)\n"
#define dbrenerr_fmt		"%s: cannot rename database %s to %s (%s)\n"
#define dbcreaterr_fmt		"%s: cannot create database %s (%s)\n"
#define dfile_err_fmt		"%s: cannot open %s (%s)\n"

static const char oldoption[] = "-old";
static const char b6option[] = "-b6";
static const char b7option[] = "-b7";
static const char ipropoption[] = "-i";
static const char verboseoption[] = "-verbose";
static const char updateoption[] = "-update";
static const char hashoption[] = "-hash";
static const char ovoption[] = "-ov";
static const char dump_tmptrail[] = "~";

/*
 * Re-encrypt the key_data with the new master key...
 */
static krb5_error_code master_key_convert(context, db_entry)
    krb5_context	  context;
    krb5_db_entry	* db_entry;
{
    krb5_error_code	retval;
    krb5_keyblock 	v5plainkey, *key_ptr;
    krb5_keysalt 	keysalt;
    int	      i, j;
    krb5_key_data	new_key_data, *key_data;
    krb5_boolean	is_mkey;

    is_mkey = krb5_principal_compare(context, master_princ, db_entry->princ);

    if (is_mkey && db_entry->n_key_data != 1)
	    fprintf(stderr,
		    "Master key db entry has %d keys, expecting only 1!\n",
		    db_entry->n_key_data);
    for (i=0; i < db_entry->n_key_data; i++) {
	key_data = &db_entry->key_data[i];
	if (key_data->key_data_length == 0)
	    continue;
	retval = krb5_dbekd_decrypt_key_data(context, &master_keyblock,
					     key_data, &v5plainkey,
					     &keysalt);
	if (retval)
		return retval;

	memset(&new_key_data, 0, sizeof(new_key_data));
	key_ptr = is_mkey ? &new_master_keyblock : &v5plainkey;
	retval = krb5_dbekd_encrypt_key_data(context, &new_master_keyblock,
					     key_ptr, &keysalt,
					     key_data->key_data_kvno,
					     &new_key_data);
	if (retval)
		return retval;
	krb5_free_keyblock_contents(context, &v5plainkey);
	for (j = 0; j < key_data->key_data_ver; j++) {
	    if (key_data->key_data_length[j]) {
		free(key_data->key_data_contents[j]);
	    }
	}
	*key_data = new_key_data;
    }
    return 0;
}

/*
 * Update the "ok" file.
 */
void update_ok_file (file_name)
     char *file_name;
{
	/* handle slave locking/failure stuff */
	char *file_ok;
	int fd;
	static char ok[]=".dump_ok";

	if ((file_ok = (char *)malloc(strlen(file_name) + strlen(ok) + 1))
	    == NULL) {
		com_err(progname, ENOMEM,
			"while allocating filename for update_ok_file");
		exit_status++;
		return;
	}
	strcpy(file_ok, file_name);
	strcat(file_ok, ok);
	if ((fd = open(file_ok, O_WRONLY|O_CREAT|O_TRUNC, 0600)) < 0) {
		com_err(progname, errno, "while creating 'ok' file, '%s'",
			file_ok);
		exit_status++;
		free(file_ok);
		return;
	}
	if (write(fd, "", 1) != 1) {
	    com_err(progname, errno, "while writing to 'ok' file, '%s'",
		    file_ok);
	     exit_status++;
	     free(file_ok);
	     return;
	}

	free(file_ok);
	close(fd);
	return;
}

/*
 * name_matches()	- See if a principal name matches a regular expression
 *			  or string.
 */
static int
name_matches(name, arglist)
    char		*name;
    struct dump_args	*arglist;
{
#if	HAVE_REGCOMP
    regex_t	match_exp;
    regmatch_t	match_match;
    int		match_error;
    char	match_errmsg[BUFSIZ];
    size_t	errmsg_size;
#elif	HAVE_REGEXP_H
    char	regexp_buffer[RE_BUF_SIZE];
#elif	HAVE_RE_COMP
    extern char	*re_comp();
    char	*re_result;
#endif	/* HAVE_RE_COMP */
    int		i, match;

    /*
     * Plow, brute force, through the list of names/regular expressions.
     */
    match = (arglist->nnames) ? 0 : 1;
    for (i=0; i<arglist->nnames; i++) {
#if	HAVE_REGCOMP
	/*
	 * Compile the regular expression.
	 */
	match_error = regcomp(&match_exp, arglist->names[i], REG_EXTENDED);
	if (match_error) {
	    errmsg_size = regerror(match_error,
				   &match_exp,
				   match_errmsg,
				   sizeof(match_errmsg));
	    fprintf(stderr, regex_err, arglist->programname, match_errmsg);
	    break;
	}
	/*
	 * See if we have a match.
	 */
	match_error = regexec(&match_exp, name, 1, &match_match, 0);
	if (match_error) {
	    if (match_error != REG_NOMATCH) {
		errmsg_size = regerror(match_error,
				       &match_exp,
				       match_errmsg,
				       sizeof(match_errmsg));
		fprintf(stderr, regex_merr,
			arglist->programname, match_errmsg);
		break;
	    }
	}
	else {
	    /*
	     * We have a match.  See if it matches the whole
	     * name.
	     */
	    if ((match_match.rm_so == 0) &&
		(match_match.rm_eo == strlen(name)))
		match = 1;
	}
	regfree(&match_exp);
#elif	HAVE_REGEXP_H
	/*
	 * Compile the regular expression.
	 */
	compile(arglist->names[i],
		regexp_buffer, 
		&regexp_buffer[RE_BUF_SIZE],
		'\0');
	if (step(name, regexp_buffer)) {
	    if ((loc1 == name) &&
		(loc2 == &name[strlen(name)]))
		match = 1;
	}
#elif	HAVE_RE_COMP
	/*
	 * Compile the regular expression.
	 */
	if (re_result = re_comp(arglist->names[i])) {
	    fprintf(stderr, regex_err, arglist->programname, re_result);
	    break;
	}
	if (re_exec(name))
	    match = 1;
#else	/* HAVE_RE_COMP */
	/*
	 * If no regular expression support, then just compare the strings.
	 */
	if (!strcmp(arglist->names[i], name))
	    match = 1;
#endif	/* HAVE_REGCOMP */
	if (match)
	    break;
    }
    return(match);
}

static krb5_error_code
find_enctype(dbentp, enctype, salttype, kentp)
    krb5_db_entry	*dbentp;
    krb5_enctype	enctype;
    krb5_int32		salttype;
    krb5_key_data	**kentp;
{
    int			i;
    int			maxkvno;
    krb5_key_data	*datap;

    maxkvno = -1;
    datap = (krb5_key_data *) NULL;
    for (i=0; i<dbentp->n_key_data; i++) {
	if (( (krb5_enctype)dbentp->key_data[i].key_data_type[0] == enctype) &&
	    ((dbentp->key_data[i].key_data_type[1] == salttype) ||
	     (salttype < 0))) {
	    maxkvno = dbentp->key_data[i].key_data_kvno;
	    datap = &dbentp->key_data[i];
	}
    }
    if (maxkvno >= 0) {
	*kentp = datap;
	return(0);
    }
    return(ENOENT);    
}

#if 0
/*
 * dump_k5beta_header()	- Make a dump header that is recognizable by Kerberos
 *			  Version 5 Beta 5 and previous releases.
 */
static krb5_error_code
dump_k5beta_header(arglist)
    struct dump_args *arglist;
{
    /* The old header consists of the leading string */
    fprintf(arglist->ofile, k5beta_dump_header);
    return(0);
}
#endif

/*
 * dump_k5beta_iterator()	- Dump an entry in a format that is usable
 *				  by Kerberos Version 5 Beta 5 and previous
 *				  releases.
 */
static krb5_error_code
dump_k5beta_iterator(ptr, entry)
    krb5_pointer	ptr;
    krb5_db_entry	*entry;
{
    krb5_error_code	retval;
    struct dump_args	*arg;
    char		*name, *mod_name;
    krb5_principal	mod_princ;
    krb5_key_data	*pkey, *akey, nullkey;
    krb5_timestamp	mod_date, last_pwd_change;
    int			i;

    /* Initialize */
    arg = (struct dump_args *) ptr;
    name = (char *) NULL;
    mod_name = (char *) NULL;
    memset(&nullkey, 0, sizeof(nullkey));

    /*
     * Flatten the principal name.
     */
    if ((retval = krb5_unparse_name(arg->kcontext,
				    entry->princ,
				    &name))) {
	fprintf(stderr, pname_unp_err, 
		arg->programname, error_message(retval));
	return(retval);
    }

    /*
     * Re-encode the keys in the new master key, if necessary.
     */
    if (mkey_convert) {
	retval = master_key_convert(arg->kcontext, entry);
	if (retval) {
	    com_err(arg->programname, retval, remaster_err_fmt, name);
	    return retval;
	}
    }
    
    /*
     * If we don't have any match strings, or if our name matches, then
     * proceed with the dump, otherwise, just forget about it.
     */
    if (!arg->nnames || name_matches(name, arg)) {
	/*
	 * Deserialize the modifier record.
	 */
	mod_name = (char *) NULL;
	mod_princ = NULL;
	last_pwd_change = mod_date = 0;
	pkey = akey = (krb5_key_data *) NULL;
	if (!(retval = krb5_dbe_lookup_mod_princ_data(arg->kcontext,
						      entry,
						      &mod_date,
						      &mod_princ))) {
	    if (mod_princ) {
		/*
		 * Flatten the modifier name.
		 */
		if ((retval = krb5_unparse_name(arg->kcontext,
						mod_princ,
						&mod_name)))
		    fprintf(stderr, mname_unp_err, arg->programname,
			    error_message(retval));
		krb5_free_principal(arg->kcontext, mod_princ);
	    }
	}
	if (!mod_name)
	    mod_name = strdup(null_mprinc_name);

	/*
	 * Find the last password change record and set it straight.
	 */
	if ((retval =
	     krb5_dbe_lookup_last_pwd_change(arg->kcontext, entry,
					     &last_pwd_change))) {
	    fprintf(stderr, nokeys_err, arg->programname, name);
	    krb5_xfree(mod_name);
	    krb5_xfree(name);
	    return(retval);
	}

	/*
	 * Find the 'primary' key and the 'alternate' key.
	 */
	if ((retval = find_enctype(entry,
				   ENCTYPE_DES_CBC_CRC,
				   KRB5_KDB_SALTTYPE_NORMAL,
				   &pkey)) &&
	    (retval = find_enctype(entry,
				   ENCTYPE_DES_CBC_CRC,
				   KRB5_KDB_SALTTYPE_V4,
				   &akey))) {
	    fprintf(stderr, nokeys_err, arg->programname, name);
	    krb5_xfree(mod_name);
	    krb5_xfree(name);
	    return(retval);
	}

	/* If we only have one type, then ship it out as the primary. */
	if (!pkey && akey) {
	    pkey = akey;
	    akey = &nullkey;
	}
	else {
	    if (!akey)
		akey = &nullkey;
	}

	/*
	 * First put out strings representing the length of the variable
	 * length data in this record, then the name and the primary key type.
	 */
	fprintf(arg->ofile, "%lu\t%lu\t%d\t%d\t%d\t%d\t%s\t%d\t",
		(unsigned long) strlen(name),
		(unsigned long) strlen(mod_name),
		(krb5_int32) pkey->key_data_length[0],
		(krb5_int32) akey->key_data_length[0],
		(krb5_int32) pkey->key_data_length[1],
		(krb5_int32) akey->key_data_length[1],
		name,
		(krb5_int32) pkey->key_data_type[0]);
	for (i=0; i<pkey->key_data_length[0]; i++) {
	    fprintf(arg->ofile, "%02x", pkey->key_data_contents[0][i]);
	}
	/*
	 * Second, print out strings representing the standard integer
	 * data in this record.
	 */
	fprintf(arg->ofile,
		"\t%u\t%u\t%u\t%u\t%u\t%u\t%u\t%u\t%u\t%u\t%s\t%u\t%u\t%u\t",
		(krb5_int32) pkey->key_data_kvno,
		entry->max_life, entry->max_renewable_life,
		1 /* Fake mkvno */, entry->expiration, entry->pw_expiration,
		last_pwd_change, entry->last_success, entry->last_failed,
		entry->fail_auth_count, mod_name, mod_date,
		entry->attributes, pkey->key_data_type[1]);

	/* Pound out the salt data, if present. */
	for (i=0; i<pkey->key_data_length[1]; i++) {
	    fprintf(arg->ofile, "%02x", pkey->key_data_contents[1][i]);
	}
	/* Pound out the alternate key type and contents */
	fprintf(arg->ofile, "\t%u\t", akey->key_data_type[0]);
	for (i=0; i<akey->key_data_length[0]; i++) {
	    fprintf(arg->ofile, "%02x", akey->key_data_contents[0][i]);
	}
	/* Pound out the alternate salt type and contents */
	fprintf(arg->ofile, "\t%u\t", akey->key_data_type[1]);
	for (i=0; i<akey->key_data_length[1]; i++) {
	    fprintf(arg->ofile, "%02x", akey->key_data_contents[1][i]);
	}
	/* Pound out the expansion data. (is null) */
	for (i=0; i < 8; i++) {
	    fprintf(arg->ofile, "\t%u", 0);
	}
	fprintf(arg->ofile, ";\n");
	/* If we're blabbing, do it */
	if (arg->verbose)
	    fprintf(stderr, "%s\n", name);
	krb5_xfree(mod_name);
    }
    krb5_xfree(name);
    return(0);
}

/*
 * dump_k5beta6_iterator()	- Output a dump record in krb5b6 format.
 */
static krb5_error_code
dump_k5beta6_iterator(ptr, entry)
    krb5_pointer	ptr;
    krb5_db_entry	*entry;
{
    return dump_k5beta6_iterator_ext(ptr, entry, 0);
}

static krb5_error_code
dump_k5beta6_iterator_ext(ptr, entry, kadm)
    krb5_pointer	ptr;
    krb5_db_entry	*entry;
    int			kadm;
{
    krb5_error_code	retval;
    struct dump_args	*arg;
    char		*name;
    krb5_tl_data	*tlp;
    krb5_key_data	*kdata;
    int			counter, skip, i, j;

    /* Initialize */
    arg = (struct dump_args *) ptr;
    name = (char *) NULL;

    /*
     * Flatten the principal name.
     */
    if ((retval = krb5_unparse_name(arg->kcontext,
				    entry->princ,
				    &name))) {
	fprintf(stderr, pname_unp_err, 
		arg->programname, error_message(retval));
	return(retval);
    }

    /*
     * Re-encode the keys in the new master key, if necessary.
     */
    if (mkey_convert) {
	retval = master_key_convert(arg->kcontext, entry);
	if (retval) {
	    com_err(arg->programname, retval, remaster_err_fmt, name);
	    return retval;
	}
    }
    
    /*
     * If we don't have any match strings, or if our name matches, then
     * proceed with the dump, otherwise, just forget about it.
     */
    if (!arg->nnames || name_matches(name, arg)) {
	/*
	 * We'd like to just blast out the contents as they would appear in
	 * the database so that we can just suck it back in, but it doesn't
	 * lend itself to easy editing.
	 */

	/*
	 * The dump format is as follows:
	 *	len strlen(name) n_tl_data n_key_data e_length
	 *	name
	 *	attributes max_life max_renewable_life expiration
	 *	pw_expiration last_success last_failed fail_auth_count
	 *	n_tl_data*[type length <contents>]
	 *	n_key_data*[ver kvno ver*(type length <contents>)]
	 *	<e_data>
	 * Fields which are not encapsulated by angle-brackets are to appear
	 * verbatim.  A bracketed field's absence is indicated by a -1 in its
	 * place
	 */

	/*
	 * Make sure that the tagged list is reasonably correct.
	 */
	counter = skip = 0;
	for (tlp = entry->tl_data; tlp; tlp = tlp->tl_data_next) {
	     /*
	      * don't dump tl data types we know aren't understood by
	      * earlier revisions [krb5-admin/89]
	      */
	     switch (tlp->tl_data_type) {
	     case KRB5_TL_KADM_DATA:
		  if (kadm)
		      counter++;
		  else
		      skip++;
		  break;
	     default:
		  counter++;
		  break;
	     }
	}
	
	if (counter + skip == entry->n_tl_data) {
	    /* Pound out header */
	    fprintf(arg->ofile, "%d\t%lu\t%d\t%d\t%d\t%s\t",
		    (int) entry->len,
		    (unsigned long) strlen(name),
		    counter,
		    (int) entry->n_key_data,
		    (int) entry->e_length,
		    name);
	    fprintf(arg->ofile, "%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t",
		    entry->attributes,
		    entry->max_life,
		    entry->max_renewable_life,
		    entry->expiration,
		    entry->pw_expiration,
		    entry->last_success,
		    entry->last_failed,
		    entry->fail_auth_count);
	    /* Pound out tagged data. */
	    for (tlp = entry->tl_data; tlp; tlp = tlp->tl_data_next) {
		if (tlp->tl_data_type == KRB5_TL_KADM_DATA && !kadm)
		     continue; /* see above, [krb5-admin/89] */

		fprintf(arg->ofile, "%d\t%d\t",
			(int) tlp->tl_data_type,
			(int) tlp->tl_data_length);
		if (tlp->tl_data_length)
		    for (i=0; i<tlp->tl_data_length; i++)
			fprintf(arg->ofile, "%02x", tlp->tl_data_contents[i]);
		else
		    fprintf(arg->ofile, "%d", -1);
		fprintf(arg->ofile, "\t");
	    }

	    /* Pound out key data */
	    for (counter=0; counter<entry->n_key_data; counter++) {
		kdata = &entry->key_data[counter];
		fprintf(arg->ofile, "%d\t%d\t",
			(int) kdata->key_data_ver,
			(int) kdata->key_data_kvno);
		for (i=0; i<kdata->key_data_ver; i++) {
		    fprintf(arg->ofile, "%d\t%d\t",
			    kdata->key_data_type[i],
			    kdata->key_data_length[i]);
		    if (kdata->key_data_length[i])
			for (j=0; j<kdata->key_data_length[i]; j++)
			    fprintf(arg->ofile, "%02x",
				    kdata->key_data_contents[i][j]);
		    else
			fprintf(arg->ofile, "%d", -1);
		    fprintf(arg->ofile, "\t");
		}
	    }

	    /* Pound out extra data */
	    if (entry->e_length)
		for (i=0; i<entry->e_length; i++)
		    fprintf(arg->ofile, "%02x", entry->e_data[i]);
	    else
		fprintf(arg->ofile, "%d", -1);

	    /* Print trailer */
	    fprintf(arg->ofile, ";\n");

	    if (arg->verbose)
		fprintf(stderr, "%s\n", name);
	}
	else {
	    fprintf(stderr, sdump_tl_inc_err,
		    arg->programname, name, counter+skip,
		    (int) entry->n_tl_data); 
	    retval = EINVAL;
	}
    }
    krb5_xfree(name);
    return(retval);
}

/*
 * dump_iprop_iterator()	- Output a dump record in iprop format.
 */
static krb5_error_code
dump_iprop_iterator(ptr, entry)
    krb5_pointer	ptr;
    krb5_db_entry	*entry;
{
    return dump_k5beta6_iterator_ext(ptr, entry, 1);
}

/*
 * dump_k5beta7_iterator()	- Output a dump record in krb5b7 format.
 */
static krb5_error_code
dump_k5beta7_princ(ptr, entry)
    krb5_pointer	ptr;
    krb5_db_entry	*entry;
{
    return dump_k5beta7_princ_ext(ptr, entry, 0);
}

static krb5_error_code
dump_k5beta7_princ_ext(ptr, entry, kadm)
    krb5_pointer	ptr;
    krb5_db_entry	*entry;
    int			kadm;
{
     krb5_error_code retval;
     struct dump_args *arg;
     char *name;
     int tmp_nnames;

     /* Initialize */
     arg = (struct dump_args *) ptr;
     name = (char *) NULL;

     /*
      * Flatten the principal name.
      */
     if ((retval = krb5_unparse_name(arg->kcontext,
				     entry->princ,
				     &name))) {
	  fprintf(stderr, pname_unp_err, 
		  arg->programname, error_message(retval));
	  return(retval);
     }
     /*
      * If we don't have any match strings, or if our name matches, then
      * proceed with the dump, otherwise, just forget about it.
      */
     if (!arg->nnames || name_matches(name, arg)) {
	  fprintf(arg->ofile, "princ\t");
	  
	  /* save the callee from matching the name again */
	  tmp_nnames = arg->nnames;
	  arg->nnames = 0;
	  retval = dump_k5beta6_iterator_ext(ptr, entry, kadm);
	  arg->nnames = tmp_nnames;
     }

     free(name);
     return retval;
}

static krb5_error_code
dump_k5beta7_princ_withpolicy(ptr, entry)
    krb5_pointer	ptr;
    krb5_db_entry	*entry;
{
    return dump_k5beta7_princ_ext(ptr, entry, 1);
}

/*
 * dump_iprop_princ()	- Output a dump record in iprop format.
 * This was created in order to dump more data, such as kadm5 tl
 */
static krb5_error_code
dump_iprop_princ(ptr, entry)
    krb5_pointer	ptr;
    krb5_db_entry	*entry;
{
     krb5_error_code retval;
     struct dump_args *arg;
     char *name;
     int tmp_nnames;

     /* Initialize */
     arg = (struct dump_args *) ptr;
     name = (char *) NULL;

     /*
      * Flatten the principal name.
      */
     if ((retval = krb5_unparse_name(arg->kcontext,
				     entry->princ,
				     &name))) {
		fprintf(stderr, _(pname_unp_err),
		  arg->programname, error_message(retval));
	  return(retval);
     }
     /*
      * If we don't have any match strings, or if our name matches, then
      * proceed with the dump, otherwise, just forget about it.
      */
     if (!arg->nnames || name_matches(name, arg)) {
	  fprintf(arg->ofile, "princ\t");
	  
	  /* save the callee from matching the name again */
	  tmp_nnames = arg->nnames;
	  arg->nnames = 0;
	  retval = dump_iprop_iterator(ptr, entry);
	  arg->nnames = tmp_nnames;
     }
     free(name);
	return (retval);
}

void dump_k5beta7_policy(void *data, osa_policy_ent_t entry)
{
     struct dump_args *arg;

     arg = (struct dump_args *) data;
     fprintf(arg->ofile, "policy\t%s\t%d\t%d\t%d\t%d\t%d\t%d\n", entry->name,
	     entry->pw_min_life, entry->pw_max_life, entry->pw_min_length,
	     entry->pw_min_classes, entry->pw_history_num,
	     entry->policy_refcnt);
}

static void print_key_data(FILE *f, krb5_key_data *key_data)
{
     int c;
     
     fprintf(f, "%d\t%d\t", key_data->key_data_type[0],
	     key_data->key_data_length[0]);
     for(c = 0; c < key_data->key_data_length[0]; c++) 
	  fprintf(f, "%02x ",
		  key_data->key_data_contents[0][c]);
}

/*
 * Function: print_princ
 * 
 * Purpose: output osa_adb_princ_ent data in a human
 *	    readable format (which is a format suitable for
 *	    ovsec_adm_import consumption)
 *
 * Arguments:
 *	data		(input) pointer to a structure containing a FILE *
 *			        and a record counter.
 *	entry		(input) entry to get dumped.
 * 	<return value>	void
 *
 * Requires:
 *	nuttin
 * 
 * Effects:
 *	writes data to the specified file pointerp.
 *
 * Modifies:
 *	nuttin
 * 
 */
static krb5_error_code dump_ov_princ(krb5_pointer ptr, krb5_db_entry *kdb)
{
    char *princstr;
    int	x, y, foundcrc;
    struct dump_args *arg;
    krb5_tl_data tl_data;
    osa_princ_ent_rec adb;
    XDR xdrs;

    arg = (struct dump_args *) ptr;
    /*
     * XXX Currently, lookup_tl_data always returns zero; it sets
     * tl_data->tl_data_length to zero if the type isn't found.
     * This should be fixed...
     */
    /*
     * XXX Should this function do nothing for a principal with no
     * admin data, or print a record of "default" values?   See
     * comment in server_kdb.c to help decide.
     */
    tl_data.tl_data_type = KRB5_TL_KADM_DATA;
    if (krb5_dbe_lookup_tl_data(arg->kcontext, kdb, &tl_data)
	|| (tl_data.tl_data_length == 0))
	 return 0;

    memset(&adb, 0, sizeof(adb));
    xdrmem_create(&xdrs, tl_data.tl_data_contents,
		  tl_data.tl_data_length, XDR_DECODE);
    if (! xdr_osa_princ_ent_rec(&xdrs, &adb)) {
	 xdr_destroy(&xdrs);
	 return(KADM5_XDR_FAILURE);
    }
    xdr_destroy(&xdrs);
    
    krb5_unparse_name(arg->kcontext, kdb->princ, &princstr);
    fprintf(arg->ofile, "princ\t%s\t", princstr);
    if(adb.policy == NULL)
	fputc('\t', arg->ofile);
    else
	fprintf(arg->ofile, "%s\t", adb.policy);
    fprintf(arg->ofile, "%lx\t%d\t%d\t%d", adb.aux_attributes,
	    adb.old_key_len,adb.old_key_next, adb.admin_history_kvno);

    for (x = 0; x < adb.old_key_len; x++) {
	 foundcrc = 0;
	 for (y = 0; y < adb.old_keys[x].n_key_data; y++) {
	      krb5_key_data *key_data = &adb.old_keys[x].key_data[y];

	      if (key_data->key_data_type[0] != ENCTYPE_DES_CBC_CRC)
		   continue;
	      if (foundcrc) {
		   fprintf(stderr, "Warning!  Multiple DES-CBC-CRC keys "
			   "for principal %s; skipping duplicates.\n",
			   princstr);
		   continue;
	      }
	      foundcrc++;

	      fputc('\t', arg->ofile);
	      print_key_data(arg->ofile, key_data);
	 }
	 if (!foundcrc)
	      fprintf(stderr, "Warning!  No DES-CBC-CRC key for principal "
		      "%s, cannot generate OV-compatible record; skipping\n",
		      princstr);
    }

    fputc('\n', arg->ofile);
    free(princstr);
    return 0;
}

/*
 * usage is:
 *	dump_db [-old] [-b6] [-b7] [-ov] [-verbose] [-mkey_convert]
 *		[-new_mkey_file mkey_file] [-rev] [-recurse]
 *		[filename [principals...]]
 */
void
dump_db(argc, argv)
    int		argc;
    char	**argv;
{
    FILE		*f;
    struct dump_args	arglist;
    char		*programname;
    char		*ofile;
    krb5_error_code	kret, retval;
    dump_version	*dump;
    int			aindex;
    krb5_boolean	locked;
    char		*new_mkey_file = 0;
    bool_t		dump_sno = FALSE;
    kdb_log_context	*log_ctx;
    char		**db_args = 0; /* XXX */

    /*
     * Parse the arguments.
     */
    programname = argv[0];
    if (strrchr(programname, (int) '/'))
	programname = strrchr(argv[0], (int) '/') + 1;
    ofile = (char *) NULL;
    dump = &r1_3_version;
    arglist.verbose = 0;
    new_mkey_file = 0;
    mkey_convert = 0;
    backwards = 0;
    recursive = 0;
    log_ctx = util_context->kdblog_context;

    /*
     * Parse the qualifiers.
     */
    for (aindex = 1; aindex < argc; aindex++) {
	if (!strcmp(argv[aindex], oldoption))
	     dump = &old_version;
	else if (!strcmp(argv[aindex], b6option))
	     dump = &beta6_version;
	else if (!strcmp(argv[aindex], b7option))
	     dump = &beta7_version;
	else if (!strcmp(argv[aindex], ovoption))
	     dump = &ov_version;
	else if (!strcmp(argv[aindex], ipropoption)) {
	    if (log_ctx && log_ctx->iproprole) {
		dump = &iprop_version;
		/*
		 * dump_sno is used to indicate if the serial
		 * # should be populated in the output
		 * file to be used later by iprop for updating
		 * the slave's update log when loading
		 */
		dump_sno = TRUE;
	    } else {
		fprintf(stderr, _("Iprop not enabled\n"));
		exit_status++;
		return;
	    }
	} else if (!strcmp(argv[aindex], verboseoption))
	    arglist.verbose++;
	else if (!strcmp(argv[aindex], "-mkey_convert"))
	    mkey_convert = 1;
	else if (!strcmp(argv[aindex], "-new_mkey_file")) {
	    new_mkey_file = argv[++aindex];
	    mkey_convert = 1;
        } else if (!strcmp(argv[aindex], "-rev"))
	    backwards = 1;
	else if (!strcmp(argv[aindex], "-recurse"))
	    recursive = 1;
	else
	    break;
    }

    arglist.names = (char **) NULL;
    arglist.nnames = 0;
    if (aindex < argc) {
	ofile = argv[aindex];
	aindex++;
	if (aindex < argc) {
	    arglist.names = &argv[aindex];
	    arglist.nnames = argc - aindex;
	}
    }

    /*
     * Make sure the database is open.  The policy database only has
     * to be opened if we try a dump that uses it.
     */
    if (!dbactive) {
	com_err(argv[0], 0, Err_no_database);
	exit_status++;
	return;
    }

    /*
     * If we're doing a master key conversion, set up for it.
     */
    if (mkey_convert) {
	    if (!valid_master_key) {
		    /* TRUE here means read the keyboard, but only once */
		    retval = krb5_db_fetch_mkey(util_context,
						master_princ,
						master_keyblock.enctype,
						TRUE, FALSE,
						(char *) NULL, 0,
						&master_keyblock);
		    if (retval) {
			    com_err(argv[0], retval,
				    "while reading master key");
			    exit(1);
		    }
		    retval = krb5_db_verify_master_key(util_context,
						       master_princ,
						       &master_keyblock);
		    if (retval) {
			    com_err(argv[0], retval,
				    "while verifying master key");
			    exit(1);
		    }
	    }
	    new_master_keyblock.enctype = global_params.enctype;
	    if (new_master_keyblock.enctype == ENCTYPE_UNKNOWN)
		    new_master_keyblock.enctype = DEFAULT_KDC_ENCTYPE;
	    if (!new_mkey_file)
		    printf("Please enter new master key....\n");
	    if ((retval = krb5_db_fetch_mkey(util_context, master_princ, 
					     new_master_keyblock.enctype,
					     (new_mkey_file == 0) ? 
					        (krb5_boolean) 1 : 0, 
					     TRUE, 
					     new_mkey_file, 0,
					     &new_master_keyblock))) { 
		    com_err(argv[0], retval, "while reading new master key");
		    exit(1);
	    }
    }

    kret = 0;
    locked = 0;
    if (ofile && strcmp(ofile, "-")) {
	/*
	 * Discourage accidental dumping to filenames beginning with '-'.
	 */
	if (ofile[0] == '-')
	    usage();
	/*
	 * Make sure that we don't open and truncate on the fopen,
	 * since that may hose an on-going kprop process.
	 * 
	 * We could also control this by opening for read and
	 * write, doing an flock with LOCK_EX, and then
	 * truncating the file once we have gotten the lock,
	 * but that would involve more OS dependencies than I
	 * want to get into.
	 */
	unlink(ofile);
	if (!(f = fopen(ofile, "w"))) {
	    fprintf(stderr, ofopen_error,
		    programname, ofile, error_message(errno));
	    exit_status++;
	    return;
       }
	if ((kret = krb5_lock_file(util_context,
				   fileno(f),
				   KRB5_LOCKMODE_EXCLUSIVE))) {
	    fprintf(stderr, oflock_error,
		    programname, ofile, error_message(kret));
	    exit_status++;
	}
	else
	    locked = 1;
    } else {
	f = stdout;
    }
    if (f && !(kret)) {
	arglist.programname = programname;
	arglist.ofile = f;
	arglist.kcontext = util_context;
	fprintf(arglist.ofile, "%s", dump->header);

	if (dump_sno) {
	    if (ulog_map(util_context, global_params.iprop_logfile,
			 global_params.iprop_ulogsize, FKCOMMAND, db_args)) {
		fprintf(stderr,
			_("%s: Could not map log\n"), programname);
		exit_status++;
		goto unlock_and_return;
	    }

	    /*
	     * We grab the lock twice (once again in the iterator call),
	     * but that's ok since the lock func handles incr locks held.
	     */
	    if (krb5_db_lock(util_context, KRB5_LOCKMODE_SHARED)) {
		fprintf(stderr,
			_("%s: Couldn't grab lock\n"), programname);
		exit_status++;
		goto unlock_and_return;
	    }

	    fprintf(f, " %u", log_ctx->ulog->kdb_last_sno);
	    fprintf(f, " %u", log_ctx->ulog->kdb_last_time.seconds);
	    fprintf(f, " %u", log_ctx->ulog->kdb_last_time.useconds);
	}

	if (dump->header[strlen(dump->header)-1] != '\n')
	     fputc('\n', arglist.ofile);
	
	if ((kret = krb5_db_iterate(util_context,
				    NULL,
				    dump->dump_princ,
				    (krb5_pointer) &arglist))) { /* TBD: backwards and recursive not supported */
	     fprintf(stderr, dumprec_err,
		     programname, dump->name, error_message(kret));
	     exit_status++;
	     if (dump_sno)
		 (void) krb5_db_unlock(util_context);
	}
	if (dump->dump_policy &&
	    (kret = krb5_db_iter_policy( util_context, "*", dump->dump_policy,
					 &arglist))) { 
	     fprintf(stderr, dumprec_err, programname, dump->name,
		     error_message(kret));
	     exit_status++;
	}
	if (ofile && f != stdout && !exit_status) {
	    if (locked) {
		(void) krb5_lock_file(util_context, fileno(f), KRB5_LOCKMODE_UNLOCK);
		locked = 0;
	    }
	    fclose(f);
	    update_ok_file(ofile);
	}
    }
unlock_and_return:
    if (locked)
	(void) krb5_lock_file(util_context, fileno(f), KRB5_LOCKMODE_UNLOCK);
}

/*
 * Read a string of bytes while counting the number of lines passed.
 */
static int
read_string(f, buf, len, lp)
    FILE	*f;
    char	*buf;
    int		len;
    int		*lp;
{
    int c;
    int i, retval;

    retval = 0;
    for (i=0; i<len; i++) {
	c = fgetc(f);
	if (c < 0) {
	    retval = 1;
	    break;
	}
	if (c == '\n')
	    (*lp)++;
	buf[i] = (char) c;
    }
    buf[len] = '\0';
    return(retval);
}

/*
 * Read a string of two character representations of bytes.
 */
static int
read_octet_string(f, buf, len)
    FILE	*f;
    krb5_octet	*buf;
    int		len;
{
    int c;
    int i, retval;

    retval = 0;
    for (i=0; i<len; i++) {
	if (fscanf(f, "%02x", &c) != 1) {
	    retval = 1;
	    break;
	}
	buf[i] = (krb5_octet) c;
    }
    return(retval);
}

/*
 * Find the end of an old format record.
 */
static void
find_record_end(f, fn, lineno)
    FILE	*f;
    char	*fn;
    int		lineno;
{
    int	ch;

    if (((ch = fgetc(f)) != ';') || ((ch = fgetc(f)) != '\n')) {
	fprintf(stderr, trash_end_fmt, fn, lineno);
	while (ch != '\n') {
	    putc(ch, stderr);
	    ch = fgetc(f);
	}
	putc(ch, stderr);
    }
}

#if 0
/*
 * update_tl_data()	- Generate the tl_data entries.
 */
static krb5_error_code
update_tl_data(kcontext, dbentp, mod_name, mod_date, last_pwd_change)
    krb5_context	kcontext;
    krb5_db_entry	*dbentp;
    krb5_principal	mod_name;
    krb5_timestamp	mod_date;
    krb5_timestamp	last_pwd_change;
{
    krb5_error_code	kret;

    kret = 0 ;

    /*
     * Handle modification principal.
     */
    if (mod_name) {
	krb5_tl_mod_princ	mprinc;

	memset(&mprinc, 0, sizeof(mprinc));
	if (!(kret = krb5_copy_principal(kcontext,
					 mod_name,
					 &mprinc.mod_princ))) {
	    mprinc.mod_date = mod_date;
	    kret = krb5_dbe_encode_mod_princ_data(kcontext,
						  &mprinc,
						  dbentp);
	}
	if (mprinc.mod_princ)
	    krb5_free_principal(kcontext, mprinc.mod_princ);
    }

    /*
     * Handle last password change.
     */
    if (!kret) {
	krb5_tl_data	*pwchg;
	krb5_boolean	linked;

	/* Find a previously existing entry */
	for (pwchg = dbentp->tl_data;
	     (pwchg) && (pwchg->tl_data_type != KRB5_TL_LAST_PWD_CHANGE);
	     pwchg = pwchg->tl_data_next);

	/* Check to see if we found one. */
	linked = 0;
	if (!pwchg) {
	    /* No, allocate a new one */
	    if ((pwchg = (krb5_tl_data *) malloc(sizeof(krb5_tl_data)))) {
		memset(pwchg, 0, sizeof(krb5_tl_data));
		if (!(pwchg->tl_data_contents =
		      (krb5_octet *) malloc(sizeof(krb5_timestamp)))) {
		    free(pwchg);
		    pwchg = (krb5_tl_data *) NULL;
		}
		else {
		    pwchg->tl_data_type = KRB5_TL_LAST_PWD_CHANGE;
		    pwchg->tl_data_length =
			(krb5_int16) sizeof(krb5_timestamp);
		}
	    }
	}
	else
	    linked = 1;

	/* Do we have an entry? */
	if (pwchg && pwchg->tl_data_contents) {
	    /* Encode it */
	    krb5_kdb_encode_int32(last_pwd_change, pwchg->tl_data_contents);
	    /* Link it in if necessary */
	    if (!linked) {
		pwchg->tl_data_next = dbentp->tl_data;
		dbentp->tl_data = pwchg;
		dbentp->n_tl_data++;
	    }
	}
	else
	    kret = ENOMEM;
    }

    return(kret);
}
#endif

/*
 * process_k5beta_record()	- Handle a dump record in old format.
 *
 * Returns -1 for end of file, 0 for success and 1 for failure.
 */
static int
process_k5beta_record(fname, kcontext, filep, verbose, linenop)
    char		*fname;
    krb5_context	kcontext;
    FILE		*filep;
    int			verbose;
    int			*linenop;
{
    int			nmatched;
    int			retval;
    krb5_db_entry	dbent;
    int			name_len, mod_name_len, key_len;
    int			alt_key_len, salt_len, alt_salt_len;
    char		*name;
    char		*mod_name;
    int			tmpint1, tmpint2, tmpint3;
    int			error;
    const char		*try2read;
    int			i;
    krb5_key_data	*pkey, *akey;
    krb5_timestamp	last_pwd_change, mod_date;
    krb5_principal	mod_princ;
    krb5_error_code	kret;

    try2read = (char *) NULL;
    (*linenop)++;
    retval = 1;
    memset((char *)&dbent, 0, sizeof(dbent));

    /* Make sure we've got key_data entries */
    if (krb5_dbe_create_key_data(kcontext, &dbent) ||
	krb5_dbe_create_key_data(kcontext, &dbent)) {
	krb5_db_free_principal(kcontext, &dbent, 1);
	return(1);
    }
    pkey = &dbent.key_data[0];
    akey = &dbent.key_data[1];

    /*
     * Match the sizes.  6 tokens to match.
     */
    nmatched = fscanf(filep, "%d\t%d\t%d\t%d\t%d\t%d\t",
		      &name_len, &mod_name_len, &key_len,
		      &alt_key_len, &salt_len, &alt_salt_len);
    if (nmatched == 6) {
        pkey->key_data_length[0] = key_len;
	akey->key_data_length[0] = alt_key_len;
	pkey->key_data_length[1] = salt_len;
	akey->key_data_length[1] = alt_salt_len;
	name = (char *) NULL;
	mod_name = (char *) NULL;
	/*
	 * Get the memory for the variable length fields.
	 */
	if ((name = (char *) malloc((size_t) (name_len + 1))) &&
	    (mod_name = (char *) malloc((size_t) (mod_name_len + 1))) &&
	    (!key_len ||
	     (pkey->key_data_contents[0] = 
	      (krb5_octet *) malloc((size_t) (key_len + 1)))) &&
	    (!alt_key_len ||
	     (akey->key_data_contents[0] = 
	      (krb5_octet *) malloc((size_t) (alt_key_len + 1)))) &&
	    (!salt_len ||
	     (pkey->key_data_contents[1] = 
	      (krb5_octet *) malloc((size_t) (salt_len + 1)))) &&
	    (!alt_salt_len ||
	     (akey->key_data_contents[1] = 
	      (krb5_octet *) malloc((size_t) (alt_salt_len + 1))))
	    ) {
	    error = 0;

	    /* Read the principal name */
	    if (read_string(filep, name, name_len, linenop)) {
		try2read = read_name_string;
		error++;
	    }
	    /* Read the key type */
	    if (!error && (fscanf(filep, "\t%d\t", &tmpint1) != 1)) {
		try2read = read_key_type;
		error++;
	    }
	    pkey->key_data_type[0] = tmpint1;
	    /* Read the old format key */
	    if (!error && read_octet_string(filep,
					    pkey->key_data_contents[0],
					    pkey->key_data_length[0])) {
		try2read = read_key_data;
		error++;
	    }
	    /* convert to a new format key */
	    /* the encrypted version is stored as the unencrypted key length
	       (4 bytes, MSB first) followed by the encrypted key. */
	    if ((pkey->key_data_length[0] > 4)
		&& (pkey->key_data_contents[0][0] == 0)
		&& (pkey->key_data_contents[0][1] == 0)) {
	      /* this really does look like an old key, so drop and swap */
	      /* the *new* length is 2 bytes, LSB first, sigh. */
	      size_t shortlen = pkey->key_data_length[0]-4+2;
	      krb5_octet *shortcopy = (krb5_octet *) malloc(shortlen);
	      krb5_octet *origdata = pkey->key_data_contents[0];
	      shortcopy[0] = origdata[3];
	      shortcopy[1] = origdata[2];
	      memcpy(shortcopy+2,origdata+4,shortlen-2);
	      free(origdata);
	      pkey->key_data_length[0] = shortlen;
	      pkey->key_data_contents[0] = shortcopy;
	    }
	      
	    /* Read principal attributes */
	    if (!error && (fscanf(filep,
				  "\t%u\t%u\t%u\t%u\t%u\t%u\t%u\t%u\t%u\t%u\t",
				  &tmpint1, &dbent.max_life,
				  &dbent.max_renewable_life,
				  &tmpint2, &dbent.expiration,
				  &dbent.pw_expiration, &last_pwd_change,
				  &dbent.last_success, &dbent.last_failed,
				  &tmpint3) != 10)) {
		try2read = read_pr_data1;
		error++;
	    }
	    pkey->key_data_kvno = tmpint1;
	    dbent.fail_auth_count = tmpint3;
	    /* Read modifier name */
	    if (!error && read_string(filep,
				      mod_name,
				      mod_name_len,
				      linenop)) {
		try2read = read_mod_name;
		error++;
	    }
	    /* Read second set of attributes */
	    if (!error && (fscanf(filep, "\t%u\t%u\t%u\t",
				  &mod_date, &dbent.attributes,
				  &tmpint1) != 3)) {
		try2read = read_pr_data2;
		error++;
	    }
	    pkey->key_data_type[1] = tmpint1;
	    /* Read salt data */
	    if (!error && read_octet_string(filep,
					    pkey->key_data_contents[1],
					    pkey->key_data_length[1])) {
		try2read = read_salt_data;
		error++;
	    }
	    /* Read alternate key type */
	    if (!error && (fscanf(filep, "\t%u\t", &tmpint1) != 1)) {
		try2read = read_akey_type;
		error++;
	    }
	    akey->key_data_type[0] = tmpint1;
	    /* Read alternate key */
	    if (!error && read_octet_string(filep,
					    akey->key_data_contents[0],
					    akey->key_data_length[0])) {
		try2read = read_akey_data;
		error++;
	    }

	    /* convert to a new format key */
	    /* the encrypted version is stored as the unencrypted key length
	       (4 bytes, MSB first) followed by the encrypted key. */
	    if ((akey->key_data_length[0] > 4)
		&& (akey->key_data_contents[0][0] == 0)
		&& (akey->key_data_contents[0][1] == 0)) {
	      /* this really does look like an old key, so drop and swap */
	      /* the *new* length is 2 bytes, LSB first, sigh. */
	      size_t shortlen = akey->key_data_length[0]-4+2;
	      krb5_octet *shortcopy = (krb5_octet *) malloc(shortlen);
	      krb5_octet *origdata = akey->key_data_contents[0];
	      shortcopy[0] = origdata[3];
	      shortcopy[1] = origdata[2];
	      memcpy(shortcopy+2,origdata+4,shortlen-2);
	      free(origdata);
	      akey->key_data_length[0] = shortlen;
	      akey->key_data_contents[0] = shortcopy;
	    }
	      
	    /* Read alternate salt type */
	    if (!error && (fscanf(filep, "\t%u\t", &tmpint1) != 1)) {
		try2read = read_asalt_type;
		error++;
	    }
	    akey->key_data_type[1] = tmpint1;
	    /* Read alternate salt data */
	    if (!error && read_octet_string(filep,
					    akey->key_data_contents[1],
					    akey->key_data_length[1])) {
		try2read = read_asalt_data;
		error++;
	    }
	    /* Read expansion data - discard it */
	    if (!error) {
		for (i=0; i<8; i++) {
		    if (fscanf(filep, "\t%u", &tmpint1) != 1) {
			try2read = read_exp_data;
			error++;
			break;
		    }
		}
		if (!error)
		    find_record_end(filep, fname, *linenop);
	    }
	
	    /*
	     * If no error, then we're done reading.  Now parse the names
	     * and store the database dbent.
	     */
	    if (!error) {
		if (!(kret = krb5_parse_name(kcontext,
					     name,
					     &dbent.princ))) {
		    if (!(kret = krb5_parse_name(kcontext,
						 mod_name,
						 &mod_princ))) {
			if (!(kret =
			      krb5_dbe_update_mod_princ_data(kcontext,
							     &dbent,
							     mod_date,
							     mod_princ)) &&
			    !(kret =
			      krb5_dbe_update_last_pwd_change(kcontext,
							      &dbent,
							      last_pwd_change))) {
			    int one = 1;

			    dbent.len = KRB5_KDB_V1_BASE_LENGTH;
			    pkey->key_data_ver = (pkey->key_data_type[1] || pkey->key_data_length[1]) ?
				2 : 1;
			    akey->key_data_ver = (akey->key_data_type[1] || akey->key_data_length[1]) ?
				2 : 1;
			    if ((pkey->key_data_type[0] ==
				 akey->key_data_type[0]) &&
				(pkey->key_data_type[1] ==
				 akey->key_data_type[1]))
				dbent.n_key_data--;
			    else if ((akey->key_data_type[0] == 0)
				     && (akey->key_data_length[0] == 0)
				     && (akey->key_data_type[1] == 0)
				     && (akey->key_data_length[1] == 0))
			        dbent.n_key_data--;

			    dbent.mask = KADM5_LOAD | KADM5_PRINCIPAL | KADM5_ATTRIBUTES |
				KADM5_MAX_LIFE | KADM5_MAX_RLIFE | KADM5_KEY_DATA |
				KADM5_PRINC_EXPIRE_TIME | KADM5_LAST_SUCCESS |
				KADM5_LAST_FAILED | KADM5_FAIL_AUTH_COUNT;

			    if ((kret = krb5_db_put_principal(kcontext,
							      &dbent,
							      &one)) ||
				(one != 1)) {
				fprintf(stderr, store_err_fmt,
					fname, *linenop, name,
					error_message(kret));
				error++;
			    }
			    else {
				if (verbose)
				    fprintf(stderr, add_princ_fmt, name);
				retval = 0;
			    }
			    dbent.n_key_data = 2;
			}
			krb5_free_principal(kcontext, mod_princ);
		    }
		    else {
			fprintf(stderr, parse_err_fmt, 
				fname, *linenop, mod_name, 
				error_message(kret));
			error++;
		    }
		}
		else {
		    fprintf(stderr, parse_err_fmt,
			    fname, *linenop, name, error_message(kret));
		    error++;
		}
	    }
	    else {
		fprintf(stderr, read_err_fmt, fname, *linenop, try2read);
	    }
	}
	else {
	    fprintf(stderr, no_mem_fmt, fname, *linenop);
	}

	krb5_db_free_principal(kcontext, &dbent, 1);
	if (mod_name)
	    free(mod_name);
	if (name)
	    free(name);
    }
    else {
	if (nmatched != EOF)
	    fprintf(stderr, rhead_err_fmt, fname, *linenop);
	else
	    retval = -1;
    }
    return(retval);
}

/*
 * process_k5beta6_record()	- Handle a dump record in krb5b6 format.
 *
 * Returns -1 for end of file, 0 for success and 1 for failure.
 */
static int
process_k5beta6_record(fname, kcontext, filep, verbose, linenop)
    char		*fname;
    krb5_context	kcontext;
    FILE		*filep;
    int			verbose;
    int			*linenop;
{
    int			retval;
    krb5_db_entry	dbentry;
    krb5_int32		t1, t2, t3, t4, t5, t6, t7, t8, t9;
    int			nread;
    int			error;
    int			i, j, one;
    char		*name;
    krb5_key_data	*kp, *kdatap;
    krb5_tl_data	**tlp, *tl;
    krb5_octet 		*op;
    krb5_error_code	kret;
    const char		*try2read;

    try2read = (char *) NULL;
    memset((char *) &dbentry, 0, sizeof(dbentry));
    (*linenop)++;
    retval = 1;
    name = (char *) NULL;
    kp = (krb5_key_data *) NULL;
    op = (krb5_octet *) NULL;
    error = 0;
    kret = 0;
    nread = fscanf(filep, "%d\t%d\t%d\t%d\t%d\t", &t1, &t2, &t3, &t4, &t5);
    if (nread == 5) {
	/* Get memory for flattened principal name */
	if (!(name = (char *) malloc((size_t) t2 + 1)))
	    error++;

	/* Get memory for and form tagged data linked list */
	tlp = &dbentry.tl_data;
	for (i=0; i<t3; i++) {
	    if ((*tlp = (krb5_tl_data *) malloc(sizeof(krb5_tl_data)))) {
		memset(*tlp, 0, sizeof(krb5_tl_data));
		tlp = &((*tlp)->tl_data_next);
		dbentry.n_tl_data++;
	    }
	    else {
		error++;
		break;
	    }
	}

	/* Get memory for key list */
	if (t4 && !(kp = (krb5_key_data *) malloc((size_t)
						  (t4*sizeof(krb5_key_data)))))
	    error++;

	/* Get memory for extra data */
	if (t5 && !(op = (krb5_octet *) malloc((size_t) t5)))
	    error++;

	if (!error) {
	    dbentry.len = t1;
	    dbentry.n_key_data = t4;
	    dbentry.e_length = t5;
	    if (kp) {
		memset(kp, 0, (size_t) (t4*sizeof(krb5_key_data)));
		dbentry.key_data = kp;
		kp = (krb5_key_data *) NULL;
	    }
	    if (op) {
		memset(op, 0, (size_t) t5);
		dbentry.e_data = op;
		op = (krb5_octet *) NULL;
	    }

	    /* Read in and parse the principal name */
	    if (!read_string(filep, name, t2, linenop) &&
		!(kret = krb5_parse_name(kcontext, name, &dbentry.princ))) {

		/* Get the fixed principal attributes */
		nread = fscanf(filep, "%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t",
			       &t2, &t3, &t4, &t5, &t6, &t7, &t8, &t9);
		if (nread == 8) {
		    dbentry.attributes = (krb5_flags) t2;
		    dbentry.max_life = (krb5_deltat) t3;
		    dbentry.max_renewable_life = (krb5_deltat) t4;
		    dbentry.expiration = (krb5_timestamp) t5;
		    dbentry.pw_expiration = (krb5_timestamp) t6;
		    dbentry.last_success = (krb5_timestamp) t7;
		    dbentry.last_failed = (krb5_timestamp) t8;
		    dbentry.fail_auth_count = (krb5_kvno) t9;
		    dbentry.mask = KADM5_LOAD | KADM5_PRINCIPAL | KADM5_ATTRIBUTES |
			KADM5_MAX_LIFE | KADM5_MAX_RLIFE |
			KADM5_PRINC_EXPIRE_TIME | KADM5_LAST_SUCCESS |
			KADM5_LAST_FAILED | KADM5_FAIL_AUTH_COUNT;
		} else {
		    try2read = read_nint_data;
		    error++;
		}

		/*
		 * Get the tagged data.
		 *
		 * Really, this code ought to discard tl data types
		 * that it knows are special to the current version
		 * and were not supported in the previous version.
		 * But it's a pain to implement that here, and doing
		 * it at dump time has almost as good an effect, so
		 * that's what I did.  [krb5-admin/89]
		 */
		if (!error && dbentry.n_tl_data) {
		    for (tl = dbentry.tl_data; tl; tl = tl->tl_data_next) {
			nread = fscanf(filep, "%d\t%d\t", &t1, &t2);
			if (nread == 2) {
			    tl->tl_data_type = (krb5_int16) t1;
			    tl->tl_data_length = (krb5_int16) t2;
			    if (tl->tl_data_length) {
				if (!(tl->tl_data_contents =
				      (krb5_octet *) malloc((size_t) t2+1)) ||
				    read_octet_string(filep,
						      tl->tl_data_contents,
						      t2)) {
				    try2read = read_tcontents;
				    error++;
				    break;
				}
				/* test to set mask fields */
				if (t1 == KRB5_TL_KADM_DATA) {
				    XDR xdrs;
				    osa_princ_ent_rec osa_princ_ent;

				    /* 
				     * Assuming aux_attributes will always be
				     * there
				     */
				    dbentry.mask |= KADM5_AUX_ATTRIBUTES;

				    /* test for an actual policy reference */
				    memset(&osa_princ_ent, 0, sizeof(osa_princ_ent));
				    xdrmem_create(&xdrs, (char *)tl->tl_data_contents,
					    tl->tl_data_length, XDR_DECODE);
				    if (xdr_osa_princ_ent_rec(&xdrs, &osa_princ_ent) &&
					    (osa_princ_ent.aux_attributes & KADM5_POLICY) &&
					    osa_princ_ent.policy != NULL) {

					dbentry.mask |= KADM5_POLICY;
					kdb_free_entry(NULL, NULL, &osa_princ_ent);
				    }
				    xdr_destroy(&xdrs);
				}
			    }
			    else {
				/* Should be a null field */
				nread = fscanf(filep, "%d", &t9);
				if ((nread != 1) || (t9 != -1)) {
				    error++;
				    try2read = read_tcontents;
				    break;
				}
			    }
			}
			else {
			    try2read = read_ttypelen;
			    error++;
			    break;
			}
		    }
		    if (!error)
			dbentry.mask |= KADM5_TL_DATA;
		}

		/* Get the key data */
		if (!error && dbentry.n_key_data) {
		    for (i=0; !error && (i<dbentry.n_key_data); i++) {
			kdatap = &dbentry.key_data[i];
			nread = fscanf(filep, "%d\t%d\t", &t1, &t2);
			if (nread == 2) {
			    kdatap->key_data_ver = (krb5_int16) t1;
			    kdatap->key_data_kvno = (krb5_int16) t2;

			    for (j=0; j<t1; j++) {
				nread = fscanf(filep, "%d\t%d\t", &t3, &t4);
				if (nread == 2) {
				    kdatap->key_data_type[j] = t3;
				    kdatap->key_data_length[j] = t4;
				    if (t4) {
					if (!(kdatap->key_data_contents[j] =
					      (krb5_octet *)
					      malloc((size_t) t4+1)) ||
					    read_octet_string(filep,
							      kdatap->key_data_contents[j],
							      t4)) {
					    try2read = read_kcontents;
					    error++;
					    break;
					}
				    }
				    else {
					/* Should be a null field */
					nread = fscanf(filep, "%d", &t9);
					if ((nread != 1) || (t9 != -1)) {
					    error++;
					    try2read = read_kcontents;
					    break;
					}
				    }
				}
				else {
				    try2read = read_ktypelen;
				    error++;
				    break;
				}
			    }
			}
		    }
		    if (!error)
			dbentry.mask |= KADM5_KEY_DATA;
		}

		/* Get the extra data */
		if (!error && dbentry.e_length) {
		    if (read_octet_string(filep,
					  dbentry.e_data,
					  (int) dbentry.e_length)) {
			try2read = read_econtents;
			error++;
		    }
		}
		else {
		    nread = fscanf(filep, "%d", &t9);
		    if ((nread != 1) || (t9 != -1)) {
			error++;
			try2read = read_econtents;
		    }
		}

		/* Finally, find the end of the record. */
		if (!error)
		    find_record_end(filep, fname, *linenop);

		/*
		 * We have either read in all the data or choked.
		 */
		if (!error) {
		    one = 1;
		    if ((kret = krb5_db_put_principal(kcontext,
						      &dbentry,
						      &one))) {
			fprintf(stderr, store_err_fmt,
				fname, *linenop,
				name, error_message(kret));
		    }
		    else {
			if (verbose)
			    fprintf(stderr, add_princ_fmt, name);
			retval = 0;
		    }
		}
		else {
		    fprintf(stderr, read_err_fmt, fname, *linenop, try2read);
		}
	    }
	    else {
		if (kret)
		    fprintf(stderr, parse_err_fmt,
			    fname, *linenop, name, error_message(kret));
		else
		    fprintf(stderr, no_mem_fmt, fname, *linenop);
	    }
	}
	else {
	    fprintf(stderr, rhead_err_fmt, fname, *linenop);
	}

	if (op)
	    free(op);
	if (kp)
	    free(kp);
	if (name)
	    free(name);
	krb5_db_free_principal(kcontext, &dbentry, 1);
    }
    else {
	if (nread == EOF)
	    retval = -1;
    }
    return(retval);
}

static int 
process_k5beta7_policy(fname, kcontext, filep, verbose, linenop, pol_db)
    char		*fname;
    krb5_context	kcontext;
    FILE		*filep;
    int			verbose;
    int			*linenop;
    void *pol_db;
{
    osa_policy_ent_rec rec;
    char namebuf[1024];
    int nread, ret;

    (*linenop)++;
    rec.name = namebuf;

    nread = fscanf(filep, "%1024s\t%d\t%d\t%d\t%d\t%d\t%d", rec.name,
		   &rec.pw_min_life, &rec.pw_max_life,
		   &rec.pw_min_length, &rec.pw_min_classes,
		   &rec.pw_history_num, &rec.policy_refcnt);
    if (nread == EOF)
	 return -1;
    else if (nread != 7) {
	 fprintf(stderr, "cannot parse policy on line %d (%d read)\n",
		 *linenop, nread);
	 return 1;
    }

    if ((ret = krb5_db_create_policy(kcontext, &rec))) {
	 if (ret &&
	     ((ret = krb5_db_put_policy(kcontext, &rec)))) {
	      fprintf(stderr, "cannot create policy on line %d: %s\n",
		      *linenop, error_message(ret));
	      return 1;
	 }
    }
    if (verbose)
	 fprintf(stderr, "created policy %s\n", rec.name);
    
    return 0;
}

/*
 * process_k5beta7_record()	- Handle a dump record in krb5b7 format.
 *
 * Returns -1 for end of file, 0 for success and 1 for failure.
 */
static int
process_k5beta7_record(fname, kcontext, filep, verbose, linenop)
    char		*fname;
    krb5_context	kcontext;
    FILE		*filep;
    int			verbose;
    int			*linenop;
{
     int nread;
     char rectype[100];

     nread = fscanf(filep, "%100s\t", rectype);
     if (nread == EOF)
	  return -1;
     else if (nread != 1)
	  return 1;
     if (strcmp(rectype, "princ") == 0)
	  process_k5beta6_record(fname, kcontext, filep, verbose,
				 linenop);
     else if (strcmp(rectype, "policy") == 0)
	  process_k5beta7_policy(fname, kcontext, filep, verbose,
				 linenop);
     else {
	  fprintf(stderr, "unknown record type \"%s\" on line %d\n",
		  rectype, *linenop);
	  return 1;
     }

     return 0;
}

/*
 * process_ov_record()	- Handle a dump record in OpenV*Secure 1.0 format.
 *
 * Returns -1 for end of file, 0 for success and 1 for failure.
 */
static int
process_ov_record(fname, kcontext, filep, verbose, linenop)
    char		*fname;
    krb5_context	kcontext;
    FILE		*filep;
    int			verbose;
    int			*linenop;
{
     int nread;
     char rectype[100];

     nread = fscanf(filep, "%100s\t", rectype);
     if (nread == EOF)
	  return -1;
     else if (nread != 1)
	  return 1;
     if (strcmp(rectype, "princ") == 0)
	  process_ov_principal(fname, kcontext, filep, verbose,
			       linenop);
     else if (strcmp(rectype, "policy") == 0)
	  process_k5beta7_policy(fname, kcontext, filep, verbose,
				 linenop);
     else if (strcmp(rectype, "End") == 0)
	  return -1;
     else {
	  fprintf(stderr, "unknown record type \"%s\" on line %d\n",
		  rectype, *linenop);
	  return 1;
     }

     return 0;
}

/*
 * restore_dump()	- Restore the database from any version dump file.
 */
static int
restore_dump(programname, kcontext, dumpfile, f, verbose, dump)
    char		*programname;
    krb5_context	kcontext;
    char		*dumpfile;
    FILE		*f;
    int			verbose;
    dump_version	*dump;
{
    int		error;	
    int		lineno;

    error = 0;
    lineno = 1;

    /*
     * Process the records.
     */
    while (!(error = (*dump->load_record)(dumpfile,
					  kcontext, 
					  f,
					  verbose,
					  &lineno)))
	 ;
    if (error != -1)
	 fprintf(stderr, err_line_fmt, programname, lineno, dumpfile);
    else
	 error = 0;

    return(error);
}

/*
 * Usage: load_db [-old] [-ov] [-b6] [-b7] [-verbose] [-update] [-hash]
 *		filename
 */
void
load_db(argc, argv)
    int		argc;
    char	**argv;
{
    kadm5_config_params newparams;
    krb5_error_code	kret;
    krb5_context	kcontext;
    FILE		*f;
    extern char		*optarg;
    extern int		optind;
    char		*programname;
    char		*dumpfile;
    char		*dbname;
    char		*dbname_tmp;
    char		buf[BUFSIZ];
    dump_version	*load;
    int			update, verbose;
    krb5_int32		crflags;
    int			aindex;
    int			db_locked = 0;
    char		iheader[MAX_HEADER];
    kdb_log_context	*log_ctx;
    int			add_update = 1;
    uint32_t		caller, last_sno, last_seconds, last_useconds;

    /*
     * Parse the arguments.
     */
    programname = argv[0];
    if (strrchr(programname, (int) '/'))
	programname = strrchr(argv[0], (int) '/') + 1;
    dumpfile = (char *) NULL;
    dbname = global_params.dbname;
    load = NULL;
    update = 0;
    verbose = 0;
    crflags = KRB5_KDB_CREATE_BTREE;
    exit_status = 0;
    dbname_tmp = (char *) NULL;
    log_ctx = util_context->kdblog_context;

    for (aindex = 1; aindex < argc; aindex++) {
	if (!strcmp(argv[aindex], oldoption))
	     load = &old_version;
	else if (!strcmp(argv[aindex], b6option))
	     load = &beta6_version;
	else if (!strcmp(argv[aindex], b7option))
	     load = &beta7_version;
	else if (!strcmp(argv[aindex], ovoption))
	     load = &ov_version;
	else if (!strcmp(argv[aindex], ipropoption)) {
	    if (log_ctx && log_ctx->iproprole) {
		load = &iprop_version;
		add_update = FALSE;
	    } else {
		fprintf(stderr, _("Iprop not enabled\n"));
		exit_status++;
		return;
	    }
	} else if (!strcmp(argv[aindex], verboseoption))
	    verbose = 1;
	else if (!strcmp(argv[aindex], updateoption))
	    update = 1;
	else if (!strcmp(argv[aindex], hashoption)) {
	    if (!add_db_arg("hash=true")) {
		com_err(progname, ENOMEM, "while parsing command arguments\n");
		exit(1);
	    }
	} else
	    break;
    }
    if ((argc - aindex) != 1) {
	usage();
	return;
    }
    dumpfile = argv[aindex];

    if (!(dbname_tmp = (char *) malloc(strlen(dbname)+
				       strlen(dump_tmptrail)+1))) {
	fprintf(stderr, no_name_mem_fmt, argv[0]);
	exit_status++;
	return;
    }
    strcpy(dbname_tmp, dbname);
    strcat(dbname_tmp, dump_tmptrail);

    /*
     * Initialize the Kerberos context and error tables.
     */
    if ((kret = kadm5_init_krb5_context(&kcontext))) {
	fprintf(stderr, ctx_err_fmt, programname);
	free(dbname_tmp);
	exit_status++;
	return;
    }

    if( (kret = krb5_set_default_realm(kcontext, util_context->default_realm)) )
    {
	fprintf(stderr, "%s: Unable to set the default realm\n", programname);
	free(dbname_tmp);
	exit_status++;
	return;
    }

    if (log_ctx && log_ctx->iproprole)
	kcontext->kdblog_context = log_ctx;

    /*
     * Open the dumpfile
     */
    if (dumpfile) {
	if ((f = fopen(dumpfile, "r")) == NULL) {
	     fprintf(stderr, dfile_err_fmt, programname, dumpfile,
		     error_message(errno)); 
	     exit_status++;
	     return;
	}
	if ((kret = krb5_lock_file(kcontext, fileno(f),
				   KRB5_LOCKMODE_SHARED))) {
	     fprintf(stderr, "%s: Cannot lock %s: %s\n", programname,
		     dumpfile, error_message(errno));
	     exit_status++;
	     return;
	}
    } else
	f = stdin;

    /*
     * Auto-detect dump version if we weren't told, verify if we
     * were told.
     */
    fgets(buf, sizeof(buf), f);
    if (load) {
	 /* only check what we know; some headers only contain a prefix */
	 if (strncmp(buf, load->header, strlen(load->header)) != 0) {
	      fprintf(stderr, head_bad_fmt, programname, dumpfile);
	      exit_status++;
	      if (dumpfile) fclose(f);
	      return;
	 }
    } else {
	 /* perhaps this should be in an array, but so what? */
	 if (strcmp(buf, old_version.header) == 0)
	      load = &old_version;
	 else if (strcmp(buf, beta6_version.header) == 0)
	      load = &beta6_version;
	 else if (strcmp(buf, beta7_version.header) == 0)
	      load = &beta7_version;
	 else if (strcmp(buf, r1_3_version.header) == 0)
	      load = &r1_3_version;
	 else if (strncmp(buf, ov_version.header,
			  strlen(ov_version.header)) == 0)
	      load = &ov_version;
	 else {
	      fprintf(stderr, head_bad_fmt, programname, dumpfile);
	      exit_status++;
	      if (dumpfile) fclose(f);
	      return;
	 }
    }
    if (load->updateonly && !update) {
	 fprintf(stderr, "%s: dump version %s can only be loaded with the "
		 "-update flag\n", programname, load->name);
	 exit_status++;
	 return;
    }

    /*
     * Cons up params for the new databases.  If we are not in update
     * mode, we create an alternate database and then promote it to
     * be the live db.
     */
    newparams = global_params;
    if (! update) {
	 newparams.mask |= KADM5_CONFIG_DBNAME;
	 newparams.dbname = dbname_tmp;

	 if ((kret = kadm5_get_config_params(kcontext, 1,
					     &newparams, &newparams))) {
	      com_err(argv[0], kret,
		      "while retreiving new configuration parameters");
	      exit_status++;
	      return;
	 }

	 if (!add_db_arg("temporary")) {
	     com_err(progname, ENOMEM, "computing parameters for database");
	     exit(1);
	 }
    }
    
    /*
     * If not an update restoration, create the database. otherwise open
     */
    if (!update) {
	if((kret = krb5_db_create(kcontext, db5util_db_args))) {
	    const char *emsg = krb5_get_error_message(kcontext, kret);
	    /* 
	     * See if something (like DAL KDB plugin) has set a specific error
	     * message and use that otherwise use default.
	     */

	    if (emsg != NULL) {
		fprintf(stderr, "%s: %s\n", programname, emsg);
		krb5_free_error_message (kcontext, emsg);
	    } else {
		fprintf(stderr, dbcreaterr_fmt,
			programname, dbname, error_message(kret));
	    }
	    exit_status++;
	    kadm5_free_config_params(kcontext, &newparams);
	    if (dumpfile) fclose(f);
	    return;
	}
    }
    else {
	    /*
	     * Initialize the database.
	     */
	    if ((kret = krb5_db_open(kcontext, db5util_db_args, 
				     KRB5_KDB_OPEN_RW | KRB5_KDB_SRV_TYPE_ADMIN))) {
		const char *emsg = krb5_get_error_message(kcontext, kret);
		/* 
		 * See if something (like DAL KDB plugin) has set a specific
		 * error message and use that otherwise use default.
		 */

		if (emsg != NULL) {
		    fprintf(stderr, "%s: %s\n", programname, emsg);
		    krb5_free_error_message (kcontext, emsg);
		} else {
		    fprintf(stderr, dbinit_err_fmt,
			    programname, error_message(kret));
		}
		exit_status++;
		goto error;
	    }
    }


    /*
     * If an update restoration, make sure the db is left unusable if
     * the update fails.
     */
    if ((kret = krb5_db_lock(kcontext, update?KRB5_DB_LOCKMODE_PERMANENT: KRB5_DB_LOCKMODE_EXCLUSIVE))) {
	/* 
	 * Ignore a not supported error since there is nothing to do about it
	 * anyway.
	 */
	if (kret != KRB5_PLUGIN_OP_NOTSUPP) {
	    fprintf(stderr, "%s: %s while permanently locking database\n",
		    programname, error_message(kret));
	    exit_status++;
	    goto error;
	}
    }
    else
	db_locked = 1;
    
    if (log_ctx && log_ctx->iproprole) {
	if (add_update)
	    caller = FKCOMMAND;
	else
	    caller = FKPROPD;

	if (ulog_map(kcontext, global_params.iprop_logfile,
		     global_params.iprop_ulogsize, caller, db5util_db_args)) {
	    fprintf(stderr, _("%s: Could not map log\n"),
		    programname);
	    exit_status++;
	    goto error;
	}

	/*
	 * We don't want to take out the ulog out from underneath
	 * kadmind so we reinit the header log.
	 *
	 * We also don't want to add to the update log since we
	 * are doing a whole sale replace of the db, because:
	 * 	we could easily exceed # of update entries
	 * 	we could implicity delete db entries during a replace
	 *	no advantage in incr updates when entire db is replaced
	 */
	if (!update) {
	    memset(log_ctx->ulog, 0, sizeof (kdb_hlog_t));

	    log_ctx->ulog->kdb_hmagic = KDB_ULOG_HDR_MAGIC;
	    log_ctx->ulog->db_version_num = KDB_VERSION;
	    log_ctx->ulog->kdb_state = KDB_STABLE;
	    log_ctx->ulog->kdb_block = ULOG_BLOCK;

	    log_ctx->iproprole = IPROP_NULL;

	    if (!add_update) {
		sscanf(buf, "%s %u %u %u", iheader, &last_sno,
		       &last_seconds, &last_useconds);

		log_ctx->ulog->kdb_last_sno = last_sno;
		log_ctx->ulog->kdb_last_time.seconds =
		    last_seconds;
		log_ctx->ulog->kdb_last_time.useconds =
		    last_useconds;
	    }
	}
    }

    if (restore_dump(programname, kcontext, (dumpfile) ? dumpfile : stdin_name,
		     f, verbose, load)) {
	 fprintf(stderr, restfail_fmt,
		 programname, load->name);
	 exit_status++;
    }

    if (!update && load->create_kadm5 &&
	((kret = kadm5_create_magic_princs(&newparams, kcontext)))) {
	 /* error message printed by create_magic_princs */
	 exit_status++;
    }
    
    if (db_locked && (kret = krb5_db_unlock(kcontext))) {
	 /* change this error? */
	 fprintf(stderr, dbunlockerr_fmt,
		 programname, dbname, error_message(kret));
	 exit_status++;
    }

#if 0
    if ((kret = krb5_db_fini(kcontext))) {
	 fprintf(stderr, close_err_fmt,
		 programname, error_message(kret));
	 exit_status++;
    }
#endif

    /* close policy db below */

    if (exit_status == 0 && !update) {
	kret = krb5_db_promote(kcontext, db5util_db_args);
	/* 
	 * Ignore a not supported error since there is nothing to do about it
	 * anyway.
	 */
	if (kret != 0 && kret != KRB5_PLUGIN_OP_NOTSUPP) {
	    fprintf(stderr, "%s: cannot make newly loaded database live (%s)\n",
		    programname, error_message(kret));
	    exit_status++;
	}
    }

error:
    /*
     * If not an update: if there was an error, destroy the temp database,
     * otherwise rename it into place.
     *
     * If an update: if there was no error, unlock the database.
     */
    if (!update) {
	 if (exit_status) {
	      kret = krb5_db_destroy(kcontext, db5util_db_args);
	      /* 
	       * Ignore a not supported error since there is nothing to do about
	       * it anyway.
	       */
	      if (kret != 0 && kret != KRB5_PLUGIN_OP_NOTSUPP) {
		   fprintf(stderr, dbdelerr_fmt,
			   programname, dbname, error_message(kret));
		   exit_status++;
	      }
	 }
    }

    if (dumpfile) {
	 (void) krb5_lock_file(kcontext, fileno(f), KRB5_LOCKMODE_UNLOCK);
	 fclose(f);
    }

    if (dbname_tmp)
	 free(dbname_tmp);
    krb5_free_context(kcontext);
}