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