summaryrefslogtreecommitdiffstats
path: root/doc/api/library.tex
diff options
context:
space:
mode:
authorSam Hartman <hartmans@mit.edu>2011-10-05 21:30:31 +0000
committerSam Hartman <hartmans@mit.edu>2011-10-05 21:30:31 +0000
commitc4deb50427a24c104458ae1439b696aee41963d2 (patch)
tree386498c31aa2852ec65c973bdbbc997788602728 /doc/api/library.tex
parentdb74c9ff528d5b9bf1bf76acdb4a53068ae621ac (diff)
From: Sam Hartman <hartmans@debian.org>
Pkinit: offer supported KDFs in client git-svn-id: svn://anonsvn.mit.edu/krb5/trunk@25308 dc483132-0cff-0310-8789-dd5450dbe970
Diffstat (limited to 'doc/api/library.tex')
0 files changed, 0 insertions, 0 deletions
d='n103' href='#n103'>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
/*
 * cns.c
 *
 * Main routine of the Kerberos user interface.  Also handles
 * all dialog level management functions.
 *
 * Copyright 1994 by the Massachusetts Institute of Technology.
 *
 * For copying and distribution information, please see the file
 * <mit-copyright.h>.
 */

#include <windows.h>
#include <windowsx.h>

#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <malloc.h>
#include <ctype.h>
#include <time.h>

#include "cns.h"
#include "tktlist.h"
#include "cns_reg.h"

#include "../lib/gic.h"

enum {				       /* Actions after login */
  LOGIN_AND_EXIT,
  LOGIN_AND_MINIMIZE,
  LOGIN_AND_RUN,
};

/*
 * Globals
 */
static HICON kwin_icons[MAX_ICONS];    /* Icons depicting time */
HFONT hfontdialog = NULL;	       /* Font in which the dialog is drawn. */
static HFONT hfonticon = NULL;	       /* Font for icon label */
HINSTANCE hinstance;
static int dlgncmdshow;		       /* ncmdshow from WinMain */
#if 0
static UINT wm_kerberos_changed;       /* message for cache changing */
#endif
static int action;		       /* After login actions */
static UINT kwin_timer_id;	       /* Timer being used for update */
BOOL alert;		       	       /* Actions on ticket expiration */
BOOL beep;
static BOOL alerted;		       /* TRUE when user already alerted */
BOOL isblocking = FALSE;	       /* TRUE when blocked in WinSock */
static DWORD blocking_end_time;	       /* Ending count for blocking timeout */
static FARPROC hook_instance;	       /* handle for blocking hook function */

char confname[FILENAME_MAX];           /* krb5.conf (or krb.conf for krb4) */

#ifdef KRB5
char ccname[FILENAME_MAX];             /* ccache file location */
BOOL forwardable;                      /* TRUE to get forwardable tickets */
BOOL noaddresses;
krb5_context k5_context;
krb5_ccache k5_ccache;
#endif

/*
 * Function: Called during blocking operations.  Implement a timeout
 *	if nothing occurs within the specified time, cancel the blocking
 *	operation.  Also permit the user to press escape in order to
 *	cancel the blocking operation.
 *
 * Returns: TRUE if we got and dispatched a message, FALSE otherwise.
 */
BOOL CALLBACK
blocking_hook_proc(void)
{
  MSG msg;
  BOOL rc;

  if (GetTickCount() > blocking_end_time) {
    WSACancelBlockingCall();
    return FALSE;
  }

  rc = (BOOL)PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
  if (!rc)
    return FALSE;

  if (msg.message == WM_KEYDOWN && msg.wParam == VK_ESCAPE) {
    WSACancelBlockingCall();
    blocking_end_time = msg.time - 1;
    return FALSE;
  }

  TranslateMessage(&msg);
  DispatchMessage(&msg);

  return TRUE;
}


/*
 * Function: Set up a blocking hook function.
 *
 * Parameters:
 *	timeout - # of seconds to block for before cancelling.
 */
void
start_blocking_hook(int timeout)
{
  FARPROC proc;

  if (isblocking)
    return;

  isblocking = TRUE;
  blocking_end_time = GetTickCount() + (1000 * timeout);
#ifdef _WIN32
  proc = WSASetBlockingHook(blocking_hook_proc);
#else
  hook_instance = MakeProcInstance(blocking_hook_proc, hinstance);
  proc = WSASetBlockingHook(hook_instance);
#endif
  assert(proc != NULL);
}


/*
 * Function: End the blocking hook fuction set up above.
 */
void
end_blocking_hook(void)
{
#ifndef _WIN32
  FreeProcInstance(hook_instance);
#endif
  WSAUnhookBlockingHook();
  isblocking = FALSE;
}


/*
 * Function: Centers the specified window on the screen.
 *
 * Parameters:
 *		hwnd - the window to center on the screen.
 */
void
center_dialog(HWND hwnd)
{
  int scrwidth, scrheight;
  int dlgwidth, dlgheight;
  RECT r;
  HDC hdc;

  if (hwnd == NULL)
    return;

  GetWindowRect(hwnd, &r);
  dlgwidth = r.right  - r.left;
  dlgheight = r.bottom - r.top ;
  hdc = GetDC(NULL);
  scrwidth = GetDeviceCaps(hdc, HORZRES);
  scrheight = GetDeviceCaps(hdc, VERTRES);
  ReleaseDC(NULL, hdc);
  r.left = (scrwidth - dlgwidth) / 2;
  r.top  = (scrheight - dlgheight) / 2;
  MoveWindow(hwnd, r.left, r.top, dlgwidth, dlgheight, TRUE);
}


/*
 * Function: Positions the kwin dialog either to the saved location
 * 	or the center of the screen if no saved location.
 *
 * Parameters:
 *		hwnd - the window to center on the screen.
 */
static void
position_dialog(HWND hwnd)
{
  int scrwidth, scrheight;
  HDC hdc;
  int x, y, cx, cy;

  if (hwnd == NULL)
    return;

  hdc = GetDC(NULL);
  scrwidth = GetDeviceCaps(hdc, HORZRES);
  scrheight = GetDeviceCaps(hdc, VERTRES);
  ReleaseDC(NULL, hdc);
  x = cns_res.x;
  y = cns_res.y;
  cx = cns_res.cx;
  cy = cns_res.cy;

  if (x > scrwidth ||
      y > scrheight ||
      x + cx <= 0 ||
      y + cy <= 0)
    center_dialog(hwnd);
  else
    MoveWindow(hwnd, x, y, cx, cy, TRUE);
}


/*
 * Function: Set font of all dialog items.
 *
 * Parameters:
 *		hwnd - the dialog to set the font of
 */
void
set_dialog_font(HWND hwnd, HFONT hfont)
{
  hwnd = GetWindow(hwnd, GW_CHILD);

  while (hwnd != NULL) {
    SetWindowFont(hwnd, hfont, 0);
    hwnd = GetWindow(hwnd, GW_HWNDNEXT);
  }
}


/*
 * Function: Trim leading and trailing white space from a string.
 *
 * Parameters:
 *	s - the string to trim.
 */
void
trim(char *s)
{
  int l;
  int i;

  for (i = 0 ; s[i] ; i++)
    if (s[i] != ' ' && s[i] != '\t')
      break;

  l = strlen(&s[i]);
  memmove(s, &s[i], l + 1);

  for (l--; l >= 0; l--) {
    if (s[l] != ' ' && s[l] != '\t')
      break;
  }
  s[l + 1] = 0;
}


/*
 * Function: This routine figures out the current time epoch and
 * returns the conversion factor.  It exists because Microloss
 * screwed the pooch on the time() and _ftime() calls in its release
 * 7.0 libraries.  They changed the epoch to Dec 31, 1899!
 */
time_t
kwin_get_epoch(void)
{
  static struct tm jan_1_70 = {0, 0, 0, 1, 0, 70};
  time_t epoch = 0;

  epoch = -mktime(&jan_1_70);		/* Seconds til 1970 localtime */
  epoch += _timezone;				/* Seconds til 1970 GMT */

  return epoch;
}


/*
 * Function: Save the credentials for later restoration.
 *
 * Parameters:
 *	c - Returned pointer to saved credential cache.
 *
 *	pname - Returned as principal name of session.
 *
 *	pinstance - Returned as principal instance of session.
 *
 *	ncred - Returned number of credentials saved.
 */
static void
push_credentials(CREDENTIALS **cp, char *pname, char *pinstance, int *ncred)
{
#ifdef KRB4
  int i;
  char service[ANAME_SZ];
  char instance[INST_SZ];
  char realm[REALM_SZ];
  CREDENTIALS *c;

  if (krb_get_tf_fullname(NULL, pname, pinstance, NULL) != KSUCCESS) {
    pname[0] = 0;

    pinstance[0] = 0;
  }

  *ncred = krb_get_num_cred();
  if (*ncred <= 0)
    return;

  c= malloc(*ncred * sizeof(CREDENTIALS));
  assert(c != NULL);
  if (c == NULL) {
    *ncred = 0;

    return;
  }

  for (i = 0; i < *ncred; i++) {
    krb_get_nth_cred(service, instance, realm, i + 1);
    krb_get_cred(service, instance, realm, &c[i]);
  }

  *cp = c;
#endif

#ifdef KRB5     /* FIXME */
  return;
#endif
}


/*
 * Function: Restore the saved credentials.
 *
 *	c - Pointer to saved credential cache.
 *
 *	pname - Principal name of session.
 *
 *	pinstance - Principal instance of session.
 *
 *	ncred - Number of credentials saved.
 */
static void
pop_credentials(CREDENTIALS *c, char *pname, char *pinstance, int ncred)
{
#ifdef KRB4
  int i;

  if (pname[0])
    in_tkt(pname, pinstance);
  else
    dest_tkt();

  if (ncred <= 0)
    return;

  for (i = 0; i < ncred; i++) {
    krb_save_credentials(c[i].service, c[i].instance, c[i].realm,
			 c[i].session, c[i].lifetime, c[i].kvno,
			 &(c[i].ticket_st),
			 c[i].issue_date);
  }

  free(c);
#endif
#ifdef KRB5     /* FIXME */
  return;
#endif
}


/*
 * Function: Save most recent login triplets for placement on the
 *	bottom of the file menu.
 *
 * Parameters:
 *	hwnd - the handle of the window containing the menu to edit.
 *
 *	name - A login name to save in the recent login list
 *
 *	instance - An instance to save in the recent login list
 *
 *	realm - A realm to save in the recent login list
 */
static void
kwin_push_login(HWND hwnd, char *name, char *instance, char *realm)
{
  HMENU hmenu;
  int i;
  int id;
  int ctitems;
  char fullname[MAX_K_NAME_SZ + 3];
  char menuitem[MAX_K_NAME_SZ + 3];
  BOOL rc;

  fullname[sizeof(fullname) - 1] = '\0';
  strncpy(fullname, "&x ", sizeof(fullname) - 1);
  strncat(fullname, name, sizeof(fullname) - 1 - strlen(fullname));
  strncat(fullname, ".", sizeof(fullname) - 1 - strlen(fullname));
  strncat(fullname, instance, sizeof(fullname) - 1 - strlen(fullname));
  strncat(fullname, "@", sizeof(fullname) - 1 - strlen(fullname));
  strncat(fullname, realm, sizeof(fullname) - 1 - strlen(fullname));

  hmenu = GetMenu(hwnd);
  assert(hmenu != NULL);

  hmenu = GetSubMenu(hmenu, 0);
  assert(hmenu != NULL);

  ctitems = GetMenuItemCount(hmenu);
  assert(ctitems >= FILE_MENU_ITEMS);

  if (ctitems == FILE_MENU_ITEMS) {
    rc = AppendMenu(hmenu, MF_SEPARATOR, 0, NULL);
    assert(rc);

    ctitems++;
  }

  for (i = FILE_MENU_ITEMS + 1; i < ctitems; i++) {
    GetMenuString(hmenu, i, menuitem, sizeof(menuitem), MF_BYPOSITION);

    if (strcmp(&fullname[3], &menuitem[3]) == 0) {
      rc = RemoveMenu(hmenu, i, MF_BYPOSITION);
      assert(rc);

      ctitems--;

      break;
    }
  }

  rc = InsertMenu(hmenu, FILE_MENU_ITEMS + 1, MF_BYPOSITION, 1, fullname);
  assert(rc);

  ctitems++;
  if (ctitems - FILE_MENU_ITEMS - 1 > FILE_MENU_MAX_LOGINS) {
    RemoveMenu(hmenu, ctitems - 1, MF_BYPOSITION);

    ctitems--;
  }

  id = 0;
  for (i = FILE_MENU_ITEMS + 1; i < ctitems; i++) {
    GetMenuString(hmenu, i, menuitem, sizeof(menuitem), MF_BYPOSITION);

    rc = RemoveMenu(hmenu, i, MF_BYPOSITION);
    assert(rc);

    menuitem[1] = '1' + id;
    rc = InsertMenu(hmenu, i, MF_BYPOSITION, IDM_FIRST_LOGIN + id, menuitem);
    assert(rc);

    id++;
  }
}


/*
 * Function: Initialize the logins on the file menu form the KERBEROS.INI
 *	file.
 *
 * Parameters:
 *	hwnd - handle of the dialog containing the file menu.
 */
static void
kwin_init_file_menu(HWND hwnd)
{
  HMENU hmenu;
  int i;
  char menuitem[MAX_K_NAME_SZ + 3];
  int id;
  BOOL rc;

  hmenu = GetMenu(hwnd);
  assert(hmenu != NULL);

  hmenu = GetSubMenu(hmenu, 0);
  assert(hmenu != NULL);

  id = 0;
  for (i = 0; i < FILE_MENU_MAX_LOGINS; i++) {
    strcpy(menuitem + 3, cns_res.logins[i]);

    if (!menuitem[3])
      continue;

    menuitem[0] = '&';
    menuitem[1] = '1' + id;
    menuitem[2] = ' ';

    if (id == 0) {
      rc = AppendMenu(hmenu, MF_SEPARATOR, 0, NULL);
      assert(rc);
    }
    AppendMenu(hmenu, MF_STRING, IDM_FIRST_LOGIN + id, menuitem);

    id++;
  }
}


/*
 * Function: Save the items on the file menu in the KERBEROS.INI file.
 *
 * Parameters:
 *	hwnd - handle of the dialog containing the file menu.
 */
static void
kwin_save_file_menu(HWND hwnd)
{
  HMENU hmenu;
  int i;
  int id;
  int ctitems;
  char menuitem[MAX_K_NAME_SZ + 3];

  hmenu = GetMenu(hwnd);
  assert(hmenu != NULL);

  hmenu = GetSubMenu(hmenu, 0);
  assert(hmenu != NULL);

  ctitems = GetMenuItemCount(hmenu);
  assert(ctitems >= FILE_MENU_ITEMS);

  id = 0;
  for (i = FILE_MENU_ITEMS + 1; i < ctitems; i++) {
    GetMenuString(hmenu, i, menuitem, sizeof(menuitem), MF_BYPOSITION);

    strcpy(cns_res.logins[id], menuitem + 3);

    id++;
  }
}



/*
 * Function: Given an expiration time, choose an appropriate
 *	icon to display.
 *
 * Parameters:
 *	expiration time of expiration in time() compatible units
 *
 * Returns: Handle of icon to display
 */
HICON
kwin_get_icon(time_t expiration)
{
  int ixicon;
  time_t dt;

  dt = expiration - time(NULL);
  dt = dt / 60;			/* convert to minutes */
  if (dt <= 0)
    ixicon = IDI_EXPIRED - IDI_FIRST_CLOCK;
  else if (dt > 60)
    ixicon = IDI_TICKET - IDI_FIRST_CLOCK;
  else
    ixicon = (int)(dt / 5);

  return kwin_icons[ixicon];
}


/*
 * Function: Intialize name fields in the Kerberos dialog.
 *
 * Parameters:
 *	hwnd - the window recieving the message.
 *
 *	fullname - the full kerberos name to initialize with
 */
void
kwin_init_name(HWND hwnd, char *fullname)
{
  char name[ANAME_SZ];
  char instance[INST_SZ];
  char realm[REALM_SZ];
  int krc;
#ifdef KRB5
  krb5_error_code code;
  char *ptr;
#endif    

  if (fullname == NULL || fullname[0] == 0) {
#ifdef KRB4
    strcpy(name, krb_get_default_user());
    strcpy(instance, cns_res.instance);
    krc = krb_get_lrealm(realm, 1);
    if (krc != KSUCCESS)
      realm[0] = 0;
    strcpy(realm, cns_res.realm);
#endif /* KRB4 */

#ifdef KRB5
    strcpy(name, cns_res.name);
    
    *realm = '\0';
    code = krb5_get_default_realm(k5_context, &ptr);
    if (!code) {
      strcpy(realm, ptr);
      /*      free(ptr); XXX */
    }
    strcpy(realm, cns_res.realm);
#endif /* KRB5 */

  } else {
#ifdef KRB4
    kname_parse(name, instance, realm, fullname);
    SetDlgItemText(hwnd, IDD_LOGIN_INSTANCE, instance);
#endif

#ifdef KRB5
    krc = k5_kname_parse(name, realm, fullname);
    *instance = '\0';
#endif
  }

  SetDlgItemText(hwnd, IDD_LOGIN_NAME, name);
  SetDlgItemText(hwnd, IDD_LOGIN_REALM, realm);
}


/*
 * Function: Set the focus to the name control if no name
 * 	exists, the realm control if no realm exists or the
 * 	password control.  Uses PostMessage not SetFocus.
 *
 * Parameters:
 *	hwnd - the Window handle of the parent.
 */
void
kwin_set_default_focus(HWND hwnd)
{
  char name[ANAME_SZ];
  char realm[REALM_SZ];
  HWND hwnditem;

  GetDlgItemText(hwnd, IDD_LOGIN_NAME, name, sizeof(name));

  trim(name);
  if (strlen(name) <= 0)
    hwnditem = GetDlgItem(hwnd, IDD_LOGIN_NAME);
  else {
    GetDlgItemText(hwnd, IDD_LOGIN_REALM, realm, sizeof(realm));
    trim(realm);

    if (strlen(realm) <= 0)
      hwnditem = GetDlgItem(hwnd, IDD_LOGIN_REALM);
    else
      hwnditem = GetDlgItem(hwnd, IDD_LOGIN_PASSWORD);
  }

  PostMessage(hwnd, WM_NEXTDLGCTL, (WPARAM)hwnditem, MAKELONG(1, 0));
}


/*
 * Function: Save the values which live in the KERBEROS.INI file.
 *
 * Parameters:
 *	hwnd - the window handle of the dialog containing fields to
 *		be saved
 */
static void
kwin_save_name(HWND hwnd)
{
  char name[ANAME_SZ];
  char instance[INST_SZ];
  char realm[REALM_SZ];

  GetDlgItemText(hwnd, IDD_LOGIN_NAME, name, sizeof(name));
  trim(name);

#ifdef KRB4
  krb_set_default_user(name);
  GetDlgItemText(hwnd, IDD_LOGIN_INSTANCE, instance, sizeof(instance));
  trim(instance);
  strcpy(cns_res.instance, instance);
#endif

#ifdef KRB5
  strcpy(cns_res.name, name);
  *instance = '\0';
#endif

  GetDlgItemText(hwnd, IDD_LOGIN_REALM, realm, sizeof(realm));
  trim(realm);
  strcpy(cns_res.realm, realm);

  kwin_push_login(hwnd, name, instance, realm);
}


/*
 * Function: Process WM_INITDIALOG messages.  Set the fonts
 *	for all items on the dialog and populate the ticket list.
 *	Also set the default values for user, instance and realm.
 *
 * Returns: TRUE if we didn't set the focus here,
 * 	FALSE if we did.
 */
static BOOL
kwin_initdialog(HWND hwnd, HWND hwndFocus, LPARAM lParam)
{
  LOGFONT lf;
  HDC hdc;
  char name[ANAME_SZ];

  position_dialog(hwnd);
  ticket_init_list(GetDlgItem(hwnd, IDD_TICKET_LIST));
  kwin_init_file_menu(hwnd);
  kwin_init_name(hwnd, (char *)lParam);
  hdc = GetDC(NULL);
  assert(hdc != NULL);

  memset(&lf, 0, sizeof(lf));
  lf.lfHeight = -MulDiv(9, GetDeviceCaps(hdc, LOGPIXELSY), 72);
  strcpy(lf.lfFaceName, "Arial");
  hfontdialog = CreateFontIndirect(&lf);
  assert(hfontdialog != NULL);

  if (hfontdialog == NULL) {
    ReleaseDC(NULL, hdc);

    return TRUE;
  }

  lf.lfHeight = -MulDiv(8, GetDeviceCaps(hdc, LOGPIXELSY), 72);
  hfonticon = CreateFontIndirect(&lf);
  assert(hfonticon != NULL);

  if (hfonticon == NULL) {
    ReleaseDC(NULL, hdc);

    return TRUE;
  }

  ReleaseDC(NULL, hdc);

  set_dialog_font(hwnd, hfontdialog);
  GetDlgItemText(hwnd, IDD_LOGIN_NAME, name, sizeof(name));
  trim(name);

  if (strlen(name) > 0)
    SetFocus(GetDlgItem(hwnd, IDD_LOGIN_PASSWORD));
  else
    SetFocus(GetDlgItem(hwnd, IDD_LOGIN_NAME));

  ShowWindow(hwnd, dlgncmdshow);

  kwin_timer_id = SetTimer(hwnd, 1, KWIN_UPDATE_PERIOD, NULL);
  assert(kwin_timer_id != 0);

  return FALSE;
}


/*
 * Function: Process WM_DESTROY messages.  Delete the font
 *	created for use by the controls.
 */
static void
kwin_destroy(HWND hwnd)
{
  RECT r;

  ticket_destroy(GetDlgItem(hwnd, IDD_TICKET_LIST));

  if (hfontdialog != NULL)
    DeleteObject(hfontdialog);

  if (hfonticon != NULL)
    DeleteObject(hfonticon);

  kwin_save_file_menu(hwnd);
  GetWindowRect(hwnd, &r);
  cns_res.x = r.left;
  cns_res.y = r.top;
  cns_res.cx = r.right - r.left;
  cns_res.cy = r.bottom - r.top;

  KillTimer(hwnd, kwin_timer_id);
}


/*
 * Function: Retrievs item WindowRect in hwnd client
 *	coordiate system.
 *
 * Parameters:
 *	hwnditem - the item to retrieve
 *
 *	item - dialog in which into which to translate
 *
 *	r - rectangle returned
 */
static void
windowrect(HWND hwnditem, HWND hwnd, RECT *r)
{
  GetWindowRect(hwnditem, r);
  ScreenToClient(hwnd, (LPPOINT)&(r->left));
  ScreenToClient(hwnd, (LPPOINT)&(r->right));
}


/*
 * Function: Process WM_SIZE messages.  Resize the
 *	list and position the buttons attractively.
 */
static void
kwin_size(HWND hwnd, UINT state, int cxdlg, int cydlg)
{
#define listgap 8
  RECT r;
  RECT rdlg;
  int hmargin, vmargin;
  HWND hwnditem;
  int cx, cy;
  int i;
  int titlebottom;
  int editbottom;
  int listbottom;
  int gap;
  int left;
  int titleleft[IDD_MAX_TITLE - IDD_MIN_TITLE + 1];

  if (state == SIZE_MINIMIZED)
    return;

  GetClientRect(hwnd, &rdlg);

  /*
   * The ticket list title
   */
  hwnditem = GetDlgItem(hwnd, IDD_TICKET_LIST_TITLE);

  if (hwnditem == NULL)
    return;

  windowrect(hwnditem, hwnd, &r);
  hmargin = r.left;
  vmargin = r.top;
  cx = cxdlg - 2 * hmargin;
  cy = r.bottom - r.top;
  MoveWindow(hwnditem, r.left, r.top, cx, cy, TRUE);

  /*
   * The buttons
   */
  cx = 0;

  for (i = IDD_MIN_BUTTON; i <= IDD_MAX_BUTTON; i++) {
    hwnditem = GetDlgItem(hwnd, i);
    windowrect(hwnditem, hwnd, &r);
    if (i == IDD_MIN_BUTTON)
      hmargin = r.left;

    cx += r.right - r.left;
  }

  gap = (cxdlg - 2 * hmargin - cx) / (IDD_MAX_BUTTON - IDD_MIN_BUTTON);
  left = hmargin;
  for (i = IDD_MIN_BUTTON; i <= IDD_MAX_BUTTON; i++) {
    hwnditem = GetDlgItem(hwnd, i);
    windowrect(hwnditem, hwnd, &r);
    editbottom = -r.top;
    cx = r.right - r.left;
    cy = r.bottom - r.top;
    r.top = rdlg.bottom - vmargin - cy;
    MoveWindow(hwnditem, left, r.top, cx, cy, TRUE);

    left += cx + gap;
  }

  /*
   * Edit fields: stretch boxes, keeping the gap between boxes equal to
   * what it was on entry.
   */
  editbottom += r.top;

  hwnditem = GetDlgItem(hwnd, IDD_MIN_EDIT);
  windowrect(hwnditem, hwnd, &r);
  gap = r.right;
  hmargin = r.left;
  editbottom += r.bottom;
  titlebottom = -r.top;

  hwnditem = GetDlgItem(hwnd, IDD_MIN_EDIT + 1);
  windowrect(hwnditem, hwnd, &r);
  gap = r.left - gap;

  cx = cxdlg - 2 * hmargin - (IDD_MAX_EDIT - IDD_MIN_EDIT) * gap;
  cx = cx / (IDD_MAX_EDIT - IDD_MIN_EDIT + 1);
  left = hmargin;

  for (i = IDD_MIN_EDIT; i <= IDD_MAX_EDIT; i++) {
    hwnditem = GetDlgItem(hwnd, i);
    windowrect(hwnditem, hwnd, &r);
    cy = r.bottom - r.top;
    r.top = editbottom - cy;
    MoveWindow(hwnditem, left, r.top, cx, cy, TRUE);
    titleleft[i-IDD_MIN_EDIT] = left;

    left += cx + gap;
  }

  /*
   * Edit field titles
   */
  titlebottom += r.top;
  windowrect(GetDlgItem(hwnd, IDD_MIN_TITLE), hwnd, &r);
  titlebottom += r.bottom;
  listbottom = -r.top;

  for (i = IDD_MIN_TITLE; i <= IDD_MAX_TITLE; i++) {
    hwnditem = GetDlgItem(hwnd, i);
    windowrect(hwnditem, hwnd, &r);
    cx = r.right - r.left;
    cy = r.bottom - r.top;
    r.top = titlebottom - cy;
    MoveWindow(hwnditem, titleleft[i-IDD_MIN_TITLE], r.top, cx, cy, TRUE);
  }

  /*
   * The list
   */
  listbottom = r.top - listgap;
  hwnditem = GetDlgItem(hwnd, IDD_TICKET_LIST);
  windowrect(hwnditem, hwnd, &r);
  hmargin = r.left;
  cx = cxdlg - 2 * hmargin;
  cy = listbottom - r.top;
  MoveWindow(hwnditem, r.left, r.top, cx, cy, TRUE);
}


/*
 * Function: Process WM_GETMINMAXINFO messages
 */
static void
kwin_getminmaxinfo(HWND hwnd, LPMINMAXINFO lpmmi)
{
  lpmmi->ptMinTrackSize.x =
    (KWIN_MIN_WIDTH * LOWORD(GetDialogBaseUnits())) / 4;

  lpmmi->ptMinTrackSize.y =
    (KWIN_MIN_HEIGHT * HIWORD(GetDialogBaseUnits())) / 8;
}


/*
 * Function: Process WM_TIMER messages
 */
static void
kwin_timer(HWND hwnd, UINT timer_id)
{
  HWND hwndfocus;
  time_t t;
  time_t expiration;
  BOOL expired;
#ifdef KRB4
  CREDENTIALS c;
  int ncred;
  int i;
  char service[ANAME_SZ];
  char instance[INST_SZ];
  char realm[REALM_SZ];
#endif
#ifdef KRB5
  krb5_error_code code;
  krb5_cc_cursor cursor;
  krb5_creds cred;
  int n;
  char *s;
#endif

  if (timer_id != 1) {
    FORWARD_WM_TIMER(hwnd, timer_id, DefDlgProc);
    return;
  }

  expired = FALSE;
  ticket_init_list(GetDlgItem(hwnd, IDD_TICKET_LIST));

  if (alerted) {
    if (IsIconic(hwnd))
      InvalidateRect(hwnd, NULL, TRUE);

    return;
  }

#ifdef KRB4
  ncred = krb_get_num_cred();
  for (i = 1; i <= ncred; i++) {
    krb_get_nth_cred(service, instance, realm, i);

    if (_stricmp(service, "krbtgt") == 0) {
      /* Warn if ticket will expire w/i TIME_BUFFER seconds */
      krb_get_cred(service, instance, realm, &c);
      expiration = c.issue_date + (long)c.lifetime * 5L * 60L;
      t = TIME_BUFFER + time(NULL);

      if (t >= expiration) {
	expired = TRUE;
	/* Don't alert because of stale tickets */
	if (t >= expiration + KWIN_UPDATE_PERIOD / 1000) {
	  alerted = TRUE;

	  if (IsIconic(hwnd))
	    InvalidateRect(hwnd, NULL, TRUE);
	  return;
	}
	break;
      }
    }
  }
#endif

#ifdef KRB5
  code = krb5_cc_start_seq_get(k5_context, k5_ccache, &cursor);

  while (code == 0) {
    code = krb5_cc_next_cred(k5_context, k5_ccache, &cursor, &cred);
    if (code)
      break;
    n = krb5_princ_component(k5_context, cred.server, 0)->length;
    s = krb5_princ_component(k5_context, cred.server, 0)->data;
    if (n != KRB5_TGS_NAME_SIZE)
      continue;
    if (memcmp(KRB5_TGS_NAME, s, KRB5_TGS_NAME_SIZE))
      continue;

    /* Warn if ticket will expire w/i TIME_BUFFER seconds */
    expiration = cred.times.endtime;
    t = TIME_BUFFER + time(NULL);

    if (t >= expiration) {
      expired = TRUE;
      /* Don't alert because of stale tickets */
      if (t >= expiration + KWIN_UPDATE_PERIOD / 1000) {
	alerted = TRUE;

	if (IsIconic(hwnd))
	  InvalidateRect(hwnd, NULL, TRUE);
	return;
      }
      break;
    }
  }
  if (code == 0 || code == KRB5_CC_END)
    krb5_cc_end_seq_get(k5_context, k5_ccache, &cursor);
    
#endif

  if (!expired) {
    if (IsIconic(hwnd))
      InvalidateRect(hwnd, NULL, TRUE);

    return;
  }

  alerted = TRUE;

  if (beep)
    MessageBeep(MB_ICONEXCLAMATION);

  if (alert) {
    if (IsIconic(hwnd)) {
      hwndfocus = GetFocus();
      ShowWindow(hwnd, SW_RESTORE);
      SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0,
		   SWP_NOACTIVATE | SWP_SHOWWINDOW | SWP_NOMOVE | SWP_NOSIZE);
      SetFocus(hwndfocus);
    }

    SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0,
		 SWP_NOACTIVATE | SWP_SHOWWINDOW | SWP_NOMOVE | SWP_NOSIZE);

    return;
  }

  if (IsIconic(hwnd))
    InvalidateRect(hwnd, NULL, TRUE);
}

/*
 * Function: Process WM_COMMAND messages
 */
static void
kwin_command(HWND hwnd, int cid, HWND hwndCtl, UINT codeNotify)
{
  char                      name[ANAME_SZ];
  char                      realm[REALM_SZ];
  char                      password[MAX_KPW_LEN];
  HCURSOR                   hcursor;
  BOOL                      blogin;
  HMENU                     hmenu;
  char                      menuitem[MAX_K_NAME_SZ + 3];
  char                      copyright[128];
  int                       id;
#ifdef KRB4
  char                      instance[INST_SZ];
  int                       lifetime;
  int                       krc;
#endif
#ifdef KRB5
  long                      lifetime;
  krb5_error_code           code;
  krb5_principal            principal;
  krb5_creds                creds;
  krb5_get_init_creds_opt   opts;
  gic_data                  gd;
#endif

#ifdef KRB4
  EnableWindow(GetDlgItem(hwnd, IDD_TICKET_DELETE), krb_get_num_cred() > 0);
#endif

#ifdef KRB5
  EnableWindow(GetDlgItem(hwnd, IDD_TICKET_DELETE), k5_get_num_cred(1) > 0);
#endif

  GetDlgItemText(hwnd, IDD_LOGIN_NAME, name, sizeof(name));
  trim(name);
  blogin = strlen(name) > 0;

  if (blogin) {
    GetDlgItemText(hwnd, IDD_LOGIN_REALM, realm, sizeof(realm));
    trim(realm);
    blogin = strlen(realm) > 0;
  }

  if (blogin) {
    GetDlgItemText(hwnd, IDD_LOGIN_PASSWORD, password, sizeof(password));
    blogin = strlen(password) > 0;
  }

  EnableWindow(GetDlgItem(hwnd, IDD_LOGIN), blogin);
  id = (blogin) ? IDD_LOGIN : IDD_PASSWORD_CR2;
  SendMessage(hwnd, DM_SETDEFID, id, 0);

  if (codeNotify != BN_CLICKED && codeNotify != 0 && codeNotify != 1)
    return; /* FALSE */

  /*
   * Check to see if this item is in a list of the ``recent hosts'' sort
   * of list, under the FILE menu.
   */
  if (cid >= IDM_FIRST_LOGIN && cid < IDM_FIRST_LOGIN + FILE_MENU_MAX_LOGINS) {
    hmenu = GetMenu(hwnd);
    assert(hmenu != NULL);

    hmenu = GetSubMenu(hmenu, 0);
    assert(hmenu != NULL);

    if (!GetMenuString(hmenu, cid, menuitem, sizeof(menuitem), MF_BYCOMMAND))
      return; /* TRUE */

    if (menuitem[0])
      kwin_init_name(hwnd, &menuitem[3]);

    return; /* TRUE */
  }

  switch (cid) {
  case IDM_EXIT:
    if (isblocking)
      WSACancelBlockingCall();
    WinHelp(hwnd, KERBEROS_HLP, HELP_QUIT, 0);
    PostQuitMessage(0);

    return; /* TRUE */

  case IDD_PASSWORD_CR2:                      /* Make CR == TAB */
    id = GetDlgCtrlID(GetFocus());
    assert(id != 0);

    if (id == IDD_MAX_EDIT)
      PostMessage(hwnd, WM_NEXTDLGCTL,
		  (WPARAM)GetDlgItem(hwnd, IDD_MIN_EDIT), MAKELONG(1, 0));
    else
      PostMessage(hwnd, WM_NEXTDLGCTL, 0, 0);

    return; /* TRUE */

  case IDD_LOGIN:
    if (isblocking)
      return; /* TRUE */

    GetDlgItemText(hwnd, IDD_LOGIN_NAME, name, sizeof(name));
    trim(name);
    GetDlgItemText(hwnd, IDD_LOGIN_REALM, realm, sizeof(realm));
    trim(realm);
    GetDlgItemText(hwnd, IDD_LOGIN_PASSWORD, password, sizeof(password));
    SetDlgItemText(hwnd, IDD_LOGIN_PASSWORD, "");  /* nuke the password */
    trim(password);

#ifdef KRB4
    GetDlgItemText(hwnd, IDD_LOGIN_INSTANCE, instance, sizeof(instance));
    trim(instance);
#endif

    hcursor = SetCursor(LoadCursor(NULL, IDC_WAIT));
    lifetime = cns_res.lifetime;
    start_blocking_hook(BLOCK_MAX_SEC);

#ifdef KRB4
    lifetime = (lifetime + 4) / 5;
    krc = krb_get_pw_in_tkt(name, instance, realm, "krbtgt", realm,
			    lifetime, password);
#endif

#ifdef KRB5
    principal = NULL;
    
    /*
     * convert the name + realm into a krb5 principal string and parse it into a principal
     */
    sprintf(menuitem, "%s@%s", name, realm);
    code = krb5_parse_name(k5_context, menuitem, &principal);
    if (code)
      goto errorpoint;
    
    /*
     * set the various ticket options.  First, initialize the structure, then set the ticket
     * to be forwardable if desired, and set the lifetime.
     */
    krb5_get_init_creds_opt_init(&opts);
    krb5_get_init_creds_opt_set_forwardable(&opts, forwardable);
    krb5_get_init_creds_opt_set_tkt_life(&opts, lifetime * 60);
    if (noaddresses) {
		krb5_get_init_creds_opt_set_address_list(&opts, NULL);
 	}    

    /*
     * get the initial creds using the password and the options we set above
     */
    gd.hinstance = hinstance;
    gd.hwnd = hwnd;
    gd.id = ID_VARDLG;
    code = krb5_get_init_creds_password(k5_context, &creds, principal, password, 
					gic_prompter, &gd, 0, NULL, &opts);
    if (code)
      goto errorpoint;
    
    /*
     * initialize the credential cache
     */
    code = krb5_cc_initialize(k5_context, k5_ccache, principal);
    if (code)
      goto errorpoint;
    
    /*
     * insert the principal into the cache
     */
    code = krb5_cc_store_cred(k5_context, k5_ccache, &creds);
    
  errorpoint:
    
    if (principal)
      krb5_free_principal(k5_context, principal);

    end_blocking_hook();
    SetCursor(hcursor);
    kwin_set_default_focus(hwnd);
    
    if (code) {
      if (code == KRB5KRB_AP_ERR_BAD_INTEGRITY)
	MessageBox(hwnd, "Password incorrect", NULL, 
		   MB_OK | MB_ICONEXCLAMATION);
      else 
	com_err(NULL, code, "while logging in");
    }
#endif /* KRB5 */
    
#ifdef KRB4
    if (krc != KSUCCESS) {
      MessageBox(hwnd, krb_get_err_text(krc),	"",
		 MB_OK | MB_ICONEXCLAMATION);

      return; /* TRUE */
    }
#endif

    kwin_save_name(hwnd);
    alerted = FALSE;

    switch (action) {
    case LOGIN_AND_EXIT:
      SendMessage(hwnd, WM_COMMAND, GET_WM_COMMAND_MPS(IDM_EXIT, 0, 0));
      break;

    case LOGIN_AND_MINIMIZE:
      ShowWindow(hwnd, SW_MINIMIZE);
      break;
    }

    return; /* TRUE */

  case IDD_TICKET_DELETE:
    if (isblocking)
      return; /* TRUE */

#ifdef KRB4
    krc = dest_tkt();
    if (krc != KSUCCESS)
      MessageBox(hwnd, krb_get_err_text(krc),	"",
		 MB_OK | MB_ICONEXCLAMATION);
#endif

#ifdef KRB5
    code = k5_dest_tkt();
#endif

    kwin_set_default_focus(hwnd);
    alerted = FALSE;

    return; /* TRUE */

  case IDD_CHANGE_PASSWORD:
    if (isblocking)
      return; /* TRUE */
    password_dialog(hwnd);
    kwin_set_default_focus(hwnd);

    return; /* TRUE */

  case IDM_OPTIONS:
    if (isblocking)
      return; /* TRUE */
    opts_dialog(hwnd);

    return; /* TRUE */

  case IDM_HELP_INDEX:
    WinHelp(hwnd, KERBEROS_HLP, HELP_INDEX, 0);

    return; /* TRUE */

  case IDM_ABOUT:
    ticket_init_list(GetDlgItem(hwnd, IDD_TICKET_LIST));
    if (isblocking)
      return; /* TRUE */

#ifdef KRB4
    strcpy(copyright, "        Kerberos 4 for Windows ");
#endif
#ifdef KRB5
    strcpy(copyright, "        Kerberos V5 for Windows ");
#endif
#ifdef _WIN32
    strncat(copyright, "32-bit\n", sizeof(copyright) - 1 - strlen(copyright));
#else
    strncat(copyright, "16-bit\n", sizeof(copyright) - 1 - strlen(copyright));
#endif
    strncat(copyright, "\n                Version 1.12\n\n",
            sizeof(copyright) - 1 - strlen(copyright));
#ifdef ORGANIZATION
    strncat(copyright, "          For information, contact:\n",
	    sizeof(copyright) - 1 - strlen(copyright));
    strncat(copyright, ORGANIZATION, sizeof(copyright) - 1 - strlen(copyright));
#endif
    MessageBox(hwnd, copyright, KWIN_DIALOG_NAME, MB_OK);

    return; /* TRUE */
  }

  return; /* FALSE */
}


/*
 * Function: Process WM_SYSCOMMAND messages by setting
 *	the focus to the password or name on restore.
 */
static void
kwin_syscommand(HWND hwnd, UINT cmd, int x, int y)
{
  if (cmd == SC_RESTORE)
    kwin_set_default_focus(hwnd);

  if (cmd == SC_CLOSE) {
    SendMessage(hwnd, WM_COMMAND, GET_WM_COMMAND_MPS(IDM_EXIT, 0, 0));
    return;
  }

  FORWARD_WM_SYSCOMMAND(hwnd, cmd, x, y, DefDlgProc);
}


/*
 * Function: Process WM_PAINT messages by displaying an
 *	informative icon when we are iconic.
 */
static void
kwin_paint(HWND hwnd)
{
  HDC hdc;
  PAINTSTRUCT ps;
  HICON hicon;
  time_t expiration = 0;
  time_t dt;
  char buf[20];
  RECT r;
#ifdef KRB4
  int i;
  int ncred;
  char service[ANAME_SZ];
  char instance[INST_SZ];
  char realm[REALM_SZ];
  CREDENTIALS c;
#endif
#ifdef KRB5
  krb5_error_code code;
  krb5_cc_cursor cursor;
  krb5_creds c;
  int n;
  char *service;
#endif

  if (!IsIconic(hwnd)) {
    FORWARD_WM_PAINT(hwnd, DefDlgProc);
    return;
  }

#ifdef KRB4
  ncred = krb_get_num_cred();

  for (i = 1; i <= ncred; i++) {
    krb_get_nth_cred(service, instance, realm, i);
    krb_get_cred(service, instance, realm, &c);
    if (_stricmp(c.service, "krbtgt") == 0) {
      expiration = c.issue_date - kwin_get_epoch()
	+ (long)c.lifetime * 5L * 60L;
      break;
    }
  }
#endif

#ifdef KRB5
  code = krb5_cc_start_seq_get(k5_context, k5_ccache, &cursor);

  while (code == 0) {
    code = krb5_cc_next_cred(k5_context, k5_ccache, &cursor, &c);
    if (code)
      break;
    n = krb5_princ_component(k5_context, c.server, 0)->length;
    service = krb5_princ_component(k5_context, c.server, 0)->data;
    if (n != KRB5_TGS_NAME_SIZE)
      continue;
    if (memcmp(KRB5_TGS_NAME, service, KRB5_TGS_NAME_SIZE))
      continue;
    expiration = c.times.endtime;
    break;
                
  }
  if (code == 0 || code == KRB5_CC_END)
    krb5_cc_end_seq_get(k5_context, k5_ccache, &cursor);
#endif

  hdc = BeginPaint(hwnd, &ps);
  GetClientRect(hwnd, &r);
  DefWindowProc(hwnd, WM_ICONERASEBKGND, (WPARAM)hdc, 0);

  if (expiration == 0) {
    strcpy(buf, KWIN_DIALOG_NAME);
    hicon = LoadIcon(hinstance, MAKEINTRESOURCE(IDI_KWIN));
  }
  else {
    hicon = kwin_get_icon(expiration);
    dt = (expiration - time(NULL)) / 60;

    if (dt <= 0)
      sprintf(buf, "%s - %s", KWIN_DIALOG_NAME, "Expired");
    else if (dt < 60) {
      dt %= 60;
      sprintf(buf, "%s - %ld min", KWIN_DIALOG_NAME, dt);
    }
    else {
      dt /= 60;
      sprintf(buf, "%s - %ld hr", KWIN_DIALOG_NAME, dt);
    }

    buf[sizeof(buf) - 1] = '\0';
    if (dt > 1)
      strncat(buf, "s", sizeof(buf) - 1 - strlen(buf));
  }

  DrawIcon(hdc, r.left, r.top, hicon);
  EndPaint(hwnd, &ps);
  SetWindowText(hwnd, buf);
}


/*
 * Function: Window procedure for the Kerberos control panel dialog.
 */
LRESULT CALLBACK
kwin_wnd_proc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{

#if 0
  if (message == wm_kerberos_changed) {       /* Message from the ccache */
    n = ticket_init_list(GetDlgItem(hwnd, IDD_TICKET_LIST));
    EnableWindow(GetDlgItem(hwnd, IDD_TICKET_DELETE), n > 0);

    return 0;
  }
#endif

  switch (message) {
    HANDLE_MSG(hwnd, WM_GETMINMAXINFO, kwin_getminmaxinfo);

    HANDLE_MSG(hwnd, WM_DESTROY, kwin_destroy);

    HANDLE_MSG(hwnd, WM_MEASUREITEM, ticket_measureitem);

    HANDLE_MSG(hwnd, WM_DRAWITEM, ticket_drawitem);

  case WM_SETCURSOR:
    if (isblocking) {
      SetCursor(LoadCursor(NULL, IDC_WAIT));
      return TRUE;
    }
    break;

    HANDLE_MSG(hwnd, WM_SIZE, kwin_size);

    HANDLE_MSG(hwnd, WM_SYSCOMMAND, kwin_syscommand);

    HANDLE_MSG(hwnd, WM_TIMER, kwin_timer);

    HANDLE_MSG(hwnd, WM_PAINT, kwin_paint);
    
  case WM_ERASEBKGND:
    if (!IsIconic(hwnd))
      break;
    return 0;

  case WM_KWIN_SETNAME:
    kwin_init_name(hwnd, (char *)lParam);
  }

  return DefDlgProc(hwnd, message, wParam, lParam);
}


/*
 * Function: Dialog procedure called by the dialog manager
 *	to process dialog specific messages.
 */
static BOOL CALLBACK
kwin_dlg_proc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
  switch (message) {
    HANDLE_MSG(hwnd, WM_INITDIALOG, kwin_initdialog);

    HANDLE_MSG(hwnd, WM_COMMAND, kwin_command);
  }

  return FALSE;
}


/*
 * Function: Initialize the kwin dialog class.
 *
 * Parameters:
 *	hinstance - the instance to initialize
 *
 * Returns: TRUE if dialog class registration is sucessfully, false otherwise.
 */
static BOOL
kwin_init(HINSTANCE hinstance)
{
  WNDCLASS class;
  ATOM rc;

  class.style = CS_HREDRAW | CS_VREDRAW;
  class.lpfnWndProc = (WNDPROC)kwin_wnd_proc;
  class.cbClsExtra = 0;
  class.cbWndExtra = DLGWINDOWEXTRA;
  class.hInstance = hinstance;
  class.hIcon = NULL;
  /*		LoadIcon(hinstance, MAKEINTRESOURCE(IDI_KWIN)); */
  class.hCursor = NULL;
  class.hbrBackground = NULL;
  class.lpszMenuName = NULL;
  class.lpszClassName = KWIN_DIALOG_CLASS;

  rc = RegisterClass(&class);
  assert(rc);

  return rc;
}


/*
 * Function: Initialize the KWIN application.  This routine should
 *	only be called if no previous instance of the application
 *	exists.  Currently it only registers a class for the kwin
 *	dialog type.
 *
 * Parameters:
 *	hinstance - the instance to initialize
 *
 * Returns: TRUE if initialized sucessfully, false otherwise.
 */
static BOOL
init_application(HINSTANCE hinstance)
{
  BOOL rc;

#if 0
#ifdef KRB4
  wm_kerberos_changed = krb_get_notification_message();
#endif

#ifdef KRB5
  wm_kerberos_changed = krb5_get_notification_message();
#endif
#endif

  rc = kwin_init(hinstance);

  return rc;
}


/*
 * Function: Quits the KWIN application.  This routine should
 *	be called when the last application instance exits.
 *
 * Parameters:
 *	hinstance - the instance which is quitting.
 *
 * Returns: TRUE if initialized sucessfully, false otherwise.
 */
static BOOL
quit_application(HINSTANCE hinstance)
{
  return TRUE;
}


/*
 * Function: Initialize the current instance of the KWIN application.
 *
 * Parameters:
 *	hinstance - the instance to initialize
 *
 *	ncmdshow - show flag to indicate wheather to come up minimized
 *		or not.
 *
 * Returns: TRUE if initialized sucessfully, false otherwise.
 */
static BOOL
init_instance(HINSTANCE hinstance, int ncmdshow)
{
  WORD versionrequested;
  WSADATA wsadata;
  int rc;
  int i;

  versionrequested = 0x0101;			/* We need version 1.1 */
  rc = WSAStartup(versionrequested, &wsadata);
  if (rc != 0) {
    MessageBox(NULL, "Couldn't initialize Winsock library", "",
	       MB_OK | MB_ICONSTOP);

    return FALSE;
  }

  if (versionrequested != wsadata.wVersion) {
    WSACleanup();
    MessageBox(NULL, "Winsock version 1.1 not available", "",
	       MB_OK | MB_ICONSTOP);

    return FALSE;
  }

#ifdef KRB5
  {
    krb5_error_code code;

    code = krb5_init_context(&k5_context);
    if (!code) {
#if 0				/* Not needed under windows */
      krb5_init_ets(k5_context);
#endif
      code = k5_init_ccache(&k5_ccache);
    }
    if (code) {
      com_err(NULL, code, "while initializing program");
      return FALSE;
    }
    k5_name_from_ccache(k5_ccache);
  }
#endif

  cns_load_registry();

  /*
   * Set up expiration action
   */
  alert = cns_res.alert;
  beep = cns_res.beep;

  /*
   * ticket options
   */
  forwardable = cns_res.forwardable;
  noaddresses = cns_res.noaddresses;

  /*
   * Load clock icons
   */
  for (i = IDI_FIRST_CLOCK; i <= IDI_LAST_CLOCK; i++)
    kwin_icons[i - IDI_FIRST_CLOCK] = LoadIcon(hinstance, MAKEINTRESOURCE(i));

#ifdef KRB4
  krb_start_session(NULL);
#endif

  return TRUE;
}


/*
 * Function: Quits the current instance of the KWIN application.
 *
 * Parameters:
 *	hinstance - the instance to quit.
 *
 * Returns: TRUE if termination was sucessfully, false otherwise.
 */
static BOOL
quit_instance(HINSTANCE hinstance)
{
  int i;

#ifdef KRB4
  krb_end_session(NULL);
#endif

#ifdef KRB5     /* FIXME */
  krb5_cc_close(k5_context, k5_ccache);
#endif

  WSACleanup();

  /*
   * Unload clock icons
   */
  for (i = IDI_FIRST_CLOCK; i <= IDI_LAST_CLOCK; i++)
    DestroyIcon(kwin_icons[i - IDI_FIRST_CLOCK]);

  return TRUE;
}


/*
 * Function: Main routine called on program invocation.
 *
 * Parameters:
 *	hinstance - the current instance
 *
 *	hprevinstance - previous instance if one exists or NULL.
 *
 *	cmdline - the command line string passed by Windows.
 *
 *	ncmdshow - show flag to indicate wheather to come up minimized
 *		or not.
 *
 * Returns: TRUE if initialized sucessfully, false otherwise.
 */
int PASCAL
WinMain(HINSTANCE hinst, HINSTANCE hprevinstance, LPSTR cmdline, int ncmdshow)
{
  DLGPROC dlgproc;
  HWND hwnd;
  HACCEL haccel;
  MSG msg;
  char *p;
  char buf[MAX_K_NAME_SZ + 9];
  char name[MAX_K_NAME_SZ];

  strcpy(buf, cmdline);
  action = LOGIN_AND_RUN;
  name[0] = 0;
  p = strtok(buf, " ,");

  while (p != NULL) {
    if (_stricmp(p, "/exit") == 0)
      action = LOGIN_AND_EXIT;
    else if (_stricmp(p, "/minimize") == 0)
      action = LOGIN_AND_MINIMIZE;
    else
      strcpy(name, p);

    p = strtok(NULL, " ,");
  }

  dlgncmdshow = ncmdshow;
  hinstance = hinst;

#ifndef _WIN32
  /*
   * If a previous instance of this application exits, bring it
   * to the front and exit.
   *
   * This code is not compiled for WIN32, since hprevinstance will always
   * be NULL.
   */
  if (hprevinstance != NULL) {
    hwnd = FindWindow(KWIN_DIALOG_CLASS, NULL);

    if (IsWindow(hwnd) && IsWindowVisible(hwnd)) {
      if (GetWindowWord(hwnd, GWW_HINSTANCE) == hprevinstance) {
	if (name[0])
	  SendMessage(hwnd, WM_KWIN_SETNAME, 0, (LONG)name);

	ShowWindow(hwnd, ncmdshow);
	SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0,
		     SWP_SHOWWINDOW | SWP_NOMOVE | SWP_NOSIZE);

	return FALSE;
      }
    }
  }

  if (hprevinstance == NULL)
#endif /* _WIN32 */

  if (!init_application(hinstance))
      return FALSE;

  if (!init_instance(hinstance, ncmdshow))
    return FALSE;

#ifdef _WIN32
  dlgproc = kwin_dlg_proc;
#else
  dlgproc = (FARPROC)MakeProcInstance(kwin_dlg_proc, hinstance);
  assert(dlgproc != NULL);

  if (dlgproc == NULL)
    return 1;
#endif

  hwnd = CreateDialogParam(hinstance, MAKEINTRESOURCE(ID_KWIN),
			   HWND_DESKTOP, dlgproc, (LONG)name);
  assert(hwnd != NULL);

  if (hwnd == NULL)
    return 1;
  haccel = LoadAccelerators(hinstance, MAKEINTRESOURCE(IDA_KWIN));
  assert(hwnd != NULL);

  while (GetMessage(&msg, NULL, 0, 0)) {
    if (!TranslateAccelerator(hwnd, haccel, &msg) &&
	!IsDialogMessage(hwnd, &msg)) {
      TranslateMessage(&msg);
      DispatchMessage(&msg);
    }
  }

  DestroyWindow(hwnd);

#ifndef _WIN32
  FreeProcInstance((FARPROC)dlgproc);
#endif

  cns_save_registry();

  return 0;
}


#if 0

#define WM_ASYNC_COMPLETED (WM_USER + 1)
#define GETHOSTBYNAME_CLASS "krb_gethostbyname"
static HTASK htaskasync;	/* Asynchronos call in progress */
static BOOL iscompleted;	/* True when async call is completed */

/*
 * This routine is called to cancel a blocking hook call within
 * the Kerberos library.  The need for this routine arises due
 * to bugs which exist in existing WINSOCK implementations.  We
 * blocking gethostbyname with WSAASyncGetHostByName.  In order
 * to cancel such an operation, this routine must be called.
 * Applications may call this routine in addition to calls to
 * WSACancelBlockingCall to get any sucy Async calls canceled.
 * Return values are as they would be for WSACancelAsyncRequest.
 */
int
krb_cancel_blocking_call(void)
{
  if (htaskasync == NULL)
    return 0;
  iscompleted = TRUE;

  return WSACancelAsyncRequest(htask);
}


/*
 * Window proceedure for temporary Windows created in
 * krb_gethostbyname.  Fields completion messages.
 */
LRESULT CALLBACK
krb_gethostbyname_wnd_proc(HWND hwnd, UINT message,
			   WPARAM wParam, LPARAM lParam)
{
  if (message == WM_ASYNC_COMPLETED) {
    iscompleted = TRUE;
    return 0;
  }
  
  return DefWindowProc(hwnd, message, wParam, lParam);
}


/*
 * The WINSOCK routine gethostbyname has a bug in both FTP and NetManage
 * implementations which causes the blocking hook, if any, not to be
 * called.  This routine attempts to work around the problem by using
 * the async routines to emulate the functionality of the synchronous
 * routines
 */
struct hostent *PASCAL
krb_gethostbyname(
		  const char *name)
{
  HWND hwnd;
  char buf[MAXGETHOSTSTRUCT];
  BOOL FARPROC blockinghook;
  WNDCLASS wc;
  static BOOL isregistered;
  
  blockinghook = WSASetBlockingHook(NULL);
  WSASetBlockingHook(blockinghook);

  if (blockinghook == NULL)
    return gethostbyname(name);

  if (RegisterWndClass() == NULL)
    return gethostbyname(name);

  if (!isregistered) {
    wc.style = 0;
    wc.lpfnWndProc = gethostbyname_wnd_proc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = hlibinstance;
    wc.hIcon = NULL;
    wc.hCursor = NULL;
    wc.hbrBackground = NULL;
    wc.lpszMenuName  = NULL;
    wc.lpszClassName = GETHOSTBYNAME_CLASS;

    if (!RegisterClass(&wc))
      return gethostbyname(name);

    isregistered = TRUE;
  }

  hwnd = CreateWindow(GETHOSTBYNAME_CLASS, "", WS_OVERLAPPED,
		      -100, -100, 0, 0, HWND_DESKTOP, NULL, hlibinstance, NULL);
  if (hwnd == NULL)
    return gethostbyname(name);

  htaskasync =
    WSAAsyncGetHostByName(hwnd, WM_ASYNC_COMPLETED, name, buf, sizeof(buf));
  b = blockinghook(NULL);
}

#endif  /* if 0 */

#ifdef KRB5

/*
 * Function: destroys all tickets in a k5 ccache
 *
 * Returns: K5 error code (0 == success)
 */
krb5_error_code
k5_dest_tkt(void)
{
  krb5_error_code code;
  krb5_principal princ;

  if (code = krb5_cc_get_principal(k5_context, k5_ccache, &princ)) {
    com_err(NULL, code, "while retrieving principal name");
    return code;
  }

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

  krb5_free_principal(k5_context, princ);

  return code;
}

/*
 * 
 * k5_get_num_cred
 * 
 * Returns: number of creds in the credential cache, -1 on error
 * 
 */
int
k5_get_num_cred(int verbose)
{
  krb5_error_code code;
  krb5_cc_cursor cursor;
  krb5_creds c;
  int ncreds = 0;

  /* Turn off OPENCLOSE and leave open while we use ccache */
  if (code = krb5_cc_set_flags(k5_context, k5_ccache, 0)) {
    if (code == KRB5_FCC_NOFILE)
      return 0;
    if (verbose)
      com_err(NULL, code,
	      "while setting cache flags (ticket cache %s)",
	      krb5_cc_get_name(k5_context, k5_ccache));
    return -1;
  }

  if (code = krb5_cc_start_seq_get(k5_context, k5_ccache, &cursor)) {
    if (verbose)
      com_err(NULL, code, "while starting to retrieve tickets.");
    return -1;
  }

  while (1) {                                 /* Loop and get creds */
    code = krb5_cc_next_cred(k5_context, k5_ccache, &cursor, &c);
    if (code)
      break;
    ++ncreds;
  }

  if (code != KRB5_CC_END) {                  /* Error while looping??? */
    if (verbose)
      com_err(NULL, code, "while retrieving a ticket.");
    return -1;
  }

  if (code = krb5_cc_end_seq_get(k5_context, k5_ccache, &cursor)) {
    if (verbose)
      com_err(NULL, code, "while closing ccache.");
  } else if (code = krb5_cc_set_flags(k5_context, k5_ccache,
				      KRB5_TC_OPENCLOSE)) {
    if (verbose)
      com_err(NULL, code, "while closing ccache.");
  }

  return ncreds;
}

static int
k5_get_num_cred2()
{
  krb5_error_code code;
  krb5_cc_cursor cursor;
  krb5_creds c;
  int ncreds = 0;

  code = krb5_cc_start_seq_get(k5_context, k5_ccache, &cursor);
  if (code == KRB5_FCC_NOFILE)
    return 0;

  while (1) {
    code = krb5_cc_next_cred(k5_context, k5_ccache, &cursor, &c);
    if (code)
      break;
    ++ncreds;
  }

  if (code == KRB5_CC_END)
    krb5_cc_end_seq_get(k5_context, k5_ccache, &cursor);

  return ncreds;
}


/*
 * Function: Parses fullname into name and realm
 *
 * Parameters:
 *  name - buffer filled with name of user
 *  realm - buffer filled with realm of user
 *  fullname - string in form name.instance@realm
 *
 * Returns: 0
 */
int
k5_kname_parse(char *name, char *realm, char *fullname)
{
  char *ptr;                                  /* For parsing */

  ptr = strchr(fullname, '@');               /* Name, realm separator */

  if (ptr != NULL)                            /* Get realm */
    strcpy(realm, ptr + 1);
  else
    *realm = '\0';

  if (ptr != NULL) {                          /* Get the name */
    strncpy(name, fullname, ptr - fullname);
    name[ptr - fullname] = '\0';
  } else
    strcpy(name, fullname);

  ptr = strchr(name, '.');                   /* K4 compatability */
  if (ptr != NULL)
    *ptr = '\0';

  return 0;
}


/*
 * 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
 */
krb5_error_code
k5_init_ccache(krb5_ccache *ccache)
{
  krb5_error_code code;
  krb5_principal princ;
  FILE *fp;

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

  code = krb5_cc_get_principal(k5_context, *ccache, &princ);
  if (code == KRB5_FCC_NOFILE) {              /* Doesn't exist yet */
    fp = fopen(krb5_cc_get_name(k5_context, *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(k5_context, *ccache));
    code = krb5_cc_get_principal(k5_context, *ccache, &princ);
    if (code == KRB5_FCC_NOFILE)            /* Doesn't exist yet */
      return 0;
    if (code)
      return code;
  }

  /*  krb5_free_principal(k5_context, princ); */

  return 0;
}


/*
 * 
 * Function: Reads the name and realm out of the ccache.
 * 
 * Parameters:
 *  ccache - credentials cache to get info from
 * 
 *  name - buffer to hold user name
 * 
 *  realm - buffer to hold the realm
 * 
 * 
 * Returns: TRUE if read names, FALSE if not
 * 
 */
int
k5_name_from_ccache(krb5_ccache k5_ccache)
{
  krb5_error_code code;
  krb5_principal princ;
  char name[ANAME_SZ];
  char realm[REALM_SZ];
  char *defname;

  if (code = krb5_cc_get_principal(k5_context, k5_ccache, &princ))
    return FALSE;

  code = krb5_unparse_name(k5_context, princ, &defname);
  if (code) {
    return FALSE;
  }

  k5_kname_parse(name, realm, defname);       /* Extract the components */
  strcpy(cns_res.name, name);
  strcpy(cns_res.realm, realm);

  return TRUE;
}
#endif /* KRB5 */