summaryrefslogtreecommitdiffstats
path: root/src/mac/kconfig/kconfig.c
blob: 153f70584095b9658426caba9a2fa09ea5ff7b50 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
/*
 * Copyright 1991-1994 by The University of Texas at Austin
 * All rights reserved.
 *
 * For infomation contact:
 * Rick Watson
 * University of Texas
 * Computation Center, COM 1
 * Austin, TX 78712
 * r.watson@utexas.edu
 * 512-471-3241
 */

/*
 * Kconfig
 */
#include <stdio.h>
#ifndef __MWERKS__
#include <Controls.h>
#include <Desk.h>
#include <DiskInit.h>
#include <Devices.h>
#include <Dialogs.h>
#include <Errors.h>
#include <Events.h>
#include <Folders.h>
#include <Fonts.h>
#include <GestaltEqu.h>
#include <Lists.h>
#include <Memory.h>
#include <Menus.h>
#include <Notification.h>
#include <OSEvents.h>
#include <OSUtils.h>
#include <Packages.h>
#include <Printing.h>
#include <QuickDraw.h>
#include <Resources.h>
#include <Scrap.h>
#include <Script.h>
#include <StdArg.h>
#include <StdLib.h>
#include <String.h>
#include <Strings.h>
#include <SysEqu.h>
#include <TextEdit.h>
#include <ToolUtils.h>
#include <Traps.h>
#include <Windows.h>
#include <StdLib.h>

#define TRUE 1
#define FALSE 0
#endif

#define CELLH 12						/* list cell height */

#ifdef KRB4
#	define	DEFINE_SOCKADDR
#	include "krb.h"
#	include "kconfig.h"
#	include "kconfig.proto.h"
#	include "krb_driver.h"
#	include "kconfig.vers"
#	include "glue.h"
#endif

#ifdef KRB5
#	include "k5-int.h"
#	include "com_err.h"
#	include "kconfig.h"
#	include "kconfig.proto.h"
#	include "kconfig.vers"
#	include "prof_int.h"
#	include "adm_proto.h"
#endif

#include "WindowUtil.h"

#define num_WaitNextEvent	0x60
#define num_JugglDispatch	0x8F	/* The Temp Memory calls (RWR) */
#define num_UnknownTrap		0x9F
#define num_ScriptTrap		0xBF
#define switchEvt	 1 /* Switching event (suspend/resume )	 for app4evt */

//#define dangerousPattern 1
#define KFAILURE 255
#define KSUCCESS 0


	//  IH 05.03.96: PPC Port, must use UPPs instead of Procedure Ptrs
static DeviceLoopDrawingUPP	gpictdrawprocUPP = NULL;
static ModalFilterUPP 		gklistFilterUPP = NULL;
static ModalFilterUPP		gokFilterUPP = NULL;
static ModalFilterUPP		ginternalBufferFilterUPP = NULL;
static UserItemUPP			gdooutlineUPP = NULL;
static UserItemUPP			gdopictUPP = NULL;
static UserItemUPP			gdrawRealmUPP = NULL;
static UserItemUPP			gdolistUPP = NULL;


/*
 * Globals
 */
#ifdef KRB4
	krbHiParmBlock khipb;
	krbParmBlock klopb;
	/* We use the mac stubs to open the driver. */
#	define	kdriver	mac_stubs_kdriver		/* .Kerberos driver reference */
#endif

#ifdef KRB5
	krb5_context kcontext;
	krb5_ccache k5_ccache;
    static char ccname[FILENAME_MAX] = "ccredcache";           /* ccache file location */
#endif

MenuHandle menus[NUM_MENUS];
DialogPtr maind = 0;					/* main dialog window */
Rect oldzoom;
ParamBlockRec pb;
queuetype domainQ = 0;
queuetype serverQ = 0;
queuetype credentialsQ = 0;
ListHandle dlist;						/* domain list */
ListHandle slist;						/* server list */
struct listfilter lf;					/* lf for maind */
Handle ddeleteHandle, deditHandle;
Handle sdeleteHandle, seditHandle;
preferences prefs;						/* preferences */

#ifdef KRB4
char *prefsFilename = "\pCNS Config Preferences";
#endif

#ifdef KRB5
char *prefsFilename = "\pCNSk5 Config Preferences";
#define kUNKNOWNUSERNAME "Unknown"
char gUserName[255];					/* last user name */
char gRealmName[255];					/* last realm name */
#endif

/*+
 * Function: Initializes ccache and catches illegal caches such as
 *  bad format or no permissions.
 *
 * Parameters:
 *  ccache - credential cache structure to use
 *
 * Returns: krb5_error_code
 */
static krb5_error_code
k5_init_ccache (krb5_ccache *ccache) {
    krb5_error_code code;
    krb5_principal princ;
    FILE *fp;

    code = krb5_cc_default (kcontext, ccache); // Initialize the ccache
    if (code)
        return code;

    code = krb5_cc_get_principal (kcontext, *ccache, &princ);
    if (code == KRB5_FCC_NOFILE) {              // Doesn't exist yet
        fp = fopen (krb5_cc_get_name(kcontext, *ccache), "w");
        if (fp == NULL)                         // Can't open it
            return KRB5_FCC_PERM;
        fclose (fp);
    }

    if (code) {                                 // Bad, delete and try again
        remove (krb5_cc_get_name(kcontext, *ccache));
        code = krb5_cc_get_principal (kcontext, *ccache, &princ);
        if (code == KRB5_FCC_NOFILE)            // Doesn't exist yet
            return 0;
        if (code)
            return code;
    }

    krb5_free_principal (kcontext, princ);
    return 0;
}

int main (void)
{
	int i, s;
	MenuHandle menuhandle;

	/*	
	 * Setup
	 */
	InitGraf (&qd.thePort); /* Init the graf port */
	InitFonts();
	InitWindows();
	InitMenus();
	TEInit();
	InitDialogs(0);
	InitCursor();
	FlushEvents(everyEvent, 0);
#ifdef KRB4
	init_cornell_des();
#endif
#ifdef KRB5
	k5_init_ccache (&k5_ccache);
	strcpy(gUserName, kUNKNOWNUSERNAME);
#endif
	
		//  IH 05.03.95: Create the UPPs for ToolBox callback routines
	gpictdrawprocUPP = NewDeviceLoopDrawingProc(pictdrawproc);
	if (gpictdrawprocUPP == NULL)
		doalert("Error creating a Universal Proc Pointer");
	gklistFilterUPP = NewModalFilterProc(klistFilter);
	if (gklistFilterUPP == NULL)
		doalert("Error creating a Universal Proc Pointer");
	gokFilterUPP = NewModalFilterProc(okFilter);
	if (gokFilterUPP == NULL)
		doalert("Error creating a Universal Proc Pointer");
	ginternalBufferFilterUPP = NewModalFilterProc(internalBufferFilter);
	if (ginternalBufferFilterUPP == NULL)
		doalert("Error creating a Universal Proc Pointer");
	gdooutlineUPP = NewUserItemProc(dooutline);	
	if (gdooutlineUPP == NULL)
		doalert("Error creating a Universal Proc Pointer");
	gdopictUPP = NewUserItemProc(dopict);	
	if (gdopictUPP == NULL)
		doalert("Error creating a Universal Proc Pointer");
	gdrawRealmUPP = NewUserItemProc(drawRealm);	
	if (gdrawRealmUPP == NULL)
		doalert("Error creating a Universal Proc Pointer");
	gdolistUPP = NewUserItemProc(dolist);	
	if (gdolistUPP == NULL)
		doalert("Error creating a Universal Proc Pointer");

	readprefs();
	
	/*
	 *	Setup the menus.  Assumes the menu resources start at 128 and are
	 *	contiguous.
	 */
	for (i = 0; i < NUM_MENUS; i++) {
		menuhandle = GetMenu(i + MENU_OFFSET);
		if (menuhandle == 0) 
			break;

		if (i < MENU_SUBMENUS)			/* if not a submenu */
			InsertMenu(menuhandle, 0);
		else
			InsertMenu(menuhandle, -1);
		menus[i] = menuhandle;
	}
	AddResMenu (menus[APPL_MENU], 'DRVR');
	DrawMenuBar();

#ifdef KRB4
	s = krb_start_session((char *)0);
	if (s != KSUCCESS) {
		doalert("Kerberos driver is not installed");
		getout(0);
	}
#endif

#ifdef KRB5
    krb5_init_context(&kcontext);
    if (kcontext->profile == 0)
    {
    	doalert("Kerberos configuration file not present");
    	getout(0);
    }
    krb5_init_ets(kcontext);
#endif

	/*
	 * build the main window
	 */
	bzero(&oldzoom, sizeof(oldzoom));
#ifdef KRB4
	getRealmMaps();
	getServerMaps();
#endif
#ifdef KRB5
	getServerMaps();	/* Get Servers first */
	getRealmMaps();		/* Need servers to get realms */
#endif

	buildmain();

	/*
	 * Run the main event loop.
	 */
	mainEvent();
}


/*
 * mainEvent
 * The main event loop.
 */
void mainEvent ()
{
	int s, state;
	int aborted;
	int in_background;
	int running = TRUE;
	unsigned long curtime;
	short item;
	EventRecord event;
	DialogPtr mydlg;
	Point cell;
	
	while (running) {
		WaitNextEvent (everyEvent, &event, 30, NULL);
		
		/*
		 * Update display items.
		 */
		updatedisplay();

		/*
		 * Set the state of the edit and delete buttons depending on if any
		 * cells are selected or not.
		 */
		SetPt(&cell, 0, 0);
		if (LGetSelect(true, &cell, dlist))
			state = 0;
		else
			state = 255;					/* disable */
		HiliteControl((ControlHandle) ddeleteHandle, state);
		HiliteControl((ControlHandle) deditHandle, state);

		SetPt(&cell, 0, 0);
		if (LGetSelect(true, &cell, slist))
			state = 0;
		else
			state = 255;					/* disable */
		HiliteControl((ControlHandle) sdeleteHandle, state);
		HiliteControl((ControlHandle) seditHandle, state);

		/*
		 * First handle some events we want to see before the
		 * Dialog Manager sees them. If we continue, we will
		 * bypass letting the Dialog Manager look at the
		 * events.
		 */
		switch (event.what) {
		case mouseDown:
			if (HandleMouseDown(&event))
				continue;
			break;

		case keyDown:
			if ((event.modifiers & cmdKey) && 
				((event.message & 0x7f) == '.')) {
				aborted = TRUE;
				SysBeep(20);
				continue;
			} else if (event.modifiers & cmdKey) {
				HandleMenu(MenuKey(event.message&charCodeMask), 
						   event.modifiers);
				continue;
			}
			break;

		case app4Evt:					/* really a suspend/resume event */
			switch ((event.message>>24) & 0xff) {
			case switchEvt:
				/* Treat switch events as activate events too */
				if (event.message & 0x01) { /* Resume Event */
					in_background = FALSE;
					doactivate(FrontWindow(), activeFlag);
					break;
				} else {				/* Suspend Event */
					in_background = TRUE;
					doactivate(FrontWindow(), 0);
					break;
				}
			}
			break;

		case updateEvt:
			if (doupdate((WindowPtr) event.message)) /* handle updates */
				continue;
			break;

		case activateEvt:				/* (de)active a window */
			if (doactivate((WindowPtr) event.message, event.modifiers))
				continue;
			break;

		case diskEvt:					/* disk inserted */
			if (((event.message >> 16) & 0xFFFF) != noErr) {
				DILoad();
				DIBadMount(event.where, event.message);
				DIUnload();
				continue;
			}
			break;
		} /* switch */

		/*
		 * Let the Dialog Manager have a crack at it.
		 */
		if (IsDialogEvent (&event))
			if (DialogSelect (&event, &mydlg, &item))
				if (mydlg == maind)
					mainhit(&event, mydlg, item);
	}									/* while */
	
	getout(0);
}


int HandleMouseDown (event)
	EventRecord *event;
{
	struct cmdw *cmdw;
	WindowPtr window;

	int windowCode = FindWindow (event->where, &window);
	
	switch (windowCode) {
	
	case inSysWindow: 
		SystemClick (event, window);
		return TRUE;
		
	case inMenuBar:
		HandleMenu(MenuSelect(event->where), event->modifiers);
		return TRUE;
		
	case inContent:
		if (window != FrontWindow ()) {
			if (window == (WindowPtr)maind) {
				SelectWindow(window);
				return TRUE;
			}
		} else if (window == (WindowPtr)maind) {
#ifdef notdef
			(void) listevents(maind, event);
			return TRUE;
#endif
		}
		break;

	case inDrag:						/* Wanna drag? */
		SelectWindow(window);
		DragWindow (window, event->where, &qd.screenBits.bounds);
		writeprefs();
		return TRUE;

	case inGoAway:
		if (window == (WindowPtr)maind)
			if (TrackGoAway (window, event->where))
				getout(0);
		break;

#ifdef notdef
	case inGrow:
		if (window != FrontWindow()) {
			SelectWindow(window);
			return TRUE;
		} else {
			if (window == (WindowPtr)maind) {
				dogrow(window, event->where);
				return TRUE;
			}
		}
		break;
#endif
		
	case inZoomOut:
		if (window == (WindowPtr)maind) {
		}
		break;
		
	} /* switch */

	return FALSE;
}


/*
 * HandleMenu - handle menu events.
 */
HandleMenu (long which, short modifiers)
{
	int id;								/* menu id */
	int item;							/* menu item */
	int s;
	short num;
	WindowPtr window;
	struct cmdw *cmdw;
	char fname[256];
	Point pt;
	SFReply reply;
	
	item = which & 0xFFFF;
	id = which >> 16;
	
	switch (id - MENU_OFFSET) {
	case APPL_MENU:						/* Mac system menu item */
		handapple(item);
		break;

	case FILE_MENU:						/* File menu */
		switch (item) {
		case LOGIN_FILE:
			doLogin();
			break;
		
		case LOGOUT_FILE:
			doLogout();
			break;
		
		case PASSWORD_FILE:
			kpass_dialog();
			break;

		case LIST_FILE:
			klist_dialog();
			break;

		case QUIT_FILE:					/* Quit */
		case CLOSE_FILE:				/* Close Window */
			getout(0);
		}
		break;

	case EDIT_MENU:
		window = FrontWindow();
	
		switch(item) {
		case UNDO_EDIT:					/* undo */
			SysBeep(3);
			break;

		case CUT_EDIT:					/* cut */
			break;

		case COPY_EDIT:					/* copy */
			break;

		case PASTE_EDIT:				/* paste */
			break;

		case CLEAR_EDIT:				/* clear */
			break;
		}
		break;

	}

	HiliteMenu(0);
}

	
/*
 * doupdate
 */
int doupdate (WindowPtr window)
{
#ifdef notdef
	GrafPtr savePort;

	GetPort (&savePort);
	SetPort (window);

	if (window == (WindowPtr)maind) {
		BeginUpdate (window);

		DrawGrowIcon(window);

		EndUpdate(window);
		return FALSE;
	}

	SetPort(savePort);
#endif
	return FALSE;
}


/*
 * doactivate
 */
int doactivate (WindowPtr window, int mod)
{
	GrafPtr savePort;
	struct cmdw *cmdw;
	
	if (!window)
		return FALSE;

	GetPort (&savePort);
	SetPort (window);

	HiliteWindow (window, ((mod & activeFlag) != 0));
	
#ifdef notdef
	if (window == (WindowPtr)maind)
		DrawGrowIcon(window);
#endif

	SetPort (savePort);
	return FALSE;
}


#ifdef notdef
/*
 * dogrow
 */
void dogrow (WindowPtr window, Point p)
{
    long gr;
    int height;
    int width;
    Rect growRect;
    GrafPtr savePort;

    growRect = qd.screenBits.bounds;
    growRect.top = 50;					/* minimal horizontal size */
    growRect.left = 50;					/* minimal vertical size */

    gr = GrowWindow(window, p, &growRect);

    if (gr == 0)
		return;
    height = HiWord (gr);
    width = LoWord (gr);

    SizeWindow (window, width, height, FALSE); /* resize the window */

    GetPort (&savePort);
    SetPort (window);
	/* setsizes(false); */
    InvalRect(&window->portRect);		/* invalidate whole window rectangle */
    EraseRect(&window->portRect);
    SetPort (savePort);
}
#endif


/* 
 * handapple - Handle the apple menu, either running a desk accessory
 *			   or calling a routine to display information about our
 *			   program.	 Use the practice of
 *			   checking for available memory, and saving the GrafPort
 *			   described in the DA Manager's Guide.
 */
handapple (accitem)
	int accitem;
{
	GrafPtr savePort;					/* Where to save current port */
	Handle acchdl;						/* holds ptr to accessory resource */
	Str255 accname;						/* string holds accessory name */
	long accsize;						/* holds size of the acc + stack */

	if (accitem == 1) {
		about ();
		return;
	}
	GetItem (menus[APPL_MENU], accitem, accname); /* get the pascal name */
	SetResLoad (FALSE);					/* don't load into memory */

	/* figure out acc size + heap */
	accsize = SizeResource (GetNamedResource ((ResType) 'DRVR', accname));
	acchdl = NewHandle (accsize);		/* try for a block this size */
	SetResLoad (TRUE);					/* reset flag for rsrc mgr */
	if (!acchdl) {						/* if not able to get a chunk */
		SysBeep(3);
		return;
	}
	DisposHandle (acchdl);				/* get rid of this handle */
	GetPort (&savePort);				/* save the current port */
	OpenDeskAcc (accname);				/* run desk accessory */
	SetPort (savePort);					/* and put back our port */
}


#define DTH 14							/* dialog text height */
void about ()
{
	int ok;
	GrafPtr savePort;
	DialogPtr dialog;
	short item;
	short itemType;
	Handle itemHandle;
	Rect itemRect;

	GetPort(&savePort);

	PositionTemplate((Rect *)0, 'DLOG', DLOG_ABOUT, 50, 50);
	dialog = GetNewDialog(DLOG_ABOUT, (Ptr)0, (WindowPtr)-1);
	SetPort((GrafPtr)dialog);

	/*
	 * Set the draw procedure for the user items.
	 */
	GetDItem(dialog, ABOUT_OUT, &itemType, &itemHandle, &itemRect);
		//  IH 05.03.96: PPC Port - Replace Procedure Pointer by UPP
	SetDItem(dialog, ABOUT_OUT, itemType, (Handle)gdooutlineUPP, &itemRect);
	GetDItem(dialog, ABOUT_PICT, &itemType, &itemHandle, &itemRect);
		//  IH 05.03.96: PPC Port - Replace Procedure Pointer by UPP
	SetDItem(dialog, ABOUT_PICT, itemType, (Handle)gdopictUPP, &itemRect);

	ok = 0;
	do {
		/* 
		 * process hits in the dialog.
		 */
		ModalDialog(0, &item);
				
		switch(item) {
		case ABOUT_OK:
			ok = 1;
			break;
		} /* switch */
	} while (ok == 0);

	DisposDialog(dialog);
	SetPort(savePort);
}


pascal void pictdrawproc (short depth, short flags, GDHandle device, DialogPtr dialog)
{
	#pragma unused (device, flags)
	
	if (depth < 8)
		drawpict(dialog, PICT_ABOUT_BW);
	else
		drawpict(dialog, PICT_ABOUT_C);
}


void drawpict (DialogPtr dialog, int id)
{
	Handle h;
	Rect rect;
    short itemType;
    Handle itemHandle;
    Rect itemRect;
	GrafPtr savePort;

	GetPort(&savePort);
	SetPort(dialog);

	GetDItem(dialog, ABOUT_PICT, &itemType, &itemHandle, &itemRect);
	if (h = Get1Resource('PICT', id)) {
		LoadResource(h);
		if (!ResError()) {
			HLock(h);

			bcopy(((char *)*h)+2, &rect, sizeof(Rect));
			AlignRect(&itemRect, &rect, 50, 50);
			DrawPicture((PicHandle)h, &rect);
			HUnlock(h);
		}
	}
	SetPort(savePort);
}


/*
 * this routine will be called by the Dialog Manager to draw the pict
 */
pascal void dopict (DialogPtr dialog, short itemNo)
{
	long qdv;
	
	if (!trapAvailable(_DeviceLoop) || Gestalt('qd  ', &qdv) || ((qdv&0xff) == 0)) { /* if old mac */
		drawpict(dialog, PICT_ABOUT_BW);
	} else {
			//  IH 05.03.96: PPC Port - Replace Procedure Pointer by UPP
		DeviceLoop(dialog->visRgn, gpictdrawprocUPP, 
				   (long)dialog, 0);
	}
}


/*
 * this routine will be called by the Dialog Manager to draw the outline of the
 * default button.
 */
pascal void dooutline (DialogPtr dialog, short itemNo)
{
	short		itemType;
	Handle		itemHandle;
	Rect		itemRect;
	
	GetDItem(dialog, itemNo, &itemType, &itemHandle, &itemRect);
	/* 
	 * outline the default button (see IM I-407).  in this case it 
	 * is the OK button. this lets the user know that pressing 
	 * the return will have the same effect as clicking this button.
	 */
	PenSize(3, 3);
	InsetRect(&itemRect, -4, -4);
	FrameRoundRect(&itemRect, 16, 16);
	PenSize(1, 1);
}


/*
 * ------------------ routines ------------------
 */


/*
 * updatedisplay
 * Update the main display window.
 */
void updatedisplay ()
{
	int s, savemode;
	Str255 scratch;
	static Str255 oldrealm = "", olduser = "";
	GrafPtr savePort;
	short itemType;
	Handle itemHandle;
	Rect itemRect;
	Point pt;
		
	if (!maind)
		return;
		
	GetPort(&savePort);
	SetPort(maind);
	
	/*
	 * Display the local realm
	 */
#ifdef KRB4
	klopb.uRealm = scratch;
	if (s = lowcall(cKrbGetLocalRealm))
		strcpy(scratch, "None");
#endif
#ifdef KRB5
{
char *ptr;
	if (krb5_get_default_realm(kcontext, &ptr) == 0)
	{
		strcpy(scratch, ptr);
		free(ptr);
	}
	else
		strcpy(scratch, "None");
}
#endif

	if (strcmp(scratch, oldrealm)) {
		GetDItem(maind, MAIN_REALM, &itemType, &itemHandle, &itemRect);
		savemode = maind->txMode;
		MoveTo(itemRect.left+4, itemRect.bottom-4);
		strcpy(oldrealm, scratch);
		c2pstr(scratch);
		TextMode(srcCopy);
		DrawString(scratch);
		GetPen(&pt);
		itemRect.right -= 17;	/* room for triangle */
		itemRect.left = pt.h;
		InsetRect(&itemRect, 1, 1);
		EraseRect(&itemRect);	/* erase remainder of space in rect */
		TextMode(savemode);
	}
	
	/*
	 * Display the local user
	 */
#ifdef KRB4
	bzero(&khipb, sizeof(krbHiParmBlock));
	khipb.user = scratch;
	if (s = hicall(cKrbGetUserName))
		strcpy(scratch, "None");
#endif
#ifdef KRB5
	if (strcmp(gUserName, kUNKNOWNUSERNAME))
	{
		strcpy(scratch, gUserName);
		strcat(scratch, "@");
		strcat(scratch, gRealmName);
	}
	else
		strcpy(scratch, kUNKNOWNUSERNAME);
#endif
	if (strcmp(scratch, olduser)) {
		strcpy(olduser, scratch);
		c2pstr(scratch);
		setText(maind, MAIN_USER, scratch);
	}
	SetPort(savePort);
}


void setText (DialogPtr dialog, int item, char *text)
{
	short itemType;
	Handle itemHandle;
	Rect itemRect;

	GetDItem(dialog, item, &itemType, &itemHandle, &itemRect);
	SetIText(itemHandle, text);
}


/*
 * buildmain
 * Build the main window.
 */
void buildmain ()
{
	int h;
	int n, cellw;
	int ndomains, nservers;
	int listwidth;
	short itemNo;				/* the item in the dialog selected */
	short itemType;				/* dummy parameter for call to GetDItem */
	Handle itemHandle;			/* dummy parameter for call to GetDItem */
	Rect itemRect;				/* the location of the list in the dialog */
	Rect dataBounds;			/* the dimensions of the data in the list */
	Point cellSize;				/* width and height of a cells rectangle */
	Point cell;					/* an index through the list */
	char string[255];
	short length;
	short checked;				/* flag for check box value */
	short bit;					/* used as a mask to test selection flags */ 
	struct user *user, *save, *tmp;
	char *cp;
	GrafPtr savePort;
    Handle wh;					/* window handle */
    Rect *rectp;
	DialogPtr dialog;
	Rect dRect, sRect;
	domaintype *dp;
	servertype *sp;
	
    /*
     * Get the dialog resource and modify the location.
     * Since it will already be in memory, GetNewDialog will use
     * the values we just set.
	 * ??? WE SHOULD MAKE SURE THE WINDOW IS ON THE SCREEN ???
     */
	if (prefs.wrect.top != prefs.wrect.bottom) {
		if (wh = GetResource('DLOG', DLOG_MAIN)) {
			rectp = (Rect *)*wh;
			bcopy(&prefs.wrect, rectp, sizeof(Rect));
			PositionRectOnScreen(rectp, false);
/*			PositionRect(rectp, rectp, 50, 50);			/* make sure on screen */
		}
	}
	maind = dialog = GetNewDialog(DLOG_MAIN, (Ptr)0, (WindowPtr) -1);
	if (!maind) {
		doalert("DLOG %d missing", DLOG_MAIN);
		getout(0);
	}
	GetPort(&savePort);
	SetPort((GrafPtr)maind);

	/* 
	 * allow the dialog manager routines to access various things
	 */
	((DialogPeek)dialog)->window.refCon = (long)&lf;
		
	/* 
	 * set the procedure pointer for the user items in the dialog.
	 * this will allow he default button to be outlined and the list 
	 * to be drawn by the Dialog Manger.
     * Also, set the correct list heights.
	 */
	GetDItem(dialog, MAIN_REALM, &itemType, &itemHandle, &itemRect);
		//  IH 05.03.96: PPC Port - Replace Procedure Pointer by UPP
	SetDItem(dialog, MAIN_REALM, itemType, (Handle)gdrawRealmUPP, &itemRect);
	
	GetDItem(dialog, MAIN_DMAP, &itemType, &itemHandle, &dRect);
	h = (((dRect.bottom - dRect.top) / CELLH) * CELLH);
	dRect.bottom = dRect.top + h;
		//  IH 05.03.96: PPC Port - Replace Procedure Pointer by UPP
	SetDItem(dialog, MAIN_DMAP, itemType, (Handle) gdolistUPP, &dRect);

	GetDItem(dialog, MAIN_SERVERS, &itemType, &itemHandle, &sRect);
	h = (((sRect.bottom - sRect.top) / CELLH) * CELLH);
	sRect.bottom = sRect.top + h;
		//  IH 05.03.96: PPC Port - Replace Procedure Pointer by UPP
	SetDItem(dialog, MAIN_SERVERS, itemType, (Handle) gdolistUPP, &sRect);

	GetDItem(dialog, MAIN_DDELETE, &itemType, &ddeleteHandle, &itemRect);
	GetDItem(dialog, MAIN_SDELETE, &itemType, &sdeleteHandle, &itemRect);
	GetDItem(dialog, MAIN_DEDIT, &itemType, &deditHandle, &itemRect);
	GetDItem(dialog, MAIN_SEDIT, &itemType, &seditHandle, &itemRect);

	listwidth = dRect.right - dRect.left;

	/* 
	 * make room for scroll bars (see IM IV-270)
	 */
	dRect.right -= 15;
	sRect.right -= 15;	

	/* 
	 * create domain list
	 */
	ndomains = 0;								/* count items */
	for (dp = (domaintype *)domainQ; dp; dp = dp->next)
		ndomains++;
	SetRect(&dataBounds, 0, 0, 1, ndomains);
	SetPt(&cellSize, dRect.right-dRect.left, CELLH);
	dlist = LNew(&dRect, &dataBounds, cellSize, 128,
				(WindowPtr) dialog, false, false, false, true);

	/* 
	 * use the default selection flags
	 */
	(*dlist)->selFlags = 0;

	/*
	 * Initialize the cells in the list.
	 */
	dp = (domaintype *)domainQ;
	cell.h = cell.v = 0;
	while (dp) {
		setdcellstring(string, dp);
		LSetCell(string, strlen(string), cell, dlist);
		cell.v++;
		dp = dp->next;
	}

	/* 
	 * create servers list
	 */
	nservers = 0;								/* count items */
	for (sp = (servertype *)serverQ; sp; sp = sp->next)
		nservers++;
	SetRect(&dataBounds, 0, 0, 1, nservers);
	SetPt(&cellSize, sRect.right-sRect.left, CELLH);
	slist = LNew(&sRect, &dataBounds, cellSize, 128, 
				(WindowPtr) dialog, false, false, false, true);

	/* 
	 * use the default selection flags
	 */
	(*slist)->selFlags = 0;

	/*
	 * Initialize the cells in the list.
	 */
	sp = (servertype *)serverQ;
	cell.h = cell.v = 0;
	while (sp) {
		setscellstring(string, sp);
		LSetCell(string, strlen(string), cell, slist);
		cell.v++;
		sp = sp->next;
	}

	lf.nlists = 2;
	lf.list[0] = dlist;
	lf.list[1] = slist;
	lf.listitem[0] = MAIN_DMAP;
	lf.listitem[1] = MAIN_SERVERS;
	lf.edititem[0] = MAIN_DEDIT;
	lf.edititem[1] = MAIN_SEDIT;

	/* 
	 * turn cell drawing on only after the cell contents have been initialized.
	 * this will avoid watching the delay between the LSetCells 
	 * calls and is faster.
	 */
	LDoDraw(true, dlist);
	LDoDraw(true, slist);
		
	DrawMenuBar();
	SetPort (savePort);					/* and put back our port */
}


/*
 * setdcellstring
 */
void setdcellstring (unsigned char *string, domaintype *dp)
{
	unsigned char *cp;

	cp = string;
	strcpy(cp, dp->host);
	cp += strlen(cp);
		
	strcpy(cp, "\x09" "170;");			/* tab over */
	cp += strlen(cp);

	strcpy(cp, dp->realm);
	cp += strlen(cp);

	*cp = '\0';
}


/*
 * setscellstring
 */
void setscellstring (unsigned char *string, servertype *sp)
{
	unsigned char *cp;

	cp = string;
	strcpy(cp, sp->host);
	cp += strlen(cp);
		
	strcpy(cp, "\x09" "170;");			/* tab over */
	cp += strlen(cp);

	strcpy(cp, sp->realm);
	cp += strlen(cp);

	if (sp->admin) {
		strcpy(cp, "\x09" "360;");
		cp += strlen(cp);
		strcpy(cp, "Admin");
		cp += strlen(cp);
	}

	*cp = '\0';
}


/*
 * setrcellstring
 */
void setrcellstring (unsigned char *string, credentialstype *rp)
{
#ifdef KRB4
	unsigned char *cp;
	
	cp = string;				/* name */
	strcpy(cp, rp->name);	
	cp += strlen(cp);
	if (rp->instance[0]) {		/* instance */
		*cp++ = '.';
		strcpy(cp, rp->instance);
		cp += strlen(cp);
	}
	if (rp->realm[0]) {			/* realm */
		*cp++ = '@';
		strcpy(cp, rp->realm);
		cp += strlen(cp);
	}
	strcpy(cp, "\x09" "170;");	/* tab */
	cp += strlen(cp);
	strcpy(cp, rp->sname);		/* sname */
	cp += strlen(cp);
	if (rp->sinstance[0]) {		/* sinstance */
		*cp++ = '.';
		strcpy(cp, rp->sinstance);
		cp += strlen(cp);
	}
	if (rp->srealm[0]) {		/* srealm */
		*cp++ = '@';
		strcpy(cp, rp->srealm);
		cp += strlen(cp);
	}
	*cp = '\0';
#endif
#ifdef KRB5
	unsigned char *cp;
	
	cp = string;

	strcpy(cp, rp->pname);		/* name */
	cp += strlen(cp);

	strcpy(cp, "\x09" "170;");	/* tab */
	cp += strlen(cp);

	strcpy(cp, rp->cname);		/* credential name */
	cp += strlen(cp);

	*cp = '\0';
#endif
}


/*
 * drawRealm
 * Called by the Dialog manager to draw user items
 */
pascal void drawRealm (DialogPtr dialog, short item)
{
	int s, savemode;
	short itemType;
	Handle itemHandle;
	Rect itemRect;
	Str255 scratch;
	GrafPtr savePort;
	Point pt;
	
	GetPort(&savePort);
	SetPort(dialog);

	/*
	 * Display the local realm
	 */
#ifdef KRB4
	klopb.uRealm = scratch;
	if (s = lowcall(cKrbGetLocalRealm))
		strcpy(scratch, "None");
#endif
#ifdef KRB5
{
char *ptr;
	if (krb5_get_default_realm(kcontext, &ptr) == 0)
	{
		strcpy(scratch, ptr);
		free(ptr);
	}
	else
		strcpy(scratch, "None");
}
#endif

	GetDItem(dialog, item, &itemType, &itemHandle, &itemRect);
	EraseRect(&itemRect);
	doshadow(&itemRect);
	dotriangle(&itemRect);

	savemode = dialog->txMode;
	MoveTo(itemRect.left+4, itemRect.bottom-4);
	c2pstr(scratch);
	TextMode(srcCopy);
	DrawString(scratch);
	TextMode(savemode);
	GetPen(&pt);
	itemRect.right -= 17;	/* room for triangle */
	itemRect.left = pt.h;
	InsetRect(&itemRect, 1, 1);
	EraseRect(&itemRect);	/* erase remainder of space in rect */

	SetPort(savePort);
}


/*
 * this routine will be called by the Dialog Manager to draw the list. 
 */
pascal void dolist (DialogPtr dialog, short itemNo)
{
	int i;
	short itemType;
	Handle itemHandle;
	Rect itemRect;
	ListHandle list;
	struct listfilter *lf;

	/*
	 * figure out which list is being updated
	 */
	lf = (struct listfilter *) ((DialogPeek)dialog)->window.refCon;
	for (i = 0; i < lf->nlists; i++)
 		if (lf->listitem[i] == itemNo)
			break;
	if (i == lf->nlists)
		return;
		
	list = lf->list[i];
	GetDItem(dialog, itemNo,  &itemType, &itemHandle, &itemRect);
	
	/* 
	 *let the List Manager draw the list
	 */
	LUpdate(dialog->visRgn, list);
	
	/* 
	 * draw the lists framing rectangle OUTSIDE the view rectangle.
	 * if the frame is drawn inside the view rectangle then these lines
	 * will be erased, drawn onto or scrolled by the List Manager 
	 * since the lines are within the rectangle LM expects to be 
	 * able to draw in.
	 */
	InsetRect(&itemRect, -1, -1);
	FrameRect(&itemRect);
}


/*
 * mainhit
 * Called when an item in the dialog box is hit.
 */
void mainhit (EventRecord *event, DialogPtr dlg, int item)
{
	int s, i, n;
	int admin;
	int listwidth;
	short itemType;				/* dummy parameter for call to GetDItem */
	Handle itemHandle;			/* dummy parameter for call to GetDItem */
	Rect itemRect;				/* the location of the list in the dialog */
	Point where;
	Point cell;
	GrafPtr savePort;
	char e1[256];
	char e2[256];
	domaintype *dp;
	servertype *sp;
	Str255 string, oldh, oldr;
	
	GetPort(&savePort);
	SetPort(dlg);

	switch (item) {
	case MAIN_LOGIN:						/* login button */
		doLogin();
		break;
		
	case MAIN_LOGOUT: 						/* logout button */
		doLogout();
		break;
		
	case MAIN_DMAP:							/* domain map ui */
		where = event->where;
		GlobalToLocal(&where);
		/*
		 * Unselect cells in other list
		 */
		cell.h = cell.v = 0;
		 while (LGetSelect(true, &cell, slist))
			LSetSelect(false, cell, slist);

		/* 
		 * let the List Manager process the mouse down. this includes 
		 * cell selection dragging, scrolling and double clicks by the 
		 * user.
		 */
		if (LClick(where, event->modifiers, dlist)) {
			/* 
			 * a double click in a cell has occured. find out in which 
			 * one of the cells the user has double clicked in.
			 */
			cell = LLastClick(dlist);
			goto dedit;
		}

		break;
		
	case MAIN_SERVERS:						/* servers map ui */
		where = event->where;
		GlobalToLocal(&where);
		/*
		 * Unselect cells in other list
		 */
		cell.h = cell.v = 0;
		 while (LGetSelect(true, &cell, dlist))
			LSetSelect(false, cell, dlist);

		/* 
		 * let the List Manager process the mouse down. this includes 
		 * cell selection dragging, scrolling and double clicks by the 
		 * user.
		 */
		if (LClick(where, event->modifiers, slist)) {
			/* 
			 * a double click in a cell has occured. find out in which 
			 * one of the cells the user has double clicked in.
			 */
			cell = LLastClick(slist);
			goto sedit;
		}
		break;
		
	case MAIN_PASSWORD:						/* change password button */
		kpass_dialog();
		break;

	case MAIN_DNEW:							/* domain new */
		e1[0] = e2[0] = '\0';
		if (editlist(DLOG_DEDIT, e1, e2, 0)) {
			if (!(dp = (domaintype *)NewPtrClear(sizeof(domaintype)))) {
				SysBeep(20);
				break;
			}
			if (newdp(dp, e1, e2)) {
				qlink(&domainQ, dp);
				cell.v = (*dlist)->dataBounds.bottom;
				cell.h = 0;
				setdcellstring(string, dp);
				LAddRow(1, cell.v, dlist);
				LSetCell(string, strlen(string), cell, dlist);
			}
			addRealmMap(e1, e2);					
		}
		break;
		
	case MAIN_DDELETE:						/* domain delete */
		/*
		 * Loop for selected cells.
		 */
		 SetPt(&cell, 0, 0);
		 while (LGetSelect(true, &cell, dlist)) {
			dp = (domaintype *)domainQ;
			i = cell.v;
			while (dp && (i-- > 0))		/* find selected credential */
				dp = dp->next;
			if (dp) {
				qunlink(&domainQ, dp);
				deleteRealmMap(dp->host);
				DisposePtr((Ptr)dp);
				LSetSelect(false, cell, dlist);
				LDelRow(1, cell.v, dlist);
				SetPt(&cell, 0, 0);
			} else {						/* we are broken */
				SysBeep(20);
				break;
			}
		}
		break;
		
	case MAIN_DEDIT:						/* domain edit */
	dedit:
		/*
		 * Loop for selected cells.
		 */
		SetPt(&cell, 0, 0);
		while (LGetSelect(true, &cell, dlist)) {
			dp = (domaintype *)domainQ;
			i = cell.v;
			while (dp && (i-- > 0))		/* find selected item */
				dp = dp->next;
			if (dp) {
				strcpy(e1, dp->host);
				strcpy(e2, dp->realm);
				strcpy(oldh, dp->host);
				if (editlist(DLOG_DEDIT, e1, e2, 0)) {
					if (newdp(dp, e1, e2)) {
						setdcellstring(string, dp);
						LSetCell(string, strlen(string), cell, dlist);
					}
					deleteRealmMap(oldh);
					addRealmMap(e1, e2);					
				}
				LSetSelect(false, cell, dlist);		/* unselect item */
				SetPt(&cell, 0, 0);
			} else {						/* we are broken */
				SysBeep(20);
				break;
			}
		}
		break;

	case MAIN_SNEW:							/* server new */
		e1[0] = e2[0] = '\0';
		admin = 0;
		if (editlist(DLOG_SEDIT, e1, e2, &admin)) {
			if (!(sp = (servertype *)NewPtrClear(sizeof(servertype)))) {
				SysBeep(20);
				break;
			}
			if (newsp(sp, e1, e2, admin)) {
				qlink(&serverQ, sp);
				cell.v = (*slist)->dataBounds.bottom;
				cell.h = 0;
				setscellstring(string, sp);
				LAddRow(1, cell.v, slist);
				LSetCell(string, strlen(string), cell, slist);
			}
			addServerMap(e1, e2, admin);
		}
		break;
		
	case MAIN_SDELETE:						/* server delete */
		/*
		 * Loop for selected cells.
		 */
		 SetPt(&cell, 0, 0);
		 while (LGetSelect(true, &cell, slist)) {
			sp = (servertype *)serverQ;
			i = cell.v;
			while (sp && (i-- > 0))		/* find selected credential */
				sp = sp->next;
			if (sp) {
				qunlink(&serverQ, sp);
				deleteServerMap(sp->host, sp->realm);
				DisposePtr((Ptr)sp);
				LSetSelect(false, cell, slist);
				LDelRow(1, cell.v, slist);
				SetPt(&cell, 0, 0);
			} else {						/* we are broken */
				SysBeep(20);
				break;
			}
		}
		break;

	case MAIN_SEDIT:						/* server edit */
	sedit:
		/*
		 * Loop for selected cells.
		 */
		SetPt(&cell, 0, 0);
		while (LGetSelect(true, &cell, slist)) {
			sp = (servertype *)serverQ;
			i = cell.v;
			while (sp && (i-- > 0))		/* find selected item */
				sp = sp->next;
			if (sp) {
				strcpy(e1, sp->host);
				strcpy(e2, sp->realm);
				strcpy(oldh, sp->host);
				strcpy(oldr, sp->realm);
				admin = sp->admin;
				if (editlist(DLOG_SEDIT, e1, e2, &admin)) {
					if (newsp(sp, e1, e2, admin)) {
						setscellstring(string, sp);
						LSetCell(string, strlen(string), cell, slist);
					}
					deleteServerMap(oldh, oldr);
					addServerMap(e1, e2, admin);
				}

				LSetSelect(false, cell, slist);		/* unselect item */
				SetPt(&cell, 0, 0);
			} else {						/* we are broken */
				SysBeep(20);
				break;
			}
		}
		break;
		
	case MAIN_REALM:
		GetDItem(dlg, MAIN_REALM, &itemType, &itemHandle, &itemRect);
		if (popRealms(&itemRect, &string)) {
			trimstring(string);
#ifdef KRB4
			bzero(&klopb, sizeof(klopb));
			klopb.uRealm = string;
			if (s = lowcall(cKrbSetLocalRealm))
				kerror("Error in cKrbSetLocalRealm", s);
#endif
#ifdef KRB5
{
int		code;
struct profile_node *node;
char	*nam, *val;
void	*state;

			if ((s = krb5_set_default_realm(kcontext, string)) != 0)
				kerror("Error in cKrbSetLocalRealm", s);
/*also change the profile string to match */
	state = NULL;
	code = profile_find_node_subsection(kcontext->profile->first_file->root, "libdefaults", &state, &nam, &node);
	code = profile_delete_node_relation(node, "default_realm");
	code = profile_add_node(node, "default_realm", string, &node);
}			
#endif
		}			
		break;

	default:
		break;
	}

	SetPort(savePort);
}


/*
 * klist_dialog
 * Display credentials and allow selection/deletion
 */
void klist_dialog ()
{
	int i, ncredentials, listwidth;
	DialogPtr dialog;			/* the dialog */
	short itemNo;				/* the item in the dialog selected */
	short itemType;				/* dummy parameter for call to GetDItem */
	Handle itemHandle;			/* dummy parameter for call to GetDItem */
	Rect itemRect;				/* the location of the list in the dialog */
	Handle deleteHandle;		/* handle of delete button */
	ListHandle list;			/* the list constructed in the dialog */
	Rect dataBounds;			/* the dimensions of the data in the list */
	Point cellSize;				/* width and height of a cells rectangle */
	Point cell;					/* an index through the list */
	GrafPtr savePort;
	unsigned char string[512+4];
	int state;
	int changed = false;
	credentialstype *rp;
	struct listfilter lf;
	
	getCredentialsList();
	
	/*
     * Get the dialog resource and modify the location.
     * Since it will already be in memory, GetNewDialog will use
     * the values we just set.
     */
	PositionTemplate((Rect *)-1, 'DLOG', DLOG_KLIST, 50, 50);
	dialog = GetNewDialog(DLOG_KLIST, (Ptr) 0, (WindowPtr) -1);
	GetPort(&savePort);
	SetPort((GrafPtr) dialog);

	GetDItem(dialog, KLIST_DELETE, &itemType, &deleteHandle, &itemRect);

#ifdef KRB5
/* use logout to delete credentials */
	HideDItem(dialog, KLIST_DELETE);
#endif

	/* 
	 * allow the dialog manager routines to access various things
	 */
	((DialogPeek)dialog)->window.refCon = (long)&lf;
		
	/* 
	 * set the procedure pointer for the user items in the dialog.
	 * this will allow he default button to be outlined and the list 
	 * to be drawn by the Dialog Manger.
	 */
	GetDItem(dialog, KLIST_OUT, &itemType, &itemHandle, &itemRect);
		//  IH 05.03.96: PPC Port - Replace Procedure Pointer by UPP
	SetDItem(dialog, KLIST_OUT, itemType, (Handle) gdooutlineUPP, &itemRect);
		
	GetDItem(dialog, KLIST_LIST, &itemType, &itemHandle, &itemRect);
		//  IH 05.03.96: PPC Port - Replace Procedure Pointer by UPP
	SetDItem(dialog, KLIST_LIST, itemType, (Handle) gdolistUPP, &itemRect);
	/* note item rect used later */

	ShowWindow(dialog);

	listwidth = itemRect.right - itemRect.left;

	/* 
	 * make room for scroll bars (see IM IV-270)
	 */
	itemRect.right -= 15;

	/* 
	 * create a list
	 */
	ncredentials = 0;								/* count credentials */
	for (rp = (credentialstype *)credentialsQ; rp; rp = rp->next)
		ncredentials++;
	SetRect(&dataBounds, 0, 0, 1, ncredentials);
	SetPt(&cellSize, itemRect.right-itemRect.left, CELLH);
	list = LNew(&itemRect, &dataBounds, cellSize, 128, 
				(WindowPtr) dialog, false, false, false, true);

	/* 
	 * use the default selection flags
	 */
	(*list)->selFlags = 0;

	/*
	 * Initialize the cells in the list.
	 */
	rp = (credentialstype *)credentialsQ;
	cell.h = cell.v = 0;
	while (rp) {
		setrcellstring(string, rp);
		LSetCell(string, strlen(string), cell, list);
		cell.v++;
		rp = rp->next;
	}

	lf.nlists = 1;
	lf.list[0] = list;
	lf.listitem[0] = KLIST_LIST;
	lf.edititem[0] = 0;

	/* 
	 * turn cell drawing on only after the cell contents have been initialized.
	 * this will avoid watching the delay between the LSetCells 
	 * calls and is faster.
	 */
	LDoDraw(true, list);
		
	do {
		/*
		 * Set the state of the edit and delete buttons depending on if any
		 * cells are selected or not.
		 */
		SetPt(&cell, 0, 0);
		if (LGetSelect(true, &cell, list))
			state = 0;
		else
			state = 255;					/* disable */
		HiliteControl((ControlHandle) deleteHandle, state);

		/* 
		 * process hits in the dialog.
		 */
			//  IH 05.03.96: PPC Port - Replace Procedure Pointer by UPP
		ModalDialog(gklistFilterUPP, &itemNo);
				
		switch(itemNo) {
			/* 
			 * process hits in the OK button.
			 */ 
		case KLIST_OK:
			/* 
			 * find out which cells have been selected.
			 */
			SetPt(&cell, 0, 0);
			while(LGetSelect(true, &cell, list)) {
				/* 
				 * there is nothing to do with the user's selections in 
				 * this sample so i'll just deselect the cells the 
				 * users has selected.
				 */
				LSetSelect(false, cell, list);
			}
			break;
			
		case KLIST_DELETE:
			changed = true;
			/*
			 * Loop for selected cells.
			 */
			 SetPt(&cell, 0, 0);
			 while (LGetSelect(true, &cell, list)) {
				rp = (credentialstype *)credentialsQ;
				i = cell.v;
				while (rp && (i-- > 0))		/* find selected credential */
					rp = rp->next;
			 	if (rp) {
					qunlink(&credentialsQ, rp);
					deleteCredentials(rp);
					DisposePtr((Ptr)rp);
					LSetSelect(false, cell, list);
					LDelRow(1, cell.v, list);
					SetPt(&cell, 0, 0);
				} else {						/* we are broken */
					SysBeep(20);
					break;
				}
			}
			break;
		}
	} while (itemNo != ok);
	
	/*	
	 * kill the list and dialog.
	 */
	SetPort(savePort);
	LDispose(list);
	DisposDialog(dialog);
}


/* 
 * we need to be able to process mouse clicks in the list. the Dialog 
 * Manager makes this possible through filter procedures like this one. 
 * since the default filter procedure will be replaced we also need to 
 * handle return key presses.
 */
pascal Boolean klistFilter (DialogPtr dialog, EventRecord *event, short *itemHit)
{
	int i;
	ListHandle list;
	Point cell;
	char character;
	Point where;
	Rect itemRect;
	short itemType;
	Handle itemHandle;
	struct listfilter *lf;
	
	lf = (struct listfilter *) ((DialogPeek)dialog)->window.refCon;

	switch (event->what) {
	
		/* 
		 * watch for mouse clicks in the List
		 */
	case mouseDown :
		for (i = 0; i < lf->nlists; i++) {
			GetDItem(dialog, lf->listitem[i], &itemType, &itemHandle, &itemRect);
			where = event->where;
			GlobalToLocal(&where);
		
			/* 
			 * if the user has clicked in the list then we'll handle the 
			 * processing here
			 */
			if (PtInRect(where, &itemRect)) {
				/* 
				 * recover the list handle. it was stuffed into the dialog 
				 * window's refCon field when it was created.
				 */
				list = lf->list[i];
				
				/* 
				 * let the List Manager process the mouse down. this includes 
				 * cell selection dragging, scrolling and double clicks by the 
				 * user.
				 */
				if (LClick(where, event->modifiers, list)) {
					/* 
					 * a double click in a cell has occured. find out in which 
					 * one of the cells the user has double clicked in.
					 */
					cell = LLastClick(list);

					if (lf->edititem[i])
						*itemHit = lf->edititem[i];		/* fake an edit hit if double click */
				} else {
					/* 
					 * tell the application that the list has been clicked in.
					 */
					*itemHit = lf->listitem[i];
				}
				return true;	/* event has been handled */
			}
		} /* for */
		break;
	
		/* 
		 * be sure and return this information so the Dialog Manager will 
		 * process the return and enter key presses as clicks by the user in 
		 * the OK button. this is only required because we have overridden 
		 * the Dialog Manager's default filtering.
		 */
	case keyDown :	
	case autoKey :
		character = event->message & charCodeMask;
		switch (character) {
		case '\n':			/* Return */
		case '\003':		/* Enter */
			/* 
			 * tell the application that the OK button has been clicked by 
			 * the user.
			 */
			*itemHit = 1;				/* item 1 must be ok button */
			return true;				/* we handled the event */
		}
		break;
	}
	
	/* 
	 * tell the Dialog Manger that the event has NOT been handled and that 
	 * it should take further action on this event.
	 */
	return false;
}


Boolean editlist (int dlog, char *e1, char *e2, int *admin)
{
	int ok, ret = false;
	short item;
	GrafPtr savePort;
	DialogPtr dialog;
	short itemType;
	Handle itemHandle;
	Rect itemRect;
	char s1[256], s2[256];
	int astate;

	PositionTemplate((Rect *)-1, 'DLOG', dlog, 50, 50);
	dialog = GetNewDialog(dlog, (Ptr) 0, (WindowPtr) -1);
	GetPort(&savePort);
	SetPort((GrafPtr) dialog);

	/*
	 * Set the draw procedure for the user items.
	 */
	GetDItem(dialog, EDIT_OUT, &itemType, &itemHandle, &itemRect);
		//  IH 05.03.96: PPC Port - Replace Procedure Pointer by UPP
	SetDItem(dialog, EDIT_OUT, itemType, (Handle)gdooutlineUPP, &itemRect);

	GetDItem(dialog, EDIT_E1, &itemType, &itemHandle, &itemRect);
	c2pstr(e1);
	SetIText(itemHandle, e1);
	p2cstr(e1);

	GetDItem(dialog, EDIT_E2, &itemType, &itemHandle, &itemRect);
	c2pstr(e2);
	SetIText(itemHandle, e2);
	p2cstr(e2);

	if (admin) {
		astate = *admin;
		GetDItem(dialog, EDIT_ADMIN, &itemType, &itemHandle, &itemRect);
		SetCtlValue((ControlHandle)itemHandle, astate);
	}

	SelIText(dialog, EDIT_E1, 0, 32767);				/* select E1 */

	ok = 0;
	do {
		/* 
		 * process hits in the dialog.
		 */
			//  IH 05.03.96: PPC Port - Replace Procedure Pointer by UPP
		ModalDialog(gokFilterUPP, &item);
		switch (item) {
		case EDIT_OK:							/* ok button */
			ok = 1;
			break;
			
		case EDIT_CANCEL:
			ok = 2;
			break;

		case EDIT_ADMIN:
			astate ^= 1;
			GetDItem(dialog, EDIT_ADMIN, &itemType, &itemHandle, &itemRect);
			SetCtlValue((ControlHandle)itemHandle, astate);
			break;
		}
	} while (ok == 0);
	
	if (ok == 1) {
		GetDItem(dialog, EDIT_E1, &itemType, &itemHandle, &itemRect);
		GetIText(itemHandle, s1);
		p2cstr(s1);

		GetDItem(dialog, EDIT_E2, &itemType, &itemHandle, &itemRect);
		GetIText(itemHandle, s2);
		p2cstr(s2);

		if (admin) {
			*admin = astate;
		}

		if (!s1[0] || !s2[0])				/* if either is empty */
			goto xit;

		strcpy(e1, s1);
		strcpy(e2, s2);

		ret = true;
	}
	
xit:
	DisposDialog(dialog);
	SetPort(savePort);
	return ret;
}


pascal Boolean okFilter (DialogPtr dialog, EventRecord *event, short *itemHit)
{
	#pragma unused (dialog)
	char character;

	switch (event->what) {
	case keyDown :	
	case autoKey :
		character = event->message & charCodeMask;
		switch (character) {
		case '\n':			/* Return */
		case '\003':		/* Enter */
			/* 
			 * tell the application that the OK button has been clicked by 
			 * the user.
			 */
			*itemHit = 1;				/* item 1 must be ok button */
			return true;				/* we handled the event */
		}
		break;
	}
	
	/* 
	 * tell the Dialog Manger that the event has NOT been handled and that 
	 * it should take further action on this event.
	 */
	return false;
}


int popRealms (Rect *rect, char *retstring)
{   
    int i, s, itsID, selected;
    MenuHandle theMenu;
    long theChoice;
	Point pt;
	servertype *sp;
	Str255 scratch, localrealm;
                
	/*
	 * Get the local realm
	 */
#ifdef KRB4
	klopb.uRealm = localrealm;
	if (s = lowcall(cKrbGetLocalRealm))
		strcpy(localrealm, "None");
#endif
#ifdef KRB5
{
char *ptr;
	if (krb5_get_default_realm(kcontext, &ptr) == 0)
	{
		strcpy(scratch, ptr);
		free(ptr);
	}
	else
		strcpy(scratch, "None");
}
#endif

    /* 
	 * get an id for the menu and create it. 
	 */
    itsID = 0;
    while (itsID < 128)
        itsID = UniqueID('MENU');
    theMenu = NewMenu(itsID,"\pxxx");        /* create the menu */
    InsertMenu(theMenu, -1);                 /* add it to the menu list */
    
    /* 
	 * add the items 
	 */
	selected = 0;
	for (i = 1, sp = (servertype *)serverQ; sp; sp = sp->next, i++) {
		strcpy(scratch, sp->realm);
		if (strcmp(scratch, localrealm) == 0)
			selected = i;
		c2pstr(scratch);
		AppendMenu(theMenu, scratch);
	}
    SetItemMark(theMenu, selected, checkMark);
	fixmenuwidth(theMenu, rect->right - rect->left);

    /* 
	 *pop it up 
	 */
	pt.h = rect->left+1;
	pt.v = rect->top;
	LocalToGlobal(&pt);
    theChoice = PopUpMenuSelect(theMenu, pt.v, pt.h, selected);
	theChoice = theChoice & 0xffff;
    
	if (theChoice) {
		GetItem(theMenu, theChoice, retstring);		
		p2cstr(retstring);
	}

    DeleteMenu(itsID);
	DisposeMenu(theMenu);
	
	return(theChoice);
}


Boolean newdp (domaintype *dp, char *e1, char *e2)
{
	char *s1, *s2;
	
	if (!e1[0] || !e2[0])					/* if empty strings */
		return false;
		
	strcpy(dp->host, e1);
	strcpy(dp->realm, e2);
	return true;
}


Boolean newsp (servertype *sp, char *e1, char *e2, int admin)
{
	char *s1, *s2;
	
	if (!e1[0] || !e2[0])					/* if empty strings */
		return false;
		
	strcpy(sp->host, e1);
	strcpy(sp->realm, e2);
	sp->admin = admin;

	return true;
}


/*
 * bzero
 * Block zero
 */
void bzero (void *dst, long n)
{
	int i;
	register char *d = dst;

	while (n--)
	*d++ = 0;
}


/*
 * bcopy
 * Block copy
 */
void bcopy (void *src, void *dst, int n)
{
	int i;
	register char *s = src;
	register char *d = dst;

	for (i = 0; i < n; i++)
		*d++ = *s++;
}


/*
 * getmem
 * malloc a block of zeroed memory
 */
Ptr getmem (size)
	size_t size;
{
	Ptr p;

	p = (Ptr) malloc(size);
	if (!p) {
		doalert("getmem: request for %ld failed", size);
		getout(1);
	}
	bzero(p, size);

	return p;
}


/*
 * getout
 * clean up and get out
 */
getout (exit)
	int exit;
{
#ifdef KRB4
	krb_end_session((char *)0);		/* Clean up nicely */
	ExitToShell();
#endif
#ifdef KRB5
/*try to dump the profile as it exists in memory to a file */

	if (kcontext->profile)
	{
	FILE	*daFile;
	char	*profilepath;
	extern char* GetMacProfilePathName(void);
		profilepath = GetMacProfilePathName();
		daFile = fopen(profilepath, "w+");
		dump_profile_to_file(kcontext->profile->first_file->root, 0, daFile);
		fclose(daFile);
		free(profilepath);
	}
	ExitToShell();
	/* FIXME */
#endif
}


/*
 * doalert
 * Bring up an alert box
 */
void doalert (char *format, ...)
{
	char string[256];
	va_list args;

	va_start(args, format);

	vsprintf(&string[1], format, args);
	string[0] = strlen(&string[1]);
	va_end(args);

	ParamText(string, "", "", "");

	PositionTemplate((Rect *)-1, 'ALRT', ALERT_DOALERT, 50, 50);
	Alert(ALERT_DOALERT, NULL);
}


/*
 * Return 0 if strings (ignoring case) match
 */
static int strcasecmp (char *a, char *b)
{
	for (;;) {
		if (toupper(*a) != toupper(*b))
			return 1;
		if (*a == '\0')
			return 0;
		a++;
		b++;
	}
}


fatal (char *string)
{
	doalert(string);
	getout(0);
}


char *copystring (char *src)
{
	int n;
	char *dst;

	if (!src || (*src == '\0'))
		return NULL;

	n = strlen(src);
	dst = malloc(n+1);
	strcpy(dst, src);

	return dst;
}


/*
 * isPressed
 * k =  any keyboard scan code, 0-127
 */
short isPressed (unsigned short k)
{
	unsigned char km[16];

	GetKeys((long *)km);
	return (( km[k>>3] >> (k & 7) ) & 1);
}


void doLogin ()
{
#ifdef KRB4
	int s;

	/*
	 * Get a TGT
	 */
	bzero(&khipb, sizeof(krbHiParmBlock));
	khipb.service = 0;
	if (s = hicall(cKrbCacheInitialTicket))
		if (s != cKrbUserCancelled)
			kerror("Error in cKrbCacheInitialTicket", s);
#endif

#ifdef KRB5
    long lifetime = 8*60;	// 8 hours
    krb5_error_code code;
    krb5_principal principal;
    krb5_creds creds;
    krb5_principal server;
    krb5_int32 sec, usec;
    char usernm[100] = "";
    char passwd[100];
    char credname[100];
    char realm[100];
    char *ptr;

	/* if the gUserName isn't uknown, we'll use that name */
	if (strcmp(gUserName, kUNKNOWNUSERNAME))
		strcpy(usernm, gUserName);

	if (GetUserInfo(usernm, passwd) == 2)
		return;

	if (krb5_get_default_realm(kcontext, &ptr) == 0)
	{
		strcpy(realm, ptr);
		free(ptr);
	}
	else
		strcpy(realm, "None");

	do {
	    principal = server = NULL;
		memset(&creds, 0, sizeof(creds));
	
	    sprintf (credname, "%s@%s", usernm, realm);
	    code = krb5_parse_name(kcontext, credname, &principal);
	    if (code) break;
	
		code = krb5_cc_initialize(kcontext, k5_ccache, principal);
	    if (code) break;
	
		code = krb5_build_principal_ext(kcontext, &server,
			krb5_princ_realm(kcontext, principal)->length,
			krb5_princ_realm(kcontext, principal)->data,
	        KRB5_TGS_NAME_SIZE, KRB5_TGS_NAME,
		    krb5_princ_realm(kcontext, principal)->length,
			krb5_princ_realm(kcontext, principal)->data, 0);
	    if (code) break;
	
		creds.client = principal;
		creds.server = server;
	
	    code = krb5_crypto_us_timeofday(&sec, &usec);
	    if (code) break;
	    creds.times.starttime = 0;
		creds.times.endtime = sec + 60L * lifetime;
		creds.times.renew_till = 0;
	
		code = krb5_get_in_tkt_with_password(kcontext, 0, NULL,
	        NULL, NULL, passwd, k5_ccache, &creds, 0);
	} while (0);
	
	if (principal)
	    krb5_free_principal(kcontext, principal);
	if (server) 
		krb5_free_principal(kcontext, server);

	if (code)
	{
		com_err (NULL, code, "while logging in.");
	}
	else
	{
		strcpy(gUserName, usernm);	/* copy the user name over to the global username */
		strcpy(gRealmName, realm);	/* copy the realm name over to the global realmname */
	}
#endif
}


#ifdef KRB5
/*+
 * Function: destroys all tickets in a k5 ccache
 *
 * Parameters:
 *  none
 *
 * Returns: K5 error code (0 == success)
 */
static krb5_error_code
k5_dest_tkt (void) {
    krb5_error_code code;
    krb5_principal princ;

    if (code = krb5_cc_get_principal(kcontext, k5_ccache, &princ)) {
        kerror ("while retrieving principal name", code);
        return code;
    }

    code = krb5_cc_initialize (kcontext, k5_ccache, princ);
    if (code != 0) {
        kerror ("when re-initializing cache", code);
        krb5_free_principal (kcontext, princ);
        return code;
    }

    krb5_free_principal (kcontext, princ);
    return code;
}
#endif

void doLogout ()
{
#ifdef KRB4
	int s;
	
	pb.cntrlParam.csCode = cKrbDeleteAllSessions;
	if ((s = PBControl(&pb, false)) || (s = pb.cntrlParam.ioResult))
		kerror("Error in cKrbDeleteAllSessions", s);
#endif
#ifdef KRB5
	k5_dest_tkt();
	strcpy(gUserName, kUNKNOWNUSERNAME);
#endif
}


void getRealmMaps ()
{
#ifdef KRB4
	int i, s;
	Str255 host, realm;
	domaintype *dp;

	for (i = 1; ;i++) {
		klopb.itemNumber = &i;
		klopb.host = host;
		klopb.uRealm = realm;
		if (s = lowcall(cKrbGetNthRealmMap))
			break;
			
		if (!(dp = (domaintype *)NewPtrClear(sizeof(domaintype))))
			return;
		strcpy(dp->realm, realm);
		strcpy(dp->host, host);
		qlink(&domainQ, dp);
	}
#endif
#ifdef KRB5
int count;
char **domainlist;
char	*realm;
int		code;
int		i;
domaintype *dp;
const char	*realm_kdc_names[4];

    realm_kdc_names[0] = "domain_realm";
    realm_kdc_names[1] = 0;

    code = profile_get_first_values(kcontext->profile, realm_kdc_names, &domainlist);

    count = 0;
    while (domainlist && domainlist[count])
	{
		code = profile_get_string(kcontext->profile, "domain_realm", domainlist[count], NULL, "", &realm);

		if (!(dp = (domaintype *)NewPtrClear(sizeof(domaintype))))
			return;
		strcpy(dp->realm, realm);
		strcpy(dp->host, domainlist[count]);
		qlink(&domainQ, dp);

	    count++;
	}
	free(domainlist);
#endif
}


void getServerMaps ()
{
#ifdef KRB4
	int i, s, ar;
	Str255 host, realm;
	servertype *sp;

	for (i = 1; ;i++) {
		klopb.itemNumber = &i;
		klopb.host = host;
		klopb.uRealm = realm;
		klopb.adminReturn = &ar;
		if (s = lowcall(cKrbGetNthServerMap))
			break;
			
		if (!(sp = (servertype *)NewPtrClear(sizeof(servertype))))
			return;
		strcpy(sp->realm, realm);
		strcpy(sp->host, host);
		sp->admin = ar;
		qlink(&serverQ, sp);
	}
#endif
#ifdef KRB5
int i, s, ar = 1;
Str255 realm;
servertype *sp;
int count;
char **realmlist;
char	*host;
int		code;
const char	*realm_kdc_names[4];

    realm_kdc_names[0] = "realms";
    realm_kdc_names[1] = 0;

    code = profile_get_first_values(kcontext->profile, realm_kdc_names, &realmlist);

    count = 0;
    while (realmlist && realmlist[count])
	{
	    realm_kdc_names[0] = "realms";
    	realm_kdc_names[1] = realmlist[count];
    	realm_kdc_names[2] = "kdc";
    	realm_kdc_names[3] = 0;

		code = profile_get_string(kcontext->profile, "realms", realmlist[count], "kdc", "", &host);
	
		if (!(sp = (servertype *)NewPtrClear(sizeof(servertype))))
			return;
		strcpy(sp->realm, realmlist[count]);
		strcpy(sp->host, host);
		code = profile_get_string(kcontext->profile, "realms", realmlist[count], "kdc", "", &host);
		sp->admin = ar;
		qlink(&serverQ, sp);

	    count++;
	}
	free(realmlist);

#endif
}


void getCredentialsList ()
{
#ifdef KRB4
	int i, j, s;
	Str255 scratch;
	Str255 name, instance, realm, sname, sinstance, srealm, tktfile;
	credentialstype *rp;

	killCredentialsList();

	/*
	 * list credentials
	 */
	bzero(&klopb, sizeof(krbParmBlock));
	klopb.uName = name;
	klopb.uInstance = instance;
	klopb.uRealm = realm;
	klopb.sName = sname;
	klopb.sInstance = sinstance;
	klopb.sRealm = srealm;
	
	i = 1;
	for (j = 1; ;j++) {
		klopb.itemNumber = &i;
		if (s = lowcall(cKrbGetNthSession)) {
			if (s != cKrbSessDoesntExist)
				kerror("cKrbGetNthSession: ", s);
			return;
		}

		klopb.itemNumber = &j;
		if (s = lowcall(cKrbGetNthCredentials)) {
			if ((s != cKrbCredsDontExist) & 
				(cKrbKerberosErrBlock - s != KFAILURE)) {
				kerror("cKrbGetNthCredentials: ", s);
				break;
			}
			i += 1;
		    j = 0;
			continue;
		}

		if (!(rp = (credentialstype *)NewPtrClear(sizeof(credentialstype))))
			return;
				
		strcpy(rp->sname, sname);
		strcpy(rp->sinstance, sinstance);
		strcpy(rp->srealm, srealm);
		
		/*	
		cKrbGetNthCredentials no longer returns the principal's, name
		instance and realm.  Instead it returns the cache name, 
		"fixed user", "fixed instance", "fixed realm".  Must get the 
		principal's name, instance, and realm by calling a routine 
		added by cns.
		*/

		bzero(&klopb, sizeof(krbParmBlock));
		klopb.fullname = tktfile;
		klopb.uName = name;
		klopb.uInstance = instance;
		klopb.uRealm = realm;
		klopb.sName = sname;
		klopb.sInstance = sinstance;
		klopb.sRealm = srealm;
		
		if (s = lowcall(cKrbGetTfFullname)) {
			if (s != KSUCCESS)
				kerror("cKrbGetTfFullname: ", s);
			return;
			}
		
		strcpy(rp->name, name);
		strcpy(rp->instance, instance);
		strcpy(rp->realm, realm);
		
		qlink(&credentialsQ, rp);
	}
#endif
#ifdef KRB5
	int i, j, s;
	Str255 scratch;
	Str255 name, instance, realm, sname, sinstance, srealm, tktfile;
	credentialstype *rp;
	krb5_cc_cursor cursor;
	krb5_creds creds;
	char *tmpstr;
	
	killCredentialsList();

	/*
	 * list credentials
	 */
	cursor = 0;
	krb5_fcc_start_seq_get(kcontext, k5_ccache, &cursor);
	while (0 == krb5_fcc_next_cred(kcontext, k5_ccache, &cursor, &creds)) {
		/* Get Cred info here */
		if (!(rp = (credentialstype *)NewPtrClear(sizeof(credentialstype))))
			return;

		strncpy(rp->name, (char*) creds.client->data->data, sizeof(Str255));
		strcpy(rp->instance, "instance");
		strncpy(rp->realm, (char*) creds.client->realm.data, sizeof(Str255));
		strncpy(rp->sname, (char*) creds.server->data->data, sizeof(Str255));
		strcpy(rp->sinstance, "sinstance");
		strncpy(rp->srealm, (char*) creds.server->realm.data, sizeof(Str255));
		krb5_unparse_name(kcontext, creds.client, &tmpstr);
		strcpy(rp->pname, tmpstr);
		free(tmpstr);
		krb5_unparse_name(kcontext, creds.server, &tmpstr);
		strcpy(rp->cname, tmpstr);
		free(tmpstr);
		qlink(&credentialsQ, rp);
	}
	krb5_fcc_end_seq_get(kcontext, k5_ccache, &cursor);
	krb5_cc_default (kcontext, &k5_ccache);
#endif
}


void killCredentialsList ()
{
	credentialstype *rp;
	
	while (rp = credentialsQ) {
		qunlink(&credentialsQ, rp);
		DisposePtr((Ptr)rp);
	}
}


void addRealmMap (char *host, char *realm)
{
#ifdef KRB4
	int s;

	klopb.host = host;
	klopb.uRealm = realm;
	if (s = lowcall(cKrbAddRealmMap))
		kerror("Error calling cKrbAddRealmMap", s);
#endif
#ifdef KRB5
int		code;
struct profile_node *node;
char	*nam, *val;
void	*state;

	state = NULL;
	code = profile_find_node_subsection(kcontext->profile->first_file->root, "domain_realm", &state, &nam, &node);
	code = profile_delete_node_relation(node, host);
	code = profile_add_node(node, host, realm, &node);

#endif
}

void deleteRealmMap (char *host)
{
#ifdef KRB4
	int s;
	
	klopb.host = host;
	if (s = lowcall(cKrbDeleteRealmMap))
		kerror("Error calling cKrbDeleteRealmMap", s);
#endif
#ifdef KRB5
int		code;
struct profile_node *node;
char	*nam, *val;
void	*state;

	state = NULL;
	code = profile_find_node_subsection(kcontext->profile->first_file->root, "domain_realm", &state, &nam, &node);
	code = profile_delete_node_relation(node, host);
#endif
}


void deleteCredentials (credentialstype *rp)
{
#ifdef KRB4
	int s;
	
	klopb.uName = rp->name;
	klopb.uInstance = rp->instance;
	klopb.uRealm = rp->realm;
	klopb.sName = rp->sname;
	klopb.sInstance = rp->sinstance;
	klopb.sRealm = rp->srealm;
	if (s = lowcall(cKrbDeleteCredentials))
		kerror("Error calling cKrbDeleteCredentials: ", s);
#endif
#ifdef KRB5
	/* FIXME */
#endif
}



void addServerMap (char *host, char *realm, int admin)
{
#ifdef KRB4
	int s;

	klopb.host = host;
	klopb.uRealm = realm;
	klopb.admin = admin;
	if (s = lowcall(cKrbAddServerMap))
		kerror("Error calling cKrbAddServerMap", s);
#endif
#ifdef KRB5
int		code;
struct profile_node *node, *node2;
char	*nam, *val;
void	*state;

	state = NULL;
	code = profile_find_node_subsection(kcontext->profile->first_file->root, "realms", &state, &nam, &node);
	code = profile_delete_node_relation(node, realm);	/* possible memory leak here */
	code = profile_add_node(node, realm, 0, &node);		/* Create the realm node */
	code = profile_add_node(node, "kdc", host, &node2);		/* Create the realm node */
	code = profile_add_node(node, "admin_server", host, &node2);		/* Create the realm node */
#endif
}


void deleteServerMap (char *host, char *realm)
{
#ifdef KRB4
	int s;
	
	klopb.host = host;
	klopb.uRealm = realm;
	if (s = lowcall(cKrbDeleteServerMap))
		kerror("Error calling cKrbDeleteServerMap", s);
#endif
#ifdef KRB5
int		code;
struct profile_node *node;
char	*nam, *val;
void	*state;

	state = NULL;
	code = profile_find_node_subsection(kcontext->profile->first_file->root, "realms", &state, &nam, &node);
	code = profile_delete_interior_node_relation(node, realm);	/* possible memory leak here */
#endif
}


void kerror (char *text, int error)
{
#ifdef KRB4
	int k;
	Str255 scratch;
	char *etext;

	switch (error) {
	case cKrbCorruptedFile:
		etext = "Couldn't find a needed resource";
		break;
	case cKrbNoKillIO:
		etext = "Can't killIO because all calls sync";
		break;
	case cKrbBadSelector:
		etext = "csCode passed doesn't select a recognized function";
		break;
	case cKrbCantClose:
		etext = "We must always remain open";
		break;
	case cKrbMapDoesntExist:
		etext = "Tried to access a map that doesn't exist";
		break;
	case cKrbSessDoesntExist:
		etext = "Tried to access a session that doesn't exist";
		break;
	case cKrbCredsDontExist:
		etext = "Tried to access credentials that don't exist";
		break;
	case cKrbTCPunavailable:
		etext = "Couldn't open MacTCP driver";
		break;
	case cKrbUserCancelled:
		etext = "User cancelled a log in operation";
		break;
	case cKrbConfigurationErr:
		etext = "Kerberos Preference file is not configured properly";
		break;
	case cKrbServerRejected:
		etext = "A server rejected our ticket";
		break;
	case cKrbServerImposter:
		etext = "Server appears to be a phoney";
		break;
	case cKrbServerRespIncomplete:
		etext = "Server response is not complete";
		break;
	case cKrbNotLoggedIn:
		etext = "Returned by cKrbGetUserName if user is not logged in";
		break;
	default:
		k = cKrbKerberosErrBlock - error;
		if ((k > 0) && (k < 256)) {
			etext = krb_get_err_text(k);
			break;
		}

		sprintf(scratch, "Mac Kerberos error #%d", error);
		etext = scratch;
		break;
	}

	doalert("%s: %s", text, etext);
#endif
#ifdef KRB5
	/* FIXME */
#endif
}

#ifdef KRB4
int lowcall (int cscode)
{
	short s;
	
	bzero(&pb, sizeof(ParamBlockRec));
	*(long *)pb.cntrlParam.csParam = (long)&klopb;
	pb.cntrlParam.ioCompletion = nil;
	pb.cntrlParam.ioCRefNum = kdriver;

	pb.cntrlParam.csCode = cscode;
	if (s = PBControl(&pb, false))
		return s;
	if (s = pb.cntrlParam.ioResult)
		return s;
	return 0;
}


int hicall (int cscode)
{
	short s;
	
	bzero(&pb, sizeof(ParamBlockRec));
	*(long *)pb.cntrlParam.csParam = (long)&khipb;
	pb.cntrlParam.ioCompletion = nil;
	pb.cntrlParam.ioCRefNum = kdriver;

	pb.cntrlParam.csCode = cscode;
	if (s = PBControl(&pb, false))
		return s;
	if (s = pb.cntrlParam.ioResult)
		return s;
	return 0;
}
#endif

/*
 * qlink
 * Add an entry to the end of a linked list
 */
void qlink (void **flist, void *fentry)
{
    struct dummy {
		struct dummy *next;
    } **list, *entry;

    list = flist;
    entry = fentry;
    
    /*
     * Find address of last entry in the list.
     */
    while (*list)
	list = &(*list)->next;

    /*
     * Link entry
     */
    *list = entry;
    entry->next = 0;
}


/*
 * qunlink
 * Remove an entry from linked list
 * Returns the entry or NULL if not found.
 */
void *qunlink (void **flist, void *fentry)
{
    struct dummy {
	struct dummy *next;
    } **list, *entry;

    list = flist;
    entry = fentry;
    
    /*
     * Find entry and unlink it
     */
    while (*list) {
	if ((*list) == entry) {
	    *list = entry->next;
	    return entry;
	}

	list = &(*list)->next;
    }
    return NULL;
}


/*
 * fixmenuwidth
 * set minimum menu width by widening item
 */
void fixmenuwidth (MenuHandle themenu, int minwidth)
{
	Str255 scratch;
	
	minwidth -= 27;
	GetItem(themenu, 1, scratch);
	if (StringWidth(scratch) >= minwidth)
		return;
	while (StringWidth(scratch) < minwidth)
		scratch[scratch[0]++ + 1] = ' ';
	SetItem(themenu, 1, scratch);
}


/*
 * doshadow
 * Draw shadowed frame
 * Also in sldef.c
 */
doshadow (Rect *rect)
{
	FrameRect(rect);
	MoveTo(rect->left+2, rect->bottom);	/* shadow */
	LineTo(rect->right, rect->bottom);
	LineTo(rect->right, rect->top+2);
}


/*
 * dotriangle
 * Also in sldef.c
 */
void dotriangle (Rect *rect)
{
	int i;
	PolyHandle poly;
	Pattern black;
	
	for (i = 0; i < sizeof(black); i++)
#ifdef dangerousPattern
		black[i] = 0xff;
#else
		black.pat[i] = 0xff;		/* ... should use qd-> */
#endif

	poly = OpenPoly();							/* should make permanent ??? */
	MoveTo(rect->right - 16, rect->top + 5);
	LineTo(rect->right - 5, rect->top + 5);
	LineTo(rect->right - 10, rect->top + 10);
	LineTo(rect->right - 16, rect->top + 5);
	ClosePoly();
#ifdef dangerousPattern
	FillPoly(poly, black);
#else
	FillPoly(poly, &black);
#endif
	KillPoly(poly);
}


/*
 * trimstring
 * Trim trailing blanks from a string
 */
void trimstring (char *cp)
{
	int n;
	
	if (*cp == ' ')
		return;
	
	if (!(n = strlen(cp)))
		return;
	cp += n - 1;
	while (*cp == ' ')
		cp--;
	*++cp = '\0';
}


/* changing passwords doesn't work presently because :src:lib:kadm doesn't
compile.  kadm doesn't compile 'cause SOCKET_STREAM isn't an available socket
type in macsock.  I'm not even real sure this is the right way to change
a password, this is the only example I've seen yet
*/

#ifdef KRB5
	krb5_error_code
	k5_change_password (
	    krb5_context k5context,
		char *user,
		char *realm,
		char *opasswd,
		char *npasswd,
	    char **text);
#endif

/*
 * kpass_dialog
 */
void kpass_dialog ()
{
	int s = 0, ok;
	short item;
	GrafPtr savePort;
	DialogPtr dialog;
	short itemType;
	Handle itemHandle;
	Rect itemRect;
	char *reason = NULL, username[256], realm[256];
	struct valcruft valcruft;
	Str255 scratch;

	PositionTemplate((Rect *)-1, 'DLOG', DLOG_KPASS, 50, 50);
	dialog = GetNewDialog(DLOG_KPASS, (Ptr) 0, (WindowPtr) -1);
	GetPort(&savePort);
	SetPort((GrafPtr) dialog);

	/*
	 * Set the draw procedure for the user items.
	 */
	GetDItem(dialog, KPASS_OUT, &itemType, &itemHandle, &itemRect);
		//  IH 05.03.96: PPC Port - Replace Procedure Pointer by UPP
	SetDItem(dialog, KPASS_OUT, itemType, (Handle)gdooutlineUPP, &itemRect);

	/* preset dialog ... */
	SetWRefCon(dialog, (long)&valcruft);	/* Stash the cruft's address */
	bzero(&valcruft, sizeof(valcruft));

#ifdef KRB4
	/* preset initial user */
	khipb.user = scratch;
	if (!(s = hicall(cKrbGetUserName))) {
		c2pstr(scratch);
		GetDItem(dialog, KPASS_USER, &itemType, &itemHandle, &itemRect);
		SetIText(itemHandle, scratch);
		SelIText(dialog, KPASS_PASS, 0, 32767);
	}

	/* get local realm */
	klopb.uRealm = realm;
	if (s = lowcall(cKrbGetLocalRealm))
		strcpy(realm, "");

#endif
#ifdef KRB5
{
char *ptr;
	GetDItem(dialog, KPASS_USER, &itemType, &itemHandle, &itemRect);
	SetIText(itemHandle, "\p");
	SelIText(dialog, KPASS_PASS, 0, 32767);

// Get default realm
	if (krb5_get_default_realm(kcontext, &ptr) == 0)
	{
		strcpy(realm, ptr);
		free(ptr);
	}
	else
		strcpy(realm, "None");
}
#endif
	
	retry:
	
	ok = 0;
	do {
		/* 
		 * process hits in the dialog.
		 */
			//  IH 05.03.96: PPC Port - Replace Procedure Pointer by UPP
		ModalDialog(ginternalBufferFilterUPP, &item);
		switch (item) {
		case KPASS_OK:					/* ok button */
			ok = 1;
			break;
			
		case KPASS_CANCEL:
			ok = 2;
			break;

		case KPASS_JPW:					/* jump to password */
			SelIText(dialog, KPASS_PASS, 0, 32767);			
			break;

		case KPASS_JNEW:				/* jump to new */
			SelIText(dialog, KPASS_NEW, 0, 32767);			
			break;

		case KPASS_JNEW2:
			SelIText(dialog, KPASS_NEW2, 0, 32767);
			break;
		}
	} while (ok == 0);
	
	if (ok == 1) {
		GetDItem(dialog, KPASS_USER, &itemType, &itemHandle, &itemRect);
		GetIText(itemHandle, username);
		p2cstr(username);

#ifndef KRB5
		/*
		 * If user put an @ in the username, ignore the realm, otherwise
		 * tack on the realm. 
		 */
		if ((strchr(username, '@') == 0) && realm[0]) {
			strcat(username, "@");
			strcat(username, realm);
		}
#endif

		p2cstr(valcruft.buffer1);				/* password */
		p2cstr(valcruft.buffer2);				/* new */
		p2cstr(valcruft.buffer3);				/* new2 */

		if (strcmp(valcruft.buffer2, valcruft.buffer3) != 0) {
			doalert("New passwords do not match");
			c2pstr(valcruft.buffer1);				/* password */
			c2pstr(valcruft.buffer2);				/* new */
			c2pstr(valcruft.buffer3);				/* new2 */
			goto retry;
		}

#ifdef KRB4
		OpenResolver(0);
		s = kerberos_changepw(username, valcruft.buffer1, valcruft.buffer2,
							  &reason);
		CloseResolver();
#endif

#ifdef KRB5
		{
			char *text;
			// Change the password from old to new
			s = k5_change_password(kcontext, username, realm, valcruft.buffer1, valcruft.buffer2, &text);
			if (s)
			{
				SysBeep(10);	// change password failed
		        com_err (NULL, s, "while logging in.");
			}
		}
#endif

		if (s) {
			kerror(reason, s);
			SelIText(dialog, KPASS_PASS, 0, 32767);		/* hilite password */
			c2pstr(valcruft.buffer1);				/* password */
			c2pstr(valcruft.buffer2);				/* new */
			c2pstr(valcruft.buffer3);				/* new2 */
			goto retry;
		}
	}
	
	DisposDialog(dialog);
	SetPort (savePort);
}


/*
 * Routines from Apple for hiding passwords
 */
pascal Boolean internalBufferFilter (DialogPtr dlog, EventRecord *event, short *itemHit)
{	
	char key;
	short start,end;
	struct valcruft *valcruft;
	unsigned char *buffer;
	Handle h;
	int i, len;
	char *cp;
	long offset;
	unsigned char scratch[256];
	int editevent;
	
	valcruft = (struct valcruft *)GetWRefCon(dlog);

	if (((DialogPeek)dlog)->editField == (KPASS_PASS - 1))
		buffer = valcruft->buffer1;
	else if (((DialogPeek)dlog)->editField == (KPASS_NEW - 1))
		buffer = valcruft->buffer2;
	else if (((DialogPeek)dlog)->editField == (KPASS_NEW2 - 1))
		buffer = valcruft->buffer3;
	else
		buffer = 0;

	start = (**((DialogPeek)dlog)->textH).selStart;	/* Get current selection */
	end = (**((DialogPeek)dlog)->textH).selEnd;
	
	/*
	 * Preprocess events, looking for edit events.
	 */
	editevent = 0;
	switch (event->what) {
	case keyDown:
	case autoKey:
		if (event->modifiers & cmdKey) {
			if (((DialogPeek)dlog)->editField != (KPASS_PASS - 1))
				return false;
			switch (event->message & charCodeMask) {
			case 'v':
			case 'V':
				editevent = EV_PASTE;
				break;
			case 'c':
			case 'C':
				editevent = EV_COPY;
				break;
			case 'x':
			case 'X':
				editevent = EV_CUT;
				break;
			default:
				return false;			/* unknown cmd key */
			}
		}
		break;

	default:							/* not key */
		return false;
	}

	/*
	 * Handle cut, copy, paste events.
	 */
	if (editevent) {
		switch (editevent) {
		case EV_PASTE:
			if (!buffer)
				break;
			if (start != end)
				DeleteRange(buffer, start, end);
			h = NewHandle(100);
			if ((len = GetScrap(h, 'TEXT', &offset)) < 0) {
				SysBeep(3);
			} else {
				cp = (char *)*h;
				for (i = 0; i < len; i++)
					InsertChar(buffer, start+i, cp[i]);
			}
			DisposHandle(h);
			buffer[(*buffer) + 1] = '\0';		/* terminate string */
			strcpy(scratch, &buffer[1]);
			hidestring(scratch);
			setctltxt(dlog, KPASS_PASS, scratch);	/* update display */
			SelIText(dlog, KPASS_PASS, start+i, start+i);
			break;
			
		case EV_COPY:
			SysBeep(3);						/* can't copy hidden field */
			return true;
		
		case EV_CUT:
			SysBeep(3);
			return true;
		}
		return true;						/* we handled it */
	}
	
	key = event->message & charCodeMask;
	switch (key) {	
	case '\n':							/* Return */
	case '\003':						/* Enter */
		/*
		 * If return, check to see that the password has been filled
		 * in. If not, jump to it unless we're already in the password
		 * field.
		 */
		switch (((DialogPeek)dlog)->editField + 1) {
		case KPASS_USER:
			if (*valcruft->buffer1 == 0) {
				*itemHit = KPASS_JPW;
				return true;
			} else if (*valcruft->buffer2 == 0) {
				*itemHit = KPASS_JNEW;
				return true;
			} else if (*valcruft->buffer3 == 0) {
				*itemHit = KPASS_JNEW2;
				return true;
			}
			break;

		case KPASS_PASS:
			if (*valcruft->buffer2 == 0) {
				*itemHit = KPASS_JNEW;
				return true;
			} else if (*valcruft->buffer3 == 0) {
				*itemHit = KPASS_JNEW2;
				return true;
			}
			break;

		case KPASS_NEW:
			if (*valcruft->buffer1 == 0) {
				*itemHit = KPASS_JPW;
				return true;
			} else if (*valcruft->buffer3 == 0) {
				*itemHit = KPASS_JNEW2;
				return true;
			}
			break;

		case KPASS_NEW2:
			if (*valcruft->buffer1 == 0) {
				*itemHit = KPASS_JPW;
				return true;
			} else if (*valcruft->buffer2 == 0) {
				*itemHit = KPASS_JNEW;
				return true;
			}
		}
		*itemHit = 1;					/* OK Button */
		return true;					/* We handled the event */
	case '\t':							/* Tab */
	case '\034':						/* Left arrow */
	case '\035':						/* Right arrow */
	case '\036':						/* Up arrow */
	case '\037':						/* Down arrow */
		return false;					/* Let ModalDialog handle them */
	default:							/* Everything else falls through */
		break;
	}
	
	switch (((DialogPeek)dlog)->editField + 1) {
	case KPASS_PASS:
	case KPASS_NEW:
	case KPASS_NEW2:
		break;

	default:
		return false;
	}

	if (start != end) {					/* If there's a selection, delete it */
		DeleteRange(buffer,start,end);
		if (key == '\010')
			return false;
	}
	
	if (key == '\010') {					// Backspace
		if (start != 0)
		DeleteRange(buffer,start-1,start);	// Delete the character to the left
	} else {
		if (*buffer >= (VCL-1))	{			/* if buffer full */
			SysBeep(10);
			return true;					/* eat event */
		}
		InsertChar(buffer,start,key);		// Insert the real key into the buffer
		event->message = '¥';			// Character to use in field
	}
	
	return false; 							// Let ModalDialog insert the fake char
}


void DeleteRange (unsigned char *buffer, short start, short end)
{	
	register unsigned char	*src,*dest,*last;
	
	last = buffer + *buffer;
	
	src = buffer + end + 1;
	dest = buffer + start + 1;
	
	while (src <= last)			// Shift character to the left over the removed characters
		*(dest++) = *(src++);
	
	(*buffer) -= (end-start);	// Adjust the buffer's length
}

void InsertChar (unsigned char *buffer, short pos, char c)
{	
	register short	index, len;
	
	len = *buffer;
	
	if (len >= (VCL-1))		// if the string is full
		return;
	
	for (index = len; index > pos; index--)	// Shift characters to the right to make room
		buffer[index+1] = buffer[index];
	
	buffer[pos+1] = c;		// Fill in the new character
	
	(*buffer)++;			// Add one to the length of the string
}


void hidestring (unsigned char *cp)
{
	while (*cp)
		*cp++ = 0xa5;			/* bullet */
}


/*
 * setctltxt
 * Set a control's text
 */
void setctltxt (DialogPtr dialog, int ctl, unsigned char *text)
{
	short itemType;
	Handle itemHandle;
	Rect itemRect;

	GetDItem(dialog, ctl, &itemType, &itemHandle, &itemRect);
	c2pstr(text);
	SetIText(itemHandle, (StringPtr)text);
	p2cstr(text);
}


/*
 * readprefs
 */
void readprefs ()
{
	short rf = -1;
	Handle h = 0;
	
	if ((rf = openprefres(true)) == -1)
		goto defaults;
	
	if ((h = Get1Resource(PREFS_TYPE, PREFS_ID)) == 0)
		goto defaults;

	HLock(h);
	bcopy(*h, &prefs, sizeof(prefs));
	
	if (prefs.version != PVERS)
		goto defaults;
		
xit:
	if (h)
		ReleaseResource(h);
	if (rf != -1)
		CloseResFile(rf);
	return;

defaults:
	bzero(&prefs, sizeof(prefs));
	prefs.version = PVERS;
	goto xit;
}



/*
 * writeprefs
 */
void writeprefs ()
{
	OSErr s;
	short rf = -1;
	Handle h = 0;
    Rect *rectp;
	Point pt;
	GrafPtr savePort;
	
	if ((rf = openprefres(true)) == -1) {
		doalert("Could not open preferences file");
		return;
	}
	
	if ((h = Get1Resource(PREFS_TYPE, PREFS_ID)) == 0) {
		if (!(h = NewHandle(sizeof(prefs)))) {
			doalert("Could not create prefs handle");
			goto xit;
		}
		AddResource(h, PREFS_TYPE, PREFS_ID, "\pPrefs");
		if (s = ResError())
			doalert("Error creating Prefs resource: %d", s);
	} else {
		SetHandleSize(h, sizeof(prefs));
		if (s = MemError()) {
			doalert("Could not resize prefs handle: %d", s);
			goto xit;
		}
	}		

	/*
	 * Update window position
	 */
	GetPort(&savePort);
	SetPort(maind);
	rectp = &maind->portRect;
	pt.h = rectp->left;
	pt.v = rectp->top;
	LocalToGlobal(&pt);
	prefs.wrect.left = pt.h;
	prefs.wrect.top = pt.v;
	pt.h = rectp->right;
	pt.v = rectp->bottom;
	LocalToGlobal(&pt);
	prefs.wrect.right = pt.h;
	prefs.wrect.bottom = pt.v;
	SetPort(savePort);

	HLock(h);
	bcopy(&prefs, *h, sizeof(prefs));
	ChangedResource(h);
	
xit:
	if (rf != -1)
		CloseResFile(rf);
}


/*
 * openprefres
 * Open CNS Config Preferences resource file
 * return rf or -1 if error
 */
int openprefres (int create)
{
	int s;
	int rf;
	short vref;
	long dirid = 0, fold;
	SysEnvRec theWorld;
	HParamBlockRec pb;
 
	/*
	 * Try to find the Preferences folder, else use the system folder.
	 */
	if (Gestalt('fold', &fold)  || 
		((fold & 1) != 1) ||
		FindFolder(kOnSystemDisk, 'pref', false, &vref, &dirid)) {
		if (SysEnvirons (1, &theWorld) == 0)
			vref = theWorld.sysVRefNum;
		else
			vref = 0;
	}

	if ((rf = HOpenResFile(vref, dirid, prefsFilename, fsRdWrPerm)) == -1) {
		s = ResError();
		if (((s == fnfErr) || (s == eofErr)) && create) {
			HCreateResFile(vref, dirid, prefsFilename);				/* create the file */
			if (s = ResError()) {
				return -1;
			}
			/*
			 * set finder info for new file, ignore errors.
			 */
			bzero(&pb, sizeof(pb));
			pb.fileParam.ioNamePtr = prefsFilename;
			pb.fileParam.ioVRefNum = vref;
			pb.fileParam.ioFDirIndex = 0;
			pb.fileParam.ioDirID = dirid;
			if (!(rf = PBHGetFInfo(&pb, false))) {
				pb.fileParam.ioFlFndrInfo.fdType = PREFS_TYPE;
				pb.fileParam.ioFlFndrInfo.fdCreator = KCONFIG_CREATOR;
				pb.fileParam.ioNamePtr = prefsFilename;
				pb.fileParam.ioVRefNum = vref;
				pb.fileParam.ioDirID = dirid;
				(void) PBHSetFInfo(&pb, false);
			}
			/*
			 * retry open
			 */
			if ((rf = HOpenResFile(vref, dirid, prefsFilename, fsRdWrPerm)) == -1) {
				s = ResError();
				return -1;
			}
		} else {
			return -1;
		}
	}
	return rf;
}


Boolean trapAvailable (int theTrap)
{
	int tType, numToolBoxTraps;
	
	if (theTrap & 0x800) {
		tType = ToolTrap;
		theTrap &= 0x7ff;
		if (NGetTrapAddress(_InitGraf, ToolTrap) == NGetTrapAddress(0xaa6e, ToolTrap))
			numToolBoxTraps = 0x200;
		else
			numToolBoxTraps = 0x400;
		if (theTrap > numToolBoxTraps)
			theTrap = _Unimplemented;
	} else {
		tType = OSTrap;
	}
	
	return (NGetTrapAddress(theTrap, tType) != NGetTrapAddress(_Unimplemented, ToolTrap));
}


/*
 * Junk so Emacs will set local variables to be compatible with Mac/MPW.
 * Should be at end of file.
 * 
 * Local Variables:
 * tab-width: 4
 * End:
 */