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