ee66000321819c7aa47641d5817af521f3cf4acf
[openafs.git] / src / WINNT / aklog / aklog.c
1 /* 
2  *  Copyright (C) 1989,2004 by the Massachusetts Institute of Technology
3  * 
4  * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
5  * distribute this software and its documentation for any purpose and
6  * without fee is hereby granted, provided that the above copyright
7  * notice appear in all copies and that both that copyright notice and
8  * this permission notice appear in supporting documentation, and that
9  * the name of M.I.T. not be used in advertising or publicity pertaining
10  * to distribution of the software without specific, written prior
11  * permission.  M.I.T. makes no representations about the suitability of
12  * this software for any purpose.  It is provided "as is" without express
13  * or implied warranty.
14  */
15
16 /*
17  * Copyright (c) 2007-2008 Secure Endpoints Inc.
18  *
19  * All rights reserved.
20  *
21  * Redistribution and use in source and binary forms, with or without
22  * modification, are permitted provided that the following conditions
23  * are met:
24  *
25  *     * Redistributions of source code must retain the above copyright
26  *       notice, this list of conditions and the following disclaimer.
27  *     * Neither the name of the Secure Endpoints Inc. nor the names of its
28  *       contributors may be used to endorse or promote products derived
29  *       from this software without specific prior written permission.
30  *
31  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
32  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
35  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
36  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
37  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
38  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
39  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
40  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
41  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42  */
43
44 #ifndef _WIN64
45 #define HAVE_KRB4
46 #endif
47
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <ctype.h>
52 #include <sys/types.h>
53 #include <sys/stat.h>
54 #include <errno.h>
55 #include <afs/stds.h>
56 #include <afs/com_err.h>
57 #ifdef HAVE_KRB4
58 #include <krb.h>
59 #else
60 #define REALM_SZ 64
61 #define ANAME_SZ 64
62 #define INST_SZ  64
63 #define KSUCCESS 0
64
65 #define CREDENTIALS void
66 #endif
67 #include <krb5.h>
68 #include <afs/ptserver.h>
69 #include <afs/ptuser.h>
70
71 #ifdef WIN32
72 #include <windows.h>
73
74 #include <cm_config.h>
75 #include <auth.h>
76 #include <cellconfig.h>
77 #include <pioctl_nt.h>
78 #include <smb_iocons.h>
79
80 #define stat _stat
81 #define lstat stat
82 #define __S_ISTYPE(mode, mask) (((mode) & _S_IFMT) == (mask))
83 #define S_ISDIR(mode)          __S_ISTYPE((mode), _S_IFDIR)
84
85 #define DONT_HAVE_GET_AD_TKT
86 #define MAXSYMLINKS 255
87
88 #ifdef HAVE_KRB4
89 /* Win32 uses get_krb_err_txt_entry(status) instead of krb_err_txt[status],
90 * so we use a bit of indirection like the GNU CVS sources.
91 */
92 #define krb_err_text(status) get_krb_err_txt_entry(status)
93 #endif
94
95 #define DRIVECOLON ':'          /* Drive letter separator */
96 #define BDIR '\\'               /* Other character that divides directories */
97
98 static int 
99 readlink(char *path, char *buf, int buffers)
100 {
101         return -1;
102 }
103
104 char * getcwd(char*, size_t);
105
106 static long 
107 get_cellconfig_callback(void *cellconfig, struct sockaddr_in *addrp, char *namep)
108 {
109         struct afsconf_cell *cc = (struct afsconf_cell *) cellconfig;
110
111         cc->hostAddr[cc->numServers] = *addrp;
112         strcpy(cc->hostName[cc->numServers], namep);
113         cc->numServers++;
114         return 0;
115 }
116
117 #else /* WIN32 */
118 #include <sys/param.h>
119 #include <netdb.h>
120 #include <arpa/inet.h>
121 #include <sys/socket.h>
122 #include <unistd.h>
123
124 #include <afs/param.h>
125 #include <afs/auth.h>
126 #include <afs/cellconfig.h>
127 #include <afs/vice.h>
128 #include <afs/venus.h>
129 #include <afs/ptserver.h>
130
131 #define krb_err_text(status) krb_err_txt[status]
132
133 /* Cheesy test for determining AFS 3.5. */
134 #ifndef AFSCONF_CLIENTNAME
135 #define AFS35
136 #endif
137
138 #ifdef AFS35
139 #include <afs/dirpath.h>
140 #else
141 #define AFSDIR_CLIENT_ETC_DIRPATH AFSCONF_CLIENTNAME
142 #endif
143
144 #endif /* WIN32 */
145
146 #include "linked_list.h"
147
148 #define AFSKEY "afs"
149 #define AFSINST ""
150
151 #define AKLOG_SUCCESS 0
152 #define AKLOG_USAGE 1
153 #define AKLOG_SOMETHINGSWRONG 2
154 #define AKLOG_AFS 3
155 #define AKLOG_KERBEROS 4
156 #define AKLOG_TOKEN 5
157 #define AKLOG_BADPATH 6
158 #define AKLOG_MISC 7
159 #define AKLOG_KFW_NOT_INSTALLED 8
160
161 #ifndef NULL
162 #define NULL 0
163 #endif
164
165 #ifndef TRUE
166 #define TRUE 1
167 #endif
168
169 #ifndef FALSE
170 #define FALSE 0
171 #endif
172
173 #ifndef MAXSYMLINKS
174 #define MAXSYMLINKS 15
175 #endif
176
177 #define DIR '/'                 /* Character that divides directories */
178 #define DIRSTRING "/"           /* String form of above */
179 #define VOLMARKER ':'           /* Character separating cellname from mntpt */
180 #define VOLMARKERSTRING ":"     /* String form of above */
181
182 typedef struct {
183     char cell[BUFSIZ];
184     char realm[REALM_SZ];
185 } cellinfo_t;
186
187
188 static char *progname = NULL;   /* Name of this program */
189 static int dflag = FALSE;       /* Give debugging information */
190 static int noprdb = FALSE;      /* Skip resolving name to id? */
191 static int force = FALSE;       /* Bash identical tokens? */
192 static linked_list authedcells; /* List of cells already logged to */
193
194 static int usev5 = TRUE;   /* use kerberos 5? */
195 static int use524 = FALSE;  /* use krb524? */
196 static krb5_context context = 0;
197 static krb5_ccache _krb425_ccache = 0;
198
199 static char * (KRB5_CALLCONV *pkrb5_get_error_message)(krb5_context context, krb5_error_code code)=NULL;
200 static void (KRB5_CALLCONV *pkrb5_free_error_message)(krb5_context context, char *s) = NULL;
201
202 void akexit(int exit_code)
203 {
204     if (_krb425_ccache)
205         krb5_cc_close(context, _krb425_ccache);
206     if (context)
207         krb5_free_context(context);
208     exit(exit_code);
209 }
210
211 /* A com_error bodge. The idea here is that this routine lets us lookup
212  * things in the system com_err, if the AFS one just tells us the error
213  * is unknown
214  */
215
216 void
217 redirect_errors(const char *who, afs_int32 code, const char *fmt, va_list ap)
218 {
219     if (who) {
220         fputs(who, stderr);
221         fputs(": ", stderr);
222     }
223     if (code) {
224         int freestr = 0;
225         char *str = (char *)afs_error_message(code);
226         if (strncmp(str, "unknown", strlen(str)) == 0) {
227             if (pkrb5_get_error_message) {
228                 str = pkrb5_get_error_message(NULL, code);
229                 freestr = 1;
230             } else
231                 str = (char *)error_message(code);
232         }
233         fputs(str, stderr);
234         fputs(" ", stderr);
235         if (freestr)
236             pkrb5_free_error_message(NULL, str);
237     }
238     if (fmt) {
239         vfprintf(stderr, fmt, ap);
240     }
241     putc('\n', stderr);
242     fflush(stderr);
243 }
244
245 long GetLocalCell(struct afsconf_dir **pconfigdir, char *local_cell)
246 {
247     if (!(*pconfigdir = afsconf_Open(AFSDIR_CLIENT_ETC_DIRPATH)))
248     {
249         fprintf(stderr, "%s: can't get afs configuration (afsconf_Open(%s))\n",
250                  progname, AFSDIR_CLIENT_ETC_DIRPATH);
251         akexit(AKLOG_AFS);
252     }
253
254     return afsconf_GetLocalCell(*pconfigdir, local_cell, MAXCELLCHARS);
255 }
256
257 long GetCellInfo(struct afsconf_dir **pconfigdir, char* cell, 
258 struct afsconf_cell **pcellconfig)
259 {
260     return afsconf_GetCellInfo(*pconfigdir, cell, NULL, *pcellconfig);
261 }
262
263 void CloseConf(struct afsconf_dir **pconfigdir)
264 {       
265     (void) afsconf_Close(*pconfigdir);
266 }
267
268 #define ALLOW_REGISTER 1
269 void ViceIDToUsername(char *username, char *realm_of_user, char *realm_of_cell,
270                       char * cell_to_use, CREDENTIALS *c,
271                       int *status, 
272                       struct ktc_principal *aclient, struct ktc_principal *aserver, struct ktc_token *atoken)
273 {
274     static char lastcell[MAXCELLCHARS+1] = { 0 };
275     static char confname[512] = { 0 };
276     char username_copy[BUFSIZ];
277     afs_int32 viceId;                   /* AFS uid of user */
278
279     if (confname[0] == '\0') {
280         strncpy(confname, AFSDIR_CLIENT_ETC_DIRPATH, sizeof(confname));
281         confname[sizeof(confname) - 2] = '\0';
282     }
283
284     if (dflag)
285         printf("About to resolve name %s to id\n", username);
286
287     strcpy(lastcell, aserver->cell);
288
289     if (!pr_Initialize (0, confname, aserver->cell)) {
290         char sname[PR_MAXNAMELEN], *at;
291
292         strncpy(sname, username, PR_MAXNAMELEN);
293         sname[PR_MAXNAMELEN-1] = '\0';
294
295         at = strchr(sname, '@');
296         if (at && !stricmp(at+1, realm_of_cell))
297             *at = '\0';
298         *status = pr_SNameToId (sname, &viceId);
299     }
300
301     if (dflag)
302     {
303         if (*status)
304             printf("pr_SNameToId Error %s\n",  afs_error_message(*status));
305         else
306             printf("Id %d\n", viceId);
307     }       
308
309     /*
310      * This code is taken from cklog -- it lets people
311      * automatically register with the ptserver in foreign cells
312      */
313
314 #ifdef ALLOW_REGISTER
315     if (*status == 0) {
316         if (viceId != ANONYMOUSID) {
317 #else /* ALLOW_REGISTER */
318             if ((*status == 0) && (viceId != ANONYMOUSID))
319 #endif /* ALLOW_REGISTER */
320             {
321 #ifdef AFS_ID_TO_NAME
322                 strncpy(username_copy, username, BUFSIZ);
323                 snprintf (username, BUFSIZ, "%s (AFS ID %d)", username_copy, (int) viceId);
324 #endif /* AFS_ID_TO_NAME */
325             }
326 #ifdef ALLOW_REGISTER
327         } else if (strcmp(realm_of_user, realm_of_cell) != 0) {
328             int i;
329             if (dflag) {
330                 printf("doing first-time registration of %s "
331                         "at %s\n", username, cell_to_use);
332             }
333             strncpy(aclient->name, username, MAXKTCNAMELEN - 1);
334             aclient->name[MAXKTCNAMELEN - 1] = '\0';
335             strcpy(aclient->instance, "");
336             strncpy(aclient->cell, cell_to_use, MAXKTCREALMLEN - 1);
337             aclient->cell[MAXKTCREALMLEN - 1] = '\0';
338
339             for ( i=0; aclient->cell[i]; i++ ) {
340                 if ( islower(aclient->cell[i]) )
341                     aclient->cell[i] = toupper(aclient->cell[i]);
342             }
343
344             if ((*status = ktc_SetToken(aserver, atoken, aclient, 0))) {
345                 afs_com_err(progname, *status,
346                              "while obtaining tokens for cell %s\n",
347                              cell_to_use);
348                 *status = AKLOG_TOKEN;
349                 return ;
350             }
351
352             /*
353              * In case you're wondering, we don't need to change the
354              * filename here because we're still connecting to the
355              * same cell -- we're just using a different authentication
356              * level
357              */
358
359             if ((*status = pr_Initialize(1L, confname, aserver->cell))) {
360                 printf("pr_Initialize Error %s\n",  afs_error_message(*status));
361                 return;
362             }
363
364             /* copy the name because pr_CreateUser lowercases the realm */
365             strncpy(username_copy, username, BUFSIZ);
366
367             viceId = 0;
368             *status = pr_CreateUser(username_copy, &viceId);
369
370             if (*status) {
371                 printf("%s: unable to create remote PTS "
372                         "user %s in cell %s (status: %s).\n", progname,
373                         username_copy, cell_to_use, afs_error_message(*status));
374             } else {
375                 printf("created cross-cell entry for %s (Id %d) at %s\n",
376                         username_copy, viceId, cell_to_use);
377 #ifdef AFS_ID_TO_NAME
378                 snprintf (username, BUFSIZ, "%s (AFS ID %d)", username_copy, (int) viceId);
379 #endif /* AFS_ID_TO_NAME */
380             }
381         }
382     }
383 #endif /* ALLOW_REGISTER */
384 }
385
386 char *LastComponent(char *str)
387 {
388     char *ret = strrchr(str, DIR);
389
390 #ifdef WIN32
391     if (!ret)
392         ret = strrchr(str, BDIR);
393 #endif
394     return ret;
395 }
396
397 int FirstComponent(char *str)
398 {
399     return (int)(
400 #ifdef WIN32
401                 strchr(str, BDIR) ||
402 #endif
403                 strchr(str, DIR));
404 }
405
406 void CopyPathColon(char *origpath, char *path, char *pathtocheck)
407 {
408 #ifdef WIN32
409     if (origpath[1] == DRIVECOLON)
410     {
411         strncpy(pathtocheck, origpath, 2);
412         strcpy(path, origpath+2);
413     }
414     else
415 #endif
416         strcpy(path, origpath);
417 }
418
419 int BeginsWithDir(char *str, int colon)
420 {
421     return (str[0] == DIR) ||
422 #ifdef WIN32
423         ((str[0] == BDIR) || (colon && str[1] == DRIVECOLON));
424 #else
425     FALSE;
426 #endif
427 }
428
429
430 /* This is a pretty gross hack.  Linking against the Transarc
431 * libraries pulls in some rxkad functions which use des.  (I don't
432 * think they ever get called.)  With Transarc-supplied libraries this
433 * creates a reliance on the symbol des_pcbc_init() which is only in
434 * Transarc's DES libraries (it's an exportability symbol-hiding
435 * thing), which we don't want to use because they don't work with
436 * MIT's krb4 routines.  So export a des_pcbc_init() symbol here so we
437 * don't have to link against Transarc's des library.
438 */
439 int des_pcbc_init()
440 {
441     abort();
442     return 0;   /* avoid warning */
443 }
444
445 #ifdef HAVE_KRB4
446 static int get_cred(char *name, char *inst, char *realm, CREDENTIALS *c)
447 {
448     int status;
449
450     status = krb_get_cred(name, inst, realm, c);
451     if (status != KSUCCESS)
452     {
453 #ifdef DONT_HAVE_GET_AD_TKT
454         KTEXT_ST ticket;
455         status = krb_mk_req(&ticket, name, inst, realm, 0);
456 #else
457         status = get_ad_tkt(name, inst, realm, 255);
458 #endif
459         if (status == KSUCCESS)
460             status = krb_get_cred(name, inst, realm, c);
461     }       
462
463     return (status);
464 }
465 #endif
466
467 static int get_v5cred(krb5_context context, 
468                       char *name, char *inst, char *realm, CREDENTIALS *c,
469                       krb5_creds **creds)
470 {
471     krb5_creds increds;
472     krb5_error_code r;
473     static krb5_principal client_principal = 0;
474
475     if (client_principal) {
476         krb5_free_principal(context, client_principal);
477         client_principal = 0;
478     }
479
480     memset(&increds, 0, sizeof(increds));
481
482     if ((r = krb5_build_principal(context, &increds.server,
483                                   (int)strlen(realm), realm,
484                                   name,
485                                   (inst && strlen(inst)) ? inst : 0,
486                                   0))) {
487         return((int)r);
488     }
489
490     if (!_krb425_ccache) {
491         if ((r = krb5_cc_default(context, &_krb425_ccache)))
492             return ((int)r);
493     }
494     if (!client_principal) {
495         if ((r = krb5_cc_get_principal(context, _krb425_ccache, &client_principal))) {
496             krb5_cc_close(context, _krb425_ccache);
497             return ((int)r);
498         }
499     }
500
501     increds.client = client_principal;
502     increds.times.endtime = 0;
503         /* Ask for DES since that is what V4 understands */
504     increds.keyblock.enctype = ENCTYPE_DES_CBC_CRC;
505
506     r = krb5_get_credentials(context, 0, _krb425_ccache, &increds, creds);
507     if (r) {
508         return((int)r);
509     }
510     /* This requires krb524d to be running with the KDC */
511     if (c != NULL)
512         r = krb5_524_convert_creds(context, *creds, c);
513
514     return((int)r);
515 }
516
517 #ifdef HAVE_KRB4
518 /* There is no header for this function.  It is supposed to be private */
519 int krb_get_admhst(char *h,char *r, int n);
520
521 static char *afs_realm_of_cell(struct afsconf_cell *cellconfig)
522 {
523     char krbhst[MAX_HSTNM];
524     static char krbrlm[REALM_SZ+1];
525
526     if (!cellconfig)
527         return 0;
528
529     strcpy(krbrlm, (char *) krb_realmofhost(cellconfig->hostName[0]));
530
531     if (krb_get_admhst(krbhst, krbrlm, 1) != KSUCCESS)
532     {
533         char *s = krbrlm;
534         char *t = cellconfig->name;
535         int c;
536
537         while (c = *t++)
538         {
539             if (islower(c))
540                 c = toupper(c);
541             *s++ = c;
542         }
543         *s++ = 0;
544     }
545     return krbrlm;
546 }
547 #endif
548
549 /* As of MIT Kerberos 1.6, krb5_get_host_realm() will return the NUL-string 
550  * if there is no domain_realm mapping for the hostname's domain.  This is 
551  * used as a trigger indicating that referrals should be used within the
552  * krb5_get_credentials() call.  However, if the KDC does not support referrals
553  * that will result in a KRB5_ERR_HOST_REALM_UNKNOWN error and we will have
554  * to manually fallback to mapping the domain of the host as a realm name.
555  * Hence, the new fallback parameter.
556  */
557 static char *afs_realm_of_cell5(krb5_context context, struct afsconf_cell *cellconfig, int fallback)
558 {
559     char ** krbrlms = 0;
560     static char krbrlm[REALM_SZ+1];
561     krb5_error_code status;
562
563     if (!cellconfig)
564         return 0;
565
566     if (fallback) {
567         char * p;
568         p = strchr(cellconfig->hostName[0], '.');
569         if (p++)
570             strcpy(krbrlm, p);
571         else
572             strcpy(krbrlm, cellconfig->name);
573         strupr(krbrlm);
574     } else {
575         status = krb5_get_host_realm( context, cellconfig->hostName[0], &krbrlms );
576         if (status == 0 && krbrlms && krbrlms[0]) {
577             strcpy(krbrlm, krbrlms[0]);
578         } else {
579             strcpy(krbrlm, cellconfig->name);
580             strupr(krbrlm);
581         }
582
583         if (krbrlms)
584             krb5_free_host_realm( context, krbrlms );
585     }
586     return krbrlm;
587 }       
588
589 static char *copy_cellinfo(cellinfo_t *cellinfo)
590 {
591     cellinfo_t *new_cellinfo;
592
593     if (new_cellinfo = (cellinfo_t *)malloc(sizeof(cellinfo_t)))
594         memcpy(new_cellinfo, cellinfo, sizeof(cellinfo_t));
595
596     return ((char *)new_cellinfo);
597 }
598
599
600 static int get_cellconfig(char *cell, struct afsconf_cell *cellconfig,
601                                                   char *local_cell)
602 {
603     int status = AKLOG_SUCCESS;
604     struct afsconf_dir *configdir = 0;
605
606     memset(local_cell, 0, sizeof(local_cell));
607     memset(cellconfig, 0, sizeof(*cellconfig));
608
609     if (GetLocalCell(&configdir, local_cell))
610     {
611         fprintf(stderr, "%s: can't determine local cell.\n", progname);
612         akexit(AKLOG_AFS);
613     }
614
615     if ((cell == NULL) || (cell[0] == 0))
616         cell = local_cell;
617
618     if (GetCellInfo(&configdir, cell, &cellconfig))
619     {
620         fprintf(stderr, "%s: Can't get information about cell %s.\n",
621                 progname, cell);
622         status = AKLOG_AFS;
623     }
624
625     if (cellconfig->linkedCell)
626         cellconfig->linkedCell = strdup(cellconfig->linkedCell);
627
628     CloseConf(&configdir);
629
630     return(status);
631 }
632
633 static int get_v5_user_realm(krb5_context context,char *realm)
634 {
635     static krb5_principal client_principal = 0;
636     krb5_error_code code;
637     int i;
638
639     if (!_krb425_ccache) {
640         code = krb5_cc_default(context, &_krb425_ccache);
641         if (code)
642             return(code);
643     }
644     if (!client_principal) {
645         code = krb5_cc_get_principal(context, _krb425_ccache, &client_principal);
646         if (code)
647             return(code);
648     }
649     i = krb5_princ_realm(context, client_principal)->length;
650     if (i < REALM_SZ-1) i = REALM_SZ-1;
651     strncpy(realm,krb5_princ_realm(context, client_principal)->data,i);
652     realm[i] = 0;
653     return(KSUCCESS);
654 }
655
656 static void
657 copy_realm_of_ticket(krb5_context context, char * dest, size_t destlen, krb5_creds *v5cred) {
658     krb5_error_code code;
659     krb5_ticket *ticket;
660     size_t len;
661
662     code = krb5_decode_ticket(&v5cred->ticket, &ticket);
663     if (code == 0) {
664         len = krb5_princ_realm(context, ticket->server)->length;
665         if (len > destlen - 1)
666             len = destlen - 1;
667
668         strncpy(dest, krb5_princ_realm(context, ticket->server)->data, len);
669         dest[len] = '\0';
670
671         krb5_free_ticket(context, ticket);
672     }
673 }
674
675 /*
676 * Log to a cell.  If the cell has already been logged to, return without
677 * doing anything.  Otherwise, log to it and mark that it has been logged
678 * to.  */
679 static int auth_to_cell(krb5_context context, char *cell, char *realm)
680 {
681     int status = AKLOG_SUCCESS;
682     char username[BUFSIZ];        /* To hold client username structure */
683
684     char name[ANAME_SZ];          /* Name of afs key */
685     char instance[INST_SZ];       /* Instance of afs key */
686     char realm_of_user[REALM_SZ]; /* Kerberos realm of user */
687     char realm_of_cell[REALM_SZ]; /* Kerberos realm of cell */
688     char local_cell[MAXCELLCHARS+1];
689     char cell_to_use[MAXCELLCHARS+1]; /* Cell to authenticate to */
690
691     krb5_creds *v5cred = NULL;
692 #ifdef HAVE_KRB4
693     CREDENTIALS c;
694 #endif
695     struct ktc_principal aserver;
696     struct ktc_principal aclient;
697     struct ktc_token atoken, btoken;
698     struct afsconf_cell ak_cellconfig; /* General information about the cell */
699     int i;
700     int getLinkedCell = 0;
701
702     /* try to avoid an expensive call to get_cellconfig */
703     if (cell && ll_string_check(&authedcells, cell))
704     {
705         if (dflag)
706             printf("Already authenticated to %s (or tried to)\n", cell);
707         return(AKLOG_SUCCESS);
708     }
709
710     memset(name, 0, sizeof(name));
711     memset(instance, 0, sizeof(instance));
712     memset(realm_of_user, 0, sizeof(realm_of_user));
713     memset(realm_of_cell, 0, sizeof(realm_of_cell));
714     memset(&ak_cellconfig, 0, sizeof(ak_cellconfig));
715
716     /* NULL or empty cell returns information on local cell */
717     if (status = get_cellconfig(cell, &ak_cellconfig, local_cell))
718         return(status);
719
720   linkedCell:
721     if (getLinkedCell)
722         strncpy(cell_to_use, ak_cellconfig.linkedCell, MAXCELLCHARS);
723     else
724         strncpy(cell_to_use, ak_cellconfig.name, MAXCELLCHARS);
725     cell_to_use[MAXCELLCHARS] = 0;
726
727     if (ll_string_check(&authedcells, cell_to_use))
728     {
729         if (dflag)
730             printf("Already authenticated to %s (or tried to)\n", cell_to_use);
731         status = AKLOG_SUCCESS;
732         goto done2;
733     }
734
735     /*
736      * Record that we have attempted to log to this cell.  We do this
737      * before we try rather than after so that we will not try
738      * and fail repeatedly for one cell.
739      */
740     (void)ll_add_string(&authedcells, cell_to_use);
741
742     if (dflag)
743         printf("Authenticating to cell %s.\n", cell_to_use);
744
745     /* We use the afs.<cellname> convention here... */
746     strcpy(name, AFSKEY);
747     strncpy(instance, cell_to_use, sizeof(instance));
748     instance[sizeof(instance)-1] = '\0';
749
750     /*
751      * Extract the session key from the ticket file and hand-frob an
752      * afs style authenticator.
753      */
754
755     if (usev5) 
756     { /* using krb5 */
757         int retry = 1;
758         int realm_fallback = 0;
759
760         if ((status = get_v5_user_realm(context, realm_of_user)) != KSUCCESS) {
761             char * msg;
762             
763             if (pkrb5_get_error_message)
764                 msg = pkrb5_get_error_message(context, status);
765             else
766                 msg = (char *)error_message(status);
767             fprintf(stderr, "%s: Couldn't determine realm of user: %s\n",
768                      progname, msg);
769             if (pkrb5_free_error_message)
770                 pkrb5_free_error_message(context, msg);
771             status = AKLOG_KERBEROS;
772             goto done;
773         }
774
775         if ( strchr(name,'.') != NULL ) {
776             fprintf(stderr, "%s: Can't support principal names including a dot.\n",
777                     progname);
778             status = AKLOG_MISC;
779             goto done;
780         }
781
782       try_v5:
783         if (realm && realm[0]) {
784             if (dflag)
785                 printf("Getting v5 tickets: %s/%s@%s\n", name, instance, realm);
786             status = get_v5cred(context, name, instance, realm, 
787 #ifdef HAVE_KRB4
788                             use524 ? &c : NULL, 
789 #else
790                             NULL,
791 #endif
792                             &v5cred);
793             strcpy(realm_of_cell, realm);
794         } else {
795             strcpy(realm_of_cell,
796                     afs_realm_of_cell5(context, &ak_cellconfig, realm_fallback));
797
798             if (retry == 1 && realm_fallback == 0) {
799                 /* Only try the realm_of_user once */
800                 status = -1;
801                 if (dflag)
802                     printf("Getting v5 tickets: %s/%s@%s\n", name, instance, realm_of_user);
803                 status = get_v5cred(context, name, instance, realm_of_user, 
804 #ifdef HAVE_KRB4
805                                      use524 ? &c : NULL, 
806 #else
807                                      NULL,
808 #endif
809                                      &v5cred);
810                 if (status == 0) {
811                     /* we have determined that the client realm 
812                      * is a valid cell realm
813                      */
814                     strcpy(realm_of_cell, realm_of_user);
815                 }
816             }
817
818             if (status != 0 && (!retry || retry && strcmp(realm_of_user,realm_of_cell))) {
819                 if (dflag)
820                     printf("Getting v5 tickets: %s/%s@%s\n", name, instance, realm_of_cell);
821                 status = get_v5cred(context, name, instance, realm_of_cell, 
822 #ifdef HAVE_KRB4
823                                      use524 ? &c : NULL, 
824 #else
825                                      NULL,
826 #endif
827                                      &v5cred);
828                 if (!status && !strlen(realm_of_cell)) 
829                     copy_realm_of_ticket(context, realm_of_cell, sizeof(realm_of_cell), v5cred);
830             }
831         }
832
833         if (!realm_fallback && status == KRB5_ERR_HOST_REALM_UNKNOWN) {
834             realm_fallback = 1;
835             goto try_v5;
836         } else if (status == KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN) {
837             if (!realm_fallback && !realm_of_cell[0]) {
838                 realm_fallback = 1;
839                 goto try_v5;
840             }
841             if (dflag)
842                 printf("Getting v5 tickets: %s@%s\n", name, realm_of_cell);
843             status = get_v5cred(context, name, "", realm_of_cell, 
844 #ifdef HAVE_KRB4
845                                 use524 ? &c : NULL, 
846 #else
847                                 NULL,
848 #endif
849                                 &v5cred);
850             if (!status && !strlen(realm_of_cell)) 
851                 copy_realm_of_ticket(context, realm_of_cell, sizeof(realm_of_cell), v5cred);
852         }
853      
854         if ( status == KRB5KRB_AP_ERR_MSG_TYPE && retry ) {
855             retry = 0;
856             realm_fallback = 0;
857             goto try_v5;
858         }       
859     }       
860     else 
861     {
862 #ifdef HAVE_KRB4
863         if (realm && realm[0])
864             strcpy(realm_of_cell, realm);
865         else
866             strcpy(realm_of_cell, afs_realm_of_cell(&ak_cellconfig));
867
868         /*
869          * Try to obtain AFS tickets.  Because there are two valid service
870          * names, we will try both, but trying the more specific first.
871          *
872          *      afs.<cell>@<realm>
873          *      afs@<realm>
874          */
875         if (dflag)
876             printf("Getting tickets: %s.%s@%s\n", name, instance, realm_of_cell);
877         status = get_cred(name, instance, realm_of_cell, &c);
878         if (status == KDC_PR_UNKNOWN)
879         {
880             if (dflag)
881                 printf("Getting tickets: %s@%s\n", name, realm_of_cell);
882             status = get_cred(name, "", realm_of_cell, &c);
883         }
884 #else
885         status = AKLOG_MISC;
886         goto done;
887 #endif
888     } 
889
890     if (status != KSUCCESS)
891     {
892         char * msg = NULL;
893         if (dflag)
894             printf("Kerberos error code returned by get_cred: %d\n", status);
895
896         if (usev5) {
897             if (pkrb5_get_error_message)
898                 msg = pkrb5_get_error_message(context, status);
899             else
900                 msg = (char *)error_message(status);
901         }
902 #ifdef HAVE_KRB4
903         else
904             msg = krb_err_text(status);
905 #endif
906         fprintf(stderr, "%s: Couldn't get %s AFS tickets: %s\n",
907                  progname, cell_to_use, msg?msg:"(unknown error)");
908         if (usev5 && pkrb5_free_error_message)
909             pkrb5_free_error_message(context, msg);
910         status = AKLOG_KERBEROS;
911         goto done;
912     }
913
914     strncpy(aserver.name, AFSKEY, MAXKTCNAMELEN - 1);
915     strncpy(aserver.instance, AFSINST, MAXKTCNAMELEN - 1);
916     strncpy(aserver.cell, cell_to_use, MAXKTCREALMLEN - 1);
917
918     if (usev5 && !use524) {
919         /* This code inserts the entire K5 ticket into the token
920          * No need to perform a krb524 translation which is
921          * commented out in the code below
922          */
923         char * p;
924         int len;
925         
926         len = min(v5cred->client->data[0].length,MAXKTCNAMELEN - 1);
927         strncpy(username, v5cred->client->data[0].data, len);
928         username[len] = '\0';
929
930         if ( v5cred->client->length > 1 ) {
931             strcat(username, ".");
932             p = username + strlen(username);
933             len = min(v5cred->client->data[1].length, (unsigned int)(MAXKTCNAMELEN - strlen(username) - 1));
934             strncpy(p, v5cred->client->data[1].data, len);
935             p[len] = '\0';
936         }
937
938         memset(&atoken, '\0', sizeof(atoken));
939         atoken.kvno = RXKAD_TKT_TYPE_KERBEROS_V5;
940         atoken.startTime = v5cred->times.starttime;
941         atoken.endTime = v5cred->times.endtime;
942         memcpy(&atoken.sessionKey, v5cred->keyblock.contents, v5cred->keyblock.length);
943         atoken.ticketLen = v5cred->ticket.length;
944         memcpy(atoken.ticket, v5cred->ticket.data, atoken.ticketLen);
945     } else {
946 #ifdef HAVE_KRB4
947         strcpy (username, c.pname);
948         if (c.pinst[0])
949         {
950             strcat(username, ".");
951             strcat(username, c.pinst);
952         }
953
954         atoken.kvno = c.kvno;
955         atoken.startTime = c.issue_date;
956         /* ticket lifetime is in five-minutes blocks. */
957         atoken.endTime = c.issue_date + ((unsigned char)c.lifetime * 5 * 60);
958
959         memcpy(&atoken.sessionKey, c.session, 8);
960         atoken.ticketLen = c.ticket_st.length;
961         memcpy(atoken.ticket, c.ticket_st.dat, atoken.ticketLen);
962 #else
963         status = AKLOG_MISC;
964         goto done;
965 #endif
966     }
967
968     if (!force &&
969          !ktc_GetToken(&aserver, &btoken, sizeof(btoken), &aclient) &&
970          atoken.kvno == btoken.kvno &&
971          atoken.ticketLen == btoken.ticketLen &&
972          !memcmp(&atoken.sessionKey, &btoken.sessionKey, sizeof(atoken.sessionKey)) &&
973          !memcmp(atoken.ticket, btoken.ticket, atoken.ticketLen))
974     {       
975         if (dflag)
976             printf("Identical tokens already exist; skipping.\n");
977         status = AKLOG_SUCCESS;
978         goto done2;
979     }
980
981     if (noprdb)
982     {
983         if (dflag)
984             printf("Not resolving name %s to id (-noprdb set)\n", username);
985     }       
986     else    
987     {
988         if (!usev5) {
989 #ifdef HAVE_KRB4
990             if ((status = krb_get_tf_realm(TKT_FILE, realm_of_user)) != KSUCCESS)
991             {
992                 fprintf(stderr, "%s: Couldn't determine realm of user: %s)",
993                          progname, krb_err_text(status));
994                 status = AKLOG_KERBEROS;
995                 goto done;
996             }
997 #else
998             status = AKLOG_MISC;
999             goto done;
1000 #endif
1001         }
1002
1003         /* For Network Identity Manager append the realm to the name */
1004         strcat(username, "@");
1005         strcat(username, realm_of_user);
1006
1007         ViceIDToUsername(username, realm_of_user, realm_of_cell, cell_to_use, 
1008 #ifdef HAVE_KRB4
1009                           &c, 
1010 #else
1011                           NULL,
1012 #endif
1013                           &status, &aclient, &aserver, &atoken);
1014     }
1015
1016     if (dflag)
1017         printf("Set username to %s\n", username);
1018
1019     /* Reset the "aclient" structure before we call ktc_SetToken.
1020      * This structure was first set by the ktc_GetToken call when
1021      * we were comparing whether identical tokens already existed.
1022      */
1023     strncpy(aclient.name, username, MAXKTCNAMELEN - 1);
1024     strcpy(aclient.instance, "");
1025     
1026     if (usev5 && !use524) {
1027         int len = min(v5cred->client->realm.length,MAXKTCNAMELEN - 1);
1028         strncpy(aclient.cell, v5cred->client->realm.data, len);
1029         aclient.cell[len] = '\0';
1030     } 
1031 #ifdef HAVE_KRB4
1032     else
1033         strncpy(aclient.cell, c.realm, MAXKTCREALMLEN - 1);
1034 #endif
1035
1036     for ( i=0; aclient.cell[i]; i++ ) {
1037         if ( islower(aclient.cell[i]) )
1038             aclient.cell[i] = toupper(aclient.cell[i]);
1039     }
1040
1041     if (dflag)
1042         printf("Getting tokens.\n");
1043     if (status = ktc_SetToken(&aserver, &atoken, &aclient, 0))
1044     {
1045         afs_com_err(progname, status,
1046                      "while obtaining tokens for cell %s\n",
1047                      cell_to_use);
1048         status = AKLOG_TOKEN;
1049     }
1050
1051   done2:
1052     if (ak_cellconfig.linkedCell && !getLinkedCell) {
1053         getLinkedCell = 1;
1054         goto linkedCell;
1055     }
1056
1057   done:
1058 #if 0
1059     /* 
1060      * intentionally leak the linkedCell field because it was allocated
1061      * using a different C RTL version.
1062      */
1063     if (ak_cellconfig.linkedCell)
1064         free(ak_cellconfig.linkedCell);
1065 #endif
1066     return(status);
1067 }
1068
1069 static int get_afs_mountpoint(char *file, char *mountpoint, int size)
1070 {
1071     char our_file[MAXPATHLEN + 1];
1072     char *parent_dir;
1073     char *last_component;
1074     struct ViceIoctl vio;
1075     char cellname[BUFSIZ];
1076
1077     memset(our_file, 0, sizeof(our_file));
1078     strcpy(our_file, file);
1079
1080     if (last_component = LastComponent(our_file))
1081     {
1082         *last_component++ = 0;
1083         parent_dir = our_file;
1084     }
1085     else
1086     {
1087         last_component = our_file;
1088         parent_dir = ".";
1089     }
1090
1091     memset(cellname, 0, sizeof(cellname));
1092
1093     vio.in = last_component;
1094     vio.in_size = (long)strlen(last_component)+1;
1095     vio.out_size = size;
1096     vio.out = mountpoint;
1097
1098     if (!pioctl(parent_dir, VIOC_AFS_STAT_MT_PT, &vio, 0))
1099     {
1100         if (strchr(mountpoint, VOLMARKER) == NULL)
1101         {
1102             vio.in = file;
1103             vio.in_size = (long)strlen(file) + 1;
1104             vio.out_size = sizeof(cellname);
1105             vio.out = cellname;
1106
1107             if (!pioctl(file, VIOC_FILE_CELL_NAME, &vio, 1))
1108             {
1109                 strcat(cellname, VOLMARKERSTRING);
1110                 strcat(cellname, mountpoint + 1);
1111                 memset(mountpoint + 1, 0, size - 1);
1112                 strcpy(mountpoint + 1, cellname);
1113             }
1114         }
1115         return(TRUE);
1116     }
1117     else {
1118         return(FALSE);
1119     }
1120 }       
1121
1122 /*
1123 * This routine each time it is called returns the next directory
1124 * down a pathname.  It resolves all symbolic links.  The first time
1125 * it is called, it should be called with the name of the path
1126 * to be descended.  After that, it should be called with the arguemnt
1127 * NULL.
1128 */
1129 static char *next_path(char *origpath)
1130 {
1131     static char path[MAXPATHLEN + 1];
1132     static char pathtocheck[MAXPATHLEN + 1];
1133
1134     int link = FALSE;           /* Is this a symbolic link? */
1135     char linkbuf[MAXPATHLEN + 1];
1136     char tmpbuf[MAXPATHLEN + 1];
1137
1138     static char *last_comp;     /* last component of directory name */
1139     static char *elast_comp;    /* End of last component */
1140     char *t;
1141     int len;
1142
1143     static int symlinkcount = 0;        /* We can't exceed MAXSYMLINKS */
1144
1145     /* If we are given something for origpath, we are initializing only. */
1146     if (origpath)
1147     {
1148         memset(path, 0, sizeof(path));
1149         memset(pathtocheck, 0, sizeof(pathtocheck));
1150         CopyPathColon(origpath, path, pathtocheck);
1151         last_comp = path;
1152         symlinkcount = 0;
1153         return(NULL);
1154     }
1155
1156     /* We were not given origpath; find then next path to check */
1157
1158     /* If we've gotten all the way through already, return NULL */
1159     if (last_comp == NULL)
1160         return(NULL);
1161
1162     do
1163     {
1164         while (BeginsWithDir(last_comp, FALSE))
1165             strncat(pathtocheck, last_comp++, 1);
1166         len = (int) ((elast_comp = LastComponent(last_comp))
1167             ? elast_comp - last_comp : strlen(last_comp));
1168         strncat(pathtocheck, last_comp, len);
1169         memset(linkbuf, 0, sizeof(linkbuf));
1170         if (link = (readlink(pathtocheck, linkbuf, sizeof(linkbuf)) > 0))
1171         {
1172             if (++symlinkcount > MAXSYMLINKS)
1173             {
1174                 fprintf(stderr, "%s: %s\n", progname, strerror(ELOOP));
1175                 akexit(AKLOG_BADPATH);
1176             }
1177             memset(tmpbuf, 0, sizeof(tmpbuf));
1178             if (elast_comp)
1179                 strcpy(tmpbuf, elast_comp);
1180             if (BeginsWithDir(linkbuf, FALSE))
1181             {
1182                 /*
1183                 * If this is a symbolic link to an absolute path,
1184                 * replace what we have by the absolute path.
1185                 */
1186                 memset(path, 0, strlen(path));
1187                 memcpy(path, linkbuf, sizeof(linkbuf));
1188                 strcat(path, tmpbuf);
1189                 last_comp = path;
1190                 elast_comp = NULL;
1191                 memset(pathtocheck, 0, sizeof(pathtocheck));
1192             }
1193             else
1194             {
1195                 /*
1196                 * If this is a symbolic link to a relative path,
1197                 * replace only the last component with the link name.
1198                 */
1199                 strncpy(last_comp, linkbuf, strlen(linkbuf) + 1);
1200                 strcat(path, tmpbuf);
1201                 elast_comp = NULL;
1202                 if (t = LastComponent(pathtocheck))
1203                 {
1204                     t++;
1205                     memset(t, 0, strlen(t));
1206                 }
1207                 else
1208                     memset(pathtocheck, 0, sizeof(pathtocheck));
1209             }
1210         }
1211         else
1212             last_comp = elast_comp;
1213     }       
1214     while(link);
1215
1216     return(pathtocheck);
1217 }
1218
1219 /*
1220 * This routine descends through a path to a directory, logging to
1221 * every cell it encounters along the way.
1222 */
1223 static int auth_to_path(krb5_context context, char *path)
1224 {
1225     int status = AKLOG_SUCCESS;
1226     int auth_to_cell_status = AKLOG_SUCCESS;
1227
1228     char *nextpath;
1229     char pathtocheck[MAXPATHLEN + 1];
1230     char mountpoint[MAXPATHLEN + 1];
1231
1232     char *cell;
1233     char *endofcell;
1234
1235     /* Initialize */
1236     if (BeginsWithDir(path, TRUE))
1237         strcpy(pathtocheck, path);
1238     else
1239     {
1240         if (getcwd(pathtocheck, sizeof(pathtocheck)) == NULL)
1241         {
1242             fprintf(stderr, "Unable to find current working directory:\n");
1243             fprintf(stderr, "%s\n", pathtocheck);
1244             fprintf(stderr, "Try an absolute pathname.\n");
1245             akexit(AKLOG_BADPATH);
1246         }
1247         else
1248         {
1249             /* in WIN32, if getcwd returns a root dir (eg: c:\), the returned string
1250             * will already have a trailing slash ('\'). Otherwise, the string will
1251             * end in the last directory name */
1252 #ifdef WIN32    
1253             if(pathtocheck[strlen(pathtocheck) - 1] != BDIR)
1254 #endif  
1255                 strcat(pathtocheck, DIRSTRING);
1256             strcat(pathtocheck, path);
1257         }
1258     }
1259     next_path(pathtocheck);
1260
1261     /* Go on to the next level down the path */
1262     while (nextpath = next_path(NULL))
1263     {
1264         strcpy(pathtocheck, nextpath);
1265         if (dflag)
1266             printf("Checking directory [%s]\n", pathtocheck);
1267         /*
1268         * If this is an afs mountpoint, determine what cell from
1269         * the mountpoint name which is of the form
1270         * #cellname:volumename or %cellname:volumename.
1271         */
1272         if (get_afs_mountpoint(pathtocheck, mountpoint, sizeof(mountpoint)))
1273         {
1274             if(dflag)
1275                 printf("Found mount point [%s]\n", mountpoint);
1276             /* skip over the '#' or '%' */
1277             cell = mountpoint + 1;
1278             if (endofcell = strchr(mountpoint, VOLMARKER))
1279             {
1280                 *endofcell = '\0';
1281                 if (auth_to_cell_status = auth_to_cell(context, cell, NULL))
1282                 {
1283                     if (status == AKLOG_SUCCESS)
1284                         status = auth_to_cell_status;
1285                     else if (status != auth_to_cell_status)
1286                         status = AKLOG_SOMETHINGSWRONG;
1287                 }
1288             }
1289         }
1290         else
1291         {
1292             struct stat st;
1293
1294             if (lstat(pathtocheck, &st) < 0)
1295             {
1296                 /*
1297                 * If we've logged and still can't stat, there's
1298                 * a problem...
1299                 */
1300                 fprintf(stderr, "%s: stat(%s): %s\n", progname,
1301                          pathtocheck, strerror(errno));
1302                 return(AKLOG_BADPATH);
1303             }
1304             else if (!S_ISDIR(st.st_mode))
1305             {
1306                 /* Allow only directories */
1307                 fprintf(stderr, "%s: %s: %s\n", progname, pathtocheck,
1308                          strerror(ENOTDIR));
1309                 return(AKLOG_BADPATH);
1310             }
1311         }
1312     }
1313
1314     return(status);
1315 }
1316
1317 /* Print usage message and exit */
1318 static void usage(void)
1319 {
1320     fprintf(stderr, "\nUsage: %s %s%s%s%s\n", progname,
1321              "[-d] [[-cell | -c] cell [-k krb_realm]] ",
1322              "[[-p | -path] pathname]\n",
1323              "    [-noprdb] [-force]\n",
1324 #ifdef HAVE_KRB4
1325              "    [-5 [-m]| -4]\n"
1326 #else
1327              "    [-5]\n"
1328 #endif
1329              );
1330     fprintf(stderr, "    -d gives debugging information.\n");
1331     fprintf(stderr, "    krb_realm is the kerberos realm of a cell.\n");
1332     fprintf(stderr, "    pathname is the name of a directory to which ");
1333     fprintf(stderr, "you wish to authenticate.\n");
1334     fprintf(stderr, "    -noprdb means don't try to determine AFS ID.\n");
1335 #ifdef HAVE_KRB4
1336     fprintf(stderr, "    -5 or -4 selects whether to use Kerberos v5 or Kerberos v4.\n"
1337                     "       (default is Kerberos v5)\n");
1338     fprintf(stderr, "       -m means use krb524d to convert Kerberos v5 tickets.\n");
1339 #else
1340     fprintf(stderr, "    -5 use Kerberos v5.\n"
1341                     "       (only Kerberos v5 is available)\n");
1342 #endif
1343     fprintf(stderr, "    No commandline arguments means ");
1344     fprintf(stderr, "authenticate to the local cell.\n");
1345     fprintf(stderr, "\n");
1346     akexit(AKLOG_USAGE);
1347 }
1348
1349 #ifndef _WIN64
1350 #define KRB5LIB "krb5_32.dll"
1351 #else
1352 #define KRB5LIB "krb5_64.dll"
1353 #endif
1354 void
1355 load_krb5_error_message_funcs(void)
1356 {
1357     HINSTANCE h = LoadLibrary(KRB5LIB);
1358     if (h) {
1359         (FARPROC)pkrb5_get_error_message = GetProcAddress(h, "krb5_get_error_message");
1360         (FARPROC)pkrb5_free_error_message = GetProcAddress(h, "krb5_free_error_message");
1361     }
1362 }
1363
1364 void
1365 validate_krb5_availability(void)
1366 {
1367     HINSTANCE h = LoadLibrary(KRB5LIB);
1368     if (h) 
1369         FreeLibrary(h);
1370     else {
1371         fprintf(stderr, "Kerberos for Windows library %s is not available.\n", KRB5LIB);
1372         akexit(AKLOG_KFW_NOT_INSTALLED);
1373     }
1374 }
1375
1376 void
1377 validate_krb4_availability(void)
1378 {
1379 #ifdef HAVE_KRB4
1380     HINSTANCE h = LoadLibrary("krbv4w32.dll");
1381     if (h) 
1382         FreeLibrary(h);
1383     else {
1384         fprintf(stderr, "Kerberos for Windows library krbv4w32.dll is not available.\n");
1385         akexit(AKLOG_KFW_NOT_INSTALLED);
1386     }
1387 #else
1388     fprintf(stderr, "Kerberos v4 is not available in this build of aklog.\n");
1389     akexit(AKLOG_USAGE);
1390 #endif
1391 }
1392
1393 int main(int argc, char *argv[])
1394 {
1395     int status = AKLOG_SUCCESS;
1396     int i;
1397     int somethingswrong = FALSE;
1398
1399     cellinfo_t cellinfo;
1400
1401     extern char *progname;      /* Name of this program */
1402
1403     extern int dflag;           /* Debug mode */
1404
1405     int cmode = FALSE;          /* Cellname mode */
1406     int pmode = FALSE;          /* Path name mode */
1407
1408     char realm[REALM_SZ];               /* Kerberos realm of afs server */
1409     char cell[BUFSIZ];          /* Cell to which we are authenticating */
1410     char path[MAXPATHLEN + 1];  /* Path length for path mode */
1411
1412     linked_list cells;          /* List of cells to log to */
1413     linked_list paths;          /* List of paths to log to */
1414     ll_node *cur_node;
1415
1416     memset(&cellinfo, 0, sizeof(cellinfo));
1417
1418     memset(realm, 0, sizeof(realm));
1419     memset(cell, 0, sizeof(cell));
1420     memset(path, 0, sizeof(path));
1421
1422     ll_init(&cells);
1423     ll_init(&paths);
1424
1425     /* Store the program name here for error messages */
1426     if (progname = LastComponent(argv[0]))
1427         progname++;
1428     else
1429         progname = argv[0];
1430
1431     /* Initialize list of cells to which we have authenticated */
1432     (void)ll_init(&authedcells);
1433
1434     /* Parse commandline arguments and make list of what to do. */
1435     for (i = 1; i < argc; i++)
1436     {
1437         if (strcmp(argv[i], "-d") == 0)
1438             dflag++;
1439         else if (strcmp(argv[i], "-5") == 0)
1440             usev5++;
1441 #ifdef HAVE_KRB4
1442         else if (strcmp(argv[i], "-m") == 0)
1443             use524++;
1444         else if (strcmp(argv[i], "-4") == 0)
1445             usev5 = 0;
1446 #endif
1447         else if (strcmp(argv[i], "-noprdb") == 0)
1448             noprdb++;
1449         else if (strcmp(argv[i], "-force") == 0)
1450             force++;
1451         else if (((strcmp(argv[i], "-cell") == 0) ||
1452                    (strcmp(argv[i], "-c") == 0)) && !pmode)
1453         {       
1454             if (++i < argc)
1455             {
1456                 cmode++;
1457                 strcpy(cell, argv[i]);
1458             }
1459             else
1460                 usage();
1461         }
1462         else if (((strcmp(argv[i], "-path") == 0) ||
1463                    (strcmp(argv[i], "-p") == 0)) && !cmode)
1464         {       
1465             if (++i < argc)
1466             {
1467                 pmode++;
1468                 strcpy(path, argv[i]);
1469             }
1470             else
1471                 usage();
1472         }
1473         else if (argv[i][0] == '-')
1474             usage();
1475         else if (!pmode && !cmode)
1476         {
1477             if (FirstComponent(argv[i]) || (strcmp(argv[i], ".") == 0) ||
1478                  (strcmp(argv[i], "..") == 0))
1479             {
1480                 pmode++;
1481                 strcpy(path, argv[i]);
1482             }
1483             else
1484             {
1485                 cmode++;
1486                 strcpy(cell, argv[i]);
1487             }
1488         }
1489         else
1490             usage();
1491
1492         if (cmode)
1493         {
1494             if (((i + 1) < argc) && (strcmp(argv[i + 1], "-k") == 0))
1495             {
1496                 i += 2;
1497                 if (i < argc)
1498                     strcpy(realm, argv[i]);
1499                 else
1500                     usage();
1501             }
1502             /* Add this cell to list of cells */
1503             strcpy(cellinfo.cell, cell);
1504             strcpy(cellinfo.realm, realm);
1505             if (cur_node = ll_add_node(&cells, ll_tail))
1506             {
1507                 char *new_cellinfo;
1508                 if (new_cellinfo = copy_cellinfo(&cellinfo))
1509                     ll_add_data(cur_node, new_cellinfo);
1510                 else
1511                 {
1512                     fprintf(stderr, "%s: failure copying cellinfo.\n", progname);
1513                     akexit(AKLOG_MISC);
1514                 }
1515             }
1516             else
1517             {
1518                 fprintf(stderr, "%s: failure adding cell to cells list.\n",
1519                          progname);
1520                 akexit(AKLOG_MISC);
1521             }
1522             memset(&cellinfo, 0, sizeof(cellinfo));
1523             cmode = FALSE;
1524             memset(cell, 0, sizeof(cell));
1525             memset(realm, 0, sizeof(realm));
1526         }
1527         else if (pmode)
1528         {
1529             /* Add this path to list of paths */
1530             if (cur_node = ll_add_node(&paths, ll_tail))
1531             {
1532                 char *new_path;
1533                 if (new_path = strdup(path))
1534                     ll_add_data(cur_node, new_path);
1535                 else
1536                 {
1537                     fprintf(stderr, "%s: failure copying path name.\n",
1538                              progname);
1539                     akexit(AKLOG_MISC);
1540                 }
1541             }
1542             else
1543             {
1544                 fprintf(stderr, "%s: failure adding path to paths list.\n",
1545                          progname);
1546                 akexit(AKLOG_MISC);
1547             }
1548             pmode = FALSE;
1549             memset(path, 0, sizeof(path));
1550         }
1551     }
1552
1553     if (!noprdb)
1554         initialize_PT_error_table();
1555
1556     if (usev5) {
1557         validate_krb5_availability();
1558         if (krb5_init_context(&context))
1559             return(AKLOG_KERBEROS);
1560         load_krb5_error_message_funcs();
1561     } else 
1562         validate_krb4_availability();
1563     afs_set_com_err_hook(redirect_errors);
1564
1565     /* If nothing was given, log to the local cell. */
1566     if ((cells.nelements + paths.nelements) == 0)
1567         status = auth_to_cell(context, NULL, NULL);
1568     else
1569     {
1570         /* Log to all cells in the cells list first */
1571         for (cur_node = cells.first; cur_node; cur_node = cur_node->next)
1572         {
1573             memcpy(&cellinfo, cur_node->data, sizeof(cellinfo));
1574             if (status = auth_to_cell(context, 
1575                                        cellinfo.cell, cellinfo.realm))
1576                 somethingswrong++;
1577         }       
1578
1579         /* Then, log to all paths in the paths list */
1580         for (cur_node = paths.first; cur_node; cur_node = cur_node->next)
1581         {
1582             if (status = auth_to_path(context, 
1583                                        cur_node->data))
1584                 somethingswrong++;
1585         }
1586
1587         /*
1588         * If only one thing was logged to, we'll return the status
1589         * of the single call.  Otherwise, we'll return a generic
1590         * something failed status.
1591         */
1592         if (somethingswrong && ((cells.nelements + paths.nelements) > 1))
1593             status = AKLOG_SOMETHINGSWRONG;
1594     }       
1595
1596     akexit(status);
1597 }