summaryrefslogtreecommitdiffstats
path: root/src/lib/krb5/ccache/cc_file.c
blob: 49ba479434438175dd9d9f7d1e2c229e91a2daae (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
/*
 * lib/krb5/ccache/cc_file.c
 *
 * Copyright 1990,1991,1992,1993,1994,2000,2004,2007 Massachusetts Institute of Technology.
 * All Rights Reserved.
 *
 * Original stdio support copyright 1995 by Cygnus Support.
 *
 * 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.
 * 
 *
 * implementation of file-based credentials cache
 */

/*
If OPENCLOSE is defined, each of the functions opens and closes the
file whenever it needs to access it.  Otherwise, the file is opened
once in initialize and closed once is close.

This library depends on UNIX-like file descriptors, and UNIX-like
behavior from the functions: open, close, read, write, lseek.

The quasi-BNF grammar for a credentials cache:

file ::= 
        principal list-of-credentials

credential ::=
	client (principal)
	server (principal)
	keyblock (keyblock)
	times (ticket_times)
	is_skey (boolean)
	ticket_flags (flags)
	ticket (data)
	second_ticket (data)

principal ::= 
	number of components (int32)
	component 1 (data)
	component 2 (data)
	...
	
data ::=
	length (int32)
	string of length bytes

etc.
 */
/* todo:
   Make sure that each time a function returns KRB5_NOMEM, everything
   allocated earlier in the function and stack tree is freed.

   File locking

   Use pread/pwrite if available, so multiple threads can read
   simultaneously.  (That may require reader/writer locks.)

   fcc_nseq.c and fcc_read don't check return values a lot.
 */
#include "k5-int.h"


#include <stdio.h>
#include <errno.h>

#if HAVE_UNISTD_H
#include <unistd.h>
#endif

#ifdef HAVE_NETINET_IN_H
#if !defined(_WIN32)
#include <netinet/in.h>
#else
#include "port-sockets.h"
#endif
#else
# error find some way to use net-byte-order file version numbers.
#endif

static krb5_error_code KRB5_CALLCONV krb5_fcc_close
        (krb5_context, krb5_ccache id);

static krb5_error_code KRB5_CALLCONV krb5_fcc_destroy
        (krb5_context, krb5_ccache id);

static krb5_error_code KRB5_CALLCONV krb5_fcc_end_seq_get
        (krb5_context, krb5_ccache id, krb5_cc_cursor *cursor);

static krb5_error_code KRB5_CALLCONV krb5_fcc_generate_new
        (krb5_context, krb5_ccache *id);

static const char * KRB5_CALLCONV krb5_fcc_get_name
        (krb5_context, krb5_ccache id);

static krb5_error_code KRB5_CALLCONV krb5_fcc_get_principal
        (krb5_context, krb5_ccache id, krb5_principal *princ);

static krb5_error_code KRB5_CALLCONV krb5_fcc_initialize
        (krb5_context, krb5_ccache id, krb5_principal princ);

static krb5_error_code KRB5_CALLCONV krb5_fcc_next_cred
        (krb5_context, krb5_ccache id, krb5_cc_cursor *cursor,
	 krb5_creds *creds);

static krb5_error_code krb5_fcc_read
        (krb5_context, krb5_ccache id, krb5_pointer buf, unsigned int len);
static krb5_error_code krb5_fcc_read_principal
        (krb5_context, krb5_ccache id, krb5_principal *princ);
static krb5_error_code krb5_fcc_read_keyblock
        (krb5_context, krb5_ccache id, krb5_keyblock *keyblock);
static krb5_error_code krb5_fcc_read_data
        (krb5_context, krb5_ccache id, krb5_data *data);
static krb5_error_code krb5_fcc_read_int32
        (krb5_context, krb5_ccache id, krb5_int32 *i);
static krb5_error_code krb5_fcc_read_ui_2
        (krb5_context, krb5_ccache id, krb5_ui_2 *i);
static krb5_error_code krb5_fcc_read_octet
        (krb5_context, krb5_ccache id, krb5_octet *i);
static krb5_error_code krb5_fcc_read_times
        (krb5_context, krb5_ccache id, krb5_ticket_times *t);
static krb5_error_code krb5_fcc_read_addrs
        (krb5_context, krb5_ccache, krb5_address ***);
static krb5_error_code krb5_fcc_read_addr
        (krb5_context, krb5_ccache, krb5_address *);
static krb5_error_code krb5_fcc_read_authdata
        (krb5_context, krb5_ccache, krb5_authdata ***);
static krb5_error_code krb5_fcc_read_authdatum
        (krb5_context, krb5_ccache, krb5_authdata *);

static krb5_error_code KRB5_CALLCONV krb5_fcc_resolve
        (krb5_context, krb5_ccache *id, const char *residual);

static krb5_error_code KRB5_CALLCONV krb5_fcc_retrieve
        (krb5_context, krb5_ccache id, krb5_flags whichfields,
	 krb5_creds *mcreds, krb5_creds *creds);

static krb5_error_code KRB5_CALLCONV krb5_fcc_start_seq_get
        (krb5_context, krb5_ccache id, krb5_cc_cursor *cursor);

static krb5_error_code KRB5_CALLCONV krb5_fcc_store
        (krb5_context, krb5_ccache id, krb5_creds *creds);

static krb5_error_code krb5_fcc_skip_header
        (krb5_context, krb5_ccache);
static krb5_error_code krb5_fcc_skip_principal
        (krb5_context, krb5_ccache id);

static krb5_error_code KRB5_CALLCONV krb5_fcc_set_flags
        (krb5_context, krb5_ccache id, krb5_flags flags);

extern const krb5_cc_ops krb5_cc_file_ops;

krb5_error_code krb5_change_cache (void);

static krb5_error_code krb5_fcc_write
        (krb5_context, krb5_ccache id, krb5_pointer buf, unsigned int len);
static krb5_error_code krb5_fcc_store_principal
        (krb5_context, krb5_ccache id, krb5_principal princ);
static krb5_error_code krb5_fcc_store_keyblock
        (krb5_context, krb5_ccache id, krb5_keyblock *keyblock);
static krb5_error_code krb5_fcc_store_data
        (krb5_context, krb5_ccache id, krb5_data *data);
static krb5_error_code krb5_fcc_store_int32
        (krb5_context, krb5_ccache id, krb5_int32 i);
static krb5_error_code krb5_fcc_store_ui_4
        (krb5_context, krb5_ccache id, krb5_ui_4 i);
static krb5_error_code krb5_fcc_store_ui_2
        (krb5_context, krb5_ccache id, krb5_int32 i);
static krb5_error_code krb5_fcc_store_octet
        (krb5_context, krb5_ccache id, krb5_int32 i);
static krb5_error_code krb5_fcc_store_times
        (krb5_context, krb5_ccache id, krb5_ticket_times *t);
static krb5_error_code krb5_fcc_store_addrs
        (krb5_context, krb5_ccache, krb5_address **);
static krb5_error_code krb5_fcc_store_addr
        (krb5_context, krb5_ccache, krb5_address *);
static krb5_error_code krb5_fcc_store_authdata
        (krb5_context, krb5_ccache, krb5_authdata **);
static krb5_error_code krb5_fcc_store_authdatum
        (krb5_context, krb5_ccache, krb5_authdata *);

static krb5_error_code krb5_fcc_interpret
        (krb5_context, int);

struct _krb5_fcc_data;
static krb5_error_code krb5_fcc_close_file
        (krb5_context, struct _krb5_fcc_data *data);
static krb5_error_code krb5_fcc_open_file
        (krb5_context, krb5_ccache, int);


#define KRB5_OK 0

#define KRB5_FCC_MAXLEN 100

/*
 * FCC version 2 contains type information for principals.  FCC
 * version 1 does not.
 *  
 * FCC version 3 contains keyblock encryption type information, and is
 * architecture independent.  Previous versions are not.
 *
 * The code will accept version 1, 2, and 3 ccaches, and depending 
 * what KRB5_FCC_DEFAULT_FVNO is set to, it will create version 1, 2,
 * or 3 FCC caches.
 *
 * The default credentials cache should be type 3 for now (see
 * init_ctx.c).
 */

#define KRB5_FCC_FVNO_1 0x0501		/* krb v5, fcc v1 */
#define KRB5_FCC_FVNO_2 0x0502		/* krb v5, fcc v2 */
#define KRB5_FCC_FVNO_3 0x0503		/* krb v5, fcc v3 */
#define KRB5_FCC_FVNO_4 0x0504		/* krb v5, fcc v4 */

#define	FCC_OPEN_AND_ERASE	1
#define	FCC_OPEN_RDWR		2
#define	FCC_OPEN_RDONLY		3

/* Credential file header tags.
 * The header tags are constructed as:
 *	krb5_ui_2	tag
 *	krb5_ui_2	len
 *	krb5_octet	data[len]
 * This format allows for older versions of the fcc processing code to skip
 * past unrecognized tag formats.
 */
#define FCC_TAG_DELTATIME	1

#ifndef TKT_ROOT
#ifdef MSDOS_FILESYSTEM
#define TKT_ROOT "\\tkt"
#else
#define TKT_ROOT "/tmp/tkt"
#endif
#endif

/* macros to make checking flags easier */
#define OPENCLOSE(id) (((krb5_fcc_data *)id->data)->flags & KRB5_TC_OPENCLOSE)

typedef struct _krb5_fcc_data {
    char *filename;
    /* Lock this one before reading or modifying the data stored here
       that can be changed.  (Filename is fixed after
       initialization.)  */
    k5_mutex_t lock;
    int file;
    krb5_flags flags;
    int mode;				/* needed for locking code */
    int version;	      		/* version number of the file */

    /* Buffer data on reading, for performance.
       We used to have a stdio option, but we get more precise control
       by using the POSIX I/O functions.  */
#define FCC_BUFSIZ 1024
    int valid_bytes;
    int cur_offset;
    char buf[FCC_BUFSIZ];
} krb5_fcc_data;

static inline void invalidate_cache(krb5_fcc_data *data)
{
    data->valid_bytes = 0;
}

static off_t fcc_lseek(krb5_fcc_data *data, off_t offset, int whence)
{
    /* If we read some extra data in advance, and then want to know or
       use our "current" position, we need to back up a little.  */
    if (whence == SEEK_CUR && data->valid_bytes) {
	assert(data->valid_bytes > 0);
	assert(data->cur_offset > 0);
	assert(data->cur_offset <= data->valid_bytes);
	offset -= (data->valid_bytes - data->cur_offset);
    }
    invalidate_cache(data);
    return lseek(data->file, offset, whence);
}

struct fcc_set {
    struct fcc_set *next;
    krb5_fcc_data *data;
    unsigned int refcount;
};

k5_mutex_t krb5int_cc_file_mutex = K5_MUTEX_PARTIAL_INITIALIZER;
static struct fcc_set *fccs = NULL;

/* An off_t can be arbitrarily complex */
typedef struct _krb5_fcc_cursor {
    off_t pos;
} krb5_fcc_cursor;

#define MAYBE_OPEN(CONTEXT, ID, MODE)					\
{									\
    k5_assert_locked(&((krb5_fcc_data *)(ID)->data)->lock);		\
    if (OPENCLOSE (ID)) {						\
	krb5_error_code maybe_open_ret;					\
	maybe_open_ret = krb5_fcc_open_file (CONTEXT,ID,MODE);		\
	if (maybe_open_ret) {						\
	    k5_mutex_unlock(&((krb5_fcc_data *)(ID)->data)->lock);	\
	    return maybe_open_ret;					\
	}								\
    }									\
}

#define MAYBE_CLOSE(CONTEXT, ID, RET)					\
{									\
    if (OPENCLOSE (ID)) {						\
	krb5_error_code maybe_close_ret;				\
        maybe_close_ret = krb5_fcc_close_file (CONTEXT,			\
					       (krb5_fcc_data *)(ID)->data); \
	if (!(RET)) RET = maybe_close_ret; } }

#define MAYBE_CLOSE_IGNORE(CONTEXT, ID) \
{                                                                       \
    if (OPENCLOSE (ID)) {                                               \
        (void) krb5_fcc_close_file (CONTEXT,(krb5_fcc_data *)(ID)->data); } }

#define CHECK(ret) if (ret != KRB5_OK) goto errout;

#define NO_FILE -1

/*
 * Effects:
 * Reads len bytes from the cache id, storing them in buf.
 *
 * Requires:
 * Must be called with mutex locked.
 *
 * Errors:
 * KRB5_CC_END - there were not len bytes available
 * system errors (read)
 */
static krb5_error_code
krb5_fcc_read(krb5_context context, krb5_ccache id, krb5_pointer buf, unsigned int len)
{
#if 0
     int ret;

     k5_assert_locked(&((krb5_fcc_data *) id->data)->lock);

     ret = read(((krb5_fcc_data *) id->data)->file, (char *) buf, len);
     if (ret == -1)
	  return krb5_fcc_interpret(context, errno);
     if (ret != len)
	  return KRB5_CC_END;
     else
	  return KRB5_OK;
#else
     krb5_fcc_data *data = (krb5_fcc_data *) id->data;

     k5_assert_locked(&data->lock);

     while (len > 0) {
	 int nread, e;
	 size_t ncopied;

	 assert (data->valid_bytes >= 0);
	 if (data->valid_bytes > 0)
	     assert(data->cur_offset <= data->valid_bytes);
	 if (data->valid_bytes == 0
	     || data->cur_offset == data->valid_bytes) {
	     /* Fill buffer from current file position.  */
	     nread = read(data->file, data->buf, sizeof(data->buf));
	     e = errno;
	     if (nread < 0)
		 return krb5_fcc_interpret(context, e);
	     if (nread == 0)
		 /* EOF */
		 return KRB5_CC_END;
	     data->valid_bytes = nread;
	     data->cur_offset = 0;
	 }
	 assert(data->cur_offset < data->valid_bytes);
	 ncopied = len;
	 assert(ncopied == len);
	 if (data->valid_bytes - data->cur_offset < ncopied)
	     ncopied = data->valid_bytes - data->cur_offset;
	 memcpy(buf, data->buf + data->cur_offset, ncopied);
	 data->cur_offset += ncopied;
	 assert(data->cur_offset > 0);
	 assert(data->cur_offset <= data->valid_bytes);
	 len -= ncopied;
	 assert(len >= 0);
	 /* Don't do arithmetic on void pointers.  */
	 buf = (char*)buf + ncopied;
     }
     return 0;
#endif
}

/*
 * FOR ALL OF THE FOLLOWING FUNCTIONS:
 *
 * Requires:
 * id is open and set to read at the appropriate place in the file
 *
 * mutex is locked
 *
 * Effects:
 * Fills in the second argument with data of the appropriate type from
 * the file.  In some cases, the functions have to allocate space for
 * variable length fields; therefore, krb5_destroy_<type> must be
 * called for each filled in structure.
 *
 * Errors:
 * system errors (read errors)
 * KRB5_CC_NOMEM
 */

#define ALLOC(NUM,TYPE) \
    (((NUM) <= (((size_t)0-1)/ sizeof(TYPE)))		\
     ? (TYPE *) calloc((NUM), sizeof(TYPE))		\
     : (errno = ENOMEM,(TYPE *) 0))

static krb5_error_code
krb5_fcc_read_principal(krb5_context context, krb5_ccache id, krb5_principal *princ)
{
    krb5_fcc_data *data = (krb5_fcc_data *)id->data;
    krb5_error_code kret;
    register krb5_principal tmpprinc;
    krb5_int32 length, type;
    int i;

    k5_assert_locked(&((krb5_fcc_data *) id->data)->lock);

    *princ = NULL;

    if (data->version == KRB5_FCC_FVNO_1) {
	type = KRB5_NT_UNKNOWN;
    } else {
        /* Read principal type */
        kret = krb5_fcc_read_int32(context, id, &type);
        if (kret != KRB5_OK)
	    return kret;
    }

    /* Read the number of components */
    kret = krb5_fcc_read_int32(context, id, &length);
    if (kret != KRB5_OK)
	return kret;

    /*
     * DCE includes the principal's realm in the count; the new format
     * does not.
     */
    if (data->version == KRB5_FCC_FVNO_1)
	length--;
    if (length < 0)
	return KRB5_CC_NOMEM;

    tmpprinc = (krb5_principal) malloc(sizeof(krb5_principal_data));
    if (tmpprinc == NULL)
	return KRB5_CC_NOMEM;
    if (length) {
	size_t msize = length;
	if (msize != length) {
	    free(tmpprinc);
	    return KRB5_CC_NOMEM;
	}
	tmpprinc->data = ALLOC (msize, krb5_data);
	if (tmpprinc->data == 0) {
	    free((char *)tmpprinc);
	    return KRB5_CC_NOMEM;
	}
    } else
	tmpprinc->data = 0;
    tmpprinc->magic = KV5M_PRINCIPAL;
    tmpprinc->length = length;
    tmpprinc->type = type;

    kret = krb5_fcc_read_data(context, id, krb5_princ_realm(context, tmpprinc));

    i = 0;
    CHECK(kret);

    for (i=0; i < length; i++) {
	kret = krb5_fcc_read_data(context, id, krb5_princ_component(context, tmpprinc, i));
	CHECK(kret);
    }
    *princ = tmpprinc;
    return KRB5_OK;

 errout:
    while(--i >= 0)
	free(krb5_princ_component(context, tmpprinc, i)->data);
    free((char *)tmpprinc->data);
    free((char *)tmpprinc);
    return kret;
}

static krb5_error_code
krb5_fcc_read_addrs(krb5_context context, krb5_ccache id, krb5_address ***addrs)
{
     krb5_error_code kret;
     krb5_int32 length;
     size_t msize;
     int i;

     k5_assert_locked(&((krb5_fcc_data *) id->data)->lock);

     *addrs = 0;

     /* Read the number of components */
     kret = krb5_fcc_read_int32(context, id, &length);
     CHECK(kret);

     /* Make *addrs able to hold length pointers to krb5_address structs
      * Add one extra for a null-terminated list
      */
     msize = length;
     msize += 1;
     if (msize == 0 || msize - 1 != length || length < 0)
	 return KRB5_CC_NOMEM;
     *addrs = ALLOC (msize, krb5_address *);
     if (*addrs == NULL)
	  return KRB5_CC_NOMEM;

     for (i=0; i < length; i++) {
	  (*addrs)[i] = (krb5_address *) malloc(sizeof(krb5_address));
	  if ((*addrs)[i] == NULL) {
	      krb5_free_addresses(context, *addrs);
	      return KRB5_CC_NOMEM;
	  }
	  (*addrs)[i]->contents = NULL;
	  kret = krb5_fcc_read_addr(context, id, (*addrs)[i]);
	  CHECK(kret);
     }

     return KRB5_OK;
 errout:
     if (*addrs) {
	 krb5_free_addresses(context, *addrs);
	 *addrs = NULL;
     }
     return kret;
}

static krb5_error_code
krb5_fcc_read_keyblock(krb5_context context, krb5_ccache id, krb5_keyblock *keyblock)
{
     krb5_fcc_data *data = (krb5_fcc_data *)id->data;
     krb5_error_code kret;
     krb5_ui_2 ui2;
     krb5_int32 int32;

     k5_assert_locked(&((krb5_fcc_data *) id->data)->lock);

     keyblock->magic = KV5M_KEYBLOCK;
     keyblock->contents = 0;

     kret = krb5_fcc_read_ui_2(context, id, &ui2);
     keyblock->enctype = ui2;
     CHECK(kret);
     if (data->version == KRB5_FCC_FVNO_3) {
	 /* This works because the old etype is the same as the new enctype. */
	     kret = krb5_fcc_read_ui_2(context, id, &ui2);
	     /* keyblock->enctype = ui2; */
	     CHECK(kret);
     }

     kret = krb5_fcc_read_int32(context, id, &int32);
     CHECK(kret);
     if (int32 < 0)
	  return KRB5_CC_NOMEM;
     keyblock->length = int32;
     /* Overflow check.  */
     if (keyblock->length != int32)
	 return KRB5_CC_NOMEM;
     if ( keyblock->length == 0 )
	 return KRB5_OK;
     keyblock->contents = ALLOC (keyblock->length, krb5_octet);
     if (keyblock->contents == NULL)
	 return KRB5_CC_NOMEM;
     
     kret = krb5_fcc_read(context, id, keyblock->contents, keyblock->length);
     if (kret)
	 goto errout;

     return KRB5_OK;
 errout:
     if (keyblock->contents) {
	 krb5_xfree(keyblock->contents);
	 keyblock->contents = NULL;
     }
     return kret;
}

static krb5_error_code
krb5_fcc_read_data(krb5_context context, krb5_ccache id, krb5_data *data)
{
     krb5_error_code kret;
     krb5_int32 len;

     k5_assert_locked(&((krb5_fcc_data *) id->data)->lock);

     data->magic = KV5M_DATA;
     data->data = 0;

     kret = krb5_fcc_read_int32(context, id, &len);
     CHECK(kret);
     if (len < 0)
        return KRB5_CC_NOMEM;
     data->length = len;
     if (data->length != len || data->length + 1 == 0)
	 return KRB5_CC_NOMEM;

     if (data->length == 0) {
	data->data = 0;
	return KRB5_OK;
     }

     data->data = (char *) malloc(data->length+1);
     if (data->data == NULL)
	  return KRB5_CC_NOMEM;

     kret = krb5_fcc_read(context, id, data->data, (unsigned) data->length);
     CHECK(kret);
     
     data->data[data->length] = 0; /* Null terminate, just in case.... */
     return KRB5_OK;
 errout:
     if (data->data) {
	 krb5_xfree(data->data);
	 data->data = NULL;
     }
     return kret;
}

static krb5_error_code
krb5_fcc_read_addr(krb5_context context, krb5_ccache id, krb5_address *addr)
{
     krb5_error_code kret;
     krb5_ui_2 ui2;
     krb5_int32 int32;

     k5_assert_locked(&((krb5_fcc_data *) id->data)->lock);

     addr->magic = KV5M_ADDRESS;
     addr->contents = 0;

     kret = krb5_fcc_read_ui_2(context, id, &ui2);
     CHECK(kret);
     addr->addrtype = ui2;
     
     kret = krb5_fcc_read_int32(context, id, &int32);
     CHECK(kret);
     if ((int32 & VALID_INT_BITS) != int32)     /* Overflow int??? */
	  return KRB5_CC_NOMEM;
     addr->length = int32;
     /* Length field is "unsigned int", which may be smaller than 32
        bits.  */
     if (addr->length != int32)
	 return KRB5_CC_NOMEM;	/* XXX */

     if (addr->length == 0)
	     return KRB5_OK;

     addr->contents = (krb5_octet *) malloc(addr->length);
     if (addr->contents == NULL)
	  return KRB5_CC_NOMEM;

     kret = krb5_fcc_read(context, id, addr->contents, addr->length);
     CHECK(kret);

     return KRB5_OK;
 errout:
     if (addr->contents) {
	 krb5_xfree(addr->contents);
	 addr->contents = NULL;
     }
     return kret;
}

static krb5_error_code
krb5_fcc_read_int32(krb5_context context, krb5_ccache id, krb5_int32 *i)
{
    krb5_fcc_data *data = (krb5_fcc_data *)id->data;
    krb5_error_code retval;
    unsigned char buf[4];
    krb5_int32 val;

    k5_assert_locked(&((krb5_fcc_data *) id->data)->lock);

    if ((data->version == KRB5_FCC_FVNO_1) ||
	(data->version == KRB5_FCC_FVNO_2)) 
	return krb5_fcc_read(context, id, (krb5_pointer) i, sizeof(krb5_int32));
    else {
	retval = krb5_fcc_read(context, id, buf, 4);
	if (retval)
	    return retval;
        val = buf[0];
        val = (val << 8) | buf[1];
        val = (val << 8) | buf[2];
        val = (val << 8) | buf[3];
        *i = val;
	return 0;
    }
}

static krb5_error_code
krb5_fcc_read_ui_2(krb5_context context, krb5_ccache id, krb5_ui_2 *i)
{
    krb5_fcc_data *data = (krb5_fcc_data *)id->data;
    krb5_error_code retval;
    unsigned char buf[2];
    
    k5_assert_locked(&((krb5_fcc_data *) id->data)->lock);

    if ((data->version == KRB5_FCC_FVNO_1) ||
	(data->version == KRB5_FCC_FVNO_2))
	return krb5_fcc_read(context, id, (krb5_pointer) i, sizeof(krb5_ui_2));
    else {
	retval = krb5_fcc_read(context, id, buf, 2);
	if (retval)
	    return retval;
	*i = (buf[0] << 8) + buf[1];
	return 0;
    }
}    

static krb5_error_code
krb5_fcc_read_octet(krb5_context context, krb5_ccache id, krb5_octet *i)
{
    k5_assert_locked(&((krb5_fcc_data *) id->data)->lock);
    return krb5_fcc_read(context, id, (krb5_pointer) i, 1);
}    


static krb5_error_code
krb5_fcc_read_times(krb5_context context, krb5_ccache id, krb5_ticket_times *t)
{
    krb5_fcc_data *data = (krb5_fcc_data *)id->data;
    krb5_error_code retval;
    krb5_int32 i;
    
    k5_assert_locked(&((krb5_fcc_data *) id->data)->lock);

    if ((data->version == KRB5_FCC_FVNO_1) ||
	(data->version == KRB5_FCC_FVNO_2))
	return krb5_fcc_read(context, id, (krb5_pointer) t, sizeof(krb5_ticket_times));
    else {
	retval = krb5_fcc_read_int32(context, id, &i);
	CHECK(retval);
	t->authtime = i;
	
	retval = krb5_fcc_read_int32(context, id, &i);
	CHECK(retval);
	t->starttime = i;

	retval = krb5_fcc_read_int32(context, id, &i);
	CHECK(retval);
	t->endtime = i;

	retval = krb5_fcc_read_int32(context, id, &i);
	CHECK(retval);
	t->renew_till = i;
    }
    return 0;
errout:
    return retval;
}

static krb5_error_code
krb5_fcc_read_authdata(krb5_context context, krb5_ccache id, krb5_authdata ***a)
{
     krb5_error_code kret;
     krb5_int32 length;
     size_t msize;
     int i;

     k5_assert_locked(&((krb5_fcc_data *) id->data)->lock);

     *a = 0;

     /* Read the number of components */
     kret = krb5_fcc_read_int32(context, id, &length);
     CHECK(kret);

     if (length == 0)
	 return KRB5_OK;

     /* Make *a able to hold length pointers to krb5_authdata structs
      * Add one extra for a null-terminated list
      */
     msize = length;
     msize += 1;
     if (msize == 0 || msize - 1 != length || length < 0)
	 return KRB5_CC_NOMEM;
     *a = ALLOC (msize, krb5_authdata *);
     if (*a == NULL)
	  return KRB5_CC_NOMEM;

     for (i=0; i < length; i++) {
	  (*a)[i] = (krb5_authdata *) malloc(sizeof(krb5_authdata));
	  if ((*a)[i] == NULL) {
	      krb5_free_authdata(context, *a);
	      return KRB5_CC_NOMEM;
	  }
	  (*a)[i]->contents = NULL;
	  kret = krb5_fcc_read_authdatum(context, id, (*a)[i]);
	  CHECK(kret);
     }

     return KRB5_OK;
 errout:
     if (*a) {
	 krb5_free_authdata(context, *a);
	 *a = NULL;
     }
     return kret;
}

static krb5_error_code
krb5_fcc_read_authdatum(krb5_context context, krb5_ccache id, krb5_authdata *a)
{
    krb5_error_code kret;
    krb5_int32 int32;
    krb5_ui_2 ui2;
    
    k5_assert_locked(&((krb5_fcc_data *) id->data)->lock);

    a->magic = KV5M_AUTHDATA;
    a->contents = NULL;

    kret = krb5_fcc_read_ui_2(context, id, &ui2);
    CHECK(kret);
    a->ad_type = (krb5_authdatatype)ui2;
    kret = krb5_fcc_read_int32(context, id, &int32);
    CHECK(kret);
    if ((int32 & VALID_INT_BITS) != int32)     /* Overflow int??? */
          return KRB5_CC_NOMEM;
    a->length = int32;
    /* Value could have gotten truncated if int is smaller than 32
       bits.  */
    if (a->length != int32)
	return KRB5_CC_NOMEM;	/* XXX */
    
    if (a->length == 0 )
	    return KRB5_OK;

    a->contents = (krb5_octet *) malloc(a->length);
    if (a->contents == NULL)
	return KRB5_CC_NOMEM;

    kret = krb5_fcc_read(context, id, a->contents, a->length);
    CHECK(kret);
    
     return KRB5_OK;
 errout:
     if (a->contents) {
	 krb5_xfree(a->contents);
	 a->contents = NULL;
     }
     return kret;
    
}
#undef CHECK

#define CHECK(ret) if (ret != KRB5_OK) return ret;

/*
 * Requires:
 * id is open
 *
 * Effects:
 * Writes len bytes from buf into the file cred cache id.
 *
 * Errors:
 * system errors
 */
static krb5_error_code
krb5_fcc_write(krb5_context context, krb5_ccache id, krb5_pointer buf, unsigned int len)
{
     int ret;

     k5_assert_locked(&((krb5_fcc_data *) id->data)->lock);
     invalidate_cache((krb5_fcc_data *) id->data);

     ret = write(((krb5_fcc_data *)id->data)->file, (char *) buf, len);
     if (ret < 0)
	  return krb5_fcc_interpret(context, errno);
     if (ret != len)
         return KRB5_CC_WRITE;
     return KRB5_OK;
}

/*
 * FOR ALL OF THE FOLLOWING FUNCTIONS:
 * 
 * Requires:
 * ((krb5_fcc_data *) id->data)->file is open and at the right position.
 *
 * mutex is locked
 * 
 * Effects:
 * Stores an encoded version of the second argument in the
 * cache file.
 *
 * Errors:
 * system errors
 */

static krb5_error_code
krb5_fcc_store_principal(krb5_context context, krb5_ccache id, krb5_principal princ)
{
    krb5_fcc_data *data = (krb5_fcc_data *)id->data;
    krb5_error_code ret;
    krb5_int32 i, length, tmp, type;

    k5_assert_locked(&((krb5_fcc_data *) id->data)->lock);

    type = krb5_princ_type(context, princ);
    tmp = length = krb5_princ_size(context, princ);

    if (data->version == KRB5_FCC_FVNO_1) {
	/*
	 * DCE-compatible format means that the length count
	 * includes the realm.  (It also doesn't include the
	 * principal type information.)
	 */
	tmp++;
    } else {
	ret = krb5_fcc_store_int32(context, id, type);
	CHECK(ret);
    }
    
    ret = krb5_fcc_store_int32(context, id, tmp);
    CHECK(ret);

    ret = krb5_fcc_store_data(context, id, krb5_princ_realm(context, princ));
    CHECK(ret);

    for (i=0; i < length; i++) {
	ret = krb5_fcc_store_data(context, id, krb5_princ_component(context, princ, i));
	CHECK(ret);
    }

    return KRB5_OK;
}

static krb5_error_code
krb5_fcc_store_addrs(krb5_context context, krb5_ccache id, krb5_address **addrs)
{
     krb5_error_code ret;
     krb5_address **temp;
     krb5_int32 i, length = 0;

     k5_assert_locked(&((krb5_fcc_data *) id->data)->lock);

     /* Count the number of components */
     if (addrs) {
	     temp = addrs;
	     while (*temp++)
		     length += 1;
     }

     ret = krb5_fcc_store_int32(context, id, length);
     CHECK(ret);
     for (i=0; i < length; i++) {
	  ret = krb5_fcc_store_addr(context, id, addrs[i]);
	  CHECK(ret);
     }

     return KRB5_OK;
}

static krb5_error_code
krb5_fcc_store_keyblock(krb5_context context, krb5_ccache id, krb5_keyblock *keyblock)
{
     krb5_fcc_data *data = (krb5_fcc_data *)id->data;
     krb5_error_code ret;

     k5_assert_locked(&((krb5_fcc_data *) id->data)->lock);

     ret = krb5_fcc_store_ui_2(context, id, keyblock->enctype);
     CHECK(ret);
     if (data->version == KRB5_FCC_FVNO_3) {
	 ret = krb5_fcc_store_ui_2(context, id, keyblock->enctype);
	 CHECK(ret);
     }
     ret = krb5_fcc_store_ui_4(context, id, keyblock->length);
     CHECK(ret);
     return krb5_fcc_write(context, id, (char *) keyblock->contents, keyblock->length);
}

static krb5_error_code
krb5_fcc_store_addr(krb5_context context, krb5_ccache id, krb5_address *addr)
{
     krb5_error_code ret;

     k5_assert_locked(&((krb5_fcc_data *) id->data)->lock);

     ret = krb5_fcc_store_ui_2(context, id, addr->addrtype);
     CHECK(ret);
     ret = krb5_fcc_store_ui_4(context, id, addr->length);
     CHECK(ret);
     return krb5_fcc_write(context, id, (char *) addr->contents, addr->length);
}


static krb5_error_code
krb5_fcc_store_data(krb5_context context, krb5_ccache id, krb5_data *data)
{
     krb5_error_code ret;

     k5_assert_locked(&((krb5_fcc_data *) id->data)->lock);

     ret = krb5_fcc_store_ui_4(context, id, data->length);
     CHECK(ret);
     return krb5_fcc_write(context, id, data->data, data->length);
}

static krb5_error_code
krb5_fcc_store_int32(krb5_context context, krb5_ccache id, krb5_int32 i)
{
    krb5_fcc_data *data = (krb5_fcc_data *)id->data;
    unsigned char buf[4];

    k5_assert_locked(&((krb5_fcc_data *) id->data)->lock);

    if ((data->version == KRB5_FCC_FVNO_1) ||
	(data->version == KRB5_FCC_FVNO_2)) 
	return krb5_fcc_write(context, id, (char *) &i, sizeof(krb5_int32));
    else {
        buf[3] = (unsigned char) (i & 0xFF);
	i >>= 8;
        buf[2] = (unsigned char) (i & 0xFF);
	i >>= 8;
        buf[1] = (unsigned char) (i & 0xFF);
	i >>= 8;
        buf[0] = (unsigned char) (i & 0xFF);
	return krb5_fcc_write(context, id, buf, 4);
    }
}

static krb5_error_code
krb5_fcc_store_ui_4(krb5_context context, krb5_ccache id, krb5_ui_4 i)
{
    krb5_fcc_data *data = (krb5_fcc_data *)id->data;
    unsigned char buf[4];

    k5_assert_locked(&((krb5_fcc_data *) id->data)->lock);

    if ((data->version == KRB5_FCC_FVNO_1) ||
	(data->version == KRB5_FCC_FVNO_2)) 
	return krb5_fcc_write(context, id, (char *) &i, sizeof(krb5_int32));
    else {
        buf[3] = (unsigned char) (i & 0xFF);
	i >>= 8;
        buf[2] = (unsigned char) (i & 0xFF);
	i >>= 8;
        buf[1] = (unsigned char) (i & 0xFF);
	i >>= 8;
        buf[0] = (unsigned char) (i & 0xFF);
	return krb5_fcc_write(context, id, buf, 4);
    }
}

static krb5_error_code
krb5_fcc_store_ui_2(krb5_context context, krb5_ccache id, krb5_int32 i)
{
    krb5_fcc_data *data = (krb5_fcc_data *)id->data;
    krb5_ui_2 ibuf;
    unsigned char buf[2];
    
    k5_assert_locked(&((krb5_fcc_data *) id->data)->lock);

    if ((data->version == KRB5_FCC_FVNO_1) ||
	(data->version == KRB5_FCC_FVNO_2)) {
        ibuf = (krb5_ui_2) i;
	return krb5_fcc_write(context, id, (char *) &ibuf, sizeof(krb5_ui_2));
    } else {
        buf[1] = (unsigned char) (i & 0xFF);
	i >>= 8;
        buf[0] = (unsigned char) (i & 0xFF);
	return krb5_fcc_write(context, id, buf, 2);
    }
}
   
static krb5_error_code
krb5_fcc_store_octet(krb5_context context, krb5_ccache id, krb5_int32 i)
{
    krb5_octet ibuf;

    k5_assert_locked(&((krb5_fcc_data *) id->data)->lock);

    ibuf = (krb5_octet) i;
    return krb5_fcc_write(context, id, (char *) &ibuf, 1);
}
   
static krb5_error_code
krb5_fcc_store_times(krb5_context context, krb5_ccache id, krb5_ticket_times *t)
{
    krb5_fcc_data *data = (krb5_fcc_data *)id->data;
    krb5_error_code retval;

    k5_assert_locked(&((krb5_fcc_data *) id->data)->lock);

    if ((data->version == KRB5_FCC_FVNO_1) ||
	(data->version == KRB5_FCC_FVNO_2))
	return krb5_fcc_write(context, id, (char *) t, sizeof(krb5_ticket_times));
    else {
	retval = krb5_fcc_store_int32(context, id, t->authtime);
	CHECK(retval);
	retval = krb5_fcc_store_int32(context, id, t->starttime);
	CHECK(retval);
	retval = krb5_fcc_store_int32(context, id, t->endtime);
	CHECK(retval);
	retval = krb5_fcc_store_int32(context, id, t->renew_till);
	CHECK(retval);
	return 0;
    }
}
   
static krb5_error_code
krb5_fcc_store_authdata(krb5_context context, krb5_ccache id, krb5_authdata **a)
{
    krb5_error_code ret;
    krb5_authdata **temp;
    krb5_int32 i, length=0;

    k5_assert_locked(&((krb5_fcc_data *) id->data)->lock);

    if (a != NULL) {
	for (temp=a; *temp; temp++)
	    length++;
    }

    ret = krb5_fcc_store_int32(context, id, length);
    CHECK(ret);
    for (i=0; i<length; i++) {
	ret = krb5_fcc_store_authdatum (context, id, a[i]);
	CHECK(ret);
    }
    return KRB5_OK;
}

static krb5_error_code
krb5_fcc_store_authdatum (krb5_context context, krb5_ccache id, krb5_authdata *a)
{
    krb5_error_code ret;

    k5_assert_locked(&((krb5_fcc_data *) id->data)->lock);

    ret = krb5_fcc_store_ui_2(context, id, a->ad_type);
    CHECK(ret);
    ret = krb5_fcc_store_ui_4(context, id, a->length);
    CHECK(ret);
    return krb5_fcc_write(context, id, (krb5_pointer) a->contents, a->length);
}
#undef CHECK

static krb5_error_code
krb5_fcc_close_file (krb5_context context, krb5_fcc_data *data)
{
     int ret;
     krb5_error_code retval;

     k5_assert_locked(&data->lock);

     if (data->file == NO_FILE)
	 return KRB5_FCC_INTERNAL;

     retval = krb5_unlock_file(context, data->file);
     ret = close (data->file);
     data->file = NO_FILE;
     if (retval)
	 return retval;

     return ret ? krb5_fcc_interpret (context, errno) : 0;
}

#if defined(ANSI_STDIO) || defined(_WIN32)
#define BINARY_MODE "b"
#else
#define BINARY_MODE ""
#endif

#ifndef HAVE_SETVBUF
#undef setvbuf
#define setvbuf(FILE,BUF,MODE,SIZE) \
  ((SIZE) < BUFSIZE ? (abort(),0) : setbuf(FILE, BUF))
#endif

static krb5_error_code
krb5_fcc_open_file (krb5_context context, krb5_ccache id, int mode)
{
    krb5_os_context os_ctx = &context->os_context;
    krb5_fcc_data *data = (krb5_fcc_data *)id->data;
    krb5_ui_2 fcc_fvno;
    krb5_ui_2 fcc_flen;
    krb5_ui_2 fcc_tag;
    krb5_ui_2 fcc_taglen;
    int f, open_flag;
    int lock_flag;
    krb5_error_code retval = 0;

    k5_assert_locked(&data->lock);
    invalidate_cache(data);

    if (data->file != NO_FILE) {
	/* Don't know what state it's in; shut down and start anew.  */
	(void) krb5_unlock_file(context, data->file);
	(void) close (data->file);
	data->file = NO_FILE;
    }

    switch(mode) {
    case FCC_OPEN_AND_ERASE:
	unlink(data->filename);
	open_flag = O_CREAT|O_EXCL|O_TRUNC|O_RDWR;
	break;
    case FCC_OPEN_RDWR:
	open_flag = O_RDWR;
	break;
    case FCC_OPEN_RDONLY:
    default:
	open_flag = O_RDONLY;
	break;
    }

    f = THREEPARAMOPEN (data->filename, open_flag | O_BINARY, 0600);
    if (f == NO_FILE) {
	switch (errno) {
	case ENOENT:
	    retval = KRB5_FCC_NOFILE;
	    krb5_set_error_message(context, retval,
				   "Credentials cache file '%s' not found",
				   data->filename);
	    return retval;
	default:
	    return krb5_fcc_interpret (context, errno);
	}
    }

    data->mode = mode;

    if (data->mode == FCC_OPEN_RDONLY)
	lock_flag = KRB5_LOCKMODE_SHARED;
    else 
	lock_flag = KRB5_LOCKMODE_EXCLUSIVE;
    if ((retval = krb5_lock_file(context, f, lock_flag))) {
	(void) close(f);
	return retval;
    }

    if (mode == FCC_OPEN_AND_ERASE) {
	 /* write the version number */
         int cnt;

         fcc_fvno = htons(context->fcc_default_format);
         data->version = context->fcc_default_format;
         if ((cnt = write(f, (char *)&fcc_fvno, sizeof(fcc_fvno))) !=
             sizeof(fcc_fvno)) {
             retval = ((cnt == -1) ? krb5_fcc_interpret(context, errno) :
                       KRB5_CC_IO);
             goto done;
         }
         data->file = f;

	 if (data->version == KRB5_FCC_FVNO_4) {
             /* V4 of the credentials cache format allows for header tags */
	     fcc_flen = 0;

	     if (os_ctx->os_flags & KRB5_OS_TOFFSET_VALID)
		 fcc_flen += (2*sizeof(krb5_ui_2) + 2*sizeof(krb5_int32));

	     /* Write header length */
	     retval = krb5_fcc_store_ui_2(context, id, (krb5_int32)fcc_flen);
	     if (retval) goto done;

	     if (os_ctx->os_flags & KRB5_OS_TOFFSET_VALID) {
		 /* Write time offset tag */
		 fcc_tag = FCC_TAG_DELTATIME;
		 fcc_taglen = 2*sizeof(krb5_int32);
		 
		 retval = krb5_fcc_store_ui_2(context,id,(krb5_int32)fcc_tag);
		 if (retval) goto done;
		 retval = krb5_fcc_store_ui_2(context,id,(krb5_int32)fcc_taglen);
		 if (retval) goto done;
		 retval = krb5_fcc_store_int32(context,id,os_ctx->time_offset);
		 if (retval) goto done;
		 retval = krb5_fcc_store_int32(context,id,os_ctx->usec_offset);
		 if (retval) goto done;
	     }
	 }
	 invalidate_cache(data);
	 goto done;
     }

     /* verify a valid version number is there */
    invalidate_cache(data);
     if (read(f, (char *)&fcc_fvno, sizeof(fcc_fvno)) != sizeof(fcc_fvno)) {
	 retval = KRB5_CC_FORMAT;
	 goto done;
     }
     data->version = ntohs(fcc_fvno);
    if ((data->version != KRB5_FCC_FVNO_4) &&
	(data->version != KRB5_FCC_FVNO_3) &&
	(data->version != KRB5_FCC_FVNO_2) &&
	(data->version != KRB5_FCC_FVNO_1)) {
	retval = KRB5_CCACHE_BADVNO;
	goto done;
    }

    data->file = f;

     if (data->version == KRB5_FCC_FVNO_4) {
	 char buf[1024];

	 if (krb5_fcc_read_ui_2(context, id, &fcc_flen) ||
	     (fcc_flen > sizeof(buf)))
	 {
	     retval = KRB5_CC_FORMAT;
	     goto done;
	 }

	 while (fcc_flen) {
	     if ((fcc_flen < (2 * sizeof(krb5_ui_2))) ||
		 krb5_fcc_read_ui_2(context, id, &fcc_tag) ||
		 krb5_fcc_read_ui_2(context, id, &fcc_taglen) ||
		 (fcc_taglen > (fcc_flen - 2*sizeof(krb5_ui_2))))
	     {
		 retval = KRB5_CC_FORMAT;
		 goto done;
	     }

	     switch (fcc_tag) {
	     case FCC_TAG_DELTATIME:
		 if (fcc_taglen != 2*sizeof(krb5_int32)) {
		     retval = KRB5_CC_FORMAT;
		     goto done;
		 }
		 if (!(context->library_options & KRB5_LIBOPT_SYNC_KDCTIME) ||
		     (os_ctx->os_flags & KRB5_OS_TOFFSET_VALID))
		 {
		     if (krb5_fcc_read(context, id, buf, fcc_taglen)) {
			 retval = KRB5_CC_FORMAT;
			 goto done;
		     }
		     break;
		 }
		 if (krb5_fcc_read_int32(context, id, &os_ctx->time_offset) ||
		     krb5_fcc_read_int32(context, id, &os_ctx->usec_offset))
		 {
		     retval = KRB5_CC_FORMAT;
		     goto done;
		 }
		 os_ctx->os_flags =
		     ((os_ctx->os_flags & ~KRB5_OS_TOFFSET_TIME) |
		      KRB5_OS_TOFFSET_VALID);
		 break;
	     default:
		 if (fcc_taglen && krb5_fcc_read(context,id,buf,fcc_taglen)) {
		     retval = KRB5_CC_FORMAT;
		     goto done;
		 }
		 break;
	     }
	     fcc_flen -= (2*sizeof(krb5_ui_2) + fcc_taglen);
	 }
     }

done:
     if (retval) {
         data->file = -1;
         (void) krb5_unlock_file(context, f);
         (void) close(f);
     }
     return retval;
}

static krb5_error_code
krb5_fcc_skip_header(krb5_context context, krb5_ccache id)
{
     krb5_fcc_data *data = (krb5_fcc_data *)id->data;
     krb5_error_code kret;
     krb5_ui_2 fcc_flen;

     k5_assert_locked(&((krb5_fcc_data *) id->data)->lock);

     fcc_lseek(data, (off_t) sizeof(krb5_ui_2), SEEK_SET);
     if (data->version == KRB5_FCC_FVNO_4) {
	 kret = krb5_fcc_read_ui_2(context, id, &fcc_flen);
	 if (kret) return kret;
         if(fcc_lseek(data, (off_t) fcc_flen, SEEK_CUR) < 0)
		return errno;
     }
     return KRB5_OK;
}

static krb5_error_code
krb5_fcc_skip_principal(krb5_context context, krb5_ccache id)
{
     krb5_error_code kret;
     krb5_principal princ;

     k5_assert_locked(&((krb5_fcc_data *) id->data)->lock);

     kret = krb5_fcc_read_principal(context, id, &princ);
     if (kret != KRB5_OK)
	  return kret;

     krb5_free_principal(context, princ);
     return KRB5_OK;
}


/*
 * Modifies:
 * id
 *
 * Effects:
 * Creates/refreshes the file cred cache id.  If the cache exists, its
 * contents are destroyed.
 *
 * Errors:
 * system errors
 * permission errors
 */
static krb5_error_code KRB5_CALLCONV
krb5_fcc_initialize(krb5_context context, krb5_ccache id, krb5_principal princ)
{
     krb5_error_code kret = 0;
     int reti = 0;

     kret = k5_mutex_lock(&((krb5_fcc_data *) id->data)->lock);
     if (kret)
	 return kret;

     MAYBE_OPEN(context, id, FCC_OPEN_AND_ERASE);

#if defined(HAVE_FCHMOD) || defined(HAVE_CHMOD)
     {
#ifdef HAVE_FCHMOD
         reti = fchmod(((krb5_fcc_data *) id->data)->file, S_IREAD | S_IWRITE);
#else
         reti = chmod(((krb5_fcc_data *) id->data)->filename, S_IREAD | S_IWRITE);
#endif
         if (reti == -1) {
             kret = krb5_fcc_interpret(context, errno);
             MAYBE_CLOSE(context, id, kret);
	     k5_mutex_unlock(&((krb5_fcc_data *) id->data)->lock);
             return kret;
         }
     }
#endif
     kret = krb5_fcc_store_principal(context, id, princ);

     MAYBE_CLOSE(context, id, kret);
     k5_mutex_unlock(&((krb5_fcc_data *) id->data)->lock);
     krb5_change_cache ();
     return kret;
}

/*
 * Drop the ref count; if it hits zero, remove the entry from the
 * fcc_set list and free it.
 */
static krb5_error_code dereference(krb5_context context, krb5_fcc_data *data)
{
    krb5_error_code kerr;
    struct fcc_set **fccsp;

    kerr = k5_mutex_lock(&krb5int_cc_file_mutex);
    if (kerr)
	return kerr;
    for (fccsp = &fccs; *fccsp != NULL; fccsp = &(*fccsp)->next)
	if ((*fccsp)->data == data)
	    break;
    assert(*fccsp != NULL);
    assert((*fccsp)->data == data);
    (*fccsp)->refcount--;
    if ((*fccsp)->refcount == 0) {
        struct fcc_set *temp;
	data = (*fccsp)->data;
	temp = *fccsp;
	*fccsp = (*fccsp)->next;
	free(temp);
	k5_mutex_unlock(&krb5int_cc_file_mutex);
	k5_mutex_assert_unlocked(&data->lock);
	free(data->filename);
	zap(data->buf, sizeof(data->buf));
	if (data->file >= 0) {
	    k5_mutex_lock(&data->lock);
	    krb5_fcc_close_file(context, data);
	    k5_mutex_unlock(&data->lock);
	}
	k5_mutex_destroy(&data->lock);
	free(data);
    } else
	k5_mutex_unlock(&krb5int_cc_file_mutex);
    return 0;
}

/*
 * Modifies:
 * id
 *
 * Effects:
 * Closes the file cache, invalidates the id, and frees any resources
 * associated with the cache.
 */
static krb5_error_code KRB5_CALLCONV
krb5_fcc_close(krb5_context context, krb5_ccache id)
{
     dereference(context, (krb5_fcc_data *) id->data);
     krb5_xfree(id);
     return KRB5_OK;
}

/*
 * Effects:
 * Destroys the contents of id.
 *
 * Errors:
 * system errors
 */
static krb5_error_code KRB5_CALLCONV
krb5_fcc_destroy(krb5_context context, krb5_ccache id)
{
     krb5_error_code kret = 0;
     krb5_fcc_data *data = (krb5_fcc_data *) id->data;
     register int ret;

     struct stat buf;
     unsigned long i, size;
     unsigned int wlen;
     char zeros[BUFSIZ];

     kret = k5_mutex_lock(&data->lock);
     if (kret)
	 return kret;

     if (OPENCLOSE(id)) {
	 invalidate_cache(data);
	  ret = THREEPARAMOPEN(data->filename,
			       O_RDWR | O_BINARY, 0);
	  if (ret < 0) {
	      kret = krb5_fcc_interpret(context, errno);
	      goto cleanup;
	  }
	  data->file = ret;
     }
     else
	  fcc_lseek(data, (off_t) 0, SEEK_SET);

#ifdef MSDOS_FILESYSTEM
/* "disgusting bit of UNIX trivia" - that's how the writers of NFS describe
** the ability of UNIX to still write to a file which has been unlinked.
** Naturally, the PC can't do this. As a result, we have to delete the file
** after we wipe it clean but that throws off all the error handling code.
** So we have do the work ourselves.
*/
    ret = fstat(data->file, &buf);
    if (ret == -1) {
        kret = krb5_fcc_interpret(context, errno);
        size = 0;                               /* Nothing to wipe clean */
    } else
        size = (unsigned long) buf.st_size;

    memset(zeros, 0, BUFSIZ);
    while (size > 0) {
        wlen = (int) ((size > BUFSIZ) ? BUFSIZ : size); /* How much to write */
        i = write(data->file, zeros, wlen);
        if (i < 0) {
            kret = krb5_fcc_interpret(context, errno);
            /* Don't jump to cleanup--we still want to delete the file. */
            break;
        }
        size -= i;                              /* We've read this much */
    }

    if (OPENCLOSE(id)) {
        (void) close(((krb5_fcc_data *)id->data)->file);
        data->file = -1;
    }

    ret = unlink(data->filename);
    if (ret < 0) {
        kret = krb5_fcc_interpret(context, errno);
        goto cleanup;
    }

#else /* MSDOS_FILESYSTEM */

     ret = unlink(data->filename);
     if (ret < 0) {
	 kret = krb5_fcc_interpret(context, errno);
	 if (OPENCLOSE(id)) {
	     (void) close(((krb5_fcc_data *)id->data)->file);
	     data->file = -1;
             kret = ret;
	 }
	 goto cleanup;
     }
     
     ret = fstat(data->file, &buf);
     if (ret < 0) {
	 kret = krb5_fcc_interpret(context, errno);
	 if (OPENCLOSE(id)) {
	     (void) close(((krb5_fcc_data *)id->data)->file);
	     data->file = -1;
	 }
	 goto cleanup;
     }

     /* XXX This may not be legal XXX */
     size = (unsigned long) buf.st_size;
     memset(zeros, 0, BUFSIZ);
     for (i=0; i < size / BUFSIZ; i++)
	  if (write(data->file, zeros, BUFSIZ) < 0) {
	      kret = krb5_fcc_interpret(context, errno);
	      if (OPENCLOSE(id)) {
		  (void) close(((krb5_fcc_data *)id->data)->file);
		  data->file = -1;
	      }
	      goto cleanup;
	  }

     wlen = (unsigned int) (size % BUFSIZ);
     if (write(data->file, zeros, wlen) < 0) {
	 kret = krb5_fcc_interpret(context, errno);
	 if (OPENCLOSE(id)) {
	     (void) close(((krb5_fcc_data *)id->data)->file);
	     data->file = -1;
	 }
	 goto cleanup;
     }

     ret = close(data->file);
     data->file = -1;

     if (ret)
	 kret = krb5_fcc_interpret(context, errno);

#endif /* MSDOS_FILESYSTEM */

  cleanup:
     k5_mutex_unlock(&data->lock);
     dereference(context, data);
     krb5_xfree(id);

     krb5_change_cache ();
     return kret;
}

extern const krb5_cc_ops krb5_fcc_ops;

/*
 * Requires:
 * residual is a legal path name, and a null-terminated string
 *
 * Modifies:
 * id
 * 
 * Effects:
 * creates a file-based cred cache that will reside in the file
 * residual.  The cache is not opened, but the filename is reserved.
 * 
 * Returns:
 * A filled in krb5_ccache structure "id".
 *
 * Errors:
 * KRB5_CC_NOMEM - there was insufficient memory to allocate the
 * 		krb5_ccache.  id is undefined.
 * permission errors
 */
static krb5_error_code KRB5_CALLCONV
krb5_fcc_resolve (krb5_context context, krb5_ccache *id, const char *residual)
{
     krb5_ccache lid;
     krb5_error_code kret;
     krb5_fcc_data *data;
     struct fcc_set *setptr;

     kret = k5_mutex_lock(&krb5int_cc_file_mutex);
     if (kret)
	 return kret;
     for (setptr = fccs; setptr; setptr = setptr->next) {
	 if (!strcmp(setptr->data->filename, residual))
	     break;
     }
     if (setptr) {
	 data = setptr->data;
	 assert(setptr->refcount != 0);
	 setptr->refcount++;
	 assert(setptr->refcount != 0);
	 kret = k5_mutex_lock(&data->lock);
	 if (kret) {
	     k5_mutex_unlock(&krb5int_cc_file_mutex);
	     return kret;
	 }
	 k5_mutex_unlock(&krb5int_cc_file_mutex);
     } else {
	 data = malloc(sizeof(krb5_fcc_data));
	 if (data == NULL) {
	     k5_mutex_unlock(&krb5int_cc_file_mutex);
	     return KRB5_CC_NOMEM;
	 }
	 data->filename = strdup(residual);
	 if (data->filename == NULL) {
	     k5_mutex_unlock(&krb5int_cc_file_mutex);
	     free(data);
	     return KRB5_CC_NOMEM;
	 }
	 kret = k5_mutex_init(&data->lock);
	 if (kret) {
	     k5_mutex_unlock(&krb5int_cc_file_mutex);
	     free(data->filename);
	     free(data);
	     return kret;
	 }
	 kret = k5_mutex_lock(&data->lock);
	 if (kret) {
	     k5_mutex_unlock(&krb5int_cc_file_mutex);
	     k5_mutex_destroy(&data->lock);
	     free(data->filename);
	     free(data);
	     return kret;
	 }
	 /* data->version,mode filled in for real later */
	 data->version = data->mode = 0;
	 data->flags = KRB5_TC_OPENCLOSE;
	 data->file = -1;
	 data->valid_bytes = 0;
	 setptr = malloc(sizeof(struct fcc_set));
	 if (setptr == NULL) {
	     k5_mutex_unlock(&krb5int_cc_file_mutex);
	     k5_mutex_destroy(&data->lock);
	     free(data->filename);
	     free(data);
	     return KRB5_CC_NOMEM;
	 }
	 setptr->refcount = 1;
	 setptr->data = data;
	 setptr->next = fccs;
	 fccs = setptr;
	 k5_mutex_unlock(&krb5int_cc_file_mutex);
     }

     k5_mutex_assert_locked(&data->lock);
     k5_mutex_unlock(&data->lock);
     lid = (krb5_ccache) malloc(sizeof(struct _krb5_ccache));
     if (lid == NULL) {
	 dereference(context, data);
	 return KRB5_CC_NOMEM;
     }

     lid->ops = &krb5_fcc_ops;
     lid->data = data;
     lid->magic = KV5M_CCACHE;

     /* other routines will get errors on open, and callers must expect them,
	if cache is non-existent/unusable */
     *id = lid;
     return KRB5_OK;
}

/*
 * Effects:
 * Prepares for a sequential search of the credentials cache.
 * Returns and krb5_cc_cursor to be used with krb5_fcc_next_cred and
 * krb5_fcc_end_seq_get.
 *
 * If the cache is modified between the time of this call and the time
 * of the final krb5_fcc_end_seq_get, the results are undefined.
 *
 * Errors:
 * KRB5_CC_NOMEM
 * system errors
 */
static krb5_error_code KRB5_CALLCONV
krb5_fcc_start_seq_get(krb5_context context, krb5_ccache id,
		       krb5_cc_cursor *cursor)
{
     krb5_fcc_cursor *fcursor;
     krb5_error_code kret = KRB5_OK;
     krb5_fcc_data *data = (krb5_fcc_data *)id->data;

     kret = k5_mutex_lock(&data->lock);
     if (kret)
	 return kret;

     fcursor = (krb5_fcc_cursor *) malloc(sizeof(krb5_fcc_cursor));
     if (fcursor == NULL) {
	 k5_mutex_unlock(&data->lock);
	 return KRB5_CC_NOMEM;
     }
     if (OPENCLOSE(id)) {
          kret = krb5_fcc_open_file(context, id, FCC_OPEN_RDONLY);
          if (kret) {
              krb5_xfree(fcursor);
	      k5_mutex_unlock(&data->lock);
              return kret;
          }
     }

     /* Make sure we start reading right after the primary principal */
     kret = krb5_fcc_skip_header(context, id);
     if (kret) goto done;
     kret = krb5_fcc_skip_principal(context, id);
     if (kret) goto done;

     fcursor->pos = fcc_lseek(data, (off_t) 0, SEEK_CUR);
     *cursor = (krb5_cc_cursor) fcursor;

done:
     MAYBE_CLOSE(context, id, kret);
     k5_mutex_unlock(&data->lock);
     return kret;
}


/*
 * Requires:
 * cursor is a krb5_cc_cursor originally obtained from
 * krb5_fcc_start_seq_get.
 *
 * Modifes:
 * cursor, creds
 * 
 * Effects:
 * Fills in creds with the "next" credentals structure from the cache
 * id.  The actual order the creds are returned in is arbitrary.
 * Space is allocated for the variable length fields in the
 * credentials structure, so the object returned must be passed to
 * krb5_destroy_credential.
 *
 * The cursor is updated for the next call to krb5_fcc_next_cred.
 *
 * Errors:
 * system errors
 */
static krb5_error_code KRB5_CALLCONV
krb5_fcc_next_cred(krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor,
		   krb5_creds *creds)
{
#define TCHECK(ret) if (ret != KRB5_OK) goto lose;
     krb5_error_code kret;
     krb5_fcc_cursor *fcursor;
     krb5_int32 int32;
     krb5_octet octet;
     krb5_fcc_data *d = (krb5_fcc_data *) id->data;

     kret = k5_mutex_lock(&d->lock);
     if (kret)
	 return kret;

     memset((char *)creds, 0, sizeof(*creds));
     MAYBE_OPEN(context, id, FCC_OPEN_RDONLY);
     fcursor = (krb5_fcc_cursor *) *cursor;

     kret = (fcc_lseek(d, fcursor->pos, SEEK_SET) == (off_t) -1);
     if (kret) {
	 kret = krb5_fcc_interpret(context, errno);
	 MAYBE_CLOSE(context, id, kret);
	 k5_mutex_unlock(&d->lock);
	 return kret;
     }

     kret = krb5_fcc_read_principal(context, id, &creds->client);
     TCHECK(kret);
     kret = krb5_fcc_read_principal(context, id, &creds->server);
     TCHECK(kret);
     kret = krb5_fcc_read_keyblock(context, id, &creds->keyblock);
     TCHECK(kret);
     kret = krb5_fcc_read_times(context, id, &creds->times);
     TCHECK(kret);
     kret = krb5_fcc_read_octet(context, id, &octet);
     TCHECK(kret);
     creds->is_skey = octet;
     kret = krb5_fcc_read_int32(context, id, &int32);
     TCHECK(kret);
     creds->ticket_flags = int32;
     kret = krb5_fcc_read_addrs(context, id, &creds->addresses);
     TCHECK(kret);
     kret = krb5_fcc_read_authdata(context, id, &creds->authdata);
     TCHECK(kret);
     kret = krb5_fcc_read_data(context, id, &creds->ticket);
     TCHECK(kret);
     kret = krb5_fcc_read_data(context, id, &creds->second_ticket);
     TCHECK(kret);
     
     fcursor->pos = fcc_lseek(d, (off_t) 0, SEEK_CUR);
     cursor = (krb5_cc_cursor *) fcursor;

lose:
     MAYBE_CLOSE (context, id, kret);
     k5_mutex_unlock(&d->lock);
     if (kret != KRB5_OK)
	 krb5_free_cred_contents(context, creds);
     return kret;
}

/*
 * Requires:
 * cursor is a krb5_cc_cursor originally obtained from
 * krb5_fcc_start_seq_get.
 *
 * Modifies:
 * id, cursor
 *
 * Effects:
 * Finishes sequential processing of the file credentials ccache id,
 * and invalidates the cursor (it must never be used after this call).
 */
/* ARGSUSED */
static krb5_error_code KRB5_CALLCONV
krb5_fcc_end_seq_get(krb5_context context, krb5_ccache id, krb5_cc_cursor *cursor)
{
     /* We don't do anything with the file cache itself, so
	no need to lock anything.  */

     /* don't close; it may be left open by the caller,
        and if not, fcc_start_seq_get and/or fcc_next_cred will do the
        MAYBE_CLOSE.
     MAYBE_CLOSE(context, id, kret); */
     krb5_xfree((krb5_fcc_cursor *) *cursor);
     return 0;
}


/*
 * Effects:
 * Creates a new file cred cache whose name is guaranteed to be
 * unique.  The name begins with the string TKT_ROOT (from fcc.h).
 * The cache is not opened, but the new filename is reserved.
 *  
 * Returns:
 * The filled in krb5_ccache id.
 *
 * Errors:
 * KRB5_CC_NOMEM - there was insufficient memory to allocate the
 * 		krb5_ccache.  id is undefined.
 * system errors (from open)
 */
static krb5_error_code KRB5_CALLCONV
krb5_fcc_generate_new (krb5_context context, krb5_ccache *id)
{
     krb5_ccache lid;
     int ret;
     krb5_error_code    kret = 0;
     char scratch[sizeof(TKT_ROOT)+6+1]; /* +6 for the scratch part, +1 for
					    NUL */
     krb5_fcc_data *data;
     krb5_int16 fcc_fvno = htons(context->fcc_default_format);
     krb5_int16 fcc_flen = 0;
     int errsave, cnt;
     struct fcc_set *setptr;
     
     /* Set master lock */
     kret = k5_mutex_lock(&krb5int_cc_file_mutex);
     if (kret)
	 return kret;

     (void) strcpy(scratch, TKT_ROOT);
     (void) strcat(scratch, "XXXXXX");
     ret = mkstemp(scratch);
     if (ret == -1) {
         k5_mutex_unlock(&krb5int_cc_file_mutex);
	 return krb5_fcc_interpret(context, errno);
     }

     /* Allocate memory */
     data = (krb5_pointer) malloc(sizeof(krb5_fcc_data));
     if (data == NULL) {
	  close(ret);
	  unlink(scratch);
	  k5_mutex_unlock(&krb5int_cc_file_mutex);
	  return KRB5_CC_NOMEM;
     }

     data->filename = strdup(scratch);
     if (data->filename == NULL) {
          k5_mutex_unlock(&krb5int_cc_file_mutex);
	  free(data);
	  close(ret);
	  unlink(scratch);
	  k5_mutex_unlock(&krb5int_cc_file_mutex);
	  return KRB5_CC_NOMEM;
     }

     kret = k5_mutex_init(&data->lock);
     if (kret) {
       k5_mutex_unlock(&krb5int_cc_file_mutex);
       free(data->filename);
       free(data);
       close(ret);
       unlink(scratch);
       return kret;
     }
     kret = k5_mutex_lock(&data->lock);
     if (kret) {
       k5_mutex_unlock(&krb5int_cc_file_mutex);
       k5_mutex_destroy(&data->lock);
       free(data->filename);
       free(data);
       close(ret);
       unlink(scratch);
       return kret;
     }

     /*
      * The file is initially closed at the end of this call...
      */
     data->flags = 0;
     data->file = -1;
     data->valid_bytes = 0;
     /* data->version,mode filled in for real later */
     data->version = data->mode = 0;


     /* Ignore user's umask, set mode = 0600 */
#ifndef HAVE_FCHMOD
#ifdef HAVE_CHMOD
     chmod(data->filename, S_IRUSR | S_IWUSR);
#endif
#else
     fchmod(ret, S_IRUSR | S_IWUSR);
#endif
     if ((cnt = write(ret, (char *)&fcc_fvno, sizeof(fcc_fvno)))
	 != sizeof(fcc_fvno)) {
	  errsave = errno;
	  (void) close(ret);
	  (void) unlink(data->filename);
	  kret = (cnt == -1) ? krb5_fcc_interpret(context, errsave) : KRB5_CC_IO;
	  goto err_out;
     }
     /* For version 4 we save a length for the rest of the header */
     if (context->fcc_default_format == KRB5_FCC_FVNO_4) {
	  if ((cnt = write(ret, (char *)&fcc_flen, sizeof(fcc_flen)))
	      != sizeof(fcc_flen)) {
	       errsave = errno;
	       (void) close(ret);
	       (void) unlink(data->filename);
	       kret = (cnt == -1) ? krb5_fcc_interpret(context, errsave) : KRB5_CC_IO;
	       goto err_out;
	  }
     }
     if (close(ret) == -1) {
	  errsave = errno;
	  (void) unlink(data->filename);
	  kret = krb5_fcc_interpret(context, errsave);
	  goto err_out;
     }


     setptr = malloc(sizeof(struct fcc_set));
     if (setptr == NULL) {
       k5_mutex_unlock(&krb5int_cc_file_mutex);
       k5_mutex_destroy(&data->lock);
       free(data->filename);
       free(data);
       (void) close(ret);
       (void) unlink(scratch);
       return KRB5_CC_NOMEM;
     }
     setptr->refcount = 1;
     setptr->data = data;
     setptr->next = fccs;
     fccs = setptr;
     k5_mutex_unlock(&krb5int_cc_file_mutex);

     k5_mutex_assert_locked(&data->lock);
     k5_mutex_unlock(&data->lock);
     lid = (krb5_ccache) malloc(sizeof(struct _krb5_ccache));
     if (lid == NULL) {
	 dereference(context, data);
	 return KRB5_CC_NOMEM;
     }

     lid->ops = &krb5_fcc_ops;
     lid->data = data;
     lid->magic = KV5M_CCACHE;

     /* default to open/close on every trn - otherwise destroy 
	will get as to state confused */
     ((krb5_fcc_data *) lid->data)->flags = KRB5_TC_OPENCLOSE;

     *id = lid;

       
     krb5_change_cache ();
     return KRB5_OK;

err_out:
     k5_mutex_unlock(&krb5int_cc_file_mutex);
     k5_mutex_destroy(&data->lock);
     free(data->filename);
     free(data);
     return kret;
}

/*
 * Requires:
 * id is a file credential cache
 * 
 * Returns:
 * The name of the file cred cache id.
 */
static const char * KRB5_CALLCONV
krb5_fcc_get_name (krb5_context context, krb5_ccache id)
{
     return (char *) ((krb5_fcc_data *) id->data)->filename;
}

/*
 * Modifies:
 * id, princ
 *
 * Effects:
 * Retrieves the primary principal from id, as set with
 * krb5_fcc_initialize.  The principal is returned is allocated
 * storage that must be freed by the caller via krb5_free_principal.
 *
 * Errors:
 * system errors
 * KRB5_CC_NOMEM
 */
static krb5_error_code KRB5_CALLCONV
krb5_fcc_get_principal(krb5_context context, krb5_ccache id, krb5_principal *princ)
{
     krb5_error_code kret = KRB5_OK;

     kret = k5_mutex_lock(&((krb5_fcc_data *) id->data)->lock);
     if (kret)
	 return kret;

     MAYBE_OPEN(context, id, FCC_OPEN_RDONLY);
     
     /* make sure we're beyond the header */
     kret = krb5_fcc_skip_header(context, id);
     if (kret) goto done;
     kret = krb5_fcc_read_principal(context, id, princ);

done:
     MAYBE_CLOSE(context, id, kret);
     k5_mutex_unlock(&((krb5_fcc_data *) id->data)->lock);
     return kret;
}

     
static krb5_error_code KRB5_CALLCONV
krb5_fcc_retrieve(krb5_context context, krb5_ccache id, krb5_flags whichfields, krb5_creds *mcreds, krb5_creds *creds)
{
    return krb5_cc_retrieve_cred_default (context, id, whichfields,
					  mcreds, creds);
}


/*
 * Modifies:
 * the file cache
 *
 * Effects:
 * stores creds in the file cred cache
 *
 * Errors:
 * system errors
 * storage failure errors
 */
static krb5_error_code KRB5_CALLCONV
krb5_fcc_store(krb5_context context, krb5_ccache id, krb5_creds *creds)
{
#define TCHECK(ret) if (ret != KRB5_OK) goto lose;
     krb5_error_code ret;

     ret = k5_mutex_lock(&((krb5_fcc_data *) id->data)->lock);
     if (ret)
	 return ret;

     /* Make sure we are writing to the end of the file */
     MAYBE_OPEN(context, id, FCC_OPEN_RDWR);

     /* Make sure we are writing to the end of the file */
     ret = fcc_lseek((krb5_fcc_data *) id->data, (off_t) 0, SEEK_END);
     if (ret < 0) {
          MAYBE_CLOSE_IGNORE(context, id);
	  k5_mutex_unlock(&((krb5_fcc_data *) id->data)->lock);
	  return krb5_fcc_interpret(context, errno);
     }

     ret = krb5_fcc_store_principal(context, id, creds->client);
     TCHECK(ret);
     ret = krb5_fcc_store_principal(context, id, creds->server);
     TCHECK(ret);
     ret = krb5_fcc_store_keyblock(context, id, &creds->keyblock);
     TCHECK(ret);
     ret = krb5_fcc_store_times(context, id, &creds->times);
     TCHECK(ret);
     ret = krb5_fcc_store_octet(context, id, (krb5_int32) creds->is_skey);
     TCHECK(ret);
     ret = krb5_fcc_store_int32(context, id, creds->ticket_flags);
     TCHECK(ret);
     ret = krb5_fcc_store_addrs(context, id, creds->addresses);
     TCHECK(ret);
     ret = krb5_fcc_store_authdata(context, id, creds->authdata);
     TCHECK(ret);
     ret = krb5_fcc_store_data(context, id, &creds->ticket);
     TCHECK(ret);
     ret = krb5_fcc_store_data(context, id, &creds->second_ticket);
     TCHECK(ret);

lose:
     MAYBE_CLOSE(context, id, ret);
     k5_mutex_unlock(&((krb5_fcc_data *) id->data)->lock);
     krb5_change_cache ();
     return ret;
#undef TCHECK
}

/* 
 * Non-functional stub implementation for krb5_fcc_remove
 * 
 * Errors:
 *    KRB5_CC_NOSUPP - not implemented
 */
static krb5_error_code KRB5_CALLCONV
krb5_fcc_remove_cred(krb5_context context, krb5_ccache cache, krb5_flags flags,
                     krb5_creds *creds)
{
    return KRB5_CC_NOSUPP;
}

/*
 * Requires:
 * id is a cred cache returned by krb5_fcc_resolve or
 * krb5_fcc_generate_new, but has not been opened by krb5_fcc_initialize.
 *
 * Modifies:
 * id
 * 
 * Effects:
 * Sets the operational flags of id to flags.
 */
static krb5_error_code KRB5_CALLCONV
krb5_fcc_set_flags(krb5_context context, krb5_ccache id, krb5_flags flags)
{
    krb5_error_code ret = KRB5_OK;

    ret = k5_mutex_lock(&((krb5_fcc_data *) id->data)->lock);
    if (ret)
	return ret;

    /* XXX This should check for illegal combinations, if any.. */
    if (flags & KRB5_TC_OPENCLOSE) {
	/* asking to turn on OPENCLOSE mode */
	if (!OPENCLOSE(id)
	    /* XXX Is this test necessary? */
	    && ((krb5_fcc_data *) id->data)->file != NO_FILE)
            (void) krb5_fcc_close_file (context, ((krb5_fcc_data *) id->data));
    } else {
	/* asking to turn off OPENCLOSE mode, meaning it must be
	   left open.  We open if it's not yet open */
        MAYBE_OPEN(context, id, FCC_OPEN_RDONLY);
    }

    ((krb5_fcc_data *) id->data)->flags = flags;
    k5_mutex_unlock(&((krb5_fcc_data *) id->data)->lock);
    return ret;
}

/*
 * Requires:
 * id is a cred cache returned by krb5_fcc_resolve or
 * krb5_fcc_generate_new, but has not been opened by krb5_fcc_initialize.
 *
 * Modifies:
 * id (mutex only; temporary)
 * 
 * Effects:
 * Returns the operational flags of id.
 */
static krb5_error_code KRB5_CALLCONV
krb5_fcc_get_flags(krb5_context context, krb5_ccache id, krb5_flags *flags)
{
    krb5_error_code ret = KRB5_OK;

    ret = k5_mutex_lock(&((krb5_fcc_data *) id->data)->lock);
    if (ret)
	return ret;
    *flags = ((krb5_fcc_data *) id->data)->flags;
    k5_mutex_unlock(&((krb5_fcc_data *) id->data)->lock);
    return ret;
}


static krb5_error_code
krb5_fcc_interpret(krb5_context context, int errnum)
{
    register krb5_error_code retval;
    switch (errnum) {
    case ENOENT:
	retval = KRB5_FCC_NOFILE;
	break;
    case EPERM:
    case EACCES:
#ifdef EISDIR
    case EISDIR:                        /* Mac doesn't have EISDIR */
#endif
    case ENOTDIR:
#ifdef ELOOP
    case ELOOP:                         /* Bad symlink is like no file. */
#endif
#ifdef ETXTBSY
    case ETXTBSY:
#endif
    case EBUSY:
    case EROFS:
	retval = KRB5_FCC_PERM;
	break;
    case EINVAL:
    case EEXIST:			/* XXX */
    case EFAULT:
    case EBADF:
#ifdef ENAMETOOLONG
    case ENAMETOOLONG:
#endif
#ifdef EWOULDBLOCK
    case EWOULDBLOCK:
#endif
	retval = KRB5_FCC_INTERNAL;
	break;
#ifdef EDQUOT
    case EDQUOT:
#endif
    case ENOSPC:
    case EIO:
    case ENFILE:
    case EMFILE:
    case ENXIO:
    default:
	retval = KRB5_CC_IO;		/* XXX */
	krb5_set_error_message(context, retval,
			       "Credentials cache I/O operation failed (%s)",
			       strerror(errnum));
    }
    return retval;
}

const krb5_cc_ops krb5_fcc_ops = {
     0,
     "FILE",
     krb5_fcc_get_name,
     krb5_fcc_resolve,
     krb5_fcc_generate_new,
     krb5_fcc_initialize,
     krb5_fcc_destroy,
     krb5_fcc_close,
     krb5_fcc_store,
     krb5_fcc_retrieve,
     krb5_fcc_get_principal,
     krb5_fcc_start_seq_get,
     krb5_fcc_next_cred,
     krb5_fcc_end_seq_get,
     krb5_fcc_remove_cred,
     krb5_fcc_set_flags,
     krb5_fcc_get_flags,
};

#if defined(_WIN32)
/*
 * krb5_change_cache should be called after the cache changes.
 * A notification message is is posted out to all top level
 * windows so that they may recheck the cache based on the
 * changes made.  We register a unique message type with which
 * we'll communicate to all other processes. 
 */

krb5_error_code 
krb5_change_cache (void) {

    PostMessage(HWND_BROADCAST, krb5_get_notification_message(), 0, 0);

    return 0;
}

unsigned int KRB5_CALLCONV
krb5_get_notification_message (void) {
    static unsigned int message = 0;

    if (message == 0)
        message = RegisterWindowMessage(WM_KERBEROS5_CHANGED);

    return message;
}
#else /* _WIN32 */

krb5_error_code
krb5_change_cache (void)
{
    return 0;
}
unsigned int
krb5_get_notification_message (void)
{
    return 0;
}

#endif /* _WIN32 */

const krb5_cc_ops krb5_cc_file_ops = {
     0,
     "FILE",
     krb5_fcc_get_name,
     krb5_fcc_resolve,
     krb5_fcc_generate_new,
     krb5_fcc_initialize,
     krb5_fcc_destroy,
     krb5_fcc_close,
     krb5_fcc_store,
     krb5_fcc_retrieve,
     krb5_fcc_get_principal,
     krb5_fcc_start_seq_get,
     krb5_fcc_next_cred,
     krb5_fcc_end_seq_get,
     krb5_fcc_remove_cred,
     krb5_fcc_set_flags,
     krb5_fcc_get_flags,
     NULL,
     NULL,
     NULL,
     NULL,
     NULL,
     NULL,
};