dangling-comments-are-bad-20040504
[openafs.git] / src / WINNT / afsd / afskfw.c
1 /*
2  * Copyright (c) 2003 SkyRope, LLC
3  * All rights reserved.
4  * 
5  * Redistribution and use in source and binary forms, with or without 
6  * modification, are permitted provided that the following conditions are met:
7  * 
8  * - Redistributions of source code must retain the above copyright notice, 
9  *   this list of conditions and the following disclaimer.
10  * - Redistributions in binary form must reproduce the above copyright notice, 
11  *   this list of conditions and the following disclaimer in the documentation 
12  *   and/or other materials provided with the distribution.
13  * - Neither the name of Skyrope, LLC nor the names of its contributors may be 
14  *   used to endorse or promote products derived from this software without 
15  *   specific prior written permission from Skyrope, LLC.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
18  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
20  * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
21  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  *
29  * Portions of this code are derived from portions of the MIT
30  * Leash Ticket Manager and LoadFuncs utilities.  For these portions the
31  * following copyright applies.
32  *
33  * Copyright (c) 2003,2004 by the Massachusetts Institute of Technology.
34  * All rights reserved.
35  *
36  * Export of this software from the United States of America may
37  *   require a specific license from the United States Government.
38  *   It is the responsibility of any person or organization contemplating
39  *   export to obtain such a license before exporting.
40  *
41  * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
42  * distribute this software and its documentation for any purpose and
43  * without fee is hereby granted, provided that the above copyright
44  * notice appear in all copies and that both that copyright notice and
45  * this permission notice appear in supporting documentation, and that
46  * the name of M.I.T. not be used in advertising or publicity pertaining
47  * to distribution of the software without specific, written prior
48  * permission.  Furthermore if you modify this software you must label
49  * your software as modified software and not distribute it in such a
50  * fashion that it might be confused with the original M.I.T. software.
51  * M.I.T. makes no representations about the suitability of
52  * this software for any purpose.  It is provided "as is" without express
53  * or implied warranty.
54  *
55  */
56
57
58 #define USE_MS2MIT
59 #define USE_KRB4
60 #include "afskfw-int.h"
61 #include "afskfw.h"
62
63 #include <osilog.h>
64 #include <rxkad_prototypes.h>   /* for life_to_time */
65
66 /*
67  * TIMING _____________________________________________________________________
68  *
69  */
70
71 #define cminREMIND_TEST      1    // test every minute for expired creds
72 #define cminREMIND_WARN      15   // warn if creds expire in 15 minutes
73 #define cminRENEW            20   // renew creds when there are 20 minutes remaining
74 #define cminMINLIFE          30   // minimum life of Kerberos creds
75
76 #define c100ns1SECOND        (LONGLONG)10000000
77 #define cmsec1SECOND         1000
78 #define cmsec1MINUTE         60000
79 #define csec1MINUTE          60
80
81 /* Function Pointer Declarations for Delayed Loading */
82 // CCAPI
83 DECL_FUNC_PTR(cc_initialize);
84 DECL_FUNC_PTR(cc_shutdown);
85 DECL_FUNC_PTR(cc_get_NC_info);
86 DECL_FUNC_PTR(cc_free_NC_info);
87
88 // leash functions
89 DECL_FUNC_PTR(Leash_get_default_lifetime);
90 DECL_FUNC_PTR(Leash_get_default_forwardable);
91 DECL_FUNC_PTR(Leash_get_default_renew_till);
92 DECL_FUNC_PTR(Leash_get_default_noaddresses);
93 DECL_FUNC_PTR(Leash_get_default_proxiable);
94 DECL_FUNC_PTR(Leash_get_default_publicip);
95 DECL_FUNC_PTR(Leash_get_default_use_krb4);
96 DECL_FUNC_PTR(Leash_get_default_life_min);
97 DECL_FUNC_PTR(Leash_get_default_life_max);
98 DECL_FUNC_PTR(Leash_get_default_renew_min);
99 DECL_FUNC_PTR(Leash_get_default_renew_max);
100 DECL_FUNC_PTR(Leash_get_default_renewable);
101
102 // krb5 functions
103 DECL_FUNC_PTR(krb5_change_password);
104 DECL_FUNC_PTR(krb5_get_init_creds_opt_init);
105 DECL_FUNC_PTR(krb5_get_init_creds_opt_set_tkt_life);
106 DECL_FUNC_PTR(krb5_get_init_creds_opt_set_renew_life);
107 DECL_FUNC_PTR(krb5_get_init_creds_opt_set_forwardable);
108 DECL_FUNC_PTR(krb5_get_init_creds_opt_set_proxiable);
109 DECL_FUNC_PTR(krb5_get_init_creds_opt_set_address_list);
110 DECL_FUNC_PTR(krb5_get_init_creds_password);
111 DECL_FUNC_PTR(krb5_build_principal_ext);
112 DECL_FUNC_PTR(krb5_cc_get_name);
113 DECL_FUNC_PTR(krb5_cc_resolve);
114 DECL_FUNC_PTR(krb5_cc_default);
115 DECL_FUNC_PTR(krb5_cc_default_name);
116 DECL_FUNC_PTR(krb5_cc_set_default_name);
117 DECL_FUNC_PTR(krb5_cc_initialize);
118 DECL_FUNC_PTR(krb5_cc_destroy);
119 DECL_FUNC_PTR(krb5_cc_close);
120 DECL_FUNC_PTR(krb5_cc_store_cred);
121 DECL_FUNC_PTR(krb5_cc_copy_creds);
122 DECL_FUNC_PTR(krb5_cc_retrieve_cred);
123 DECL_FUNC_PTR(krb5_cc_get_principal);
124 DECL_FUNC_PTR(krb5_cc_start_seq_get);
125 DECL_FUNC_PTR(krb5_cc_next_cred);
126 DECL_FUNC_PTR(krb5_cc_end_seq_get);
127 DECL_FUNC_PTR(krb5_cc_remove_cred);
128 DECL_FUNC_PTR(krb5_cc_set_flags);
129 DECL_FUNC_PTR(krb5_cc_get_type);
130 DECL_FUNC_PTR(krb5_free_context);
131 DECL_FUNC_PTR(krb5_free_cred_contents);
132 DECL_FUNC_PTR(krb5_free_principal);
133 DECL_FUNC_PTR(krb5_get_in_tkt_with_password);
134 DECL_FUNC_PTR(krb5_init_context);
135 DECL_FUNC_PTR(krb5_parse_name);
136 DECL_FUNC_PTR(krb5_timeofday);
137 DECL_FUNC_PTR(krb5_timestamp_to_sfstring);
138 DECL_FUNC_PTR(krb5_unparse_name);
139 DECL_FUNC_PTR(krb5_get_credentials);
140 DECL_FUNC_PTR(krb5_mk_req);
141 DECL_FUNC_PTR(krb5_sname_to_principal);
142 DECL_FUNC_PTR(krb5_get_credentials_renew);
143 DECL_FUNC_PTR(krb5_free_data);
144 DECL_FUNC_PTR(krb5_free_data_contents);
145 DECL_FUNC_PTR(krb5_free_unparsed_name);
146 DECL_FUNC_PTR(krb5_os_localaddr);
147 DECL_FUNC_PTR(krb5_copy_keyblock_contents);
148 DECL_FUNC_PTR(krb5_copy_data);
149 DECL_FUNC_PTR(krb5_free_creds);
150 DECL_FUNC_PTR(krb5_build_principal);
151 DECL_FUNC_PTR(krb5_get_renewed_creds);
152 DECL_FUNC_PTR(krb5_get_default_config_files);
153 DECL_FUNC_PTR(krb5_free_config_files);
154 DECL_FUNC_PTR(krb5_get_default_realm);
155 DECL_FUNC_PTR(krb5_free_ticket);
156 DECL_FUNC_PTR(krb5_decode_ticket);
157 DECL_FUNC_PTR(krb5_get_host_realm);
158 DECL_FUNC_PTR(krb5_free_host_realm);
159 DECL_FUNC_PTR(krb5_free_addresses);
160 DECL_FUNC_PTR(krb5_c_random_make_octets);
161
162 // Krb524 functions
163 DECL_FUNC_PTR(krb524_init_ets);
164 DECL_FUNC_PTR(krb524_convert_creds_kdc);
165
166 // krb4 functions
167 DECL_FUNC_PTR(krb_get_cred);
168 DECL_FUNC_PTR(tkt_string);
169 DECL_FUNC_PTR(krb_get_tf_realm);
170 DECL_FUNC_PTR(krb_mk_req);
171
172 // ComErr functions
173 DECL_FUNC_PTR(com_err);
174 DECL_FUNC_PTR(error_message);
175
176 // Profile functions
177 DECL_FUNC_PTR(profile_init);
178 DECL_FUNC_PTR(profile_release);
179 DECL_FUNC_PTR(profile_get_subsection_names);
180 DECL_FUNC_PTR(profile_free_list);
181 DECL_FUNC_PTR(profile_get_string);
182 DECL_FUNC_PTR(profile_release_string);
183
184 // Service functions
185 DECL_FUNC_PTR(OpenSCManagerA);
186 DECL_FUNC_PTR(OpenServiceA);
187 DECL_FUNC_PTR(QueryServiceStatus);
188 DECL_FUNC_PTR(CloseServiceHandle);
189 #ifdef USE_MS2MIT
190 DECL_FUNC_PTR(LsaNtStatusToWinError);
191 #endif /* USE_MS2MIT */
192
193 #ifdef USE_MS2MIT
194 // LSA Functions
195 DECL_FUNC_PTR(LsaConnectUntrusted);
196 DECL_FUNC_PTR(LsaLookupAuthenticationPackage);
197 DECL_FUNC_PTR(LsaCallAuthenticationPackage);
198 DECL_FUNC_PTR(LsaFreeReturnBuffer);
199 DECL_FUNC_PTR(LsaGetLogonSessionData);
200 #endif /* USE_MS2MIT */
201
202 // AFS36 Token Functions
203 DECL_FUNC_PTR(ktc_ListTokens);
204 DECL_FUNC_PTR(ktc_GetToken);
205 DECL_FUNC_PTR(ktc_SetToken);
206 DECL_FUNC_PTR(ktc_ForgetAllTokens);
207
208 // AFS36 Config Functions
209 DECL_FUNC_PTR(cm_SearchCellFile);
210 DECL_FUNC_PTR(cm_GetRootCellName);
211
212 // CCAPI
213 FUNC_INFO ccapi_fi[] = {
214     MAKE_FUNC_INFO(cc_initialize),
215     MAKE_FUNC_INFO(cc_shutdown),
216     MAKE_FUNC_INFO(cc_get_NC_info),
217     MAKE_FUNC_INFO(cc_free_NC_info),
218     END_FUNC_INFO
219 };
220
221 FUNC_INFO leash_fi[] = {
222     MAKE_FUNC_INFO(Leash_get_default_lifetime),
223     MAKE_FUNC_INFO(Leash_get_default_renew_till),
224     MAKE_FUNC_INFO(Leash_get_default_forwardable),
225     MAKE_FUNC_INFO(Leash_get_default_noaddresses),
226     MAKE_FUNC_INFO(Leash_get_default_proxiable),
227     MAKE_FUNC_INFO(Leash_get_default_publicip),
228     MAKE_FUNC_INFO(Leash_get_default_use_krb4),
229     MAKE_FUNC_INFO(Leash_get_default_life_min),
230     MAKE_FUNC_INFO(Leash_get_default_life_max),
231     MAKE_FUNC_INFO(Leash_get_default_renew_min),
232     MAKE_FUNC_INFO(Leash_get_default_renew_max),
233     MAKE_FUNC_INFO(Leash_get_default_renewable),
234     END_FUNC_INFO
235 };
236
237 FUNC_INFO k5_fi[] = {
238     MAKE_FUNC_INFO(krb5_change_password),
239     MAKE_FUNC_INFO(krb5_get_init_creds_opt_init),
240     MAKE_FUNC_INFO(krb5_get_init_creds_opt_set_tkt_life),
241     MAKE_FUNC_INFO(krb5_get_init_creds_opt_set_renew_life),
242     MAKE_FUNC_INFO(krb5_get_init_creds_opt_set_forwardable),
243     MAKE_FUNC_INFO(krb5_get_init_creds_opt_set_proxiable),
244     MAKE_FUNC_INFO(krb5_get_init_creds_opt_set_address_list),
245     MAKE_FUNC_INFO(krb5_get_init_creds_password),
246     MAKE_FUNC_INFO(krb5_build_principal_ext),
247     MAKE_FUNC_INFO(krb5_cc_get_name),
248     MAKE_FUNC_INFO(krb5_cc_resolve),
249     MAKE_FUNC_INFO(krb5_cc_default),
250     MAKE_FUNC_INFO(krb5_cc_default_name),
251     MAKE_FUNC_INFO(krb5_cc_set_default_name),
252     MAKE_FUNC_INFO(krb5_cc_initialize),
253     MAKE_FUNC_INFO(krb5_cc_destroy),
254     MAKE_FUNC_INFO(krb5_cc_close),
255     MAKE_FUNC_INFO(krb5_cc_copy_creds),
256     MAKE_FUNC_INFO(krb5_cc_store_cred),
257     MAKE_FUNC_INFO(krb5_cc_retrieve_cred),
258     MAKE_FUNC_INFO(krb5_cc_get_principal),
259     MAKE_FUNC_INFO(krb5_cc_start_seq_get),
260     MAKE_FUNC_INFO(krb5_cc_next_cred),
261     MAKE_FUNC_INFO(krb5_cc_end_seq_get),
262     MAKE_FUNC_INFO(krb5_cc_remove_cred),
263     MAKE_FUNC_INFO(krb5_cc_set_flags),
264     MAKE_FUNC_INFO(krb5_cc_get_type),
265     MAKE_FUNC_INFO(krb5_free_context),
266     MAKE_FUNC_INFO(krb5_free_cred_contents),
267     MAKE_FUNC_INFO(krb5_free_principal),
268     MAKE_FUNC_INFO(krb5_get_in_tkt_with_password),
269     MAKE_FUNC_INFO(krb5_init_context),
270     MAKE_FUNC_INFO(krb5_parse_name),
271     MAKE_FUNC_INFO(krb5_timeofday),
272     MAKE_FUNC_INFO(krb5_timestamp_to_sfstring),
273     MAKE_FUNC_INFO(krb5_unparse_name),
274     MAKE_FUNC_INFO(krb5_get_credentials),
275     MAKE_FUNC_INFO(krb5_mk_req),
276     MAKE_FUNC_INFO(krb5_sname_to_principal),
277     MAKE_FUNC_INFO(krb5_get_credentials_renew),
278     MAKE_FUNC_INFO(krb5_free_data),
279     MAKE_FUNC_INFO(krb5_free_data_contents),
280     MAKE_FUNC_INFO(krb5_free_unparsed_name),
281     MAKE_FUNC_INFO(krb5_os_localaddr),
282     MAKE_FUNC_INFO(krb5_copy_keyblock_contents),
283     MAKE_FUNC_INFO(krb5_copy_data),
284     MAKE_FUNC_INFO(krb5_free_creds),
285     MAKE_FUNC_INFO(krb5_build_principal),
286     MAKE_FUNC_INFO(krb5_get_renewed_creds),
287     MAKE_FUNC_INFO(krb5_free_addresses),
288     MAKE_FUNC_INFO(krb5_get_default_config_files),
289     MAKE_FUNC_INFO(krb5_free_config_files),
290     MAKE_FUNC_INFO(krb5_get_default_realm),
291     MAKE_FUNC_INFO(krb5_free_ticket),
292     MAKE_FUNC_INFO(krb5_decode_ticket),
293     MAKE_FUNC_INFO(krb5_get_host_realm),
294     MAKE_FUNC_INFO(krb5_free_host_realm),
295     MAKE_FUNC_INFO(krb5_free_addresses),
296     MAKE_FUNC_INFO(krb5_c_random_make_octets),
297     END_FUNC_INFO
298 };
299
300 FUNC_INFO k4_fi[] = {
301     MAKE_FUNC_INFO(krb_get_cred),
302     MAKE_FUNC_INFO(krb_get_tf_realm),
303     MAKE_FUNC_INFO(krb_mk_req),
304     MAKE_FUNC_INFO(tkt_string),
305     END_FUNC_INFO
306 };
307
308 FUNC_INFO k524_fi[] = {
309     MAKE_FUNC_INFO(krb524_init_ets),
310     MAKE_FUNC_INFO(krb524_convert_creds_kdc),
311     END_FUNC_INFO
312 };
313
314 FUNC_INFO profile_fi[] = {
315         MAKE_FUNC_INFO(profile_init),
316         MAKE_FUNC_INFO(profile_release),
317         MAKE_FUNC_INFO(profile_get_subsection_names),
318         MAKE_FUNC_INFO(profile_free_list),
319         MAKE_FUNC_INFO(profile_get_string),
320         MAKE_FUNC_INFO(profile_release_string),
321         END_FUNC_INFO
322 };
323
324 FUNC_INFO ce_fi[] = {
325     MAKE_FUNC_INFO(com_err),
326     MAKE_FUNC_INFO(error_message),
327     END_FUNC_INFO
328 };
329
330 FUNC_INFO service_fi[] = {
331     MAKE_FUNC_INFO(OpenSCManagerA),
332     MAKE_FUNC_INFO(OpenServiceA),
333     MAKE_FUNC_INFO(QueryServiceStatus),
334     MAKE_FUNC_INFO(CloseServiceHandle),
335 #ifdef USE_MS2MIT
336     MAKE_FUNC_INFO(LsaNtStatusToWinError),
337 #endif /* USE_MS2MIT */
338     END_FUNC_INFO
339 };
340
341 #ifdef USE_MS2MIT
342 FUNC_INFO lsa_fi[] = {
343     MAKE_FUNC_INFO(LsaConnectUntrusted),
344     MAKE_FUNC_INFO(LsaLookupAuthenticationPackage),
345     MAKE_FUNC_INFO(LsaCallAuthenticationPackage),
346     MAKE_FUNC_INFO(LsaFreeReturnBuffer),
347     MAKE_FUNC_INFO(LsaGetLogonSessionData),
348     END_FUNC_INFO
349 };
350 #endif /* USE_MS2MIT */
351
352 FUNC_INFO afst_fi[] = {
353     MAKE_FUNC_INFO(ktc_ListTokens),
354     MAKE_FUNC_INFO(ktc_GetToken),
355     MAKE_FUNC_INFO(ktc_SetToken),
356     MAKE_FUNC_INFO(ktc_ForgetAllTokens),
357     END_FUNC_INFO
358 };
359
360 FUNC_INFO afsc_fi[] = {
361     MAKE_FUNC_INFO(cm_SearchCellFile),
362     MAKE_FUNC_INFO(cm_GetRootCellName),
363     END_FUNC_INFO
364 };
365
366 /* Static Prototypes */
367 char *afs_realm_of_cell(struct afsconf_cell *);
368 static long get_cellconfig_callback(void *, struct sockaddr_in *, char *);
369 int KFW_AFS_get_cellconfig(char *, struct afsconf_cell *, char *);
370 static krb5_error_code KRB5_CALLCONV KRB5_prompter( krb5_context context,
371            void *data, const char *name, const char *banner, int num_prompts,
372            krb5_prompt prompts[]);
373
374
375 /* Static Declarations */
376 static int                inited = 0;
377 static int                mid_cnt = 0;
378 static struct textField * mid_tb = NULL;
379 static HINSTANCE hKrb5 = 0;
380 static HINSTANCE hKrb4 = 0;
381 static HINSTANCE hKrb524 = 0;
382 #ifdef USE_MS2MIT
383 static HINSTANCE hSecur32 = 0;
384 #endif /* USE_MS2MIT */
385 static HINSTANCE hAdvApi32 = 0;
386 static HINSTANCE hAfsTokens = 0;
387 static HINSTANCE hAfsConf = 0;
388 static HINSTANCE hComErr = 0;
389 static HINSTANCE hService = 0;
390 static HINSTANCE hProfile = 0;
391 static HINSTANCE hLeash = 0;
392 static HINSTANCE hCCAPI = 0;
393 static struct principal_ccache_data * princ_cc_data = NULL;
394 static struct cell_principal_map    * cell_princ_map = NULL;
395
396 void
397 KFW_initialize(void)
398 {
399     static int inited = 0;
400
401     if ( !inited ) {
402         char mutexName[MAX_PATH];
403         HANDLE hMutex = NULL;
404
405         sprintf(mutexName, "AFS KFW Init pid=%d", getpid());
406         
407         hMutex = CreateMutex( NULL, TRUE, mutexName );
408         if ( GetLastError() == ERROR_ALREADY_EXISTS ) {
409             if ( WaitForSingleObject( hMutex, INFINITE ) != WAIT_OBJECT_0 ) {
410                 return;
411             }
412         }
413         if ( !inited ) {
414             inited = 1;
415             LoadFuncs(KRB5_DLL, k5_fi, &hKrb5, 0, 1, 0, 0);
416             LoadFuncs(KRB4_DLL, k4_fi, &hKrb4, 0, 1, 0, 0);
417             LoadFuncs(COMERR_DLL, ce_fi, &hComErr, 0, 0, 1, 0);
418             LoadFuncs(SERVICE_DLL, service_fi, &hService, 0, 1, 0, 0);
419 #ifdef USE_MS2MIT
420             LoadFuncs(SECUR32_DLL, lsa_fi, &hSecur32, 0, 1, 1, 1);
421 #endif /* USE_MS2MIT */
422             LoadFuncs(KRB524_DLL, k524_fi, &hKrb524, 0, 1, 1, 1);
423             LoadFuncs(PROFILE_DLL, profile_fi, &hProfile, 0, 1, 0, 0);
424             LoadFuncs(AFSTOKENS_DLL, afst_fi, &hAfsTokens, 0, 1, 0, 0);
425             LoadFuncs(AFSCONF_DLL, afsc_fi, &hAfsConf, 0, 1, 0, 0);
426             LoadFuncs(LEASH_DLL, leash_fi, &hLeash, 0, 1, 0, 0);
427             LoadFuncs(CCAPI_DLL, ccapi_fi, &hCCAPI, 0, 1, 0, 0);
428
429             if ( KFW_is_available() ) {
430                 char rootcell[MAXCELLCHARS+1];
431 #ifdef USE_MS2MIT
432                 KFW_import_windows_lsa();
433 #endif /* USE_MS2MIT */
434                 KFW_import_ccache_data();
435                 KFW_AFS_renew_expiring_tokens();
436
437                 /* WIN32 NOTE: no way to get max chars */
438                 if (!pcm_GetRootCellName(rootcell))
439                     KFW_AFS_renew_token_for_cell(rootcell);
440             }
441         }
442         ReleaseMutex(hMutex);
443         CloseHandle(hMutex);
444     }
445 }
446
447 void
448 KFW_cleanup(void)
449 {
450     if (hKrb5)
451         FreeLibrary(hKrb5);
452     if (hKrb4)
453         FreeLibrary(hKrb4);
454     if (hProfile)
455         FreeLibrary(hProfile);
456     if (hAfsTokens)
457         FreeLibrary(hAfsTokens);
458     if (hAfsConf)
459         FreeLibrary(hAfsConf);
460     if (hComErr)
461         FreeLibrary(hComErr);
462     if (hService)
463         FreeLibrary(hService);
464 #ifdef USE_MS2MIT
465     if (hSecur32)
466         FreeLibrary(hSecur32);
467 #endif /* USE_MS2MIT */
468     if (hKrb524)
469         FreeLibrary(hKrb524);
470     if (hLeash)
471         FreeLibrary(hLeash);
472     if (hCCAPI)
473         FreeLibrary(hCCAPI);
474 }
475
476 static char OpenAFSConfigKeyName[] = "SOFTWARE\\OpenAFS\\Client";
477
478 int 
479 KFW_is_available(void)
480 {
481     HKEY parmKey;
482         DWORD code, len;
483     DWORD enableKFW = 1;
484
485     code = RegOpenKeyEx(HKEY_CURRENT_USER, OpenAFSConfigKeyName,
486                          0, KEY_QUERY_VALUE, &parmKey);
487     if (code != ERROR_SUCCESS)
488         code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, OpenAFSConfigKeyName,
489                              0, KEY_QUERY_VALUE, &parmKey);
490         if (code == ERROR_SUCCESS) {
491         len = sizeof(enableKFW);
492         code = RegQueryValueEx(parmKey, "EnableKFW", NULL, NULL,
493                                 (BYTE *) &enableKFW, &len);
494         if (code != ERROR_SUCCESS) {
495             enableKFW = 1;
496         }
497         RegCloseKey (parmKey);
498         }
499
500     if ( !enableKFW )
501         return FALSE;
502
503     KFW_initialize();
504     if ( hKrb5 && hComErr && hService && 
505 #ifdef USE_MS2MIT
506          hSecur32 && 
507 #endif /* USE_MS2MIT */
508          hKrb524 &&
509          hProfile && hAfsTokens && hAfsConf && hLeash && hCCAPI )
510         return TRUE;
511     return FALSE;
512 }
513
514 int 
515 KRB5_error(krb5_error_code rc, LPCSTR FailedFunctionName, 
516                  int FreeContextFlag, krb5_context * ctx, 
517                  krb5_ccache * cache)
518 {
519     char message[256];
520     const char *errText;
521     int krb5Error = ((int)(rc & 255));  
522     
523     /*
524     switch (krb5Error)
525     {
526         // Wrong password
527         case 31:
528         case 8:
529             return;
530     }
531     */
532         
533     errText = perror_message(rc);   
534     _snprintf(message, sizeof(message), 
535               "%s\n(Kerberos error %ld)\n\n%s failed", 
536               errText, 
537               krb5Error, 
538               FailedFunctionName);
539
540     if ( IsDebuggerPresent() )
541         OutputDebugString(message);
542
543     MessageBox(NULL, message, "Kerberos Five", MB_OK | MB_ICONERROR | 
544                MB_TASKMODAL | 
545                MB_SETFOREGROUND);
546     if (FreeContextFlag == 1)
547     {
548         if (ctx && *ctx != NULL)
549         {
550             if (cache && *cache != NULL) {
551                 pkrb5_cc_close(*ctx, *cache);
552                                 *cache = NULL;
553                         }
554         
555             pkrb5_free_context(*ctx);
556                         *ctx = NULL;
557         }
558     }
559
560     return rc;
561 }
562
563 void
564 KFW_AFS_update_princ_ccache_data(krb5_context ctx, krb5_ccache cc, int lsa)
565 {
566     struct principal_ccache_data * next = princ_cc_data;
567     krb5_principal principal = 0;
568     char * pname = NULL;
569     const char * ccname = NULL;
570     krb5_error_code code = 0;
571     krb5_error_code cc_code = 0;
572     krb5_cc_cursor cur;
573     krb5_creds creds;
574     krb5_flags flags=0;
575     krb5_timestamp now;
576
577     if (ctx == 0 || cc == 0)
578         return;
579
580     code = pkrb5_cc_get_principal(ctx, cc, &principal);
581     if ( code ) return;
582
583     code = pkrb5_unparse_name(ctx, principal, &pname);
584     if ( code ) goto cleanup;
585
586     ccname = pkrb5_cc_get_name(ctx, cc);
587     if (!ccname) goto cleanup;
588
589     // Search the existing list to see if we have a match 
590     if ( next ) {
591         for ( ; next ; next = next->next ) {
592             if ( !strcmp(next->principal,pname) && !strcmp(next->ccache_name, ccname) )
593                 break;
594         }
595     } 
596
597     // If not, match add a new node to the beginning of the list and assign init it
598     if ( !next ) {
599         next = (struct principal_ccache_data *) malloc(sizeof(struct principal_ccache_data));
600         next->next = princ_cc_data;
601         princ_cc_data = next;
602         next->principal = _strdup(pname);
603         next->ccache_name = _strdup(ccname);
604         next->from_lsa = lsa;
605         next->expired = 1;
606         next->expiration_time = 0;
607         next->renew = 0;
608     }
609
610     flags = 0;  // turn off OPENCLOSE mode
611     code = pkrb5_cc_set_flags(ctx, cc, flags);
612     if ( code ) goto cleanup;
613
614     code = pkrb5_timeofday(ctx, &now);
615
616     cc_code = pkrb5_cc_start_seq_get(ctx, cc, &cur);
617
618     while (!(cc_code = pkrb5_cc_next_cred(ctx, cc, &cur, &creds))) {
619         if ( creds.ticket_flags & TKT_FLG_INITIAL ) {
620             int valid;
621             // we found the ticket we are looking for
622             // check validity of timestamp 
623             // We add a 5 minutes fudge factor to compensate for potential
624             // clock skew errors between the KDC and client OS
625
626             valid = ((creds.times.starttime > 0) &&
627                      now >= (creds.times.starttime - 300) &&
628                      now < (creds.times.endtime + 300) &&
629                      !(creds.ticket_flags & TKT_FLG_INVALID));
630
631             if ( next->from_lsa) {
632                 next->expired = 0;
633                 next->expiration_time = creds.times.endtime;
634                 next->renew = 1;
635             } else if ( valid ) {
636                 next->expired = 0;
637                 next->expiration_time = creds.times.endtime;
638                 next->renew = (creds.times.renew_till > creds.times.endtime) && 
639                                (creds.ticket_flags & TKT_FLG_RENEWABLE);
640             } else {
641                 next->expired = 1;
642                 next->expiration_time = 0;
643                 next->renew = 0;
644             }
645
646             pkrb5_free_cred_contents(ctx, &creds);
647             cc_code = KRB5_CC_END;
648             break;
649         }
650         pkrb5_free_cred_contents(ctx, &creds);
651     }
652
653     if (cc_code == KRB5_CC_END) {
654         code = pkrb5_cc_end_seq_get(ctx, cc, &cur);
655         if (code) goto cleanup;
656     }
657
658   cleanup:
659     flags = KRB5_TC_OPENCLOSE;  //turn on OPENCLOSE
660     code = pkrb5_cc_set_flags(ctx, cc, flags);
661
662     if ( pname )
663         pkrb5_free_unparsed_name(ctx,pname);
664     if ( principal )
665         pkrb5_free_principal(ctx,principal);
666 }   
667
668 int
669 KFW_AFS_find_ccache_for_principal(krb5_context ctx, char * principal, char **ccache, int valid_only)
670 {
671     struct principal_ccache_data * next = princ_cc_data;
672     char * response = NULL;
673
674     if ( !principal || !ccache )
675         return 0;
676
677     while ( next ) {
678         if ( (!valid_only || !next->expired) && !strcmp(next->principal,principal) ) {
679             if (response) {
680                 // we always want to prefer the MS Kerberos LSA cache or
681                 // the cache afscreds created specifically for the principal
682                 // if the current entry is either one, drop the previous find
683                 if ( next->from_lsa || !strcmp(next->ccache_name,principal) )
684                     free(response);
685             }
686             response = _strdup(next->ccache_name);
687             // MS Kerberos LSA is our best option so use it and quit
688             if ( next->from_lsa )   
689                 break;
690         }
691         next = next->next;
692     }
693
694     if ( response ) {
695         *ccache = response;
696         return 1;
697     }
698     return 0;
699 }
700
701 void 
702 KFW_AFS_delete_princ_ccache_data(krb5_context ctx, char * pname, char * ccname)
703 {
704     struct principal_ccache_data ** next = &princ_cc_data;
705
706     if ( !pname && !ccname )
707         return;
708
709     while ( (*next) ) {
710         if ( !strcmp((*next)->principal,pname) || 
711              !strcmp((*next)->ccache_name,ccname) ) {
712             void * temp;
713             free((*next)->principal);
714             free((*next)->ccache_name);
715             temp = (*next);
716             (*next) = (*next)->next;
717             free(temp);
718         }
719     }
720 }
721
722 void 
723 KFW_AFS_update_cell_princ_map(krb5_context ctx, char * cell, char *pname, int active)
724 {
725     struct cell_principal_map * next = cell_princ_map;
726
727     // Search the existing list to see if we have a match 
728     if ( next ) {
729         for ( ; next ; next = next->next ) {
730             if ( !strcmp(next->cell, cell) ) {
731                 if ( !strcmp(next->principal,pname) ) {
732                     next->active = active;
733                                         break;
734                 } else {
735                     // OpenAFS currently has a restriction of one active token per cell
736                     // Therefore, whenever we update the table with a new active cell we
737                     // must mark all of the other principal to cell entries as inactive.
738                     if (active)
739                         next->active = 0;
740                 }
741             }
742         }
743     } 
744
745     // If not, match add a new node to the beginning of the list and assign init it
746     if ( !next ) {
747         next = (struct cell_principal_map *) malloc(sizeof(struct cell_principal_map));
748         next->next = cell_princ_map;
749         cell_princ_map = next;
750         next->principal = _strdup(pname);
751         next->cell = _strdup(cell);
752         next->active = active;
753     }
754 }
755
756 void 
757 KFW_AFS_delete_cell_princ_maps(krb5_context ctx, char * pname, char * cell)
758 {
759     struct cell_principal_map ** next = &cell_princ_map;
760
761     if ( !pname && !cell )
762         return;
763
764     while ( (*next) ) {
765         if ( !strcmp((*next)->principal,pname) || 
766              !strcmp((*next)->cell,cell) ) {
767             void * temp;
768             free((*next)->principal);
769             free((*next)->cell);
770             temp = (*next);
771             (*next) = (*next)->next;
772             free(temp);
773         }
774     }
775 }
776
777 // Returns (if possible) a principal which has been known in 
778 // the past to have been used to obtain tokens for the specified
779 // cell.  
780 // TODO: Attempt to return one which has not yet expired by checking
781 // the principal/ccache data
782 int
783 KFW_AFS_find_principals_for_cell(krb5_context ctx, char * cell, char **principals[], int active_only)
784 {
785     struct cell_principal_map * next_map = cell_princ_map;
786     const char * princ = NULL;
787     int count = 0, i;
788
789     if ( !cell )
790         return 0;
791
792     while ( next_map ) {
793         if ( (!active_only || next_map->active) && !strcmp(next_map->cell,cell) ) {
794             count++;
795         }
796         next_map = next_map->next;
797     }
798
799     if ( !principals || !count )
800         return count;
801
802     *principals = (char **) malloc(sizeof(char *) * count);
803     for ( next_map = cell_princ_map, i=0 ; next_map && i<count; next_map = next_map->next )
804     {
805         if ( (!active_only || next_map->active) && !strcmp(next_map->cell,cell) ) {
806             (*principals)[i++] = _strdup(next_map->principal);
807         }
808     }
809     return count;
810 }
811
812 int
813 KFW_AFS_find_cells_for_princ(krb5_context ctx, char * pname, char **cells[], int active_only)
814 {
815     int     count = 0, i;
816     struct cell_principal_map * next_map = cell_princ_map;
817     const char * princ = NULL;
818     
819     if ( !pname )
820         return 0;
821
822     while ( next_map ) {
823         if ( (!active_only || next_map->active) && !strcmp(next_map->principal,pname) ) {
824             count++;
825         }
826         next_map = next_map->next;
827     }
828
829     if ( !cells )
830         return count;
831
832     *cells = (char **) malloc(sizeof(char *) * count);
833     for ( next_map = cell_princ_map, i=0 ; next_map && i<count; next_map = next_map->next )
834     {
835         if ( (!active_only || next_map->active) && !strcmp(next_map->principal,pname) ) {
836             (*cells)[i++] = _strdup(next_map->cell);
837         }
838     }
839     return count;
840 }
841
842 /* Given a principal return an existing ccache or create one and return */
843 int
844 KFW_get_ccache(krb5_context alt_ctx, krb5_principal principal, krb5_ccache * cc)
845 {
846     krb5_context ctx;
847     char * pname = 0;
848     char * ccname = 0;
849     krb5_error_code code;
850
851     if (!pkrb5_init_context)
852         return 0;
853
854     if ( alt_ctx ) {
855         ctx = alt_ctx;
856     } else {
857         code = pkrb5_init_context(&ctx);
858         if (code) goto cleanup;
859     }
860
861     if ( principal ) {
862         code = pkrb5_unparse_name(ctx, principal, &pname);
863         if (code) goto cleanup;
864
865         if ( !KFW_AFS_find_ccache_for_principal(ctx,pname,&ccname,TRUE) &&
866              !KFW_AFS_find_ccache_for_principal(ctx,pname,&ccname,FALSE)) {
867             ccname = (char *)malloc(strlen(pname) + 5);
868             sprintf(ccname,"API:%s",pname);
869         }
870         code = pkrb5_cc_resolve(ctx, ccname, cc);
871     } else {
872         code = pkrb5_cc_default(ctx, cc);
873         if (code) goto cleanup;
874     }
875
876   cleanup:
877     if (ccname)
878         free(ccname);
879     if (pname)
880         pkrb5_free_unparsed_name(ctx,pname);
881     if (ctx && (ctx != alt_ctx))
882         pkrb5_free_context(ctx);
883     return(code);
884 }
885
886 #ifdef USE_MS2MIT
887 // Import Microsoft Credentials into a new MIT ccache
888 void
889 KFW_import_windows_lsa(void)
890 {
891     krb5_context ctx = 0;
892     krb5_ccache  cc = 0;
893     krb5_principal princ = 0;
894     char * pname = NULL;
895     krb5_data *  realm;
896     krb5_error_code code;
897     char cell[128]="";
898     int i;
899          
900     if (!pkrb5_init_context)
901         return;
902
903 #ifdef COMMENT
904     if ( !MSLSA_IsKerberosLogon() )
905         return;
906 #endif
907
908     code = pkrb5_init_context(&ctx);
909     if (code) goto cleanup;
910
911     code = pkrb5_cc_resolve(ctx, LSA_CCNAME, &cc);
912     if (code) goto cleanup;
913
914     KFW_AFS_update_princ_ccache_data(ctx, cc, TRUE);
915
916     code = pkrb5_cc_get_principal(ctx, cc, &princ);
917     if ( code ) goto cleanup;
918
919     code = pkrb5_unparse_name(ctx,princ,&pname);
920     if ( code ) goto cleanup;
921
922     realm = krb5_princ_realm(ctx, princ);
923     for ( i=0; i<realm->length; i++ ) {
924         cell[i] = tolower(realm->data[i]);
925     }
926         cell[i] = '\0';
927
928     code = KFW_AFS_klog(ctx, cc, "afs", cell, realm->data, pLeash_get_default_lifetime(),NULL);
929     if ( IsDebuggerPresent() ) {
930         char message[256];
931         sprintf(message,"KFW_AFS_klog() returns: %d\n",code);
932         OutputDebugString(message);
933     }
934     if ( code ) goto cleanup;
935
936     KFW_AFS_update_cell_princ_map(ctx, cell, pname, TRUE);
937
938   cleanup:
939     if (pname)
940         pkrb5_free_unparsed_name(ctx,pname);
941     if (princ)
942         pkrb5_free_principal(ctx,princ);
943     if (cc)
944         pkrb5_cc_close(ctx,cc);
945     if (ctx)
946         pkrb5_free_context(ctx);
947 }
948 #endif /* USE_MS2MIT */
949
950 // If there are existing MIT credentials, copy them to a new
951 // ccache named after the principal
952
953 // Enumerate all existing MIT ccaches and construct entries
954 // in the principal_ccache table
955
956 // Enumerate all existing AFS Tokens and construct entries
957 // in the cell_principal table
958 void
959 KFW_import_ccache_data(void)
960 {
961     krb5_context ctx = 0;
962     krb5_ccache  cc = 0;
963     krb5_principal principal = 0;
964     krb5_creds creds;
965     krb5_error_code code;
966     krb5_error_code cc_code;
967     krb5_cc_cursor cur;
968     apiCB * cc_ctx = 0;
969     struct _infoNC ** pNCi = NULL;
970     int i, j, flags;
971
972     if ( !pcc_initialize )
973         return;
974
975     if ( IsDebuggerPresent() )
976         OutputDebugString("KFW_import_ccache_data()\n");
977
978     code = pcc_initialize(&cc_ctx, CC_API_VER_2, NULL, NULL);
979     if (code) goto cleanup;
980
981     code = pcc_get_NC_info(cc_ctx, &pNCi);
982     if (code) goto cleanup;
983
984     code = pkrb5_init_context(&ctx);
985     if (code) goto cleanup;
986
987     for ( i=0; pNCi[i]; i++ ) {
988         if ( pNCi[i]->vers != CC_CRED_V5 )
989             continue;
990         if ( IsDebuggerPresent() ) {
991             OutputDebugString("Principal: ");
992             OutputDebugString(pNCi[i]->principal);
993             OutputDebugString(" in ccache ");
994             OutputDebugString(pNCi[i]->name);
995             OutputDebugString("\n");
996         }
997         if ( strcmp(pNCi[i]->name,pNCi[i]->principal)
998              && strcmp(pNCi[i]->name,LSA_CCNAME) 
999              ) {
1000             int found = 0;
1001             for ( j=0; pNCi[j]; j++ ) {
1002                 if (!strcmp(pNCi[j]->name,pNCi[i]->principal)) {
1003                     found = 1;
1004                     break;
1005                 }
1006             }
1007             
1008             code = pkrb5_cc_resolve(ctx, pNCi[i]->principal, &cc);
1009             if (code) goto loop_cleanup;
1010
1011             if (!found) {
1012                 krb5_ccache oldcc = 0;
1013
1014                 if ( IsDebuggerPresent() )
1015                     OutputDebugString("copying ccache data to new ccache\n");
1016
1017                 code = pkrb5_parse_name(ctx, pNCi[i]->principal, &principal);
1018                 if (code) goto loop_cleanup;
1019                 code = pkrb5_cc_initialize(ctx, cc, principal);
1020                 if (code) goto loop_cleanup;
1021
1022                 code = pkrb5_cc_resolve(ctx, pNCi[i]->name, &oldcc);
1023                 if (code) goto loop_cleanup;
1024                 code = pkrb5_cc_copy_creds(ctx,oldcc,cc);
1025                 if (code) {
1026                     code = pkrb5_cc_close(ctx,cc);
1027                     cc = 0;
1028                     code = pkrb5_cc_close(ctx,oldcc);
1029                     cc = 0;
1030                     KRB5_error(code, "krb5_cc_copy_creds", 0, NULL, NULL);
1031                     continue;
1032                 }
1033                 code = pkrb5_cc_close(ctx,oldcc);
1034             }
1035         } else {
1036             code = pkrb5_cc_resolve(ctx, pNCi[i]->name, &cc);
1037             if (code) goto loop_cleanup;
1038         }
1039
1040         flags = 0;  // turn off OPENCLOSE mode
1041         code = pkrb5_cc_set_flags(ctx, cc, flags);
1042         if ( code ) goto cleanup;
1043
1044         KFW_AFS_update_princ_ccache_data(ctx, cc, !strcmp(pNCi[i]->name,LSA_CCNAME));
1045
1046         cc_code = pkrb5_cc_start_seq_get(ctx, cc, &cur);
1047
1048         while (!(cc_code = pkrb5_cc_next_cred(ctx, cc, &cur, &creds))) {
1049             krb5_data * sname = krb5_princ_name(ctx, creds.server);
1050             krb5_data * cell  = krb5_princ_component(ctx, creds.server, 1);
1051             krb5_data * realm = krb5_princ_realm(ctx, creds.server);
1052             if ( sname && cell && !strcmp("afs",sname->data) ) {
1053                 struct ktc_principal    aserver;
1054                 struct ktc_principal    aclient;
1055                 struct ktc_token        atoken;
1056                 int active = TRUE;
1057
1058                 if ( IsDebuggerPresent() )  {
1059                     OutputDebugString("Found AFS ticket: ");
1060                     OutputDebugString(sname->data);
1061                     if ( cell->data ) {
1062                         OutputDebugString("/");
1063                         OutputDebugString(cell->data);
1064                     }
1065                     OutputDebugString("@");
1066                     OutputDebugString(realm->data);
1067                     OutputDebugString("\n");
1068                 }
1069
1070                 memset(&aserver, '\0', sizeof(aserver));
1071                 strcpy(aserver.name, sname->data);
1072                 strcpy(aserver.cell, cell->data);
1073
1074                 code = pktc_GetToken(&aserver, &atoken, sizeof(atoken), &aclient);
1075                 if (!code) {
1076                     // Found a token in AFS Client Server which matches
1077                     char pname[128], *p, *q;
1078                     for ( p=pname, q=aclient.name; *q; p++, q++)
1079                         *p = *q;
1080                     for ( *p++ = '@', q=aclient.cell; *q; p++, q++)
1081                         *p = toupper(*q);
1082                     *p = '\0';
1083
1084                     if ( IsDebuggerPresent() )  {
1085                         OutputDebugString("Found AFS token: ");
1086                         OutputDebugString(pname);
1087                         OutputDebugString("\n");
1088                     }
1089
1090                     if ( strcmp(pname,pNCi[i]->principal)  )
1091                         active = FALSE;
1092                     KFW_AFS_update_cell_princ_map(ctx, cell->data, pNCi[i]->principal, active);
1093                 } else {
1094                     // Attempt to import it
1095                     KFW_AFS_update_cell_princ_map(ctx, cell->data, pNCi[i]->principal, active);
1096
1097                     if ( IsDebuggerPresent() )  {
1098                         OutputDebugString("Calling KFW_AFS_klog() to obtain token\n");
1099                     }
1100
1101                     code = KFW_AFS_klog(ctx, cc, "afs", cell->data, realm->data, pLeash_get_default_lifetime(),NULL);
1102                     if ( IsDebuggerPresent() ) {
1103                         char message[256];
1104                         sprintf(message,"KFW_AFS_klog() returns: %d\n",code);
1105                         OutputDebugString(message);
1106                     }
1107                 }
1108             } else if ( IsDebuggerPresent() ) {
1109                 OutputDebugString("Found ticket: ");
1110                 OutputDebugString(sname->data);
1111                 if ( cell && cell->data ) {
1112                     OutputDebugString("/");
1113                     OutputDebugString(cell->data);
1114                 }
1115                 OutputDebugString("@");
1116                 OutputDebugString(realm->data);
1117                 OutputDebugString("\n");
1118             }
1119             pkrb5_free_cred_contents(ctx, &creds);
1120         }
1121
1122         if (cc_code == KRB5_CC_END) {
1123             cc_code = pkrb5_cc_end_seq_get(ctx, cc, &cur);
1124             if (cc_code) goto loop_cleanup;
1125         }
1126
1127       loop_cleanup:
1128         flags = KRB5_TC_OPENCLOSE;  //turn on OPENCLOSE
1129         code = pkrb5_cc_set_flags(ctx, cc, flags);
1130         if (cc) {
1131             pkrb5_cc_close(ctx,cc);
1132             cc = 0;
1133         }
1134         if (principal) {
1135             pkrb5_free_principal(ctx,principal);
1136             principal = 0;
1137         }
1138     }
1139
1140   cleanup:
1141     if (ctx)
1142         pkrb5_free_context(ctx);
1143     if (pNCi)
1144         pcc_free_NC_info(cc_ctx, &pNCi);
1145     if (cc_ctx)
1146         pcc_shutdown(&cc_ctx);
1147 }
1148
1149
1150 int
1151 KFW_AFS_get_cred(char * username, 
1152                   char * instance, 
1153                   char * cell,
1154                   char * password,
1155                   int lifetime,
1156                   char * smbname,
1157                   char ** reasonP )
1158 {
1159     krb5_context ctx = 0;
1160     krb5_ccache cc = 0;
1161     char * realm = 0;
1162     char ** realmlist = 0;
1163     krb5_principal principal = 0;
1164     char * pname = 0;
1165     krb5_error_code code;
1166         char local_cell[MAXCELLCHARS+1];
1167     char **cells = NULL;
1168     int  cell_count=0;
1169     struct afsconf_cell cellconfig;
1170
1171     if (!pkrb5_init_context)
1172         return 0;
1173
1174     if ( IsDebuggerPresent() ) {
1175         OutputDebugString("KFW_AFS_get_cred for token ");
1176         OutputDebugString(username);
1177         if ( instance ) {
1178             OutputDebugString("/");
1179             OutputDebugString(instance);
1180         }
1181         OutputDebugString("@");
1182         OutputDebugString(cell);
1183         OutputDebugString("\n");
1184     }
1185
1186     code = pkrb5_init_context(&ctx);
1187     if ( code ) goto cleanup;
1188
1189     code = KFW_AFS_get_cellconfig( cell, (void*)&cellconfig, local_cell);
1190     if ( code ) goto cleanup;
1191
1192     realm = strchr(username,'@');
1193     if (realm) {
1194         *realm = '\0';
1195         realm++;
1196     }
1197     if ( !realm || !realm[0] )
1198         realm = afs_realm_of_cell(&cellconfig);  // do not free
1199
1200     if ( IsDebuggerPresent() ) {
1201         OutputDebugString("Realm: ");
1202         OutputDebugString(realm);
1203         OutputDebugString("\n");
1204     }
1205
1206     code = pkrb5_build_principal(ctx, &principal, strlen(realm),
1207                                  realm, username, 
1208                                  (instance && instance[0]) ? instance : NULL, 
1209                                  NULL);
1210
1211     code = KFW_get_ccache(ctx, principal, &cc);
1212     if ( code ) goto cleanup;
1213
1214     code = pkrb5_unparse_name(ctx, principal, &pname);
1215     if ( code ) goto cleanup;
1216
1217     if ( lifetime == 0 )
1218         lifetime = pLeash_get_default_lifetime();
1219
1220     code = KFW_kinit(ctx, cc, HWND_DESKTOP, 
1221                       pname, 
1222                       password,
1223                       lifetime,
1224                       pLeash_get_default_forwardable(),
1225                       pLeash_get_default_proxiable(),
1226                       pLeash_get_default_renewable() ? pLeash_get_default_renew_till() : 0,
1227                       pLeash_get_default_noaddresses(),
1228                       pLeash_get_default_publicip());
1229     if ( IsDebuggerPresent() ) {
1230         char message[256];
1231         sprintf(message,"KFW_kinit() returns: %d\n",code);
1232         OutputDebugString(message);
1233     }
1234     if ( code ) goto cleanup;
1235                    
1236     KFW_AFS_update_princ_ccache_data(ctx, cc, FALSE);
1237
1238     code = KFW_AFS_klog(ctx, cc, "afs", cell, realm, lifetime,smbname);
1239     if ( IsDebuggerPresent() ) {
1240         char message[256];
1241         sprintf(message,"KFW_AFS_klog() returns: %d\n",code);
1242         OutputDebugString(message);
1243     }
1244     if ( code ) goto cleanup;
1245
1246     KFW_AFS_update_cell_princ_map(ctx, cell, pname, TRUE);
1247
1248     // Attempt to obtain new tokens for other cells supported by the same 
1249     // principal
1250     cell_count = KFW_AFS_find_cells_for_princ(ctx, pname, &cells, TRUE);
1251     if ( cell_count > 1 ) {
1252         while ( cell_count-- ) {
1253             if ( strcmp(cells[cell_count],cell) ) {
1254                 if ( IsDebuggerPresent() ) {
1255                     char message[256];
1256                     sprintf(message,"found another cell for the same principal: %s\n",cell);
1257                     OutputDebugString(message);
1258                 }
1259                 code = KFW_AFS_get_cellconfig( cells[cell_count], (void*)&cellconfig, local_cell);
1260                 if ( code ) continue;
1261     
1262                 realm = afs_realm_of_cell(&cellconfig);  // do not free
1263                 if ( IsDebuggerPresent() ) {
1264                     OutputDebugString("Realm: ");
1265                     OutputDebugString(realm);
1266                     OutputDebugString("\n");
1267                 }
1268                 
1269                 code = KFW_AFS_klog(ctx, cc, "afs", cells[cell_count], realm, lifetime,smbname);
1270                 if ( IsDebuggerPresent() ) {
1271                     char message[256];
1272                     sprintf(message,"KFW_AFS_klog() returns: %d\n",code);
1273                     OutputDebugString(message);
1274                 }
1275             }
1276             free(cells[cell_count]);
1277         }
1278         free(cells);
1279     } else if ( cell_count == 1 ) {
1280         free(cells[0]);
1281         free(cells);
1282     }
1283
1284   cleanup:
1285     if ( pname )
1286         pkrb5_free_unparsed_name(ctx,pname);
1287     if ( cc )
1288         pkrb5_cc_close(ctx, cc);
1289
1290     if ( code && reasonP ) {
1291         *reasonP = (char *)perror_message(code);
1292     }
1293     return(code);
1294 }
1295
1296 int 
1297 KFW_AFS_destroy_tickets_for_cell(char * cell)
1298 {
1299     krb5_context                ctx = 0;
1300     krb5_error_code             code;
1301     int count;
1302     char ** principals = NULL;
1303
1304     if (!pkrb5_init_context)
1305         return 0;
1306
1307     if ( IsDebuggerPresent() ) {
1308         OutputDebugString("KFW_AFS_destroy_ticets_for_cell: ");
1309         OutputDebugString(cell);
1310         OutputDebugString("\n");
1311     }
1312
1313     code = pkrb5_init_context(&ctx);
1314     if (code) ctx = 0;
1315
1316     count = KFW_AFS_find_principals_for_cell(ctx, cell, &principals, FALSE);
1317     if ( count > 0 ) {
1318         krb5_principal      princ = 0;
1319         krb5_ccache                     cc  = 0;
1320
1321         while ( count-- ) {
1322             int cell_count = KFW_AFS_find_cells_for_princ(ctx, principals[count], NULL, TRUE);
1323             if ( cell_count > 1 ) {
1324                 // TODO - What we really should do here is verify whether or not any of the
1325                 // other cells which use this principal to obtain its credentials actually
1326                 // have valid tokens or not.  If they are currently using these credentials
1327                 // we will skip them.  For the time being we assume that if there is an active
1328                 // map in the table that they are actively being used.
1329                 goto loop_cleanup;
1330             }
1331
1332             code = pkrb5_parse_name(ctx, principals[count], &princ);
1333             if (code) goto loop_cleanup;
1334
1335             code = KFW_get_ccache(ctx, princ, &cc);
1336             if (code) goto loop_cleanup;
1337
1338             code = pkrb5_cc_destroy(ctx, cc);
1339             if (!code) cc = 0;
1340
1341           loop_cleanup:
1342             if ( cc ) {
1343                 pkrb5_cc_close(ctx, cc);
1344                 cc = 0;
1345             }
1346             if ( princ ) {
1347                 pkrb5_free_principal(ctx, princ);
1348                 princ = 0;
1349             }
1350
1351             KFW_AFS_update_cell_princ_map(ctx, cell, principals[count], FALSE);
1352             free(principals[count]);
1353         }
1354         free(principals);
1355     }
1356     pkrb5_free_context(ctx);
1357     return 0;
1358 }
1359
1360 int
1361 KFW_AFS_renew_expiring_tokens(void)
1362 {
1363     krb5_error_code                     code = 0;
1364     krb5_context                        ctx = 0;
1365     krb5_ccache                         cc = 0;
1366     krb5_timestamp now;
1367     struct principal_ccache_data * pcc_next = princ_cc_data;
1368     int cell_count;
1369     char ** cells=NULL;
1370     const char * realm = NULL;
1371     char local_cell[MAXCELLCHARS+1]="";
1372     struct afsconf_cell cellconfig;
1373
1374     if (!pkrb5_init_context)
1375         return 0;
1376
1377     if ( pcc_next == NULL ) // nothing to do
1378         return 0;
1379
1380     if ( IsDebuggerPresent() ) {
1381         OutputDebugString("KFW_AFS_renew_expiring_tokens\n");
1382     }
1383
1384     code = pkrb5_init_context(&ctx);
1385     if (code) goto cleanup;
1386
1387     code = pkrb5_timeofday(ctx, &now);
1388     if (code) goto cleanup; 
1389
1390     for ( ; pcc_next ; pcc_next = pcc_next->next ) {
1391         if ( pcc_next->expired ) 
1392             continue;
1393
1394         if ( now >= (pcc_next->expiration_time) ) {
1395             if ( !pcc_next->from_lsa ) {
1396                 pcc_next->expired = 1;
1397                 continue;
1398             }
1399         }
1400
1401         if ( pcc_next->renew && now >= (pcc_next->expiration_time - cminRENEW * csec1MINUTE) ) {
1402             code = pkrb5_cc_resolve(ctx, pcc_next->ccache_name, &cc);
1403             if ( code ) 
1404                                 goto loop_cleanup;
1405             code = KFW_renew(ctx,cc);
1406 #ifdef USE_MS2MIT
1407             if ( code && pcc_next->from_lsa)
1408                 goto loop_cleanup;
1409 #endif /* USE_MS2MIT */
1410
1411
1412             KFW_AFS_update_princ_ccache_data(ctx, cc, pcc_next->from_lsa);
1413             if (code) goto loop_cleanup;
1414
1415             // Attempt to obtain new tokens for other cells supported by the same 
1416             // principal
1417             cell_count = KFW_AFS_find_cells_for_princ(ctx, pcc_next->principal, &cells, TRUE);
1418             if ( cell_count > 0 ) {
1419                 while ( cell_count-- ) {
1420                     if ( IsDebuggerPresent() ) {
1421                         OutputDebugString("Cell: ");
1422                         OutputDebugString(cells[cell_count]);
1423                         OutputDebugString("\n");
1424                     }
1425                     code = KFW_AFS_get_cellconfig( cells[cell_count], (void*)&cellconfig, local_cell);
1426                     if ( code ) continue;
1427                     realm = afs_realm_of_cell(&cellconfig);  // do not free
1428                     if ( IsDebuggerPresent() ) {
1429                         OutputDebugString("Realm: ");
1430                         OutputDebugString(realm);
1431                         OutputDebugString("\n");
1432                     }
1433                     code = KFW_AFS_klog(ctx, cc, "afs", cells[cell_count], (char *)realm, pLeash_get_default_lifetime(),NULL);
1434                     if ( IsDebuggerPresent() ) {
1435                         char message[256];
1436                         sprintf(message,"KFW_AFS_klog() returns: %d\n",code);
1437                         OutputDebugString(message);
1438                     }
1439                     free(cells[cell_count]);
1440                 }
1441                 free(cells);
1442             }
1443         }
1444
1445       loop_cleanup:
1446         if ( cc ) {
1447             pkrb5_cc_close(ctx,cc);
1448             cc = 0;
1449         }
1450     }
1451
1452   cleanup:
1453     if ( cc )
1454         pkrb5_cc_close(ctx,cc);
1455     if ( ctx )
1456         pkrb5_free_context(ctx);
1457
1458     return 0;
1459 }
1460
1461
1462 BOOL
1463 KFW_AFS_renew_token_for_cell(char * cell)
1464 {
1465     krb5_error_code                     code = 0;
1466     krb5_context                        ctx = 0;
1467     int count;
1468     char ** principals = NULL;
1469
1470     if (!pkrb5_init_context)
1471         return 0;
1472
1473     if ( IsDebuggerPresent() ) {
1474         OutputDebugString("KFW_AFS_renew_token_for_cell:");
1475         OutputDebugString(cell);
1476         OutputDebugString("\n");
1477     }
1478
1479     code = pkrb5_init_context(&ctx);
1480     if (code) goto cleanup;
1481
1482     count = KFW_AFS_find_principals_for_cell(ctx, cell, &principals, TRUE);
1483     if ( count == 0 ) {
1484         // We know we must have a credential somewhere since we are
1485         // trying to renew a token
1486
1487         KFW_import_ccache_data();
1488         count = KFW_AFS_find_principals_for_cell(ctx, cell, &principals, TRUE);
1489     }
1490     if ( count > 0 ) {
1491         krb5_principal      princ = 0;
1492         krb5_principal      service = 0;
1493 #ifdef COMMENT
1494         krb5_creds          mcreds, creds;
1495 #endif /* COMMENT */
1496         krb5_ccache                     cc  = 0;
1497         const char * realm = NULL;
1498         struct afsconf_cell cellconfig;
1499         char local_cell[MAXCELLCHARS+1];
1500
1501         while ( count-- ) {
1502             code = pkrb5_parse_name(ctx, principals[count], &princ);
1503             if (code) goto loop_cleanup;
1504
1505             code = KFW_get_ccache(ctx, princ, &cc);
1506             if (code) goto loop_cleanup;
1507
1508             code = KFW_AFS_get_cellconfig( cell, (void*)&cellconfig, local_cell);
1509             if ( code ) goto loop_cleanup;
1510
1511             realm = afs_realm_of_cell(&cellconfig);  // do not free
1512             if ( IsDebuggerPresent() ) {
1513                 OutputDebugString("Realm: ");
1514                 OutputDebugString(realm);
1515                 OutputDebugString("\n");
1516             }
1517
1518 #ifdef COMMENT
1519             /* krb5_cc_remove_cred() is not implemented 
1520              * for a single cred 
1521              */
1522             code = pkrb5_build_principal(ctx, &service, strlen(realm),
1523                                           realm, "afs", cell, NULL);
1524             if (!code) {
1525                 memset(&mcreds, 0, sizeof(krb5_creds));
1526                 mcreds.client = princ;
1527                 mcreds.server = service;
1528
1529                 code = pkrb5_cc_retrieve_cred(ctx, cc, 0, &mcreds, &creds);
1530                 if (!code) {
1531                     if ( IsDebuggerPresent() ) {
1532                         char * cname, *sname;
1533                         pkrb5_unparse_name(ctx, creds.client, &cname);
1534                         pkrb5_unparse_name(ctx, creds.server, &sname);
1535                         OutputDebugString("Removing credential for client \"");
1536                         OutputDebugString(cname);
1537                         OutputDebugString("\" and service \"");
1538                         OutputDebugString(sname);
1539                         OutputDebugString("\"\n");
1540                         pkrb5_free_unparsed_name(ctx,cname);
1541                         pkrb5_free_unparsed_name(ctx,sname);
1542                     }
1543
1544                     code = pkrb5_cc_remove_cred(ctx, cc, 0, &creds);
1545                     pkrb5_free_principal(ctx, creds.client);
1546                     pkrb5_free_principal(ctx, creds.server);
1547                 }
1548             }
1549 #endif /* COMMENT */
1550
1551             code = KFW_AFS_klog(ctx, cc, "afs", cell, (char *)realm, pLeash_get_default_lifetime(),NULL);
1552             if ( IsDebuggerPresent() ) {
1553                 char message[256];
1554                 sprintf(message,"KFW_AFS_klog() returns: %d\n",code);
1555                 OutputDebugString(message);
1556             }
1557
1558           loop_cleanup:
1559             if (cc) {
1560                 pkrb5_cc_close(ctx, cc);
1561                 cc = 0;
1562             }
1563             if (princ) {
1564                 pkrb5_free_principal(ctx, princ);
1565                 princ = 0;
1566             }
1567             if (service) {
1568                 pkrb5_free_principal(ctx, service);
1569                 princ = 0;
1570             }
1571
1572             KFW_AFS_update_cell_princ_map(ctx, cell, principals[count], code ? FALSE : TRUE);
1573             free(principals[count]);
1574         }
1575         free(principals);
1576     } else
1577         code = -1;      // we did not renew the tokens 
1578
1579   cleanup:
1580     pkrb5_free_context(ctx);
1581     return (code ? FALSE : TRUE);
1582
1583 }
1584
1585 int
1586 KFW_AFS_renew_tokens_for_all_cells(void)
1587 {
1588     struct cell_principal_map * next = cell_princ_map;
1589
1590     if ( IsDebuggerPresent() )
1591         OutputDebugString("KFW_AFS_renew_tokens_for_all()\n");
1592
1593     if ( !next )
1594         return 0;
1595
1596     for ( ; next ; next = next->next ) {
1597         if ( next->active )
1598             KFW_AFS_renew_token_for_cell(next->cell);
1599     }
1600     return 0;
1601 }
1602
1603 int
1604 KFW_renew(krb5_context alt_ctx, krb5_ccache alt_cc)
1605 {
1606     krb5_error_code                     code = 0;
1607     krb5_context                        ctx = 0;
1608     krb5_ccache                         cc = 0;
1609     krb5_principal                      me = 0;
1610     krb5_principal              server = 0;
1611     krb5_creds                          my_creds;
1612     krb5_data                   *realm = 0;
1613
1614     if (!pkrb5_init_context)
1615         return 0;
1616
1617         memset(&my_creds, 0, sizeof(krb5_creds));
1618
1619     if ( alt_ctx ) {
1620         ctx = alt_ctx;
1621     } else {
1622         code = pkrb5_init_context(&ctx);
1623         if (code) goto cleanup;
1624     }
1625
1626     if ( alt_cc ) {
1627         cc = alt_cc;
1628     } else {
1629         code = pkrb5_cc_default(ctx, &cc);
1630         if (code) goto cleanup;
1631     }
1632
1633     code = pkrb5_cc_get_principal(ctx, cc, &me);
1634     if (code) goto cleanup;
1635
1636     realm = krb5_princ_realm(ctx, me);
1637
1638     code = pkrb5_build_principal_ext(ctx, &server,
1639                                     realm->length,realm->data,
1640                                     KRB5_TGS_NAME_SIZE, KRB5_TGS_NAME,
1641                                     realm->length,realm->data,
1642                                     0);
1643     if ( code ) 
1644         goto cleanup;
1645
1646     if ( IsDebuggerPresent() ) {
1647         char * cname, *sname;
1648         pkrb5_unparse_name(ctx, me, &cname);
1649         pkrb5_unparse_name(ctx, server, &sname);
1650         OutputDebugString("Renewing credential for client \"");
1651         OutputDebugString(cname);
1652         OutputDebugString("\" and service \"");
1653         OutputDebugString(sname);
1654         OutputDebugString("\"\n");
1655         pkrb5_free_unparsed_name(ctx,cname);
1656         pkrb5_free_unparsed_name(ctx,sname);
1657     }
1658
1659     my_creds.client = me;
1660     my_creds.server = server;
1661
1662     code = pkrb5_get_renewed_creds(ctx, &my_creds, me, cc, NULL);
1663     if (code) {
1664         if ( IsDebuggerPresent() ) {
1665             char message[256];
1666             sprintf(message,"krb5_get_renewed_creds() failed: %d\n",code);
1667             OutputDebugString(message);
1668         }
1669         goto cleanup;
1670     }
1671
1672     code = pkrb5_cc_initialize(ctx, cc, me);
1673     if (code) {
1674         if ( IsDebuggerPresent() ) {
1675             char message[256];
1676             sprintf(message,"krb5_cc_initialize() failed: %d\n",code);
1677             OutputDebugString(message);
1678         }
1679         goto cleanup;
1680     }
1681
1682     code = pkrb5_cc_store_cred(ctx, cc, &my_creds);
1683     if (code) {
1684         if ( IsDebuggerPresent() ) {
1685             char message[256];
1686             sprintf(message,"krb5_cc_store_cred() failed: %d\n",code);
1687             OutputDebugString(message);
1688         }
1689         goto cleanup;
1690     }
1691
1692   cleanup:
1693     if (my_creds.client == me)
1694         my_creds.client = 0;
1695     if (my_creds.server == server)
1696         my_creds.server = 0;
1697     pkrb5_free_cred_contents(ctx, &my_creds);
1698     if (me)
1699         pkrb5_free_principal(ctx, me);
1700     if (server)
1701         pkrb5_free_principal(ctx, server);
1702     if (cc && (cc != alt_cc))
1703         pkrb5_cc_close(ctx, cc);
1704     if (ctx && (ctx != alt_ctx))
1705         pkrb5_free_context(ctx);
1706     return(code);
1707 }
1708
1709 int
1710 KFW_kinit( krb5_context alt_ctx,
1711             krb5_ccache  alt_cc,
1712             HWND hParent,
1713             char *principal_name,
1714             char *password,
1715             krb5_deltat lifetime,
1716             DWORD                       forwardable,
1717             DWORD                       proxiable,
1718             krb5_deltat                 renew_life,
1719             DWORD                       addressless,
1720             DWORD                       publicIP
1721             )
1722 {
1723     krb5_error_code                     code = 0;
1724     krb5_context                        ctx = 0;
1725     krb5_ccache                         cc = 0;
1726     krb5_principal                      me = 0;
1727     char*                       name = 0;
1728     krb5_creds                          my_creds;
1729     krb5_get_init_creds_opt     options;
1730     krb5_address **             addrs = NULL;
1731     int                         i = 0, addr_count = 0;
1732
1733     if (!pkrb5_init_context)
1734         return 0;
1735
1736     pkrb5_get_init_creds_opt_init(&options);
1737     memset(&my_creds, 0, sizeof(my_creds));
1738
1739     if (alt_ctx)
1740     {
1741         ctx = alt_ctx;
1742     }
1743     else
1744     {
1745         code = pkrb5_init_context(&ctx);
1746         if (code) goto cleanup;
1747     }
1748
1749     if ( alt_cc ) {
1750         cc = alt_cc;
1751     } else {
1752         code = pkrb5_cc_default(ctx, &cc);  
1753         if (code) goto cleanup;
1754     }
1755
1756     code = pkrb5_parse_name(ctx, principal_name, &me);
1757     if (code) 
1758                 goto cleanup;
1759
1760     code = pkrb5_unparse_name(ctx, me, &name);
1761     if (code) 
1762                 goto cleanup;
1763
1764     if (lifetime == 0)
1765         lifetime = pLeash_get_default_lifetime();
1766     else
1767         lifetime *= 5*60;
1768
1769         if (renew_life > 0)
1770                 renew_life *= 5*60;
1771
1772     if (lifetime)
1773         pkrb5_get_init_creds_opt_set_tkt_life(&options, lifetime);
1774         pkrb5_get_init_creds_opt_set_forwardable(&options,
1775                                                  forwardable ? 1 : 0);
1776         pkrb5_get_init_creds_opt_set_proxiable(&options,
1777                                                proxiable ? 1 : 0);
1778         pkrb5_get_init_creds_opt_set_renew_life(&options,
1779                                                renew_life);
1780     if (addressless)
1781         pkrb5_get_init_creds_opt_set_address_list(&options,NULL);
1782     else {
1783                 if (publicIP)
1784         {
1785             // we are going to add the public IP address specified by the user
1786             // to the list provided by the operating system
1787             krb5_address ** local_addrs=NULL;
1788             DWORD           netIPAddr;
1789
1790             pkrb5_os_localaddr(ctx, &local_addrs);
1791             while ( local_addrs[i++] );
1792             addr_count = i + 1;
1793
1794             addrs = (krb5_address **) malloc((addr_count+1) * sizeof(krb5_address *));
1795             if ( !addrs ) {
1796                 pkrb5_free_addresses(ctx, local_addrs);
1797                 goto cleanup;
1798             }
1799             memset(addrs, 0, sizeof(krb5_address *) * (addr_count+1));
1800             i = 0;
1801             while ( local_addrs[i] ) {
1802                 addrs[i] = (krb5_address *)malloc(sizeof(krb5_address));
1803                 if (addrs[i] == NULL) {
1804                     pkrb5_free_addresses(ctx, local_addrs);
1805                     goto cleanup;
1806                 }
1807
1808                 addrs[i]->magic = local_addrs[i]->magic;
1809                 addrs[i]->addrtype = local_addrs[i]->addrtype;
1810                 addrs[i]->length = local_addrs[i]->length;
1811                 addrs[i]->contents = (unsigned char *)malloc(addrs[i]->length);
1812                 if (!addrs[i]->contents) {
1813                     pkrb5_free_addresses(ctx, local_addrs);
1814                     goto cleanup;
1815                 }
1816
1817                 memcpy(addrs[i]->contents,local_addrs[i]->contents,
1818                         local_addrs[i]->length);        /* safe */
1819                 i++;
1820             }
1821             pkrb5_free_addresses(ctx, local_addrs);
1822
1823             addrs[i] = (krb5_address *)malloc(sizeof(krb5_address));
1824             if (addrs[i] == NULL)
1825                 goto cleanup;
1826
1827             addrs[i]->magic = KV5M_ADDRESS;
1828             addrs[i]->addrtype = AF_INET;
1829             addrs[i]->length = 4;
1830             addrs[i]->contents = (unsigned char *)malloc(addrs[i]->length);
1831             if (!addrs[i]->contents)
1832                 goto cleanup;
1833
1834             netIPAddr = htonl(publicIP);
1835             memcpy(addrs[i]->contents,&netIPAddr,4);
1836         
1837             pkrb5_get_init_creds_opt_set_address_list(&options,addrs);
1838
1839         }
1840     }
1841
1842     code = pkrb5_get_init_creds_password(ctx, 
1843                                        &my_creds, 
1844                                        me,
1845                                        password, // password
1846                                        KRB5_prompter, // prompter
1847                                        hParent, // prompter data
1848                                        0, // start time
1849                                        0, // service name
1850                                        &options);
1851     if (code) 
1852                 goto cleanup;
1853
1854     code = pkrb5_cc_initialize(ctx, cc, me);
1855     if (code) 
1856                 goto cleanup;
1857
1858     code = pkrb5_cc_store_cred(ctx, cc, &my_creds);
1859     if (code) 
1860                 goto cleanup;
1861
1862  cleanup:
1863     if ( addrs ) {
1864         for ( i=0;i<addr_count;i++ ) {
1865             if ( addrs[i] ) {
1866                 if ( addrs[i]->contents )
1867                     free(addrs[i]->contents);
1868                 free(addrs[i]);
1869             }
1870         }
1871     }
1872     if (my_creds.client == me)
1873         my_creds.client = 0;
1874     pkrb5_free_cred_contents(ctx, &my_creds);
1875     if (name)
1876         pkrb5_free_unparsed_name(ctx, name);
1877     if (me)
1878         pkrb5_free_principal(ctx, me);
1879     if (cc && (cc != alt_cc))
1880         pkrb5_cc_close(ctx, cc);
1881     if (ctx && (ctx != alt_ctx))
1882         pkrb5_free_context(ctx);
1883     return(code);
1884 }
1885
1886
1887 int
1888 KFW_kdestroy(krb5_context alt_ctx, krb5_ccache alt_cc)
1889 {
1890     krb5_context                ctx;
1891     krb5_ccache                 cc;
1892     krb5_error_code             code;
1893
1894     if (!pkrb5_init_context)
1895         return 0;
1896
1897     if (alt_ctx)
1898     {
1899         ctx = alt_ctx;
1900     }
1901     else
1902     {
1903         code = pkrb5_init_context(&ctx);
1904         if (code) goto cleanup;
1905     }
1906
1907     if ( alt_cc ) {
1908         cc = alt_cc;
1909     } else {
1910         code = pkrb5_cc_default(ctx, &cc);  
1911         if (code) goto cleanup;
1912     }
1913
1914     code = pkrb5_cc_destroy(ctx, cc);
1915     if ( !code ) cc = 0;
1916
1917   cleanup:
1918     if (cc && (cc != alt_cc))
1919         pkrb5_cc_close(ctx, cc);
1920     if (ctx && (ctx != alt_ctx))
1921         pkrb5_free_context(ctx);
1922
1923     return(code);
1924 }
1925
1926
1927 #ifdef USE_MS2MIT
1928 static BOOL
1929 GetSecurityLogonSessionData(PSECURITY_LOGON_SESSION_DATA * ppSessionData)
1930 {
1931     NTSTATUS Status = 0;
1932     HANDLE  TokenHandle;
1933     TOKEN_STATISTICS Stats;
1934     DWORD   ReqLen;
1935     BOOL    Success;
1936
1937     if (!ppSessionData)
1938         return FALSE;
1939     *ppSessionData = NULL;
1940
1941     Success = OpenProcessToken( GetCurrentProcess(), TOKEN_QUERY, &TokenHandle );
1942     if ( !Success )
1943         return FALSE;
1944
1945     Success = GetTokenInformation( TokenHandle, TokenStatistics, &Stats, sizeof(TOKEN_STATISTICS), &ReqLen );
1946     CloseHandle( TokenHandle );
1947     if ( !Success )
1948         return FALSE;
1949
1950     Status = pLsaGetLogonSessionData( &Stats.AuthenticationId, ppSessionData );
1951     if ( FAILED(Status) || !ppSessionData )
1952         return FALSE;
1953
1954     return TRUE;
1955 }
1956
1957 //
1958 // MSLSA_IsKerberosLogon() does not validate whether or not there are valid tickets in the 
1959 // cache.  It validates whether or not it is reasonable to assume that if we 
1960 // attempted to retrieve valid tickets we could do so.  Microsoft does not 
1961 // automatically renew expired tickets.  Therefore, the cache could contain
1962 // expired or invalid tickets.  Microsoft also caches the user's password 
1963 // and will use it to retrieve new TGTs if the cache is empty and tickets
1964 // are requested.
1965
1966 static BOOL
1967 MSLSA_IsKerberosLogon(VOID)
1968 {
1969     PSECURITY_LOGON_SESSION_DATA pSessionData = NULL;
1970     BOOL    Success = FALSE;
1971
1972     if ( GetSecurityLogonSessionData(&pSessionData) ) {
1973         if ( pSessionData->AuthenticationPackage.Buffer ) {
1974             WCHAR buffer[256];
1975             WCHAR *usBuffer;
1976             int usLength;
1977
1978             Success = FALSE;
1979             usBuffer = (pSessionData->AuthenticationPackage).Buffer;
1980             usLength = (pSessionData->AuthenticationPackage).Length;
1981             if (usLength < 256)
1982             {
1983                 lstrcpynW (buffer, usBuffer, usLength);
1984                 lstrcatW (buffer,L"");
1985                 if ( !lstrcmpW(L"Kerberos",buffer) )
1986                     Success = TRUE;
1987             }
1988         }
1989         pLsaFreeReturnBuffer(pSessionData);
1990     }
1991     return Success;
1992 }
1993 #endif /* USE_MS2MIT */
1994
1995 static BOOL CALLBACK 
1996 MultiInputDialogProc( HWND hDialog, UINT message, WPARAM wParam, LPARAM lParam)
1997 {
1998     int i;
1999
2000     switch ( message ) {
2001     case WM_INITDIALOG:
2002         if ( GetDlgCtrlID((HWND) wParam) != ID_MID_TEXT )
2003         {
2004             SetFocus(GetDlgItem( hDialog, ID_MID_TEXT));
2005             return FALSE;
2006         }
2007                 for ( i=0; i < mid_cnt ; i++ ) {
2008                         if (mid_tb[i].echo == 0)
2009                                 SendDlgItemMessage(hDialog, ID_MID_TEXT+i, EM_SETPASSWORDCHAR, 32, 0);
2010                     else if (mid_tb[i].echo == 2) 
2011                                 SendDlgItemMessage(hDialog, ID_MID_TEXT+i, EM_SETPASSWORDCHAR, '*', 0);
2012                 }
2013         return TRUE;
2014
2015     case WM_COMMAND:
2016         switch ( LOWORD(wParam) ) {
2017         case IDOK:
2018             for ( i=0; i < mid_cnt ; i++ ) {
2019                 if ( !GetDlgItemText(hDialog, ID_MID_TEXT+i, mid_tb[i].buf, mid_tb[i].len) )
2020                     *mid_tb[i].buf = '\0';
2021             }
2022             /* fallthrough */
2023         case IDCANCEL:
2024             EndDialog(hDialog, LOWORD(wParam));
2025             return TRUE;
2026         }
2027     }
2028     return FALSE;
2029 }
2030
2031 static LPWORD 
2032 lpwAlign( LPWORD lpIn )
2033 {
2034     ULONG ul;
2035
2036     ul = (ULONG) lpIn;
2037     ul += 3;
2038     ul >>=2;
2039     ul <<=2;
2040     return (LPWORD) ul;;
2041 }
2042
2043 /*
2044  * dialog widths are measured in 1/4 character widths
2045  * dialog height are measured in 1/8 character heights
2046  */
2047
2048 static LRESULT
2049 MultiInputDialog( HINSTANCE hinst, HWND hwndOwner, 
2050                   char * ptext[], int numlines, int width, 
2051                   int tb_cnt, struct textField * tb)
2052 {
2053     HGLOBAL hgbl;
2054     LPDLGTEMPLATE lpdt;
2055     LPDLGITEMTEMPLATE lpdit;
2056     LPWORD lpw;
2057     LPWSTR lpwsz;
2058     LRESULT ret;
2059     int nchar, i, pwid;
2060
2061     hgbl = GlobalAlloc(GMEM_ZEROINIT, 4096);
2062     if (!hgbl)
2063         return -1;
2064  
2065     mid_cnt = tb_cnt;
2066     mid_tb = tb;
2067
2068     lpdt = (LPDLGTEMPLATE)GlobalLock(hgbl);
2069  
2070     // Define a dialog box.
2071  
2072     lpdt->style = WS_POPUP | WS_BORDER | WS_SYSMENU
2073                    | DS_MODALFRAME | WS_CAPTION | DS_CENTER 
2074                    | DS_SETFOREGROUND | DS_3DLOOK
2075                    | DS_SETFONT | DS_FIXEDSYS | DS_NOFAILCREATE;
2076     lpdt->cdit = numlines + (2 * tb_cnt) + 2;  // number of controls
2077     lpdt->x  = 10;  
2078     lpdt->y  = 10;
2079     lpdt->cx = 20 + width * 4; 
2080     lpdt->cy = 20 + (numlines + tb_cnt + 4) * 14;
2081
2082     lpw = (LPWORD) (lpdt + 1);
2083     *lpw++ = 0;   // no menu
2084     *lpw++ = 0;   // predefined dialog box class (by default)
2085
2086     lpwsz = (LPWSTR) lpw;
2087     nchar = MultiByteToWideChar (CP_ACP, 0, "", -1, lpwsz, 128);
2088     lpw   += nchar;
2089     *lpw++ = 8;                        // font size (points)
2090     lpwsz = (LPWSTR) lpw;
2091     nchar = MultiByteToWideChar (CP_ACP, 0, "MS Shell Dlg", 
2092                                     -1, lpwsz, 128);
2093     lpw   += nchar;
2094
2095     //-----------------------
2096     // Define an OK button.
2097     //-----------------------
2098     lpw = lpwAlign (lpw); // align DLGITEMTEMPLATE on DWORD boundary
2099     lpdit = (LPDLGITEMTEMPLATE) lpw;
2100     lpdit->style = WS_CHILD | WS_VISIBLE | BS_DEFPUSHBUTTON | WS_TABSTOP | WS_BORDER;
2101     lpdit->dwExtendedStyle = 0;
2102     lpdit->x  = (lpdt->cx - 14)/4 - 20; 
2103     lpdit->y  = 10 + (numlines + tb_cnt + 2) * 14;
2104     lpdit->cx = 40; 
2105     lpdit->cy = 14;
2106     lpdit->id = IDOK;  // OK button identifier
2107
2108     lpw = (LPWORD) (lpdit + 1);
2109     *lpw++ = 0xFFFF;
2110     *lpw++ = 0x0080;    // button class
2111
2112     lpwsz = (LPWSTR) lpw;
2113     nchar = MultiByteToWideChar (CP_ACP, 0, "OK", -1, lpwsz, 50);
2114     lpw   += nchar;
2115     *lpw++ = 0;           // no creation data
2116
2117     //-----------------------
2118     // Define an Cancel button.
2119     //-----------------------
2120     lpw = lpwAlign (lpw); // align DLGITEMTEMPLATE on DWORD boundary
2121     lpdit = (LPDLGITEMTEMPLATE) lpw;
2122     lpdit->style = WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP | WS_BORDER;
2123     lpdit->dwExtendedStyle = 0;
2124     lpdit->x  = (lpdt->cx - 14)*3/4 - 20; 
2125     lpdit->y  = 10 + (numlines + tb_cnt + 2) * 14;
2126     lpdit->cx = 40; 
2127     lpdit->cy = 14;
2128     lpdit->id = IDCANCEL;  // CANCEL button identifier
2129
2130     lpw = (LPWORD) (lpdit + 1);
2131     *lpw++ = 0xFFFF;
2132     *lpw++ = 0x0080;    // button class
2133
2134     lpwsz = (LPWSTR) lpw;
2135     nchar = MultiByteToWideChar (CP_ACP, 0, "Cancel", -1, lpwsz, 50);
2136     lpw   += nchar;
2137     *lpw++ = 0;           // no creation data
2138
2139     /* Add controls for preface data */
2140     for ( i=0; i<numlines; i++) {
2141         /*-----------------------
2142          * Define a static text control.
2143          *-----------------------*/
2144         lpw = lpwAlign (lpw); /* align DLGITEMTEMPLATE on DWORD boundary */
2145         lpdit = (LPDLGITEMTEMPLATE) lpw;
2146         lpdit->style = WS_CHILD | WS_VISIBLE | SS_LEFT;
2147         lpdit->dwExtendedStyle = 0;
2148         lpdit->x  = 10; 
2149         lpdit->y  = 10 + i * 14;
2150         lpdit->cx = strlen(ptext[i]) * 4 + 10; 
2151         lpdit->cy = 14;
2152         lpdit->id = ID_TEXT + i;  // text identifier
2153
2154         lpw = (LPWORD) (lpdit + 1);
2155         *lpw++ = 0xFFFF;
2156         *lpw++ = 0x0082;                         // static class
2157
2158         lpwsz = (LPWSTR) lpw;
2159         nchar = MultiByteToWideChar (CP_ACP, 0, ptext[i], 
2160                                          -1, lpwsz, 2*width);
2161         lpw   += nchar;
2162         *lpw++ = 0;           // no creation data
2163     }
2164     
2165     for ( i=0, pwid = 0; i<tb_cnt; i++) {
2166         if ( pwid < strlen(tb[i].label) )
2167             pwid = strlen(tb[i].label);
2168     }
2169
2170     for ( i=0; i<tb_cnt; i++) {
2171         /* Prompt */
2172         /*-----------------------
2173          * Define a static text control.
2174          *-----------------------*/
2175         lpw = lpwAlign (lpw); /* align DLGITEMTEMPLATE on DWORD boundary */
2176         lpdit = (LPDLGITEMTEMPLATE) lpw;
2177         lpdit->style = WS_CHILD | WS_VISIBLE | SS_LEFT;
2178         lpdit->dwExtendedStyle = 0;
2179         lpdit->x  = 10; 
2180         lpdit->y  = 10 + (numlines + i + 1) * 14;
2181         lpdit->cx = pwid * 4; 
2182         lpdit->cy = 14;
2183         lpdit->id = ID_TEXT + numlines + i;  // text identifier
2184
2185         lpw = (LPWORD) (lpdit + 1);
2186         *lpw++ = 0xFFFF;
2187         *lpw++ = 0x0082;                         // static class
2188
2189         lpwsz = (LPWSTR) lpw;
2190         nchar = MultiByteToWideChar (CP_ACP, 0, tb[i].label ? tb[i].label : "", 
2191                                      -1, lpwsz, 128);
2192         lpw   += nchar;
2193         *lpw++ = 0;           // no creation data
2194
2195         /*-----------------------
2196          * Define an edit control.
2197          *-----------------------*/
2198         lpw = lpwAlign (lpw); /* align DLGITEMTEMPLATE on DWORD boundary */
2199         lpdit = (LPDLGITEMTEMPLATE) lpw;
2200         lpdit->style = WS_CHILD | WS_VISIBLE | ES_LEFT | WS_TABSTOP | WS_BORDER | (tb[i].echo == 1 ? 0L : ES_PASSWORD);
2201         lpdit->dwExtendedStyle = 0;
2202         lpdit->x  = 10 + (pwid + 1) * 4; 
2203         lpdit->y  = 10 + (numlines + i + 1) * 14;
2204         lpdit->cx = (width - (pwid + 1)) * 4; 
2205         lpdit->cy = 14;
2206         lpdit->id = ID_MID_TEXT + i;             // identifier
2207
2208         lpw = (LPWORD) (lpdit + 1);
2209         *lpw++ = 0xFFFF;
2210         *lpw++ = 0x0081;                         // edit class
2211
2212         lpwsz = (LPWSTR) lpw;
2213         nchar = MultiByteToWideChar (CP_ACP, 0, tb[i].def ? tb[i].def : "", 
2214                                      -1, lpwsz, 128);
2215         lpw   += nchar;
2216         *lpw++ = 0;           // no creation data
2217     }
2218
2219     GlobalUnlock(hgbl); 
2220     ret = DialogBoxIndirect(hinst, (LPDLGTEMPLATE) hgbl, 
2221                                                         hwndOwner, (DLGPROC) MultiInputDialogProc); 
2222     GlobalFree(hgbl); 
2223
2224     switch ( ret ) {
2225     case 0:     /* Timeout */
2226         return -1;
2227     case IDOK:
2228         return 1;
2229     case IDCANCEL:
2230         return 0;
2231     default: {
2232         char buf[256];
2233         sprintf(buf,"DialogBoxIndirect() failed: %d",GetLastError());
2234         MessageBox(hwndOwner,
2235                     buf,
2236                     "GetLastError()",
2237                     MB_OK | MB_ICONINFORMATION | MB_TASKMODAL);
2238         return -1;
2239     }
2240     }
2241 }
2242
2243 static int
2244 multi_field_dialog(HWND hParent, char * preface, int n, struct textField tb[])
2245 {
2246         HINSTANCE hInst = 0;
2247     int maxwidth = 0;
2248     int numlines = 0;
2249     int len;
2250     char * plines[16], *p = preface ? preface : "";
2251     int i;
2252
2253     for ( i=0; i<16; i++ ) 
2254         plines[i] = NULL;
2255
2256     while (*p && numlines < 16) {
2257         plines[numlines++] = p;
2258         for ( ;*p && *p != '\r' && *p != '\n'; p++ );
2259         if ( *p == '\r' && *(p+1) == '\n' ) {
2260             *p++ = '\0';
2261             p++;
2262         } else if ( *p == '\n' ) {
2263             *p++ = '\0';
2264         } 
2265         if ( strlen(plines[numlines-1]) > maxwidth )
2266             maxwidth = strlen(plines[numlines-1]);
2267     }
2268
2269     for ( i=0;i<n;i++ ) {
2270         len = strlen(tb[i].label) + 1 + (tb[i].len > 40 ? 40 : tb[i].len);
2271         if ( maxwidth < len )
2272             maxwidth = len;
2273     }
2274
2275     return(MultiInputDialog(hInst, hParent, plines, numlines, maxwidth, n, tb));
2276 }
2277
2278 static krb5_error_code KRB5_CALLCONV
2279 KRB5_prompter( krb5_context context,
2280                void *data,
2281                const char *name,
2282                const char *banner,
2283                int num_prompts,
2284                krb5_prompt prompts[])
2285 {
2286     krb5_error_code     errcode = 0;
2287     int                 i;
2288     struct textField * tb = NULL;
2289     int    len = 0, blen=0, nlen=0;
2290         HWND hParent = (HWND)data;
2291
2292     if (name)
2293         nlen = strlen(name)+2;
2294
2295     if (banner)
2296         blen = strlen(banner)+2;
2297
2298     tb = (struct textField *) malloc(sizeof(struct textField) * num_prompts);
2299     if ( tb != NULL ) {
2300         int ok;
2301         memset(tb,0,sizeof(struct textField) * num_prompts);
2302         for ( i=0; i < num_prompts; i++ ) {
2303             tb[i].buf = prompts[i].reply->data;
2304             tb[i].len = prompts[i].reply->length;
2305             tb[i].label = prompts[i].prompt;
2306             tb[i].def = NULL;
2307             tb[i].echo = (prompts[i].hidden ? 2 : 1);
2308         }   
2309
2310         ok = multi_field_dialog(hParent,(char *)banner,num_prompts,tb);
2311         if ( ok ) {
2312             for ( i=0; i < num_prompts; i++ )
2313                 prompts[i].reply->length = strlen(prompts[i].reply->data);
2314         } else
2315             errcode = -2;
2316     }
2317
2318     if ( tb )
2319         free(tb);
2320     if (errcode) {
2321         for (i = 0; i < num_prompts; i++) {
2322             memset(prompts[i].reply->data, 0, prompts[i].reply->length);
2323         }
2324     }
2325     return errcode;
2326 }
2327
2328 BOOL
2329 KFW_AFS_wait_for_service_start(void)
2330 {
2331     char    HostName[64];
2332     DWORD   CurrentState;
2333
2334     CurrentState = SERVICE_START_PENDING;
2335     memset(HostName, '\0', sizeof(HostName));
2336     gethostname(HostName, sizeof(HostName));
2337
2338     while (CurrentState != SERVICE_RUNNING || CurrentState != SERVICE_STOPPED)
2339     {
2340         if (GetServiceStatus(HostName, TRANSARCAFSDAEMON, &CurrentState) != NOERROR)
2341             return(0);
2342         if ( IsDebuggerPresent() ) {
2343             switch ( CurrentState ) {
2344             case SERVICE_STOPPED:
2345                 OutputDebugString("SERVICE_STOPPED\n");
2346                 break;
2347             case SERVICE_START_PENDING:
2348                 OutputDebugString("SERVICE_START_PENDING\n");
2349                 break;
2350             case SERVICE_STOP_PENDING:
2351                 OutputDebugString("SERVICE_STOP_PENDING\n");
2352                 break;
2353             case SERVICE_RUNNING:
2354                 OutputDebugString("SERVICE_RUNNING\n");
2355                 break;
2356             case SERVICE_CONTINUE_PENDING:
2357                 OutputDebugString("SERVICE_CONTINUE_PENDING\n");
2358                 break;
2359             case SERVICE_PAUSE_PENDING:
2360                 OutputDebugString("SERVICE_PAUSE_PENDING\n");
2361                 break;
2362             case SERVICE_PAUSED:
2363                 OutputDebugString("SERVICE_PAUSED\n");
2364                 break;
2365             default:
2366                 OutputDebugString("UNKNOWN Service State\n");
2367             }
2368         }
2369         if (CurrentState == SERVICE_STOPPED)
2370             return(0);
2371         if (CurrentState == SERVICE_RUNNING)
2372             return(1);
2373         Sleep(500);
2374     }
2375     return(0);
2376 }
2377
2378
2379 int
2380 KFW_AFS_unlog(void)
2381 {
2382     long        rc;
2383     char    HostName[64];
2384     DWORD   CurrentState;
2385
2386     CurrentState = 0;
2387     memset(HostName, '\0', sizeof(HostName));
2388     gethostname(HostName, sizeof(HostName));
2389     if (GetServiceStatus(HostName, TRANSARCAFSDAEMON, &CurrentState) != NOERROR)
2390         return(0);
2391     if (CurrentState != SERVICE_RUNNING)
2392         return(0);
2393
2394     rc = pktc_ForgetAllTokens();
2395
2396     return(0);
2397 }
2398
2399 int
2400 KFW_AFS_klog(
2401     krb5_context alt_ctx,
2402     krb5_ccache  alt_cc,
2403     char *service,
2404     char *cell,
2405     char *realm,
2406     int LifeTime,
2407     char *smbname
2408     )
2409 {
2410     long        rc = 0;
2411     CREDENTIALS creds;
2412     KTEXT_ST    ticket;
2413     struct ktc_principal        aserver;
2414     struct ktc_principal        aclient;
2415     char        realm_of_user[REALM_SZ]; /* Kerberos realm of user */
2416     char        realm_of_cell[REALM_SZ]; /* Kerberos realm of cell */
2417     char        local_cell[MAXCELLCHARS+1];
2418     char        Dmycell[MAXCELLCHARS+1];
2419     struct ktc_token    atoken;
2420     struct ktc_token    btoken;
2421     struct afsconf_cell ak_cellconfig; /* General information about the cell */
2422     char        RealmName[128];
2423     char        CellName[128];
2424     char        ServiceName[128];
2425     DWORD       CurrentState;
2426     char        HostName[64];
2427     BOOL        try_krb5 = 0;
2428     krb5_context  ctx = 0;
2429     krb5_ccache   cc = 0;
2430     krb5_creds increds;
2431     krb5_creds * k5creds = 0;
2432     krb5_error_code code;
2433     krb5_principal client_principal = 0;
2434     char * cname = 0, *sname = 0;
2435     int i, retry = 0;
2436
2437     CurrentState = 0;
2438     memset(HostName, '\0', sizeof(HostName));
2439     gethostname(HostName, sizeof(HostName));
2440     if (GetServiceStatus(HostName, TRANSARCAFSDAEMON, &CurrentState) != NOERROR) {
2441         if ( IsDebuggerPresent() )
2442             OutputDebugString("Unable to retrieve AFSD Service Status\n");
2443         return(-1);
2444     }
2445     if (CurrentState != SERVICE_RUNNING) {
2446         if ( IsDebuggerPresent() )
2447             OutputDebugString("AFSD Service NOT RUNNING\n");
2448         return(-2);
2449     }
2450
2451     if (!pkrb5_init_context)
2452         return 0;
2453
2454     memset(RealmName, '\0', sizeof(RealmName));
2455     memset(CellName, '\0', sizeof(CellName));
2456     memset(ServiceName, '\0', sizeof(ServiceName));
2457     memset(realm_of_user, '\0', sizeof(realm_of_user));
2458     memset(realm_of_cell, '\0', sizeof(realm_of_cell));
2459         if (cell && cell[0])
2460                 strcpy(Dmycell, cell);
2461         else
2462                 memset(Dmycell, '\0', sizeof(Dmycell));
2463
2464     // NULL or empty cell returns information on local cell
2465     if (rc = KFW_AFS_get_cellconfig(Dmycell, &ak_cellconfig, local_cell))
2466     {
2467         // KFW_AFS_error(rc, "get_cellconfig()");
2468         return(rc);
2469     }
2470
2471     if ( alt_ctx ) {
2472         ctx = alt_ctx;
2473     } else {
2474         code = pkrb5_init_context(&ctx);
2475         if (code) goto cleanup;
2476     }
2477
2478     if ( alt_cc ) {
2479         cc = alt_cc;
2480     } else {
2481         code = pkrb5_cc_default(ctx, &cc);
2482         if (code) goto skip_krb5_init;
2483     }
2484
2485     memset((char *)&increds, 0, sizeof(increds));
2486
2487     code = pkrb5_cc_get_principal(ctx, cc, &client_principal);
2488         if (code) {
2489         if ( code == KRB5_CC_NOTFOUND && IsDebuggerPresent() ) 
2490         {
2491             OutputDebugString("Principal Not Found for ccache\n");
2492         }
2493         goto skip_krb5_init;
2494     }
2495     i = krb5_princ_realm(ctx, client_principal)->length;
2496     if (i > REALM_SZ-1) 
2497         i = REALM_SZ-1;
2498     strncpy(realm_of_user,krb5_princ_realm(ctx, client_principal)->data,i);
2499     realm_of_user[i] = 0;
2500     try_krb5 = 1;
2501
2502   skip_krb5_init:
2503 #ifdef USE_KRB4
2504     if ( !try_krb5 || !realm_of_user[0] ) {
2505         if ((rc = (*pkrb_get_tf_realm)((*ptkt_string)(), realm_of_user)) != KSUCCESS)
2506         {
2507             goto cleanup;
2508         }       
2509     }
2510 #else
2511     goto cleanup;
2512 #endif
2513     strcpy(realm_of_cell, afs_realm_of_cell(&ak_cellconfig));
2514
2515     if (strlen(service) == 0)
2516         strcpy(ServiceName, "afs");
2517     else
2518         strcpy(ServiceName, service);
2519
2520     if (strlen(cell) == 0)
2521         strcpy(CellName, local_cell);
2522     else
2523         strcpy(CellName, cell);
2524
2525     if (strlen(realm) == 0)
2526         strcpy(RealmName, realm_of_cell);
2527     else
2528         strcpy(RealmName, realm);
2529
2530     memset(&creds, '\0', sizeof(creds));
2531
2532     if ( try_krb5 ) {
2533         int len;
2534
2535         /* First try service/cell@REALM */
2536         if (code = pkrb5_build_principal(ctx, &increds.server,
2537                                           strlen(RealmName),
2538                                           RealmName,
2539                                           ServiceName,
2540                                           CellName,
2541                                           0)) 
2542         {
2543             goto cleanup;
2544         }
2545
2546         increds.client = client_principal;
2547         increds.times.endtime = 0;
2548         /* Ask for DES since that is what V4 understands */
2549         increds.keyblock.enctype = ENCTYPE_DES_CBC_CRC;
2550
2551
2552         if ( IsDebuggerPresent() ) {
2553             pkrb5_unparse_name(ctx, increds.client, &cname);
2554             pkrb5_unparse_name(ctx, increds.server, &sname);
2555             OutputDebugString("Getting tickets for \"");
2556             OutputDebugString(cname);
2557             OutputDebugString("\" and service \"");
2558             OutputDebugString(sname);
2559             OutputDebugString("\"\n");
2560             cname = sname = 0;
2561         }
2562
2563         code = pkrb5_get_credentials(ctx, 0, cc, &increds, &k5creds);
2564         if (code == KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN ||
2565              code == KRB5KRB_ERR_GENERIC /* heimdal */ ||
2566                          code == KRB5KRB_AP_ERR_MSG_TYPE) {
2567             /* Or service@REALM */
2568             pkrb5_free_principal(ctx,increds.server);
2569             increds.server = 0;
2570             code = pkrb5_build_principal(ctx, &increds.server,
2571                                           strlen(RealmName),
2572                                           RealmName,
2573                                           ServiceName,
2574                                           0);
2575
2576             if ( IsDebuggerPresent() ) {
2577                 char * cname, *sname;
2578                 pkrb5_unparse_name(ctx, increds.client, &cname);
2579                 pkrb5_unparse_name(ctx, increds.server, &sname);
2580                 OutputDebugString("krb5_get_credentials() returned Service Principal Unknown\n");
2581                 OutputDebugString("Trying again: getting tickets for \"");
2582                 OutputDebugString(cname);
2583                 OutputDebugString("\" and service \"");
2584                 OutputDebugString(sname);
2585                 OutputDebugString("\"\n");
2586                 pkrb5_free_unparsed_name(ctx,cname);
2587                 pkrb5_free_unparsed_name(ctx,sname);
2588                 cname = sname = 0;
2589             }
2590
2591             if (!code)
2592                 code = pkrb5_get_credentials(ctx, 0, cc, &increds, &k5creds);
2593         }
2594
2595         if ((code == KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN ||
2596               code == KRB5KRB_ERR_GENERIC /* heimdal */ ||
2597                           code == KRB5KRB_AP_ERR_MSG_TYPE) &&
2598              strcmp(RealmName, realm_of_cell)) {
2599             /* Or service/cell@REALM_OF_CELL */
2600             strcpy(RealmName, realm_of_cell);
2601             pkrb5_free_principal(ctx,increds.server);
2602             increds.server = 0;
2603             code = pkrb5_build_principal(ctx, &increds.server,
2604                                          strlen(RealmName),
2605                                          RealmName,
2606                                          ServiceName,
2607                                          CellName,
2608                                          0);
2609
2610             if ( IsDebuggerPresent() ) {
2611                 char * cname, *sname;
2612                 pkrb5_unparse_name(ctx, increds.client, &cname);
2613                 pkrb5_unparse_name(ctx, increds.server, &sname);
2614                 OutputDebugString("krb5_get_credentials() returned Service Principal Unknown\n");
2615                 OutputDebugString("Trying again: getting tickets for \"");
2616                 OutputDebugString(cname);
2617                 OutputDebugString("\" and service \"");
2618                 OutputDebugString(sname);
2619                 OutputDebugString("\"\n");
2620                 pkrb5_free_unparsed_name(ctx,cname);
2621                 pkrb5_free_unparsed_name(ctx,sname);
2622                 cname = sname = 0;
2623             }
2624
2625             if (!code)
2626                 code = pkrb5_get_credentials(ctx, 0, cc, &increds, &k5creds);
2627
2628         
2629             if (code == KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN ||
2630                  code == KRB5KRB_ERR_GENERIC /* heimdal */ ||
2631                                  code == KRB5KRB_AP_ERR_MSG_TYPE) {
2632                 /* Or service@REALM_OF_CELL */
2633                 pkrb5_free_principal(ctx,increds.server);
2634                 increds.server = 0;
2635                 code = pkrb5_build_principal(ctx, &increds.server,
2636                                               strlen(RealmName),
2637                                               RealmName,
2638                                               ServiceName,
2639                                               0);
2640
2641                 if ( IsDebuggerPresent() ) {
2642                     char * cname, *sname;
2643                     pkrb5_unparse_name(ctx, increds.client, &cname);
2644                     pkrb5_unparse_name(ctx, increds.server, &sname);
2645                     OutputDebugString("krb5_get_credentials() returned Service Principal Unknown\n");
2646                     OutputDebugString("Trying again: getting tickets for \"");
2647                     OutputDebugString(cname);
2648                     OutputDebugString("\" and service \"");
2649                     OutputDebugString(sname);
2650                     OutputDebugString("\"\n");
2651                     pkrb5_free_unparsed_name(ctx,cname);
2652                     pkrb5_free_unparsed_name(ctx,sname);
2653                     cname = sname = 0;
2654                 }
2655
2656                 if (!code)
2657                     code = pkrb5_get_credentials(ctx, 0, cc, &increds, &k5creds);
2658             }
2659         }
2660
2661         if (code) {
2662             if ( IsDebuggerPresent() ) {
2663                 char message[256];
2664                 sprintf(message,"krb5_get_credentials returns: %d\n",code);
2665                 OutputDebugString(message);
2666             }
2667             try_krb5 = 0;
2668             goto use_krb4;
2669         }
2670
2671         /* This code inserts the entire K5 ticket into the token
2672          * No need to perform a krb524 translation which is 
2673          * commented out in the code below
2674          */
2675         if (k5creds->ticket.length > MAXKTCTICKETLEN)
2676             goto try_krb524d;
2677
2678         memset(&aserver, '\0', sizeof(aserver));
2679         strncpy(aserver.name, ServiceName, MAXKTCNAMELEN - 1);
2680         strncpy(aserver.cell, CellName, MAXKTCREALMLEN - 1);
2681
2682         memset(&atoken, '\0', sizeof(atoken));
2683         atoken.kvno = RXKAD_TKT_TYPE_KERBEROS_V5;
2684         atoken.startTime = k5creds->times.starttime;
2685         atoken.endTime = k5creds->times.endtime;
2686         memcpy(&atoken.sessionKey, k5creds->keyblock.contents, k5creds->keyblock.length);
2687         atoken.ticketLen = k5creds->ticket.length;
2688         memcpy(atoken.ticket, k5creds->ticket.data, atoken.ticketLen);
2689
2690       retry_gettoken5:
2691         rc = pktc_GetToken(&aserver, &btoken, sizeof(btoken), &aclient);
2692         if (rc != 0 && rc != KTC_NOENT && rc != KTC_NOCELL) {
2693             if ( rc == KTC_NOCM && retry < 20 ) {
2694                 Sleep(500);
2695                 retry++;
2696                 goto retry_gettoken5;
2697             }
2698             goto try_krb524d;
2699         }
2700
2701         if (atoken.kvno == btoken.kvno &&
2702              atoken.ticketLen == btoken.ticketLen &&
2703              !memcmp(&atoken.sessionKey, &btoken.sessionKey, sizeof(atoken.sessionKey)) &&
2704              !memcmp(atoken.ticket, btoken.ticket, atoken.ticketLen)) 
2705         {
2706             /* Success - Nothing to do */
2707             goto cleanup;
2708         }
2709
2710         // * Reset the "aclient" structure before we call ktc_SetToken.
2711         // * This structure was first set by the ktc_GetToken call when
2712         // * we were comparing whether identical tokens already existed.
2713
2714         len = min(k5creds->client->data[0].length,MAXKTCNAMELEN - 1);
2715         strncpy(aclient.name, k5creds->client->data[0].data, len);
2716         aclient.name[len] = '\0';
2717
2718         if ( k5creds->client->length > 1 ) {
2719             char * p;
2720             strcat(aclient.name, ".");
2721             p = aclient.name + strlen(aclient.name);
2722             len = min(k5creds->client->data[1].length,MAXKTCNAMELEN - strlen(aclient.name) - 1);
2723             strncpy(p, k5creds->client->data[1].data, len);
2724             p[len] = '\0';
2725         }
2726         aclient.instance[0] = '\0';
2727
2728         strcpy(aclient.cell, realm_of_cell);
2729
2730         len = min(k5creds->client->realm.length,strlen(realm_of_cell));
2731         if ( strncmp(realm_of_cell, k5creds->client->realm.data, len) ) {
2732             char * p;
2733             strcat(aclient.name, "@");
2734             p = aclient.name + strlen(aclient.name);
2735             len = min(k5creds->client->realm.length,MAXKTCNAMELEN - strlen(aclient.name) - 1);
2736             strncpy(p, k5creds->client->realm.data, len);
2737             p[len] = '\0';
2738         }
2739
2740         if ( smbname ) {
2741             strncpy(aclient.smbname, smbname, MAXRANDOMNAMELEN);
2742             aclient.smbname[MAXRANDOMNAMELEN-1] = '\0';
2743         } else {
2744             aclient.smbname[0] = '\0';
2745         }
2746
2747         rc = pktc_SetToken(&aserver, &atoken, &aclient, 0);
2748         if (!rc)
2749             goto cleanup;   /* We have successfully inserted the token */
2750
2751       try_krb524d:
2752         /* Otherwise, the ticket could have been too large so try to
2753          * convert using the krb524d running with the KDC 
2754          */
2755         code = pkrb524_convert_creds_kdc(ctx, k5creds, &creds);
2756         pkrb5_free_creds(ctx, k5creds);
2757         if (code) {
2758             if ( IsDebuggerPresent() ) {
2759                 char message[256];
2760                 sprintf(message,"krb524_convert_creds_kdc returns: %d\n",code);
2761                 OutputDebugString(message);
2762             }
2763             try_krb5 = 0;
2764             goto use_krb4;
2765         }
2766     } else {
2767       use_krb4:
2768 #ifdef USE_KRB4
2769         code = (*pkrb_get_cred)(ServiceName, CellName, RealmName, &creds);
2770         if (code == NO_TKT_FIL) {
2771             // if the problem is that we have no krb4 tickets
2772             // do not attempt to continue
2773             goto cleanup;
2774         }
2775         if (code != KSUCCESS)
2776             code = (*pkrb_get_cred)(ServiceName, "", RealmName, &creds);
2777
2778         if (code != KSUCCESS)
2779         {
2780             if ((code = (*pkrb_mk_req)(&ticket, ServiceName, CellName, RealmName, 0)) == KSUCCESS)
2781             {
2782                 if ((code = (*pkrb_get_cred)(ServiceName, CellName, RealmName, &creds)) != KSUCCESS)
2783                 {
2784                     goto cleanup;
2785                 }
2786             }
2787             else if ((code = (*pkrb_mk_req)(&ticket, ServiceName, "", RealmName, 0)) == KSUCCESS)
2788             {
2789                 if ((code = (*pkrb_get_cred)(ServiceName, "", RealmName, &creds)) != KSUCCESS)
2790                 {
2791                     goto cleanup;
2792                 }
2793             }
2794             else
2795             {
2796                 goto cleanup;
2797             }
2798         }
2799 #else
2800         goto cleanup;
2801 #endif
2802     }
2803
2804     memset(&aserver, '\0', sizeof(aserver));
2805     strncpy(aserver.name, ServiceName, MAXKTCNAMELEN - 1);
2806     strncpy(aserver.cell, CellName, MAXKTCREALMLEN - 1);
2807
2808     memset(&atoken, '\0', sizeof(atoken));
2809     atoken.kvno = creds.kvno;
2810     atoken.startTime = creds.issue_date;
2811     atoken.endTime = creds.issue_date + life_to_time(0,creds.lifetime);
2812     memcpy(&atoken.sessionKey, creds.session, 8);
2813     atoken.ticketLen = creds.ticket_st.length;
2814     memcpy(atoken.ticket, creds.ticket_st.dat, atoken.ticketLen);
2815
2816   retry_gettoken:
2817     rc = pktc_GetToken(&aserver, &btoken, sizeof(btoken), &aclient);
2818     if (rc != 0 && rc != KTC_NOENT && rc != KTC_NOCELL) {
2819         if ( rc == KTC_NOCM && retry < 20 ) {
2820             Sleep(500);
2821             retry++;
2822             goto retry_gettoken;
2823         }
2824         KFW_AFS_error(rc, "ktc_GetToken()");
2825         code = rc;
2826         goto cleanup;
2827     }
2828
2829     if (atoken.kvno == btoken.kvno &&
2830         atoken.ticketLen == btoken.ticketLen &&
2831         !memcmp(&atoken.sessionKey, &btoken.sessionKey, sizeof(atoken.sessionKey)) &&
2832         !memcmp(atoken.ticket, btoken.ticket, atoken.ticketLen)) 
2833     {
2834         goto cleanup;
2835     }
2836
2837     // * Reset the "aclient" structure before we call ktc_SetToken.
2838     // * This structure was first set by the ktc_GetToken call when
2839     // * we were comparing whether identical tokens already existed.
2840
2841     strncpy(aclient.name, creds.pname, MAXKTCNAMELEN - 1);
2842     if (creds.pinst[0])
2843     {
2844         strncat(aclient.name, ".", MAXKTCNAMELEN - 1);
2845         strncat(aclient.name, creds.pinst, MAXKTCNAMELEN - 1);
2846     }
2847     strcpy(aclient.instance, "");
2848
2849     if ( strcmp(realm_of_cell, creds.realm) ) 
2850     {
2851         strncat(aclient.name, "@", MAXKTCNAMELEN - 1);
2852         strncpy(aclient.name, creds.realm, MAXKTCREALMLEN - 1);
2853     }
2854     aclient.name[MAXKTCREALMLEN-1] = '\0';
2855
2856     strcpy(aclient.cell, CellName);
2857
2858     if ( smbname ) {
2859         strncpy(aclient.smbname, smbname, MAXRANDOMNAMELEN);
2860         aclient.smbname[MAXRANDOMNAMELEN-1] = '\0';
2861     } else {
2862         aclient.smbname[0] = '\0';
2863     }
2864
2865     if (rc = pktc_SetToken(&aserver, &atoken, &aclient, 0))
2866     {
2867         KFW_AFS_error(rc, "ktc_SetToken()");
2868         code = rc;
2869         goto cleanup;
2870     }
2871
2872   cleanup:
2873     if (cname)
2874         pkrb5_free_unparsed_name(ctx,cname);
2875     if (sname)
2876         pkrb5_free_unparsed_name(ctx,sname);
2877     if (client_principal)
2878         pkrb5_free_principal(ctx,client_principal);
2879     /* increds.client == client_principal */
2880     if (increds.server)
2881         pkrb5_free_principal(ctx,increds.server);
2882     if (cc && (cc != alt_cc))
2883         pkrb5_cc_close(ctx, cc);
2884     if (ctx && (ctx != alt_ctx))
2885         pkrb5_free_context(ctx);
2886
2887         return(rc? rc : code);
2888 }
2889
2890 /**************************************/
2891 /* afs_realm_of_cell():               */
2892 /**************************************/
2893 static char *
2894 afs_realm_of_cell(struct afsconf_cell *cellconfig)
2895 {
2896     static char krbrlm[REALM_SZ+1]="";
2897     krb5_context  ctx = 0;
2898     char ** realmlist=NULL;
2899     krb5_error_code r;
2900
2901     if (!cellconfig)
2902         return 0;
2903
2904     if (!pkrb5_init_context)
2905         return 0;
2906
2907     r = pkrb5_init_context(&ctx); 
2908     if ( !r )
2909         r = pkrb5_get_host_realm(ctx, cellconfig->hostName[0], &realmlist);
2910     if ( !r && realmlist && realmlist[0] ) {
2911         strcpy(krbrlm, realmlist[0]);
2912         pkrb5_free_host_realm(ctx, realmlist);
2913     }
2914     if (ctx)
2915         pkrb5_free_context(ctx);
2916
2917     if ( !krbrlm[0] )
2918     {
2919         char *s = krbrlm;
2920         char *t = cellconfig->name;
2921         int c;
2922
2923         while (c = *t++)
2924         {
2925             if (islower(c)) c=toupper(c);
2926             *s++ = c;
2927         }
2928         *s++ = 0;
2929     }
2930     return(krbrlm);
2931 }
2932
2933 /**************************************/
2934 /* KFW_AFS_get_cellconfig():                  */
2935 /**************************************/
2936 int 
2937 KFW_AFS_get_cellconfig(char *cell, struct afsconf_cell *cellconfig, char *local_cell)
2938 {
2939     int rc;
2940     char newcell[MAXCELLCHARS+1];
2941
2942     local_cell[0] = (char)0;
2943     memset(cellconfig, 0, sizeof(*cellconfig));
2944
2945     /* WIN32: cm_GetRootCellName(local_cell) - NOTE: no way to get max chars */
2946     if (rc = pcm_GetRootCellName(local_cell))
2947     {
2948         return(rc);
2949     }
2950
2951     if (strlen(cell) == 0)
2952         strcpy(cell, local_cell);
2953
2954     /* WIN32: cm_SearchCellFile(cell, pcallback, pdata) */
2955     strcpy(cellconfig->name, cell);
2956
2957     return pcm_SearchCellFile(cell, newcell, get_cellconfig_callback, (void*)cellconfig);
2958 }
2959
2960 /**************************************/
2961 /* get_cellconfig_callback():         */
2962 /**************************************/
2963 static long 
2964 get_cellconfig_callback(void *cellconfig, struct sockaddr_in *addrp, char *namep)
2965 {
2966     struct afsconf_cell *cc = (struct afsconf_cell *)cellconfig;
2967
2968     cc->hostAddr[cc->numServers] = *addrp;
2969     strcpy(cc->hostName[cc->numServers], namep);
2970     cc->numServers++;
2971     return(0);
2972 }
2973
2974
2975 /**************************************/
2976 /* KFW_AFS_error():                  */
2977 /**************************************/
2978 void
2979 KFW_AFS_error(LONG rc, LPCSTR FailedFunctionName)
2980 {
2981     char message[256];
2982     const char *errText; 
2983
2984     // Using AFS defines as error messages for now, until Transarc 
2985     // gets back to me with "string" translations of each of these 
2986     // const. defines. 
2987     if (rc == KTC_ERROR)
2988       errText = "KTC_ERROR";
2989     else if (rc == KTC_TOOBIG)
2990       errText = "KTC_TOOBIG";
2991     else if (rc == KTC_INVAL)
2992       errText = "KTC_INVAL";
2993     else if (rc == KTC_NOENT)
2994       errText = "KTC_NOENT";
2995     else if (rc == KTC_PIOCTLFAIL)
2996       errText = "KTC_PIOCTLFAIL";
2997     else if (rc == KTC_NOPIOCTL)
2998       errText = "KTC_NOPIOCTL";
2999     else if (rc == KTC_NOCELL)
3000       errText = "KTC_NOCELL";
3001     else if (rc == KTC_NOCM)
3002       errText = "KTC_NOCM: The service, Transarc AFS Daemon, most likely is not started!";
3003     else
3004       errText = "Unknown error!";
3005
3006     sprintf(message, "%s (0x%x)\n(%s failed)", errText, rc, FailedFunctionName);
3007
3008     if ( IsDebuggerPresent() ) {
3009         OutputDebugString(message);
3010         OutputDebugString("\n");
3011     }
3012     MessageBox(NULL, message, "AFS", MB_OK | MB_ICONERROR | MB_TASKMODAL | MB_SETFOREGROUND);
3013     return;
3014 }
3015
3016 static DWORD 
3017 GetServiceStatus(
3018     LPSTR lpszMachineName, 
3019     LPSTR lpszServiceName,
3020     DWORD *lpdwCurrentState) 
3021
3022     DWORD           hr               = NOERROR; 
3023     SC_HANDLE       schSCManager     = NULL; 
3024     SC_HANDLE       schService       = NULL; 
3025     DWORD           fdwDesiredAccess = 0; 
3026     SERVICE_STATUS  ssServiceStatus  = {0}; 
3027     BOOL            fRet             = FALSE; 
3028
3029     *lpdwCurrentState = 0; 
3030  
3031     fdwDesiredAccess = GENERIC_READ; 
3032  
3033     schSCManager = OpenSCManager(lpszMachineName,  
3034                                  NULL,
3035                                  fdwDesiredAccess); 
3036  
3037     if(schSCManager == NULL) 
3038     { 
3039         hr = GetLastError();
3040         goto cleanup; 
3041     } 
3042  
3043     schService = OpenService(schSCManager,
3044                              lpszServiceName,
3045                              fdwDesiredAccess); 
3046  
3047     if(schService == NULL) 
3048     { 
3049         hr = GetLastError();
3050         goto cleanup; 
3051     } 
3052  
3053     fRet = QueryServiceStatus(schService,
3054                               &ssServiceStatus); 
3055  
3056     if(fRet == FALSE) 
3057     { 
3058         hr = GetLastError(); 
3059         goto cleanup; 
3060     } 
3061  
3062     *lpdwCurrentState = ssServiceStatus.dwCurrentState; 
3063  
3064 cleanup: 
3065  
3066     CloseServiceHandle(schService); 
3067     CloseServiceHandle(schSCManager); 
3068  
3069     return(hr); 
3070
3071
3072 void
3073 UnloadFuncs(
3074     FUNC_INFO fi[], 
3075     HINSTANCE h
3076     )
3077 {
3078     int n;
3079     if (fi)
3080         for (n = 0; fi[n].func_ptr_var; n++)
3081             *(fi[n].func_ptr_var) = 0;
3082     if (h) FreeLibrary(h);
3083 }
3084
3085 int
3086 LoadFuncs(
3087     const char* dll_name, 
3088     FUNC_INFO fi[], 
3089     HINSTANCE* ph,  // [out, optional] - DLL handle
3090     int* pindex,    // [out, optional] - index of last func loaded (-1 if none)
3091     int cleanup,    // cleanup function pointers and unload on error
3092     int go_on,      // continue loading even if some functions cannot be loaded
3093     int silent      // do not pop-up a system dialog if DLL cannot be loaded
3094     )
3095 {
3096     HINSTANCE h;
3097     int i, n, last_i;
3098     int error = 0;
3099     UINT em;
3100
3101     if (ph) *ph = 0;
3102     if (pindex) *pindex = -1;
3103
3104     for (n = 0; fi[n].func_ptr_var; n++)
3105         *(fi[n].func_ptr_var) = 0;
3106
3107     if (silent)
3108         em = SetErrorMode(SEM_FAILCRITICALERRORS);
3109     h = LoadLibrary(dll_name);
3110     if (silent)
3111         SetErrorMode(em);
3112
3113     if (!h)
3114         return 0;
3115
3116     last_i = -1;
3117     for (i = 0; (go_on || !error) && (i < n); i++)
3118     {
3119         void* p = (void*)GetProcAddress(h, fi[i].func_name);
3120         if (!p)
3121             error = 1;
3122         else
3123         {
3124             last_i = i;
3125             *(fi[i].func_ptr_var) = p;
3126         }
3127     }
3128     if (pindex) *pindex = last_i;
3129     if (error && cleanup && !go_on) {
3130         for (i = 0; i < n; i++) {
3131             *(fi[i].func_ptr_var) = 0;
3132         }
3133         FreeLibrary(h);
3134         return 0;
3135     }
3136     if (ph) *ph = h;
3137     if (error) return 0;
3138     return 1;
3139 }
3140
3141 BOOL KFW_probe_kdc(struct afsconf_cell * cellconfig)
3142 {
3143     krb5_context ctx = 0;
3144     krb5_ccache cc = 0;
3145     krb5_error_code code;
3146     krb5_data pwdata;
3147     const char * realm = 0;
3148     krb5_principal principal = 0;
3149     char * pname = 0;
3150     char   password[PROBE_PASSWORD_LEN+1];
3151     BOOL serverReachable = 0;
3152
3153     realm = afs_realm_of_cell(cellconfig);  // do not free
3154
3155     code = pkrb5_build_principal(ctx, &principal, strlen(realm),
3156                                   realm, PROBE_USERNAME, NULL, NULL);
3157     if ( code ) goto cleanup;
3158
3159     code = KFW_get_ccache(ctx, principal, &cc);
3160     if ( code ) goto cleanup;
3161
3162     code = pkrb5_unparse_name(ctx, principal, &pname);
3163     if ( code ) goto cleanup;
3164
3165     pwdata.data = password;
3166     pwdata.length = PROBE_PASSWORD_LEN;
3167     code = pkrb5_c_random_make_octets(ctx, &pwdata);
3168     if (code) {
3169         int i;
3170         for ( i=0 ; i<PROBE_PASSWORD_LEN ; i++ )
3171             password[i] = 'x';
3172     }
3173     password[PROBE_PASSWORD_LEN] = '\0';
3174
3175     code = KFW_kinit(NULL, NULL, HWND_DESKTOP, 
3176                       pname, 
3177                       password,
3178                       5,
3179                       0,
3180                       0,
3181                       0,
3182                       1,
3183                       0);
3184     switch ( code ) {
3185     case KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN:
3186     case KRB5KDC_ERR_CLIENT_REVOKED:
3187     case KRB5KDC_ERR_CLIENT_NOTYET:
3188     case KRB5KDC_ERR_PREAUTH_FAILED:
3189     case KRB5KDC_ERR_PREAUTH_REQUIRED:
3190     case KRB5KDC_ERR_PADATA_TYPE_NOSUPP:
3191         serverReachable = TRUE;
3192         break;
3193     default:
3194         serverReachable = FALSE;
3195     }
3196
3197   cleanup:
3198     if ( pname )
3199         pkrb5_free_unparsed_name(ctx,pname);
3200     if ( principal )
3201         pkrb5_free_principal(ctx,principal);
3202     if (cc)
3203         pkrb5_cc_close(ctx,cc);
3204     if (ctx)
3205         pkrb5_free_context(ctx);
3206
3207     return serverReachable;
3208 }
3209