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