Windows: fix building of aklog
[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     if (c != NULL)
516         increds.session.keytype = ENCTYPE_DES_CBC_CRC;
517
518     r = krb5_get_credentials(context, 0, _krb425_ccache, &increds, creds);
519     if (r) {
520         return((int)r);
521     }
522 #ifdef HAVE_KRB4
523     /* This requires krb524d to be running with the KDC */
524     if (c != NULL)
525         r = krb5_524_convert_creds(context, *creds, c);
526 #endif
527
528     return((int)r);
529 }
530
531 #ifdef HAVE_KRB4
532 /* There is no header for this function.  It is supposed to be private */
533 int krb_get_admhst(char *h,char *r, int n);
534
535 static char *afs_realm_of_cell(struct afsconf_cell *cellconfig)
536 {
537     char krbhst[MAX_HSTNM];
538     static char krbrlm[REALM_SZ+1];
539
540     if (!cellconfig)
541         return 0;
542
543     strcpy(krbrlm, (char *) krb_realmofhost(cellconfig->hostName[0]));
544
545     if (krb_get_admhst(krbhst, krbrlm, 1) != KSUCCESS)
546     {
547         char *s = krbrlm;
548         char *t = cellconfig->name;
549         int c;
550
551         while (c = *t++)
552         {
553             if (islower(c))
554                 c = toupper(c);
555             *s++ = c;
556         }
557         *s++ = 0;
558     }
559     return krbrlm;
560 }
561 #endif
562
563 /* As of MIT Kerberos 1.6, krb5_get_host_realm() will return the NUL-string
564  * if there is no domain_realm mapping for the hostname's domain.  This is
565  * used as a trigger indicating that referrals should be used within the
566  * krb5_get_credentials() call.  However, if the KDC does not support referrals
567  * that will result in a KRB5_ERR_HOST_REALM_UNKNOWN error and we will have
568  * to manually fallback to mapping the domain of the host as a realm name.
569  * Hence, the new fallback parameter.
570  */
571 static char *afs_realm_of_cell5(krb5_context context, struct afsconf_cell *cellconfig, int fallback)
572 {
573     char ** krbrlms = 0;
574     static char krbrlm[REALM_SZ+1];
575     krb5_error_code status;
576
577     if (!cellconfig)
578         return 0;
579
580     if (fallback) {
581         char * p;
582         p = strchr(cellconfig->hostName[0], '.');
583         if (p++)
584             strcpy(krbrlm, p);
585         else
586             strcpy(krbrlm, cellconfig->name);
587         strupr(krbrlm);
588     } else {
589         status = krb5_get_host_realm( context, cellconfig->hostName[0], &krbrlms );
590         if (status == 0 && krbrlms && krbrlms[0]) {
591             strcpy(krbrlm, krbrlms[0]);
592         } else {
593             strcpy(krbrlm, cellconfig->name);
594             strupr(krbrlm);
595         }
596
597         if (krbrlms)
598             krb5_free_host_realm( context, krbrlms );
599     }
600     return krbrlm;
601 }
602
603 static char *copy_cellinfo(cellinfo_t *cellinfo)
604 {
605     cellinfo_t *new_cellinfo;
606
607     if (new_cellinfo = (cellinfo_t *)malloc(sizeof(cellinfo_t)))
608         memcpy(new_cellinfo, cellinfo, sizeof(cellinfo_t));
609
610     return ((char *)new_cellinfo);
611 }
612
613
614 static int get_cellconfig(char *cell, struct afsconf_cell *cellconfig,
615                                                   char *local_cell)
616 {
617     int status = AKLOG_SUCCESS;
618     struct afsconf_dir *configdir = 0;
619
620     memset(local_cell, 0, sizeof(local_cell));
621     memset(cellconfig, 0, sizeof(*cellconfig));
622
623     if (GetLocalCell(&configdir, local_cell))
624     {
625         fprintf(stderr, "%s: can't determine local cell.\n", progname);
626         akexit(AKLOG_AFS);
627     }
628
629     if ((cell == NULL) || (cell[0] == 0))
630         cell = local_cell;
631
632     if (GetCellInfo(&configdir, cell, &cellconfig))
633     {
634         fprintf(stderr, "%s: Can't get information about cell %s.\n",
635                 progname, cell);
636         status = AKLOG_AFS;
637     }
638
639     if (cellconfig->linkedCell)
640         cellconfig->linkedCell = strdup(cellconfig->linkedCell);
641
642     CloseConf(&configdir);
643
644     return(status);
645 }
646
647 static int get_v5_user_realm(krb5_context context,char *realm)
648 {
649     static krb5_principal client_principal = 0;
650     krb5_error_code code;
651
652     if (!_krb425_ccache) {
653         code = krb5_cc_default(context, &_krb425_ccache);
654         if (code)
655             return(code);
656     }
657     if (!client_principal) {
658         code = krb5_cc_get_principal(context, _krb425_ccache, &client_principal);
659         if (code)
660             return(code);
661     }
662     strncpy(realm, krb5_principal_get_realm(context, client_principal), REALM_SZ - 1);
663     realm[REALM_SZ - 1] = 0;
664     return(KSUCCESS);
665 }
666
667 static void
668 copy_realm_of_ticket(krb5_context context, char * dest, size_t destlen, krb5_creds *v5cred) {
669     Ticket ticket;
670     size_t len;
671     int ret;
672
673     ret = decode_Ticket(v5cred->ticket.data, v5cred->ticket.length,
674                         &ticket, &len);
675     if (ret == 0) {
676         strncpy(dest, ticket.realm, destlen - 1);
677         dest[destlen - 1] = '\0';
678
679         free_Ticket(&ticket);
680     }
681 }
682
683 typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
684 static
685 int is_wow64()
686 {
687     static int init = TRUE;
688     static int bIsWow64 = FALSE;
689
690     if (init) {
691         HMODULE hModule;
692         LPFN_ISWOW64PROCESS fnIsWow64Process = NULL;
693
694         hModule = GetModuleHandle(TEXT("kernel32"));
695         if (hModule) {
696             fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(hModule, "IsWow64Process");
697
698             if (NULL != fnIsWow64Process)
699             {
700                 if (!fnIsWow64Process(GetCurrentProcess(),&bIsWow64))
701                 {
702                     // on error, assume FALSE.
703                     // in other words, do nothing.
704                 }
705             }
706             FreeLibrary(hModule);
707         }
708         init = FALSE;
709     }
710     return bIsWow64;
711 }
712
713 static int
714 accept_dotted_usernames(void)
715 {
716     HKEY parmKey;
717     DWORD code, len;
718     DWORD value = 1;
719
720     code = RegOpenKeyEx(HKEY_CURRENT_USER, AFSREG_USER_OPENAFS_SUBKEY,
721                          0, (is_wow64()?KEY_WOW64_64KEY:0)|KEY_QUERY_VALUE, &parmKey);
722     if (code == ERROR_SUCCESS) {
723         len = sizeof(value);
724         code = RegQueryValueEx(parmKey, "AcceptDottedPrincipalNames", NULL, NULL,
725                                 (BYTE *) &value, &len);
726         RegCloseKey(parmKey);
727     }
728     if (code != ERROR_SUCCESS) {
729         code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_OPENAFS_SUBKEY,
730                              0, (is_wow64()?KEY_WOW64_64KEY:0)|KEY_QUERY_VALUE, &parmKey);
731         if (code == ERROR_SUCCESS) {
732             len = sizeof(value);
733             code = RegQueryValueEx(parmKey, "AcceptDottedPrincipalNames", NULL, NULL,
734                                     (BYTE *) &value, &len);
735             RegCloseKey (parmKey);
736         }
737     }
738     return value;
739 }
740
741
742 /*
743 * Log to a cell.  If the cell has already been logged to, return without
744 * doing anything.  Otherwise, log to it and mark that it has been logged
745 * to.  */
746 static int auth_to_cell(krb5_context context, char *cell, char *realm)
747 {
748     int status = AKLOG_SUCCESS;
749     char username[BUFSIZ];        /* To hold client username structure */
750
751     char name[ANAME_SZ];          /* Name of afs key */
752     char instance[INST_SZ];       /* Instance of afs key */
753     char realm_of_user[REALM_SZ]; /* Kerberos realm of user */
754     char realm_of_cell[REALM_SZ]; /* Kerberos realm of cell */
755     char local_cell[MAXCELLCHARS+1];
756     char cell_to_use[MAXCELLCHARS+1]; /* Cell to authenticate to */
757
758     krb5_creds *v5cred = NULL;
759 #ifdef HAVE_KRB4
760     CREDENTIALS c;
761 #endif
762     struct ktc_principal aserver;
763     struct ktc_principal aclient;
764     struct ktc_token atoken, btoken;
765     struct afsconf_cell ak_cellconfig; /* General information about the cell */
766     int i;
767     int getLinkedCell = 0;
768     int flags = 0;
769     char * smbname = getenv("AFS_SMBNAME");
770
771     /* try to avoid an expensive call to get_cellconfig */
772     if (cell && ll_string_check(&authedcells, cell))
773     {
774         if (dflag)
775             printf("Already authenticated to %s (or tried to)\n", cell);
776         return(AKLOG_SUCCESS);
777     }
778
779     memset(name, 0, sizeof(name));
780     memset(instance, 0, sizeof(instance));
781     memset(realm_of_user, 0, sizeof(realm_of_user));
782     memset(realm_of_cell, 0, sizeof(realm_of_cell));
783     memset(&ak_cellconfig, 0, sizeof(ak_cellconfig));
784
785     /* NULL or empty cell returns information on local cell */
786     if (status = get_cellconfig(cell, &ak_cellconfig, local_cell))
787         return(status);
788
789   linkedCell:
790     if (getLinkedCell)
791         strncpy(cell_to_use, ak_cellconfig.linkedCell, MAXCELLCHARS);
792     else
793         strncpy(cell_to_use, ak_cellconfig.name, MAXCELLCHARS);
794     cell_to_use[MAXCELLCHARS] = 0;
795
796     if (ll_string_check(&authedcells, cell_to_use))
797     {
798         if (dflag)
799             printf("Already authenticated to %s (or tried to)\n", cell_to_use);
800         status = AKLOG_SUCCESS;
801         goto done2;
802     }
803
804     /*
805      * Record that we have attempted to log to this cell.  We do this
806      * before we try rather than after so that we will not try
807      * and fail repeatedly for one cell.
808      */
809     (void)ll_add_string(&authedcells, cell_to_use);
810
811     if (dflag)
812         printf("Authenticating to cell %s.\n", cell_to_use);
813
814     /* We use the afs.<cellname> convention here... */
815     strcpy(name, AFSKEY);
816     strncpy(instance, cell_to_use, sizeof(instance));
817     instance[sizeof(instance)-1] = '\0';
818
819     /*
820      * Extract the session key from the ticket file and hand-frob an
821      * afs style authenticator.
822      */
823
824     if (usev5)
825     { /* using krb5 */
826         int retry = 1;
827         int realm_fallback = 0;
828
829         if ((status = get_v5_user_realm(context, realm_of_user)) != KSUCCESS) {
830             char * msg;
831
832             msg = krb5_get_error_message(context, status);
833             fprintf(stderr, "%s: Couldn't determine realm of user: %s\n",
834                     progname, msg);
835             krb5_free_error_message(context, msg);
836             status = AKLOG_KERBEROS;
837             goto done;
838         }
839
840         if ( strchr(name,'.') != NULL && !accept_dotted_usernames()) {
841             fprintf(stderr, "%s: Can't support principal names including a dot.\n",
842                     progname);
843             status = AKLOG_MISC;
844             goto done;
845         }
846
847       try_v5:
848         if (realm && realm[0]) {
849             if (dflag)
850                 printf("Getting v5 tickets: %s/%s@%s\n", name, instance, realm);
851             status = get_v5cred(context, name, instance, realm,
852 #ifdef HAVE_KRB4
853                             use524 ? &c : NULL,
854 #else
855                             NULL,
856 #endif
857                             &v5cred);
858             strcpy(realm_of_cell, realm);
859         } else {
860             strcpy(realm_of_cell,
861                     afs_realm_of_cell5(context, &ak_cellconfig, realm_fallback));
862
863             if (retry == 1 && realm_fallback == 0) {
864                 /* Only try the realm_of_user once */
865                 status = -1;
866                 if (dflag)
867                     printf("Getting v5 tickets: %s/%s@%s\n", name, instance, realm_of_user);
868                 status = get_v5cred(context, name, instance, realm_of_user,
869 #ifdef HAVE_KRB4
870                                      use524 ? &c : NULL,
871 #else
872                                      NULL,
873 #endif
874                                      &v5cred);
875                 if (status == 0) {
876                     /* we have determined that the client realm
877                      * is a valid cell realm
878                      */
879                     strcpy(realm_of_cell, realm_of_user);
880                 }
881             }
882
883             if (status != 0 && (!retry || retry && strcmp(realm_of_user,realm_of_cell))) {
884                 if (dflag)
885                     printf("Getting v5 tickets: %s/%s@%s\n", name, instance, realm_of_cell);
886                 status = get_v5cred(context, name, instance, realm_of_cell,
887 #ifdef HAVE_KRB4
888                                      use524 ? &c : NULL,
889 #else
890                                      NULL,
891 #endif
892                                      &v5cred);
893                 if (!status && !strlen(realm_of_cell))
894                     copy_realm_of_ticket(context, realm_of_cell, sizeof(realm_of_cell), v5cred);
895             }
896         }
897
898         if (!realm_fallback && status == KRB5_ERR_HOST_REALM_UNKNOWN) {
899             realm_fallback = 1;
900             goto try_v5;
901         } else if (status == KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN) {
902             if (!realm_fallback && !realm_of_cell[0]) {
903                 realm_fallback = 1;
904                 goto try_v5;
905             }
906             if (dflag)
907                 printf("Getting v5 tickets: %s@%s\n", name, realm_of_cell);
908             status = get_v5cred(context, name, "", realm_of_cell,
909 #ifdef HAVE_KRB4
910                                 use524 ? &c : NULL,
911 #else
912                                 NULL,
913 #endif
914                                 &v5cred);
915             if (!status && !strlen(realm_of_cell))
916                 copy_realm_of_ticket(context, realm_of_cell, sizeof(realm_of_cell), v5cred);
917         }
918
919         if ( status == KRB5KRB_AP_ERR_MSG_TYPE && retry ) {
920             retry = 0;
921             realm_fallback = 0;
922             goto try_v5;
923         }
924     }
925     else
926     {
927 #ifdef HAVE_KRB4
928         if (realm && realm[0])
929             strcpy(realm_of_cell, realm);
930         else
931             strcpy(realm_of_cell, afs_realm_of_cell(&ak_cellconfig));
932
933         /*
934          * Try to obtain AFS tickets.  Because there are two valid service
935          * names, we will try both, but trying the more specific first.
936          *
937          *      afs.<cell>@<realm>
938          *      afs@<realm>
939          */
940         if (dflag)
941             printf("Getting tickets: %s.%s@%s\n", name, instance, realm_of_cell);
942         status = get_cred(name, instance, realm_of_cell, &c);
943         if (status == KDC_PR_UNKNOWN)
944         {
945             if (dflag)
946                 printf("Getting tickets: %s@%s\n", name, realm_of_cell);
947             status = get_cred(name, "", realm_of_cell, &c);
948         }
949 #else
950         status = AKLOG_MISC;
951         goto done;
952 #endif
953     }
954
955     if (status != KSUCCESS)
956     {
957         char * msg = NULL;
958         if (dflag)
959             printf("Kerberos error code returned by get_cred: %d\n", status);
960
961         if (usev5) {
962             msg = krb5_get_error_message(context, status);
963         }
964 #ifdef HAVE_KRB4
965         else
966             msg = krb_err_text(status);
967 #endif
968         fprintf(stderr, "%s: Couldn't get %s AFS tickets: %s\n",
969                 progname, cell_to_use, msg?msg:"(unknown error)");
970         if (usev5)
971             krb5_free_error_message(context, msg);
972         status = AKLOG_KERBEROS;
973         goto done;
974     }
975
976     strncpy(aserver.name, AFSKEY, MAXKTCNAMELEN - 1);
977     strncpy(aserver.instance, AFSINST, MAXKTCNAMELEN - 1);
978     strncpy(aserver.cell, cell_to_use, MAXKTCREALMLEN - 1);
979
980     if (usev5 && !use524) {
981         /* This code inserts the entire K5 ticket into the token
982          * No need to perform a krb524 translation which is
983          * commented out in the code below
984          */
985         char * p;
986         int len;
987         const char *un;
988
989         un = krb5_principal_get_comp_string(context, v5cred->client, 0);
990         strncpy(username, un, MAXKTCNAMELEN - 1);
991         username[MAXKTCNAMELEN - 1] = '\0';
992
993         if ( krb5_principal_get_num_comp(context, v5cred->client) > 1 ) {
994             strcat(username, ".");
995             p = username + strlen(username);
996             len = (unsigned int)(MAXKTCNAMELEN - strlen(username) - 1);
997             strncpy(p, krb5_principal_get_comp_string(context, v5cred->client, 1), len);
998             p[len] = '\0';
999         }
1000
1001         memset(&atoken, '\0', sizeof(atoken));
1002         atoken.kvno = RXKAD_TKT_TYPE_KERBEROS_V5;
1003         atoken.startTime = v5cred->times.starttime;
1004         atoken.endTime = v5cred->times.endtime;
1005         if (tkt_DeriveDesKey(v5cred->session.keytype,
1006                              v5cred->session.keyvalue.data,
1007                              v5cred->session.keyvalue.length, &atoken.sessionKey)) {
1008             status = AKLOG_MISC;
1009             goto done;
1010         }
1011         atoken.ticketLen = v5cred->ticket.length;
1012         memcpy(atoken.ticket, v5cred->ticket.data, atoken.ticketLen);
1013     } else {
1014 #ifdef HAVE_KRB4
1015         strcpy (username, c.pname);
1016         if (c.pinst[0])
1017         {
1018             strcat(username, ".");
1019             strcat(username, c.pinst);
1020         }
1021
1022         atoken.kvno = c.kvno;
1023         atoken.startTime = c.issue_date;
1024         /* ticket lifetime is in five-minutes blocks. */
1025         atoken.endTime = c.issue_date + ((unsigned char)c.lifetime * 5 * 60);
1026
1027         memcpy(&atoken.sessionKey, c.session, 8);
1028         atoken.ticketLen = c.ticket_st.length;
1029         memcpy(atoken.ticket, c.ticket_st.dat, atoken.ticketLen);
1030 #else
1031         status = AKLOG_MISC;
1032         goto done;
1033 #endif
1034     }
1035
1036     if (!force &&
1037         !smbname &&
1038         !ktc_GetToken(&aserver, &btoken, sizeof(btoken), &aclient) &&
1039         atoken.kvno == btoken.kvno &&
1040         atoken.ticketLen == btoken.ticketLen &&
1041         !memcmp(&atoken.sessionKey, &btoken.sessionKey, sizeof(atoken.sessionKey)) &&
1042         !memcmp(atoken.ticket, btoken.ticket, atoken.ticketLen))
1043     {
1044         if (dflag)
1045             printf("Identical tokens already exist; skipping.\n");
1046         status = AKLOG_SUCCESS;
1047         goto done2;
1048     }
1049
1050     if (noprdb)
1051     {
1052         if (dflag)
1053             printf("Not resolving name %s to id (-noprdb set)\n", username);
1054     }
1055     else
1056     {
1057         if (!usev5) {
1058 #ifdef HAVE_KRB4
1059             if ((status = krb_get_tf_realm(TKT_FILE, realm_of_user)) != KSUCCESS)
1060             {
1061                 fprintf(stderr, "%s: Couldn't determine realm of user: %s)",
1062                          progname, krb_err_text(status));
1063                 status = AKLOG_KERBEROS;
1064                 goto done;
1065             }
1066 #else
1067             status = AKLOG_MISC;
1068             goto done;
1069 #endif
1070         }
1071
1072         /* For Network Identity Manager append the realm to the name */
1073         strcat(username, "@");
1074         strcat(username, realm_of_user);
1075
1076         ViceIDToUsername(username, realm_of_user, realm_of_cell, cell_to_use,
1077 #ifdef HAVE_KRB4
1078                           &c,
1079 #else
1080                           NULL,
1081 #endif
1082                           &status, &aclient, &aserver, &atoken);
1083     }
1084
1085     if (dflag)
1086         printf("Set username to %s\n", username);
1087
1088     /* Reset the "aclient" structure before we call ktc_SetToken.
1089      * This structure was first set by the ktc_GetToken call when
1090      * we were comparing whether identical tokens already existed.
1091      */
1092     strncpy(aclient.name, username, MAXKTCNAMELEN - 1);
1093     strcpy(aclient.instance, "");
1094
1095     if (usev5 && !use524) {
1096         strncpy(aclient.cell,
1097                 krb5_principal_get_realm(context, v5cred->client), MAXKTCNAMELEN - 1);
1098         aclient.cell[MAXKTCNAMELEN - 1] = '\0';
1099     }
1100 #ifdef HAVE_KRB4
1101     else
1102         strncpy(aclient.cell, c.realm, MAXKTCREALMLEN - 1);
1103 #endif
1104
1105     for ( i=0; aclient.cell[i]; i++ ) {
1106         if ( islower(aclient.cell[i]) )
1107             aclient.cell[i] = toupper(aclient.cell[i]);
1108     }
1109
1110     if ( smbname ) {
1111         if (dflag)
1112             printf("Setting tokens for %s.\n", smbname);
1113
1114         strncpy(aclient.smbname, smbname, MAXKTCNAMELEN - 1);
1115         aclient.smbname[MAXKTCNAMELEN - 1] = '\0';
1116         flags = AFS_SETTOK_LOGON;
1117     } else {
1118         if (dflag)
1119             printf("Setting tokens.\n");
1120     }
1121
1122     if (status = ktc_SetToken(&aserver, &atoken, &aclient, flags))
1123     {
1124         afs_com_err(progname, status,
1125                      "while setting token for cell %s\n",
1126                      cell_to_use);
1127         status = AKLOG_TOKEN;
1128     }
1129
1130   done2:
1131     if (ak_cellconfig.linkedCell && !getLinkedCell) {
1132         getLinkedCell = 1;
1133         goto linkedCell;
1134     }
1135
1136   done:
1137 #if 0
1138     /*
1139      * intentionally leak the linkedCell field because it was allocated
1140      * using a different C RTL version.
1141      */
1142     if (ak_cellconfig.linkedCell)
1143         free(ak_cellconfig.linkedCell);
1144 #endif
1145     return(status);
1146 }
1147
1148 static int get_afs_mountpoint(char *file, char *mountpoint, int size)
1149 {
1150     char our_file[MAXPATHLEN + 1];
1151     char *parent_dir;
1152     char *last_component;
1153     struct ViceIoctl vio;
1154     char cellname[BUFSIZ];
1155
1156     memset(our_file, 0, sizeof(our_file));
1157     strcpy(our_file, file);
1158
1159     if (last_component = LastComponent(our_file))
1160     {
1161         *last_component++ = 0;
1162         parent_dir = our_file;
1163     }
1164     else
1165     {
1166         last_component = our_file;
1167         parent_dir = ".";
1168     }
1169
1170     memset(cellname, 0, sizeof(cellname));
1171
1172     vio.in = last_component;
1173     vio.in_size = (long)strlen(last_component)+1;
1174     vio.out_size = size;
1175     vio.out = mountpoint;
1176
1177     if (!pioctl(parent_dir, VIOC_AFS_STAT_MT_PT, &vio, 0))
1178     {
1179         if (strchr(mountpoint, VOLMARKER) == NULL)
1180         {
1181             vio.in = file;
1182             vio.in_size = (long)strlen(file) + 1;
1183             vio.out_size = sizeof(cellname);
1184             vio.out = cellname;
1185
1186             if (!pioctl(file, VIOC_FILE_CELL_NAME, &vio, 1))
1187             {
1188                 strcat(cellname, VOLMARKERSTRING);
1189                 strcat(cellname, mountpoint + 1);
1190                 memset(mountpoint + 1, 0, size - 1);
1191                 strcpy(mountpoint + 1, cellname);
1192             }
1193         }
1194         return(TRUE);
1195     }
1196     else {
1197         return(FALSE);
1198     }
1199 }
1200
1201 /*
1202 * This routine each time it is called returns the next directory
1203 * down a pathname.  It resolves all symbolic links.  The first time
1204 * it is called, it should be called with the name of the path
1205 * to be descended.  After that, it should be called with the arguemnt
1206 * NULL.
1207 */
1208 static char *next_path(char *origpath)
1209 {
1210     static char path[MAXPATHLEN + 1];
1211     static char pathtocheck[MAXPATHLEN + 1];
1212
1213     int link = FALSE;           /* Is this a symbolic link? */
1214     char linkbuf[MAXPATHLEN + 1];
1215     char tmpbuf[MAXPATHLEN + 1];
1216
1217     static char *last_comp;     /* last component of directory name */
1218     static char *elast_comp;    /* End of last component */
1219     char *t;
1220     int len;
1221
1222     static int symlinkcount = 0;        /* We can't exceed MAXSYMLINKS */
1223
1224     /* If we are given something for origpath, we are initializing only. */
1225     if (origpath)
1226     {
1227         memset(path, 0, sizeof(path));
1228         memset(pathtocheck, 0, sizeof(pathtocheck));
1229         CopyPathColon(origpath, path, pathtocheck);
1230         last_comp = path;
1231         symlinkcount = 0;
1232         return(NULL);
1233     }
1234
1235     /* We were not given origpath; find then next path to check */
1236
1237     /* If we've gotten all the way through already, return NULL */
1238     if (last_comp == NULL)
1239         return(NULL);
1240
1241     do
1242     {
1243         while (BeginsWithDir(last_comp, FALSE))
1244             strncat(pathtocheck, last_comp++, 1);
1245         len = (int) ((elast_comp = LastComponent(last_comp))
1246             ? elast_comp - last_comp : strlen(last_comp));
1247         strncat(pathtocheck, last_comp, len);
1248         memset(linkbuf, 0, sizeof(linkbuf));
1249         if (link = (readlink(pathtocheck, linkbuf, sizeof(linkbuf)) > 0))
1250         {
1251             if (++symlinkcount > MAXSYMLINKS)
1252             {
1253                 fprintf(stderr, "%s: %s\n", progname, strerror(ELOOP));
1254                 akexit(AKLOG_BADPATH);
1255             }
1256             memset(tmpbuf, 0, sizeof(tmpbuf));
1257             if (elast_comp)
1258                 strcpy(tmpbuf, elast_comp);
1259             if (BeginsWithDir(linkbuf, FALSE))
1260             {
1261                 /*
1262                 * If this is a symbolic link to an absolute path,
1263                 * replace what we have by the absolute path.
1264                 */
1265                 memset(path, 0, strlen(path));
1266                 memcpy(path, linkbuf, sizeof(linkbuf));
1267                 strcat(path, tmpbuf);
1268                 last_comp = path;
1269                 elast_comp = NULL;
1270                 memset(pathtocheck, 0, sizeof(pathtocheck));
1271             }
1272             else
1273             {
1274                 /*
1275                 * If this is a symbolic link to a relative path,
1276                 * replace only the last component with the link name.
1277                 */
1278                 strncpy(last_comp, linkbuf, strlen(linkbuf) + 1);
1279                 strcat(path, tmpbuf);
1280                 elast_comp = NULL;
1281                 if (t = LastComponent(pathtocheck))
1282                 {
1283                     t++;
1284                     memset(t, 0, strlen(t));
1285                 }
1286                 else
1287                     memset(pathtocheck, 0, sizeof(pathtocheck));
1288             }
1289         }
1290         else
1291             last_comp = elast_comp;
1292     }
1293     while(link);
1294
1295     return(pathtocheck);
1296 }
1297
1298 /*
1299 * This routine descends through a path to a directory, logging to
1300 * every cell it encounters along the way.
1301 */
1302 static int auth_to_path(krb5_context context, char *path)
1303 {
1304     int status = AKLOG_SUCCESS;
1305     int auth_to_cell_status = AKLOG_SUCCESS;
1306
1307     char *nextpath;
1308     char pathtocheck[MAXPATHLEN + 1];
1309     char mountpoint[MAXPATHLEN + 1];
1310
1311     char *cell;
1312     char *endofcell;
1313
1314     /* Initialize */
1315     if (BeginsWithDir(path, TRUE))
1316         strcpy(pathtocheck, path);
1317     else
1318     {
1319         if (getcwd(pathtocheck, sizeof(pathtocheck)) == NULL)
1320         {
1321             fprintf(stderr, "Unable to find current working directory:\n");
1322             fprintf(stderr, "%s\n", pathtocheck);
1323             fprintf(stderr, "Try an absolute pathname.\n");
1324             akexit(AKLOG_BADPATH);
1325         }
1326         else
1327         {
1328             /* in WIN32, if getcwd returns a root dir (eg: c:\), the returned string
1329             * will already have a trailing slash ('\'). Otherwise, the string will
1330             * end in the last directory name */
1331 #ifdef WIN32
1332             if(pathtocheck[strlen(pathtocheck) - 1] != BDIR)
1333 #endif
1334                 strcat(pathtocheck, DIRSTRING);
1335             strcat(pathtocheck, path);
1336         }
1337     }
1338     next_path(pathtocheck);
1339
1340     /* Go on to the next level down the path */
1341     while (nextpath = next_path(NULL))
1342     {
1343         strcpy(pathtocheck, nextpath);
1344         if (dflag)
1345             printf("Checking directory [%s]\n", pathtocheck);
1346         /*
1347         * If this is an afs mountpoint, determine what cell from
1348         * the mountpoint name which is of the form
1349         * #cellname:volumename or %cellname:volumename.
1350         */
1351         if (get_afs_mountpoint(pathtocheck, mountpoint, sizeof(mountpoint)))
1352         {
1353             if(dflag)
1354                 printf("Found mount point [%s]\n", mountpoint);
1355             /* skip over the '#' or '%' */
1356             cell = mountpoint + 1;
1357             if (endofcell = strchr(mountpoint, VOLMARKER))
1358             {
1359                 *endofcell = '\0';
1360                 if (auth_to_cell_status = auth_to_cell(context, cell, NULL))
1361                 {
1362                     if (status == AKLOG_SUCCESS)
1363                         status = auth_to_cell_status;
1364                     else if (status != auth_to_cell_status)
1365                         status = AKLOG_SOMETHINGSWRONG;
1366                 }
1367             }
1368         }
1369         else
1370         {
1371             struct stat st;
1372
1373             if (lstat(pathtocheck, &st) < 0)
1374             {
1375                 /*
1376                 * If we've logged and still can't stat, there's
1377                 * a problem...
1378                 */
1379                 fprintf(stderr, "%s: stat(%s): %s\n", progname,
1380                          pathtocheck, strerror(errno));
1381                 return(AKLOG_BADPATH);
1382             }
1383             else if (!S_ISDIR(st.st_mode))
1384             {
1385                 /* Allow only directories */
1386                 fprintf(stderr, "%s: %s: %s\n", progname, pathtocheck,
1387                          strerror(ENOTDIR));
1388                 return(AKLOG_BADPATH);
1389             }
1390         }
1391     }
1392
1393     return(status);
1394 }
1395
1396 /* Print usage message and exit */
1397 static void usage(void)
1398 {
1399     fprintf(stderr, "\nUsage: %s %s%s%s%s\n", progname,
1400              "[-d] [[-cell | -c] cell [-k krb_realm]] ",
1401              "[[-p | -path] pathname]\n",
1402              "    [-noprdb] [-force]\n",
1403 #ifdef HAVE_KRB4
1404              "    [-5 [-m]| -4]\n"
1405 #else
1406              "    [-5]\n"
1407 #endif
1408              );
1409     fprintf(stderr, "    -d gives debugging information.\n");
1410     fprintf(stderr, "    krb_realm is the kerberos realm of a cell.\n");
1411     fprintf(stderr, "    pathname is the name of a directory to which ");
1412     fprintf(stderr, "you wish to authenticate.\n");
1413     fprintf(stderr, "    -noprdb means don't try to determine AFS ID.\n");
1414 #ifdef HAVE_KRB4
1415     fprintf(stderr, "    -5 or -4 selects whether to use Kerberos v5 or Kerberos v4.\n"
1416                     "       (default is Kerberos v5)\n");
1417     fprintf(stderr, "       -m means use krb524d to convert Kerberos v5 tickets.\n");
1418 #else
1419     fprintf(stderr, "    -5 use Kerberos v5.\n"
1420                     "       (only Kerberos v5 is available)\n");
1421 #endif
1422     fprintf(stderr, "    No commandline arguments means ");
1423     fprintf(stderr, "authenticate to the local cell.\n");
1424     fprintf(stderr, "\n");
1425     akexit(AKLOG_USAGE);
1426 }
1427
1428 void
1429 validate_krb5_availability(void)
1430 {
1431     if (!DelayLoadHeimdal()) {
1432         fprintf(stderr, "Kerberos for Windows or Heimdal is not available.\n");
1433         akexit(AKLOG_KFW_NOT_INSTALLED);
1434     }
1435 }
1436
1437 void
1438 validate_krb4_availability(void)
1439 {
1440 #ifdef HAVE_KRB4
1441     HINSTANCE h = LoadLibrary("krbv4w32.dll");
1442     if (h)
1443         FreeLibrary(h);
1444     else {
1445         fprintf(stderr, "Kerberos for Windows library krbv4w32.dll is not available.\n");
1446         akexit(AKLOG_KFW_NOT_INSTALLED);
1447     }
1448 #else
1449     fprintf(stderr, "Kerberos v4 is not available in this build of aklog.\n");
1450     akexit(AKLOG_USAGE);
1451 #endif
1452 }
1453
1454 int main(int argc, char *argv[])
1455 {
1456     int status = AKLOG_SUCCESS;
1457     int i;
1458     int somethingswrong = FALSE;
1459
1460     cellinfo_t cellinfo;
1461
1462     extern char *progname;      /* Name of this program */
1463
1464     extern int dflag;           /* Debug mode */
1465
1466     int cmode = FALSE;          /* Cellname mode */
1467     int pmode = FALSE;          /* Path name mode */
1468
1469     char realm[REALM_SZ];               /* Kerberos realm of afs server */
1470     char cell[BUFSIZ];          /* Cell to which we are authenticating */
1471     char path[MAXPATHLEN + 1];  /* Path length for path mode */
1472
1473     linked_list cells;          /* List of cells to log to */
1474     linked_list paths;          /* List of paths to log to */
1475     ll_node *cur_node;
1476
1477     memset(&cellinfo, 0, sizeof(cellinfo));
1478
1479     memset(realm, 0, sizeof(realm));
1480     memset(cell, 0, sizeof(cell));
1481     memset(path, 0, sizeof(path));
1482
1483     ll_init(&cells);
1484     ll_init(&paths);
1485
1486     /* Store the program name here for error messages */
1487     if (progname = LastComponent(argv[0]))
1488         progname++;
1489     else
1490         progname = argv[0];
1491
1492     /* Initialize list of cells to which we have authenticated */
1493     (void)ll_init(&authedcells);
1494
1495     /* Parse commandline arguments and make list of what to do. */
1496     for (i = 1; i < argc; i++)
1497     {
1498         if (strcmp(argv[i], "-d") == 0)
1499             dflag++;
1500         else if (strcmp(argv[i], "-5") == 0)
1501             usev5++;
1502 #ifdef HAVE_KRB4
1503         else if (strcmp(argv[i], "-m") == 0)
1504             use524++;
1505         else if (strcmp(argv[i], "-4") == 0)
1506             usev5 = 0;
1507 #endif
1508         else if (strcmp(argv[i], "-noprdb") == 0)
1509             noprdb++;
1510         else if (strcmp(argv[i], "-force") == 0)
1511             force++;
1512         else if (((strcmp(argv[i], "-cell") == 0) ||
1513                    (strcmp(argv[i], "-c") == 0)) && !pmode)
1514         {
1515             if (++i < argc)
1516             {
1517                 cmode++;
1518                 strcpy(cell, argv[i]);
1519             }
1520             else
1521                 usage();
1522         }
1523         else if (((strcmp(argv[i], "-path") == 0) ||
1524                    (strcmp(argv[i], "-p") == 0)) && !cmode)
1525         {
1526             if (++i < argc)
1527             {
1528                 pmode++;
1529                 strcpy(path, argv[i]);
1530             }
1531             else
1532                 usage();
1533         }
1534         else if (argv[i][0] == '-')
1535             usage();
1536         else if (!pmode && !cmode)
1537         {
1538             if (FirstComponent(argv[i]) || (strcmp(argv[i], ".") == 0) ||
1539                  (strcmp(argv[i], "..") == 0))
1540             {
1541                 pmode++;
1542                 strcpy(path, argv[i]);
1543             }
1544             else
1545             {
1546                 cmode++;
1547                 strcpy(cell, argv[i]);
1548             }
1549         }
1550         else
1551             usage();
1552
1553         if (cmode)
1554         {
1555             if (((i + 1) < argc) && (strcmp(argv[i + 1], "-k") == 0))
1556             {
1557                 i += 2;
1558                 if (i < argc)
1559                     strcpy(realm, argv[i]);
1560                 else
1561                     usage();
1562             }
1563             /* Add this cell to list of cells */
1564             strcpy(cellinfo.cell, cell);
1565             strcpy(cellinfo.realm, realm);
1566             if (cur_node = ll_add_node(&cells, ll_tail))
1567             {
1568                 char *new_cellinfo;
1569                 if (new_cellinfo = copy_cellinfo(&cellinfo))
1570                     ll_add_data(cur_node, new_cellinfo);
1571                 else
1572                 {
1573                     fprintf(stderr, "%s: failure copying cellinfo.\n", progname);
1574                     akexit(AKLOG_MISC);
1575                 }
1576             }
1577             else
1578             {
1579                 fprintf(stderr, "%s: failure adding cell to cells list.\n",
1580                          progname);
1581                 akexit(AKLOG_MISC);
1582             }
1583             memset(&cellinfo, 0, sizeof(cellinfo));
1584             cmode = FALSE;
1585             memset(cell, 0, sizeof(cell));
1586             memset(realm, 0, sizeof(realm));
1587         }
1588         else if (pmode)
1589         {
1590             /* Add this path to list of paths */
1591             if (cur_node = ll_add_node(&paths, ll_tail))
1592             {
1593                 char *new_path;
1594                 if (new_path = strdup(path))
1595                     ll_add_data(cur_node, new_path);
1596                 else
1597                 {
1598                     fprintf(stderr, "%s: failure copying path name.\n",
1599                              progname);
1600                     akexit(AKLOG_MISC);
1601                 }
1602             }
1603             else
1604             {
1605                 fprintf(stderr, "%s: failure adding path to paths list.\n",
1606                          progname);
1607                 akexit(AKLOG_MISC);
1608             }
1609             pmode = FALSE;
1610             memset(path, 0, sizeof(path));
1611         }
1612     }
1613
1614     if (!noprdb)
1615         initialize_PT_error_table();
1616
1617     if (usev5) {
1618         validate_krb5_availability();
1619         if (krb5_init_context(&context))
1620             return(AKLOG_KERBEROS);
1621         if (krb5_enctype_valid(context, ETYPE_DES_CBC_CRC))
1622             krb5_enctype_enable(context, ETYPE_DES_CBC_CRC);
1623     } else
1624         validate_krb4_availability();
1625     afs_set_com_err_hook(redirect_errors);
1626
1627     /* If nothing was given, log to the local cell. */
1628     if ((cells.nelements + paths.nelements) == 0)
1629         status = auth_to_cell(context, NULL, NULL);
1630     else
1631     {
1632         /* Log to all cells in the cells list first */
1633         for (cur_node = cells.first; cur_node; cur_node = cur_node->next)
1634         {
1635             memcpy(&cellinfo, cur_node->data, sizeof(cellinfo));
1636             if (status = auth_to_cell(context,
1637                                        cellinfo.cell, cellinfo.realm))
1638                 somethingswrong++;
1639         }
1640
1641         /* Then, log to all paths in the paths list */
1642         for (cur_node = paths.first; cur_node; cur_node = cur_node->next)
1643         {
1644             if (status = auth_to_path(context,
1645                                        cur_node->data))
1646                 somethingswrong++;
1647         }
1648
1649         /*
1650         * If only one thing was logged to, we'll return the status
1651         * of the single call.  Otherwise, we'll return a generic
1652         * something failed status.
1653         */
1654         if (somethingswrong && ((cells.nelements + paths.nelements) > 1))
1655             status = AKLOG_SOMETHINGSWRONG;
1656     }
1657
1658     akexit(status);
1659 }