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