File: kt_file.c

package info (click to toggle)
krb5 1.17-6
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 55,116 kB
  • sloc: ansic: 303,225; exp: 13,198; cpp: 9,731; python: 8,927; makefile: 7,178; sh: 6,279; perl: 2,289; asm: 1,460; yacc: 1,005; awk: 396; csh: 147; xml: 135; lisp: 104; sed: 41
file content (1650 lines) | stat: -rw-r--r-- 50,406 bytes parent folder | download
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
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/* lib/krb5/keytab/kt_file.c */
/*
 * Copyright 1990,1991,1995,2007,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.
 */
/*
 * Copyright (c) Hewlett-Packard Company 1991
 * Released to the Massachusetts Institute of Technology for inclusion
 * in the Kerberos source code distribution.
 *
 * Copyright 1990,1991 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.
 */

#ifndef LEAN_CLIENT

#include "k5-int.h"
#include "../os/os-proto.h"
#include <stdio.h>

/*
 * Information needed by internal routines of the file-based ticket
 * cache implementation.
 */


/*
 * Constants
 */

#define KRB5_KT_VNO_1   0x0501  /* krb v5, keytab version 1 (DCE compat) */
#define KRB5_KT_VNO     0x0502  /* krb v5, keytab version 2 (standard)  */

#define KRB5_KT_DEFAULT_VNO KRB5_KT_VNO

/*
 * Types
 */
typedef struct _krb5_ktfile_data {
    char *name;                 /* Name of the file */
    FILE *openf;                /* open file, if any. */
    char iobuf[BUFSIZ];         /* so we can zap it later */
    int version;                /* Version number of keytab */
    unsigned int iter_count;    /* Number of active iterators */
    long start_offset;          /* Starting offset after version */
    k5_mutex_t lock;            /* Protect openf, version */
} krb5_ktfile_data;

/*
 * Some limitations:
 *
 * If the file OPENF is left open between calls, we have an iterator
 * active, and OPENF is opened in read-only mode.  So, no changes
 * can be made via that handle.
 *
 * An advisory file lock is used while the file is open.  Thus,
 * multiple handles on the same underlying file cannot be used without
 * disrupting the locking in effect.
 *
 * The start_offset field is only valid if the file is open.  It will
 * almost certainly always be the same constant.  It's used so that
 * if an iterator is active, and we start another one, we don't have
 * to seek back to the start and re-read the version number to set
 * the position for the iterator.
 */

/*
 * Macros
 */
#define KTPRIVATE(id) ((krb5_ktfile_data *)(id)->data)
#define KTFILENAME(id) (((krb5_ktfile_data *)(id)->data)->name)
#define KTFILEP(id) (((krb5_ktfile_data *)(id)->data)->openf)
#define KTFILEBUFP(id) (((krb5_ktfile_data *)(id)->data)->iobuf)
#define KTVERSION(id) (((krb5_ktfile_data *)(id)->data)->version)
#define KTITERS(id) (((krb5_ktfile_data *)(id)->data)->iter_count)
#define KTSTARTOFF(id) (((krb5_ktfile_data *)(id)->data)->start_offset)
#define KTLOCK(id) k5_mutex_lock(&((krb5_ktfile_data *)(id)->data)->lock)
#define KTUNLOCK(id) k5_mutex_unlock(&((krb5_ktfile_data *)(id)->data)->lock)
#define KTCHECKLOCK(id) k5_mutex_assert_locked(&((krb5_ktfile_data *)(id)->data)->lock)

extern const struct _krb5_kt_ops krb5_ktf_ops;
extern const struct _krb5_kt_ops krb5_ktf_writable_ops;

static krb5_error_code KRB5_CALLCONV
krb5_ktfile_resolve(krb5_context, const char *, krb5_keytab *);

static krb5_error_code KRB5_CALLCONV
krb5_ktfile_get_name(krb5_context, krb5_keytab, char *, unsigned int);

static krb5_error_code KRB5_CALLCONV
krb5_ktfile_close(krb5_context, krb5_keytab);

static krb5_error_code KRB5_CALLCONV
krb5_ktfile_get_entry(krb5_context, krb5_keytab, krb5_const_principal,
                      krb5_kvno, krb5_enctype, krb5_keytab_entry *);

static krb5_error_code KRB5_CALLCONV
krb5_ktfile_start_seq_get(krb5_context, krb5_keytab, krb5_kt_cursor *);

static krb5_error_code KRB5_CALLCONV
krb5_ktfile_get_next(krb5_context, krb5_keytab, krb5_keytab_entry *,
                     krb5_kt_cursor *);

static krb5_error_code KRB5_CALLCONV
krb5_ktfile_end_get(krb5_context, krb5_keytab, krb5_kt_cursor *);

/* routines to be included on extended version (write routines) */
static krb5_error_code KRB5_CALLCONV
krb5_ktfile_add(krb5_context, krb5_keytab, krb5_keytab_entry *);

static krb5_error_code KRB5_CALLCONV
krb5_ktfile_remove(krb5_context, krb5_keytab, krb5_keytab_entry *);

static krb5_error_code
krb5_ktfileint_openr(krb5_context, krb5_keytab);

static krb5_error_code
krb5_ktfileint_openw(krb5_context, krb5_keytab);

static krb5_error_code
krb5_ktfileint_close(krb5_context, krb5_keytab);

static krb5_error_code
krb5_ktfileint_read_entry(krb5_context, krb5_keytab, krb5_keytab_entry *);

static krb5_error_code
krb5_ktfileint_write_entry(krb5_context, krb5_keytab, krb5_keytab_entry *);

static krb5_error_code
krb5_ktfileint_delete_entry(krb5_context, krb5_keytab, krb5_int32);

static krb5_error_code
krb5_ktfileint_internal_read_entry(krb5_context, krb5_keytab,
                                   krb5_keytab_entry *, krb5_int32 *);

static krb5_error_code
krb5_ktfileint_size_entry(krb5_context, krb5_keytab_entry *, krb5_int32 *);

static krb5_error_code
krb5_ktfileint_find_slot(krb5_context, krb5_keytab, krb5_int32 *,
                         krb5_int32 *);


/*
 * This is an implementation specific resolver.  It returns a keytab id
 * initialized with file keytab routines.
 */

static krb5_error_code KRB5_CALLCONV
krb5_ktfile_resolve(krb5_context context, const char *name,
                    krb5_keytab *id_out)
{
    krb5_ktfile_data *data = NULL;
    krb5_error_code err = ENOMEM;
    krb5_keytab id;

    *id_out = NULL;

    id = calloc(1, sizeof(*id));
    if (id == NULL)
        return ENOMEM;

    id->ops = &krb5_ktf_ops;
    data = calloc(1, sizeof(krb5_ktfile_data));
    if (data == NULL)
        goto cleanup;

    data->name = strdup(name);
    if (data->name == NULL)
        goto cleanup;

    err = k5_mutex_init(&data->lock);
    if (err)
        goto cleanup;

    data->openf = 0;
    data->version = 0;
    data->iter_count = 0;

    id->data = (krb5_pointer) data;
    id->magic = KV5M_KEYTAB;
    *id_out = id;
    return 0;
cleanup:
    if (data)
        free(data->name);
    free(data);
    free(id);
    return err;
}


/*
 * "Close" a file-based keytab and invalidate the id.  This means
 * free memory hidden in the structures.
 */

static krb5_error_code KRB5_CALLCONV
krb5_ktfile_close(krb5_context context, krb5_keytab id)
/*
 * This routine is responsible for freeing all memory allocated
 * for this keytab.  There are no system resources that need
 * to be freed nor are there any open files.
 *
 * This routine should undo anything done by krb5_ktfile_resolve().
 */
{
    free(KTFILENAME(id));
    zap(KTFILEBUFP(id), BUFSIZ);
    k5_mutex_destroy(&((krb5_ktfile_data *)id->data)->lock);
    free(id->data);
    id->ops = 0;
    free(id);
    return (0);
}

/* Return true if k1 is more recent than k2, applying wraparound heuristics. */
static krb5_boolean
more_recent(const krb5_keytab_entry *k1, const krb5_keytab_entry *k2)
{
    /*
     * If a small kvno was written at the same time or later than a large kvno,
     * the kvno probably wrapped at some boundary, so consider the small kvno
     * more recent.  Wraparound can happen due to pre-1.14 keytab file format
     * limitations (8-bit kvno storage), pre-1.14 kadmin protocol limitations
     * (8-bit kvno marshalling), or KDB limitations (16-bit kvno storage).
     */
    if (!ts_after(k2->timestamp, k1->timestamp) &&
        k1->vno < 128 && k2->vno > 240)
        return TRUE;
    if (!ts_after(k1->timestamp, k2->timestamp) &&
        k1->vno > 240 && k2->vno < 128)
        return FALSE;

    /* Otherwise do a simple version comparison. */
    return k1->vno > k2->vno;
}

/*
 * This is the get_entry routine for the file based keytab implementation.
 * It opens the keytab file, and either retrieves the entry or returns
 * an error.
 */

static krb5_error_code KRB5_CALLCONV
krb5_ktfile_get_entry(krb5_context context, krb5_keytab id,
                      krb5_const_principal principal, krb5_kvno kvno,
                      krb5_enctype enctype, krb5_keytab_entry *entry)
{
    krb5_keytab_entry cur_entry, new_entry;
    krb5_error_code kerror = 0;
    int found_wrong_kvno = 0;
    int was_open;
    char *princname;

    KTLOCK(id);

    if (KTFILEP(id) != NULL) {
        was_open = 1;

        if (fseek(KTFILEP(id), KTSTARTOFF(id), SEEK_SET) == -1) {
            KTUNLOCK(id);
            return errno;
        }
    } else {
        was_open = 0;

        /* Open the keyfile for reading */
        if ((kerror = krb5_ktfileint_openr(context, id))) {
            KTUNLOCK(id);
            return(kerror);
        }
    }

    /*
     * For efficiency and simplicity, we'll use a while true that
     * is exited with a break statement.
     */
    cur_entry.principal = 0;
    cur_entry.vno = 0;
    cur_entry.key.contents = 0;

    while (TRUE) {
        if ((kerror = krb5_ktfileint_read_entry(context, id, &new_entry)))
            break;

        /* by the time this loop exits, it must either free cur_entry,
           and copy new_entry there, or free new_entry.  Otherwise, it
           leaks. */

        /* if the principal isn't the one requested, free new_entry
           and continue to the next. */

        if (!krb5_principal_compare(context, principal, new_entry.principal)) {
            krb5_kt_free_entry(context, &new_entry);
            continue;
        }

        /* If the enctype is not ignored and doesn't match, free new_entry and
           continue to the next. */
        if (enctype != IGNORE_ENCTYPE && enctype != new_entry.key.enctype) {
            krb5_kt_free_entry(context, &new_entry);
            continue;
        }

        if (kvno == IGNORE_VNO || new_entry.vno == IGNORE_VNO) {
            /* If this entry is more recent (or the first match), free the
             * current and keep the new.  Otherwise, free the new. */
            if (cur_entry.principal == NULL ||
                more_recent(&new_entry, &cur_entry)) {
                krb5_kt_free_entry(context, &cur_entry);
                cur_entry = new_entry;
            } else {
                krb5_kt_free_entry(context, &new_entry);
            }
        } else {
            /*
             * If this kvno matches exactly, free the current, keep the new,
             * and break out.  If it matches the low 8 bits of the desired
             * kvno, remember the first match (because the recorded kvno may
             * have been truncated due to pre-1.14 keytab format or kadmin
             * protocol limitations) but keep looking for an exact match.
             * Otherwise, remember that we were here so we can return the right
             * error, and free the new.
             */
            if (new_entry.vno == kvno) {
                krb5_kt_free_entry(context, &cur_entry);
                cur_entry = new_entry;
                if (new_entry.vno == kvno)
                    break;
            } else if (new_entry.vno == (kvno & 0xff) &&
                       cur_entry.principal == NULL) {
                cur_entry = new_entry;
            } else {
                found_wrong_kvno++;
                krb5_kt_free_entry(context, &new_entry);
            }
        }
    }

    if (kerror == KRB5_KT_END) {
        if (cur_entry.principal)
            kerror = 0;
        else if (found_wrong_kvno)
            kerror = KRB5_KT_KVNONOTFOUND;
        else {
            kerror = KRB5_KT_NOTFOUND;
            if (krb5_unparse_name(context, principal, &princname) == 0) {
                k5_setmsg(context, kerror,
                          _("No key table entry found for %s"), princname);
                free(princname);
            }
        }
    }
    if (kerror) {
        if (was_open == 0)
            (void) krb5_ktfileint_close(context, id);
        KTUNLOCK(id);
        krb5_kt_free_entry(context, &cur_entry);
        return kerror;
    }
    if (was_open == 0 && (kerror = krb5_ktfileint_close(context, id)) != 0) {
        KTUNLOCK(id);
        krb5_kt_free_entry(context, &cur_entry);
        return kerror;
    }
    KTUNLOCK(id);
    *entry = cur_entry;
    return 0;
}

/*
 * Get the name of the file containing a file-based keytab.
 */

static krb5_error_code KRB5_CALLCONV
krb5_ktfile_get_name(krb5_context context, krb5_keytab id, char *name, unsigned int len)
/*
 * This routine returns the name of the name of the file associated with
 * this file-based keytab.  name is zeroed and the filename is truncated
 * to fit in name if necessary.  The name is prefixed with PREFIX:, so that
 * trt will happen if the name is passed back to resolve.
 */
{
    int result;

    memset(name, 0, len);
    result = snprintf(name, len, "%s:%s", id->ops->prefix, KTFILENAME(id));
    if (SNPRINTF_OVERFLOW(result, len))
        return(KRB5_KT_NAME_TOOLONG);
    return(0);
}

/*
 * krb5_ktfile_start_seq_get()
 */

static krb5_error_code KRB5_CALLCONV
krb5_ktfile_start_seq_get(krb5_context context, krb5_keytab id, krb5_kt_cursor *cursorp)
{
    krb5_error_code retval;
    long *fileoff;

    KTLOCK(id);

    if (KTITERS(id) == 0) {
        if ((retval = krb5_ktfileint_openr(context, id))) {
            KTUNLOCK(id);
            return retval;
        }
    }

    if (!(fileoff = (long *)malloc(sizeof(*fileoff)))) {
        if (KTITERS(id) == 0)
            krb5_ktfileint_close(context, id);
        KTUNLOCK(id);
        return ENOMEM;
    }
    *fileoff = KTSTARTOFF(id);
    *cursorp = (krb5_kt_cursor)fileoff;
    KTITERS(id)++;
    if (KTITERS(id) == 0) {
        /* Wrapped?!  */
        KTITERS(id)--;
        KTUNLOCK(id);
        k5_setmsg(context, KRB5_KT_IOERR, "Too many keytab iterators active");
        return KRB5_KT_IOERR;   /* XXX */
    }
    KTUNLOCK(id);

    return 0;
}

/*
 * krb5_ktfile_get_next()
 */

static krb5_error_code KRB5_CALLCONV
krb5_ktfile_get_next(krb5_context context, krb5_keytab id, krb5_keytab_entry *entry, krb5_kt_cursor *cursor)
{
    long *fileoff = (long *)*cursor;
    krb5_keytab_entry cur_entry;
    krb5_error_code kerror;

    KTLOCK(id);
    if (KTFILEP(id) == NULL) {
        KTUNLOCK(id);
        return KRB5_KT_IOERR;
    }
    if (fseek(KTFILEP(id), *fileoff, 0) == -1) {
        KTUNLOCK(id);
        return KRB5_KT_END;
    }
    if ((kerror = krb5_ktfileint_read_entry(context, id, &cur_entry))) {
        KTUNLOCK(id);
        return kerror;
    }
    *fileoff = ftell(KTFILEP(id));
    *entry = cur_entry;
    KTUNLOCK(id);
    return 0;
}

/*
 * krb5_ktfile_end_get()
 */

static krb5_error_code KRB5_CALLCONV
krb5_ktfile_end_get(krb5_context context, krb5_keytab id, krb5_kt_cursor *cursor)
{
    krb5_error_code kerror;

    free(*cursor);
    KTLOCK(id);
    KTITERS(id)--;
    if (KTFILEP(id) != NULL && KTITERS(id) == 0)
        kerror = krb5_ktfileint_close(context, id);
    else
        kerror = 0;
    KTUNLOCK(id);
    return kerror;
}

/*
 * ser_ktf.c - Serialize keytab file context for subsequent reopen.
 */

static const char ktfile_def_name[] = ".";

/*
 * Routines to deal with externalizing krb5_keytab for [WR]FILE: variants.
 *      krb5_ktf_keytab_size();
 *      krb5_ktf_keytab_externalize();
 *      krb5_ktf_keytab_internalize();
 */
static krb5_error_code
krb5_ktf_keytab_size(krb5_context, krb5_pointer, size_t *);

static krb5_error_code
krb5_ktf_keytab_externalize(krb5_context, krb5_pointer, krb5_octet **,
                            size_t *);

static krb5_error_code
krb5_ktf_keytab_internalize(krb5_context,krb5_pointer *, krb5_octet **,
                            size_t *);

/*
 * Serialization entry for this type.
 */
const krb5_ser_entry krb5_ktfile_ser_entry = {
    KV5M_KEYTAB,                        /* Type                 */
    krb5_ktf_keytab_size,               /* Sizer routine        */
    krb5_ktf_keytab_externalize,        /* Externalize routine  */
    krb5_ktf_keytab_internalize         /* Internalize routine  */
};

/*
 * krb5_ktf_keytab_size()       - Determine the size required to externalize
 *                                this krb5_keytab variant.
 */
static krb5_error_code
krb5_ktf_keytab_size(krb5_context kcontext, krb5_pointer arg, size_t *sizep)
{
    krb5_error_code     kret;
    krb5_keytab         keytab;
    size_t              required;
    krb5_ktfile_data    *ktdata;

    kret = EINVAL;
    if ((keytab = (krb5_keytab) arg)) {
        /*
         * Saving FILE: variants of krb5_keytab requires at minimum:
         *      krb5_int32      for KV5M_KEYTAB
         *      krb5_int32      for length of keytab name.
         *      krb5_int32      for file status.
         *      krb5_int32      for file position.
         *      krb5_int32      for file position.
         *      krb5_int32      for version.
         *      krb5_int32      for KV5M_KEYTAB
         */
        required = sizeof(krb5_int32) * 7;
        if (keytab->ops && keytab->ops->prefix)
            required += (strlen(keytab->ops->prefix)+1);

        /*
         * The keytab name is formed as follows:
         *      <prefix>:<name>
         * If there's no name, we use a default name so that we have something
         * to call krb5_keytab_resolve with.
         */
        ktdata = (krb5_ktfile_data *) keytab->data;
        required += strlen((ktdata && ktdata->name) ?
                           ktdata->name : ktfile_def_name);
        kret = 0;

        if (!kret)
            *sizep += required;
    }
    return(kret);
}

/*
 * krb5_ktf_keytab_externalize()        - Externalize the krb5_keytab.
 */
static krb5_error_code
krb5_ktf_keytab_externalize(krb5_context kcontext, krb5_pointer arg, krb5_octet **buffer, size_t *lenremain)
{
    krb5_error_code     kret;
    krb5_keytab         keytab;
    size_t              required;
    krb5_octet          *bp;
    size_t              remain;
    krb5_ktfile_data    *ktdata;
    krb5_int32          file_is_open;
    int64_t             file_pos;
    char                *ktname;
    const char          *fnamep;

    required = 0;
    bp = *buffer;
    remain = *lenremain;
    kret = EINVAL;
    if ((keytab = (krb5_keytab) arg)) {
        kret = ENOMEM;
        if (!krb5_ktf_keytab_size(kcontext, arg, &required) &&
            (required <= remain)) {
            /* Our identifier */
            (void) krb5_ser_pack_int32(KV5M_KEYTAB, &bp, &remain);

            ktdata = (krb5_ktfile_data *) keytab->data;
            file_is_open = 0;
            file_pos = 0;

            /* Calculate the length of the name */
            if (ktdata && ktdata->name)
                fnamep = ktdata->name;
            else
                fnamep = ktfile_def_name;

            if (keytab->ops && keytab->ops->prefix) {
                if (asprintf(&ktname, "%s:%s", keytab->ops->prefix, fnamep) < 0)
                    ktname = NULL;
            } else
                ktname = strdup(fnamep);

            if (ktname) {
                /* Fill in the file-specific keytab information. */
                if (ktdata) {
                    if (ktdata->openf) {
                        long    fpos;
                        int     fflags = 0;

                        file_is_open = 1;
#if !defined(_WIN32)
                        fflags = fcntl(fileno(ktdata->openf), F_GETFL, 0);
                        if (fflags > 0)
                            file_is_open |= ((fflags & O_ACCMODE) << 1);
#else
                        file_is_open = 0;
#endif
                        fpos = ftell(ktdata->openf);
                        file_pos = fpos; /* XX range check? */
                    }
                }

                /* Put the length of the file name */
                (void) krb5_ser_pack_int32((krb5_int32) strlen(ktname),
                                           &bp, &remain);

                /* Put the name */
                (void) krb5_ser_pack_bytes((krb5_octet *) ktname,
                                           strlen(ktname),
                                           &bp, &remain);

                /* Put the file open flag */
                (void) krb5_ser_pack_int32(file_is_open, &bp, &remain);

                /* Put the file position */
                (void) krb5_ser_pack_int64(file_pos, &bp, &remain);

                /* Put the version */
                (void) krb5_ser_pack_int32((krb5_int32) ((ktdata) ?
                                                         ktdata->version : 0),
                                           &bp, &remain);

                /* Put the trailer */
                (void) krb5_ser_pack_int32(KV5M_KEYTAB, &bp, &remain);
                kret = 0;
                *buffer = bp;
                *lenremain = remain;
                free(ktname);
            }
        }
    }
    return(kret);
}

/*
 * krb5_ktf_keytab_internalize()        - Internalize the krb5_ktf_keytab.
 */
static krb5_error_code
krb5_ktf_keytab_internalize(krb5_context kcontext, krb5_pointer *argp, krb5_octet **buffer, size_t *lenremain)
{
    krb5_error_code     kret;
    krb5_keytab         keytab = NULL;
    krb5_int32          ibuf;
    krb5_octet          *bp;
    size_t              remain;
    char                *ktname = NULL;
    krb5_ktfile_data    *ktdata;
    krb5_int32          file_is_open;
    int64_t             foff;

    *argp = NULL;
    bp = *buffer;
    remain = *lenremain;

    /* Read our magic number */
    if (krb5_ser_unpack_int32(&ibuf, &bp, &remain) || ibuf != KV5M_KEYTAB)
        return EINVAL;

    /* Read the keytab name */
    kret = krb5_ser_unpack_int32(&ibuf, &bp, &remain);
    if (kret)
        return kret;
    ktname = malloc(ibuf + 1);
    if (!ktname)
        return ENOMEM;
    kret = krb5_ser_unpack_bytes((krb5_octet *) ktname, (size_t) ibuf,
                                 &bp, &remain);
    if (kret)
        goto cleanup;
    ktname[ibuf] = '\0';

    /* Resolve the keytab. */
    kret = krb5_kt_resolve(kcontext, ktname, &keytab);
    if (kret)
        goto cleanup;

    if (keytab->ops != &krb5_ktf_ops) {
        kret = EINVAL;
        goto cleanup;
    }
    ktdata = (krb5_ktfile_data *) keytab->data;

    if (remain < (sizeof(krb5_int32)*5)) {
        kret = EINVAL;
        goto cleanup;
    }
    (void) krb5_ser_unpack_int32(&file_is_open, &bp, &remain);
    (void) krb5_ser_unpack_int64(&foff, &bp, &remain);
    (void) krb5_ser_unpack_int32(&ibuf, &bp, &remain);
    ktdata->version = (int) ibuf;
    (void) krb5_ser_unpack_int32(&ibuf, &bp, &remain);
    if (ibuf != KV5M_KEYTAB) {
        kret = EINVAL;
        goto cleanup;
    }

    if (file_is_open) {
        int     fmode;
        long    fpos;

#if !defined(_WIN32)
        fmode = (file_is_open >> 1) & O_ACCMODE;
#else
        fmode = 0;
#endif
        if (fmode)
            kret = krb5_ktfileint_openw(kcontext, keytab);
        else
            kret = krb5_ktfileint_openr(kcontext, keytab);
        if (kret)
            goto cleanup;
        fpos = foff; /* XX range check? */
        if (fseek(KTFILEP(keytab), fpos, SEEK_SET) == -1) {
            kret = errno;
            goto cleanup;
        }
    }

    *buffer = bp;
    *lenremain = remain;
    *argp = (krb5_pointer) keytab;
cleanup:
    if (kret != 0 && keytab)
        krb5_kt_close(kcontext, keytab);
    free(ktname);
    return kret;
}


/*
 * krb5_ktfile_add()
 */

static krb5_error_code KRB5_CALLCONV
krb5_ktfile_add(krb5_context context, krb5_keytab id, krb5_keytab_entry *entry)
{
    krb5_error_code retval;

    KTLOCK(id);
    if (KTFILEP(id)) {
        /* Iterator(s) active -- no changes.  */
        KTUNLOCK(id);
        k5_setmsg(context, KRB5_KT_IOERR,
                  _("Cannot change keytab with keytab iterators active"));
        return KRB5_KT_IOERR;   /* XXX */
    }
    if ((retval = krb5_ktfileint_openw(context, id))) {
        KTUNLOCK(id);
        return retval;
    }
    if (fseek(KTFILEP(id), 0, 2) == -1) {
        KTUNLOCK(id);
        return KRB5_KT_END;
    }
    retval = krb5_ktfileint_write_entry(context, id, entry);
    krb5_ktfileint_close(context, id);
    KTUNLOCK(id);
    return retval;
}

/*
 * krb5_ktfile_remove()
 */

static krb5_error_code KRB5_CALLCONV
krb5_ktfile_remove(krb5_context context, krb5_keytab id, krb5_keytab_entry *entry)
{
    krb5_keytab_entry   cur_entry;
    krb5_error_code     kerror;
    krb5_int32          delete_point;

    KTLOCK(id);
    if (KTFILEP(id)) {
        /* Iterator(s) active -- no changes.  */
        KTUNLOCK(id);
        k5_setmsg(context, KRB5_KT_IOERR,
                  _("Cannot change keytab with keytab iterators active"));
        return KRB5_KT_IOERR;   /* XXX */
    }

    if ((kerror = krb5_ktfileint_openw(context, id))) {
        KTUNLOCK(id);
        return kerror;
    }

    /*
     * For efficiency and simplicity, we'll use a while true that
     * is exited with a break statement.
     */
    while (TRUE) {
        if ((kerror = krb5_ktfileint_internal_read_entry(context, id,
                                                         &cur_entry,
                                                         &delete_point)))
            break;

        if ((entry->vno == cur_entry.vno) &&
            (entry->key.enctype == cur_entry.key.enctype) &&
            krb5_principal_compare(context, entry->principal, cur_entry.principal)) {
            /* found a match */
            krb5_kt_free_entry(context, &cur_entry);
            break;
        }
        krb5_kt_free_entry(context, &cur_entry);
    }

    if (kerror == KRB5_KT_END)
        kerror = KRB5_KT_NOTFOUND;

    if (kerror) {
        (void) krb5_ktfileint_close(context, id);
        KTUNLOCK(id);
        return kerror;
    }

    kerror = krb5_ktfileint_delete_entry(context, id, delete_point);

    if (kerror) {
        (void) krb5_ktfileint_close(context, id);
    } else {
        kerror = krb5_ktfileint_close(context, id);
    }
    KTUNLOCK(id);
    return kerror;
}

/*
 * krb5_ktf_ops
 */

const struct _krb5_kt_ops krb5_ktf_ops = {
    0,
    "FILE",     /* Prefix -- this string should not appear anywhere else! */
    krb5_ktfile_resolve,
    krb5_ktfile_get_name,
    krb5_ktfile_close,
    krb5_ktfile_get_entry,
    krb5_ktfile_start_seq_get,
    krb5_ktfile_get_next,
    krb5_ktfile_end_get,
    krb5_ktfile_add,
    krb5_ktfile_remove,
    &krb5_ktfile_ser_entry
};

/*
 * krb5_ktf_writable_ops -- this is the same as krb5_ktf_ops except for the
 * prefix.  WRFILE should no longer be needed, but is effectively aliased to
 * FILE for compatibility.
 */

const struct _krb5_kt_ops krb5_ktf_writable_ops = {
    0,
    "WRFILE",   /* Prefix -- this string should not appear anywhere else! */
    krb5_ktfile_resolve,
    krb5_ktfile_get_name,
    krb5_ktfile_close,
    krb5_ktfile_get_entry,
    krb5_ktfile_start_seq_get,
    krb5_ktfile_get_next,
    krb5_ktfile_end_get,
    krb5_ktfile_add,
    krb5_ktfile_remove,
    &krb5_ktfile_ser_entry
};

/*
 * krb5_kt_dfl_ops
 */

const krb5_kt_ops krb5_kt_dfl_ops = {
    0,
    "FILE",     /* Prefix -- this string should not appear anywhere else! */
    krb5_ktfile_resolve,
    krb5_ktfile_get_name,
    krb5_ktfile_close,
    krb5_ktfile_get_entry,
    krb5_ktfile_start_seq_get,
    krb5_ktfile_get_next,
    krb5_ktfile_end_get,
    0,
    0,
    &krb5_ktfile_ser_entry
};

/* Formerly lib/krb5/keytab/file/ktf_util.c */

/*
 * This function contains utilities for the file based implementation of
 * the keytab.  There are no public functions in this file.
 *
 * This file is the only one that has knowledge of the format of a
 * keytab file.
 *
 * The format is as follows:
 *
 * <file format vno>
 * <record length>
 * principal timestamp vno key
 * <record length>
 * principal timestamp vno key
 * ....
 *
 * A length field (sizeof(krb5_int32)) exists between entries.  When this
 * length is positive it indicates an active entry, when negative a hole.
 * The length indicates the size of the block in the file (this may be
 * larger than the size of the next record, since we are using a first
 * fit algorithm for re-using holes and the first fit may be larger than
 * the entry we are writing).  Another (compatible) implementation could
 * break up holes when allocating them to smaller entries to minimize
 * wasted space.  (Such an implementation should also coalesce adjacent
 * holes to reduce fragmentation).  This implementation does neither.
 *
 * There are no separators between fields of an entry.
 * A principal is a length-encoded array of length-encoded strings.  The
 * length is a krb5_int16 in each case.  The specific format, then, is
 * multiple entries concatinated with no separators.  An entry has this
 * exact format:
 *
 * sizeof(krb5_int16) bytes for number of components in the principal;
 * then, each component listed in ordser.
 * For each component, sizeof(krb5_int16) bytes for the number of bytes
 * in the component, followed by the component.
 * sizeof(krb5_int32) for the principal type (for KEYTAB V2 and higher)
 * sizeof(krb5_int32) bytes for the timestamp
 * sizeof(krb5_octet) bytes for the key version number
 * sizeof(krb5_int16) bytes for the enctype
 * sizeof(krb5_int16) bytes for the key length, followed by the key
 */

#ifndef SEEK_SET
#define SEEK_SET 0
#define SEEK_CUR 1
#endif

typedef krb5_int16  krb5_kt_vno;

#define krb5_kt_default_vno ((krb5_kt_vno)KRB5_KT_DEFAULT_VNO)

static krb5_error_code
krb5_ktfileint_open(krb5_context context, krb5_keytab id, int mode)
{
    krb5_error_code kerror;
    krb5_kt_vno kt_vno;
    int writevno = 0;

    KTCHECKLOCK(id);
    errno = 0;
    KTFILEP(id) = fopen(KTFILENAME(id),
                        (mode == KRB5_LOCKMODE_EXCLUSIVE) ? "rb+" : "rb");
    if (!KTFILEP(id)) {
        if ((mode == KRB5_LOCKMODE_EXCLUSIVE) && (errno == ENOENT)) {
            /* try making it first time around */
            k5_create_secure_file(context, KTFILENAME(id));
            errno = 0;
            KTFILEP(id) = fopen(KTFILENAME(id), "rb+");
            if (!KTFILEP(id))
                goto report_errno;
            writevno = 1;
        } else {
        report_errno:
            switch (errno) {
            case 0:
                /* XXX */
                return EMFILE;
            case ENOENT:
                k5_setmsg(context, ENOENT,
                          _("Key table file '%s' not found"), KTFILENAME(id));
                return ENOENT;
            default:
                return errno;
            }
        }
    }
    set_cloexec_file(KTFILEP(id));
    if ((kerror = krb5_lock_file(context, fileno(KTFILEP(id)), mode))) {
        (void) fclose(KTFILEP(id));
        KTFILEP(id) = 0;
        return kerror;
    }
    /* assume ANSI or BSD-style stdio */
    setbuf(KTFILEP(id), KTFILEBUFP(id));

    /* get the vno and verify it */
    if (writevno) {
        kt_vno = htons(krb5_kt_default_vno);
        KTVERSION(id) = krb5_kt_default_vno;
        if (!fwrite(&kt_vno, sizeof(kt_vno), 1, KTFILEP(id))) {
            kerror = errno;
            (void) krb5_unlock_file(context, fileno(KTFILEP(id)));
            (void) fclose(KTFILEP(id));
            KTFILEP(id) = 0;
            return kerror;
        }
    } else {
        /* gotta verify it instead... */
        if (!fread(&kt_vno, sizeof(kt_vno), 1, KTFILEP(id))) {
            if (feof(KTFILEP(id)))
                kerror = KRB5_KEYTAB_BADVNO;
            else
                kerror = errno;
            (void) krb5_unlock_file(context, fileno(KTFILEP(id)));
            (void) fclose(KTFILEP(id));
            KTFILEP(id) = 0;
            return kerror;
        }
        kt_vno = KTVERSION(id) = ntohs(kt_vno);
        if ((kt_vno != KRB5_KT_VNO) &&
            (kt_vno != KRB5_KT_VNO_1)) {
            (void) krb5_unlock_file(context, fileno(KTFILEP(id)));
            (void) fclose(KTFILEP(id));
            KTFILEP(id) = 0;
            return KRB5_KEYTAB_BADVNO;
        }
    }
    KTSTARTOFF(id) = ftell(KTFILEP(id));
    return 0;
}

static krb5_error_code
krb5_ktfileint_openr(krb5_context context, krb5_keytab id)
{
    return krb5_ktfileint_open(context, id, KRB5_LOCKMODE_SHARED);
}

static krb5_error_code
krb5_ktfileint_openw(krb5_context context, krb5_keytab id)
{
    return krb5_ktfileint_open(context, id, KRB5_LOCKMODE_EXCLUSIVE);
}

static krb5_error_code
krb5_ktfileint_close(krb5_context context, krb5_keytab id)
{
    krb5_error_code kerror;

    KTCHECKLOCK(id);
    if (!KTFILEP(id))
        return 0;
    kerror = krb5_unlock_file(context, fileno(KTFILEP(id)));
    (void) fclose(KTFILEP(id));
    KTFILEP(id) = 0;
    return kerror;
}

static krb5_error_code
krb5_ktfileint_delete_entry(krb5_context context, krb5_keytab id, krb5_int32 delete_point)
{
    krb5_int32  size;
    krb5_int32  len;
    char        iobuf[BUFSIZ];

    KTCHECKLOCK(id);
    if (fseek(KTFILEP(id), delete_point, SEEK_SET)) {
        return errno;
    }
    if (!fread(&size, sizeof(size), 1, KTFILEP(id))) {
        return KRB5_KT_END;
    }
    if (KTVERSION(id) != KRB5_KT_VNO_1)
        size = ntohl(size);

    if (size > 0) {
        krb5_int32 minus_size = -size;
        if (KTVERSION(id) != KRB5_KT_VNO_1)
            minus_size = htonl(minus_size);

        if (fseek(KTFILEP(id), delete_point, SEEK_SET)) {
            return errno;
        }

        if (!fwrite(&minus_size, sizeof(minus_size), 1, KTFILEP(id))) {
            return KRB5_KT_IOERR;
        }

        if (size < BUFSIZ) {
            len = size;
        } else {
            len = BUFSIZ;
        }

        memset(iobuf, 0, (size_t) len);
        while (size > 0) {
            if (!fwrite(iobuf, 1, (size_t) len, KTFILEP(id))) {
                return KRB5_KT_IOERR;
            }
            size -= len;
            if (size < len) {
                len = size;
            }
        }

        return k5_sync_disk_file(context, KTFILEP(id));
    }

    return 0;
}

static krb5_error_code
krb5_ktfileint_internal_read_entry(krb5_context context, krb5_keytab id, krb5_keytab_entry *ret_entry, krb5_int32 *delete_point)
{
    krb5_octet vno;
    krb5_int16 count;
    unsigned int u_count, u_princ_size;
    krb5_int16 enctype;
    krb5_int16 princ_size;
    int i;
    krb5_int32 size;
    krb5_int32 start_pos, pos;
    krb5_error_code error;
    char        *tmpdata;
    krb5_data   *princ;
    uint32_t    vno32;

    KTCHECKLOCK(id);
    memset(ret_entry, 0, sizeof(krb5_keytab_entry));
    ret_entry->magic = KV5M_KEYTAB_ENTRY;

    /* fseek to synchronise buffered I/O on the key table. */

    if (fseek(KTFILEP(id), 0L, SEEK_CUR) < 0)
    {
        return errno;
    }

    do {
        *delete_point = ftell(KTFILEP(id));
        if (!fread(&size, sizeof(size), 1, KTFILEP(id))) {
            return KRB5_KT_END;
        }
        if (KTVERSION(id) != KRB5_KT_VNO_1)
            size = ntohl(size);

        if (size < 0) {
            if (fseek(KTFILEP(id), -size, SEEK_CUR)) {
                return errno;
            }
        }
    } while (size < 0);

    if (size == 0) {
        return KRB5_KT_END;
    }

    start_pos = ftell(KTFILEP(id));

    /* deal with guts of parsing... */

    /* first, int16 with #princ components */
    if (!fread(&count, sizeof(count), 1, KTFILEP(id)))
        return KRB5_KT_END;
    if (KTVERSION(id) == KRB5_KT_VNO_1) {
        count -= 1;         /* V1 includes the realm in the count */
    } else {
        count = ntohs(count);
    }
    if (!count || (count < 0))
        return KRB5_KT_END;
    ret_entry->principal = (krb5_principal)malloc(sizeof(krb5_principal_data));
    if (!ret_entry->principal)
        return ENOMEM;

    u_count = count;
    ret_entry->principal->magic = KV5M_PRINCIPAL;
    ret_entry->principal->length = u_count;
    ret_entry->principal->data = (krb5_data *)
        calloc(u_count, sizeof(krb5_data));
    if (!ret_entry->principal->data) {
        free(ret_entry->principal);
        ret_entry->principal = 0;
        return ENOMEM;
    }

    /* Now, get the realm data */
    if (!fread(&princ_size, sizeof(princ_size), 1, KTFILEP(id))) {
        error = KRB5_KT_END;
        goto fail;
    }
    if (KTVERSION(id) != KRB5_KT_VNO_1)
        princ_size = ntohs(princ_size);
    if (!princ_size || (princ_size < 0)) {
        error = KRB5_KT_END;
        goto fail;
    }
    u_princ_size = princ_size;

    ret_entry->principal->realm.length = u_princ_size;
    tmpdata = malloc(u_princ_size+1);
    if (!tmpdata) {
        error = ENOMEM;
        goto fail;
    }
    if (fread(tmpdata, 1, u_princ_size, KTFILEP(id)) != (size_t) princ_size) {
        free(tmpdata);
        error = KRB5_KT_END;
        goto fail;
    }
    tmpdata[princ_size] = 0;    /* Some things might be expecting null */
                                /* termination...  ``Be conservative in */
                                /* what you send out'' */
    ret_entry->principal->realm.data = tmpdata;

    for (i = 0; i < count; i++) {
        princ = &ret_entry->principal->data[i];
        if (!fread(&princ_size, sizeof(princ_size), 1, KTFILEP(id))) {
            error = KRB5_KT_END;
            goto fail;
        }
        if (KTVERSION(id) != KRB5_KT_VNO_1)
            princ_size = ntohs(princ_size);
        if (!princ_size || (princ_size < 0)) {
            error = KRB5_KT_END;
            goto fail;
        }

        u_princ_size = princ_size;
        princ->length = u_princ_size;
        princ->data = malloc(u_princ_size+1);
        if (!princ->data) {
            error = ENOMEM;
            goto fail;
        }
        if (!fread(princ->data, sizeof(char), u_princ_size, KTFILEP(id))) {
            error = KRB5_KT_END;
            goto fail;
        }
        princ->data[princ_size] = 0; /* Null terminate */
    }

    /* read in the principal type, if we can get it */
    if (KTVERSION(id) != KRB5_KT_VNO_1) {
        if (!fread(&ret_entry->principal->type,
                   sizeof(ret_entry->principal->type), 1, KTFILEP(id))) {
            error = KRB5_KT_END;
            goto fail;
        }
        ret_entry->principal->type = ntohl(ret_entry->principal->type);
    }

    /* read in the timestamp */
    if (!fread(&ret_entry->timestamp, sizeof(ret_entry->timestamp), 1, KTFILEP(id))) {
        error = KRB5_KT_END;
        goto fail;
    }
    if (KTVERSION(id) != KRB5_KT_VNO_1)
        ret_entry->timestamp = ntohl(ret_entry->timestamp);

    /* read in the version number */
    if (!fread(&vno, sizeof(vno), 1, KTFILEP(id))) {
        error = KRB5_KT_END;
        goto fail;
    }
    ret_entry->vno = (krb5_kvno)vno;

    /* key type */
    if (!fread(&enctype, sizeof(enctype), 1, KTFILEP(id))) {
        error = KRB5_KT_END;
        goto fail;
    }
    if (KTVERSION(id) != KRB5_KT_VNO_1)
        enctype = ntohs(enctype);
    ret_entry->key.enctype = (krb5_enctype)enctype;

    /* key contents */
    ret_entry->key.magic = KV5M_KEYBLOCK;

    if (!fread(&count, sizeof(count), 1, KTFILEP(id))) {
        error = KRB5_KT_END;
        goto fail;
    }
    if (KTVERSION(id) != KRB5_KT_VNO_1)
        count = ntohs(count);
    if (!count || (count < 0)) {
        error = KRB5_KT_END;
        goto fail;
    }

    u_count = count;
    ret_entry->key.length = u_count;

    ret_entry->key.contents = (krb5_octet *)malloc(u_count);
    if (!ret_entry->key.contents) {
        error = ENOMEM;
        goto fail;
    }
    if (!fread(ret_entry->key.contents, sizeof(krb5_octet), count,
               KTFILEP(id))) {
        error = KRB5_KT_END;
        goto fail;
    }

    /* Check for a 32-bit kvno extension if four or more bytes remain. */
    pos = ftell(KTFILEP(id));
    if (pos - start_pos + 4 <= size) {
        if (!fread(&vno32, sizeof(vno32), 1, KTFILEP(id))) {
            error = KRB5_KT_END;
            goto fail;
        }
        if (KTVERSION(id) != KRB5_KT_VNO_1)
            vno32 = ntohl(vno32);
        /* If the value is 0, the bytes are just zero-fill. */
        if (vno32)
            ret_entry->vno = vno32;
    }

    /*
     * Reposition file pointer to the next inter-record length field.
     */
    if (fseek(KTFILEP(id), start_pos + size, SEEK_SET) == -1) {
        error = errno;
        goto fail;
    }

    return 0;
fail:

    for (i = 0; i < ret_entry->principal->length; i++)
        free(ret_entry->principal->data[i].data);
    free(ret_entry->principal->data);
    ret_entry->principal->data = 0;
    free(ret_entry->principal);
    ret_entry->principal = 0;
    return error;
}

static krb5_error_code
krb5_ktfileint_read_entry(krb5_context context, krb5_keytab id, krb5_keytab_entry *entryp)
{
    krb5_int32 delete_point;

    return krb5_ktfileint_internal_read_entry(context, id, entryp, &delete_point);
}

static krb5_error_code
krb5_ktfileint_write_entry(krb5_context context, krb5_keytab id, krb5_keytab_entry *entry)
{
    krb5_octet vno;
    krb5_data *princ;
    krb5_int16 count, size, enctype;
    krb5_error_code retval = 0;
    krb5_timestamp timestamp;
    krb5_int32  princ_type;
    krb5_int32  size_needed;
    krb5_int32  commit_point = -1;
    uint32_t    vno32;
    int         i;

    KTCHECKLOCK(id);
    retval = krb5_ktfileint_size_entry(context, entry, &size_needed);
    if (retval)
        return retval;
    retval = krb5_ktfileint_find_slot(context, id, &size_needed, &commit_point);
    if (retval)
        return retval;

    /* fseek to synchronise buffered I/O on the key table. */
    /* XXX Without the weird setbuf crock, can we get rid of this now?  */
    if (fseek(KTFILEP(id), 0L, SEEK_CUR) < 0)
    {
        return errno;
    }

    if (KTVERSION(id) == KRB5_KT_VNO_1) {
        count = (krb5_int16)entry->principal->length + 1;
    } else {
        count = htons((u_short)entry->principal->length);
    }

    if (!fwrite(&count, sizeof(count), 1, KTFILEP(id))) {
    abend:
        return KRB5_KT_IOERR;
    }
    size = entry->principal->realm.length;
    if (KTVERSION(id) != KRB5_KT_VNO_1)
        size = htons(size);
    if (!fwrite(&size, sizeof(size), 1, KTFILEP(id))) {
        goto abend;
    }
    if (!fwrite(entry->principal->realm.data, sizeof(char),
                entry->principal->realm.length, KTFILEP(id))) {
        goto abend;
    }

    count = (krb5_int16)entry->principal->length;
    for (i = 0; i < count; i++) {
        princ = &entry->principal->data[i];
        size = princ->length;
        if (KTVERSION(id) != KRB5_KT_VNO_1)
            size = htons(size);
        if (!fwrite(&size, sizeof(size), 1, KTFILEP(id))) {
            goto abend;
        }
        if (!fwrite(princ->data, sizeof(char), princ->length, KTFILEP(id))) {
            goto abend;
        }
    }

    /*
     * Write out the principal type
     */
    if (KTVERSION(id) != KRB5_KT_VNO_1) {
        princ_type = htonl(entry->principal->type);
        if (!fwrite(&princ_type, sizeof(princ_type), 1, KTFILEP(id))) {
            goto abend;
        }
    }

    /*
     * Fill in the time of day the entry was written to the keytab.
     */
    if (krb5_timeofday(context, &entry->timestamp)) {
        entry->timestamp = 0;
    }
    if (KTVERSION(id) == KRB5_KT_VNO_1)
        timestamp = entry->timestamp;
    else
        timestamp = htonl(entry->timestamp);
    if (!fwrite(&timestamp, sizeof(timestamp), 1, KTFILEP(id))) {
        goto abend;
    }

    /* key version number */
    vno = (krb5_octet)entry->vno;
    if (!fwrite(&vno, sizeof(vno), 1, KTFILEP(id))) {
        goto abend;
    }
    /* key type */
    if (KTVERSION(id) == KRB5_KT_VNO_1)
        enctype = entry->key.enctype;
    else
        enctype = htons(entry->key.enctype);
    if (!fwrite(&enctype, sizeof(enctype), 1, KTFILEP(id))) {
        goto abend;
    }
    /* key length */
    if (KTVERSION(id) == KRB5_KT_VNO_1)
        size = entry->key.length;
    else
        size = htons(entry->key.length);
    if (!fwrite(&size, sizeof(size), 1, KTFILEP(id))) {
        goto abend;
    }
    if (!fwrite(entry->key.contents, sizeof(krb5_octet),
                entry->key.length, KTFILEP(id))) {
        goto abend;
    }

    /* 32-bit key version number */
    vno32 = entry->vno;
    if (KTVERSION(id) != KRB5_KT_VNO_1)
        vno32 = htonl(vno32);
    if (!fwrite(&vno32, sizeof(vno32), 1, KTFILEP(id)))
        goto abend;

    if (fflush(KTFILEP(id)))
        goto abend;

    retval = k5_sync_disk_file(context, KTFILEP(id));

    if (retval) {
        return retval;
    }

    if (fseek(KTFILEP(id), commit_point, SEEK_SET)) {
        return errno;
    }
    if (KTVERSION(id) != KRB5_KT_VNO_1)
        size_needed = htonl(size_needed);
    if (!fwrite(&size_needed, sizeof(size_needed), 1, KTFILEP(id))) {
        goto abend;
    }
    if (fflush(KTFILEP(id)))
        goto abend;
    retval = k5_sync_disk_file(context, KTFILEP(id));

    return retval;
}

/*
 * Determine the size needed for a file entry for the given
 * keytab entry.
 */
static krb5_error_code
krb5_ktfileint_size_entry(krb5_context context, krb5_keytab_entry *entry, krb5_int32 *size_needed)
{
    krb5_int16 count;
    krb5_int32 total_size, i;
    krb5_error_code retval = 0;

    count = (krb5_int16)entry->principal->length;

    total_size = sizeof(count);
    total_size += entry->principal->realm.length + sizeof(krb5_int16);

    for (i = 0; i < count; i++)
        total_size += entry->principal->data[i].length + sizeof(krb5_int16);

    total_size += sizeof(entry->principal->type);
    total_size += sizeof(entry->timestamp);
    total_size += sizeof(krb5_octet);
    total_size += sizeof(krb5_int16);
    total_size += sizeof(krb5_int16) + entry->key.length;
    total_size += sizeof(uint32_t);

    *size_needed = total_size;
    return retval;
}

/*
 * Find and reserve a slot in the file for an entry of the needed size.
 * The commit point will be set to the position in the file where the
 * the length (sizeof(krb5_int32) bytes) of this node should be written
 * when commiting the write.  The file position left as a result of this
 * call is the position where the actual data should be written.
 *
 * The size_needed argument may be adjusted if we find a hole that is
 * larger than the size needed.  (Recall that size_needed will be used
 * to commit the write, but that this field must indicate the size of the
 * block in the file rather than the size of the actual entry)
 */
static krb5_error_code
krb5_ktfileint_find_slot(krb5_context context, krb5_keytab id, krb5_int32 *size_needed, krb5_int32 *commit_point_ptr)
{
    FILE *fp;
    krb5_int32 size, zero_point, commit_point;
    krb5_kt_vno kt_vno;

    KTCHECKLOCK(id);
    fp = KTFILEP(id);
    /* Skip over file version number. */
    if (fseek(fp, 0, SEEK_SET))
        return errno;
    if (!fread(&kt_vno, sizeof(kt_vno), 1, fp))
        return errno;

    for (;;) {
        commit_point = ftell(fp);
        if (commit_point == -1)
            return errno;
        if (!fread(&size, sizeof(size), 1, fp)) {
            /* Hit the end of file, reserve this slot. */
            /* Necessary to avoid a later fseek failing on Solaris 10. */
            if (fseek(fp, 0, SEEK_CUR))
                return errno;
            /* htonl(0) is 0, so no need to worry about byte order */
            size = 0;
            if (!fwrite(&size, sizeof(size), 1, fp))
                return errno;
            break;
        }

        if (KTVERSION(id) != KRB5_KT_VNO_1)
            size = ntohl(size);

        if (size > 0) {
            /* Non-empty record; seek past it. */
            if (fseek(fp, size, SEEK_CUR))
                return errno;
        } else if (size < 0) {
            /* Empty record; use if it's big enough, seek past otherwise. */
            size = -size;
            if (size >= *size_needed) {
                *size_needed = size;
                break;
            } else {
                if (fseek(fp, size, SEEK_CUR))
                    return errno;
            }
        } else {
            /* Empty record at end of file; use it. */
            /* Ensure the new record will be followed by another 0. */
            zero_point = ftell(fp);
            if (zero_point == -1)
                return errno;
            if (fseek(fp, *size_needed, SEEK_CUR))
                return errno;
            /* htonl(0) is 0, so no need to worry about byte order */
            if (!fwrite(&size, sizeof(size), 1, fp))
                return errno;
            if (fseek(fp, zero_point, SEEK_SET))
                return errno;
            break;
        }
    }

    *commit_point_ptr = commit_point;
    return 0;
}
#endif /* LEAN_CLIENT */