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