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