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