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