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