Linux: fix aklog -setpag to work with ktc_SetTokenEx
[openafs.git] / src / auth / ktc.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  *
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 /* ticket caching code */
11
12 #include <afsconfig.h>
13 #include <afs/param.h>
14
15 #if defined(UKERNEL)
16 #include "afsincludes.h"
17 #endif
18
19 #ifdef  AFS_SUN5_ENV
20 #include <unistd.h>
21 #endif
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <afs/stds.h>
25 #include <afs/pthread_glock.h>
26 #include <sys/types.h>
27 #include <ctype.h>
28 #include <sys/stat.h>
29 #include <signal.h>
30 #include <errno.h>
31 #include <sys/ioctl.h>
32 #include <netinet/in.h>
33 #include <string.h>
34 #include <afs/vice.h>
35 #ifdef  AFS_AIX_ENV
36 #include <sys/lockf.h>
37 #ifdef AFS_AIX51_ENV
38 #include <sys/cred.h>
39 #ifdef HAVE_SYS_PAG_H
40 #include <sys/pag.h>
41 #endif
42 #endif
43 #endif
44 #ifdef HAVE_CRT_EXTERNS_H
45 #include <crt_externs.h>
46 #endif
47 #ifdef HAVE_UNISTD_H
48 #include <unistd.h>
49 #endif
50 #include <afs/auth.h>
51 #include <afs/venus.h>
52 #include <afs/afsutil.h>
53
54 #if !defined(UKERNEL)
55 #include <afs/sys_prototypes.h>
56 #endif
57
58 #include "token.h"
59
60 #if defined(AFS_LINUX26_ENV)
61 #include <sys/syscall.h>
62 #if defined(SYS_keyctl)
63 /* Open code this value to avoid a dependency on keyutils */
64 #define KEYCTL_SESSION_TO_PARENT        18
65 #endif
66 #endif
67
68 /* For malloc() */
69 #include <stdlib.h>
70 #include "ktc.h"
71
72 #ifdef  notdef
73 /* AFS_KERBEROS_ENV is now conditionally defined in the Makefile */
74 #define AFS_KERBEROS_ENV
75 #endif
76
77 #ifdef AFS_KERBEROS_ENV
78 #include <fcntl.h>
79 #include <sys/file.h>
80 #include <afs/cellconfig.h>
81 static char lcell[MAXCELLCHARS];
82
83 #define TKT_ROOT "/tmp/tkt"
84
85 #define KSUCCESS 0
86 #define KFAILURE 255
87
88 /* Definitions for ticket file utilities */
89 #define R_TKT_FIL       0
90 #define W_TKT_FIL       1
91
92 /* Error codes returned by ticket file utilities */
93 #define         NO_TKT_FIL      76      /* No ticket file found */
94 #define         TKT_FIL_ACC     77      /* Couldn't access tkt file */
95 #define         TKT_FIL_LCK     78      /* Couldn't lock ticket file */
96 #define         TKT_FIL_FMT     79      /* Bad ticket file format */
97 #define         TKT_FIL_INI     80      /* afs_tf_init not called first */
98
99 /* Values returned by get_credentials */
100 #define         RET_TKFIL      21       /* Can't read ticket file */
101
102 #ifndef BUFSIZ
103 #define BUFSIZ 4096
104 #endif
105
106 #ifdef  AFS_HPUX_ENV
107 #include <unistd.h>
108 #endif
109 #if     defined(AFS_AIX_ENV) || defined(AFS_SUN5_ENV)
110 static struct flock fileWlock = { F_WRLCK, 0, 0, 0, 0, 0 };
111 static struct flock fileRlock = { F_RDLCK, 0, 0, 0, 0, 0 };
112 static struct flock fileUlock = { F_UNLCK, 0, 0, 0, 0, 0 };
113 #endif
114 #ifdef AFS_HPUX_ENV
115 static struct flock fileWlock = { F_WRLCK, 0, 0, 0, 0 };
116 static struct flock fileRlock = { F_RDLCK, 0, 0, 0, 0 };
117 static struct flock fileUlock = { F_UNLCK, 0, 0, 0, 0 };
118 #endif
119
120 #ifndef EOF
121 #define EOF (-1)
122 #endif
123
124 /* the following routines aren't static anymore on behalf of the kerberos IV
125  * compatibility library built in subtree krb.
126  */
127 int afs_tf_init(char *, int);
128 int afs_tf_get_pname(char *);
129 int afs_tf_get_pinst(char *);
130 int afs_tf_get_cred(struct ktc_principal *, struct ktc_token *);
131 int afs_tf_save_cred(struct ktc_principal *, struct ktc_token *,
132                      struct ktc_principal *);
133 int afs_tf_close(void);
134 int afs_tf_create(char *, char *);
135 int afs_tf_dest_tkt(void);
136 static void ktc_LocalCell(void);
137 #endif /* AFS_KERBEROS_ENV */
138
139 #ifdef AFS_DUX40_ENV
140 #define PIOCTL afs_pioctl
141 #elif defined(UKERNEL)
142 #define PIOCTL(A,B,C,D) call_syscall(AFSCALL_PIOCTL,A,B,C,D)
143 #else
144 #define PIOCTL pioctl
145 #endif
146
147 #if !defined(UKERNEL)
148 /* this is a structure used to communicate with the afs cache mgr, but is
149  * otherwise irrelevant */
150 struct ClearToken {
151     afs_int32 AuthHandle;
152     char HandShakeKey[8];
153     afs_int32 ViceId;
154     afs_int32 BeginTimestamp;
155     afs_int32 EndTimestamp;
156 };
157 #endif /* !defined(UKERNEL) */
158
159 #define MAXLOCALTOKENS 4
160
161 static struct {
162     int valid;
163     struct ktc_principal server;
164     struct ktc_principal client;
165     struct ktc_token token;
166 } local_tokens[MAXLOCALTOKENS] = { {
167 0}, {
168 0}, {
169 0}, {
170 0}};
171
172
173 #define MAXPIOCTLTOKENLEN \
174 (3*sizeof(afs_int32)+MAXKTCTICKETLEN+sizeof(struct ClearToken)+MAXKTCREALMLEN)
175
176 static int
177 SetToken(struct ktc_principal *aserver, struct ktc_token *atoken,
178             struct ktc_principal *aclient, afs_int32 flags)
179 {
180     struct ViceIoctl iob;
181     char tbuffer[MAXPIOCTLTOKENLEN];
182     char *tp;
183     struct ClearToken ct;
184     afs_int32 code;
185     afs_int32 temp;
186
187     if (strcmp(aserver->name, "afs") != 0) {
188         int found = -1;
189         int i;
190         for (i = 0; i < MAXLOCALTOKENS; i++)
191             if (local_tokens[i].valid) {
192                 if ((strcmp(local_tokens[i].server.name, aserver->name) == 0)
193                     &&
194                     (strcmp
195                      (local_tokens[i].server.instance,
196                       aserver->instance) == 0)
197                     && (strcmp(local_tokens[i].server.cell, aserver->cell) ==
198                         0)) {
199                     found = i;  /* replace existing entry */
200                     break;
201                 } else          /* valid, but no match */
202                     ;
203             } else
204                 found = i;      /* remember this empty slot */
205         if (found == -1)
206             return KTC_NOENT;
207         memcpy(&local_tokens[found].token, atoken, sizeof(struct ktc_token));
208         local_tokens[found].server = *aserver;
209         local_tokens[found].client = *aclient;
210         local_tokens[found].valid = 1;
211         return 0;
212     }
213     tp = tbuffer;               /* start copying here */
214     if ((atoken->ticketLen < MINKTCTICKETLEN)
215         || (atoken->ticketLen > MAXKTCTICKETLEN))
216         return KTC_TOOBIG;
217     memcpy(tp, &atoken->ticketLen, sizeof(afs_int32));  /* copy in ticket length */
218     tp += sizeof(afs_int32);
219     memcpy(tp, atoken->ticket, atoken->ticketLen);      /* copy in ticket */
220     tp += atoken->ticketLen;
221     /* next, copy in the "clear token", describing who we are */
222     ct.AuthHandle = atoken->kvno;       /* hide auth handle here */
223     memcpy(ct.HandShakeKey, &atoken->sessionKey, 8);
224
225     ct.BeginTimestamp = atoken->startTime;
226     ct.EndTimestamp = atoken->endTime;
227     if (ct.BeginTimestamp == 0)
228         ct.BeginTimestamp = 1;
229
230     if ((strlen(aclient->name) > strlen("AFS ID "))
231         && (aclient->instance[0] == 0)) {
232         int sign = 1;
233         afs_int32 viceId = 0;
234         char *cp = aclient->name + strlen("AFS ID ");
235         if (*cp == '-') {
236             sign = -1;
237             cp++;
238         }
239         while (*cp) {
240             if (isdigit(*cp))
241                 viceId = viceId * 10 + (int)(*cp - '0');
242             else
243                 goto not_vice_id;
244             cp++;
245         }
246         ct.ViceId = viceId * sign;      /* OK to let any value here? */
247         if (((ct.EndTimestamp - ct.BeginTimestamp) & 1) == 0)
248             ct.BeginTimestamp++;        /* force lifetime to be odd */
249     } else {
250       not_vice_id:
251         ct.ViceId = getuid();   /* wrong, but works in primary cell */
252         if (((ct.EndTimestamp - ct.BeginTimestamp) & 1) == 1)
253             ct.BeginTimestamp++;        /* force lifetime to be even */
254     }
255
256 #ifdef UKERNEL
257     /*
258      * Information needed by the user space cache manager
259      */
260     get_user_struct()->u_expiration = ct.EndTimestamp;
261     get_user_struct()->u_viceid = ct.ViceId;
262 #endif
263
264     temp = sizeof(struct ClearToken);
265     memcpy(tp, &temp, sizeof(afs_int32));
266     tp += sizeof(afs_int32);
267     memcpy(tp, &ct, sizeof(struct ClearToken));
268     tp += sizeof(struct ClearToken);
269
270     /* next copy in primary flag */
271     temp = 0;
272
273     /*
274      * The following means that setpag will happen inside afs just before
275      * the authentication to prevent the setpag/klog race condition.
276      *
277      * The following means that setpag will affect the parent process as
278      * well as the current process.
279      */
280     if (flags & AFS_SETTOK_SETPAG)
281         temp |= 0x8000;
282
283     memcpy(tp, &temp, sizeof(afs_int32));
284     tp += sizeof(afs_int32);
285
286     /* finally copy in the cell name */
287     temp = strlen(aserver->cell);
288     if (temp >= MAXKTCREALMLEN)
289         return KTC_TOOBIG;
290     strcpy(tp, aserver->cell);
291     tp += temp + 1;
292
293     /* now setup for the pioctl */
294     iob.in = tbuffer;
295     iob.in_size = tp - tbuffer;
296     iob.out = tbuffer;
297     iob.out_size = sizeof(tbuffer);
298
299 #if defined(NO_AFS_CLIENT)
300     {
301         int fd;                 /* DEBUG */
302         char *tkfile;
303         if ((tkfile = getenv("TKTFILE"))
304             &&
305             ((fd =
306               open(tkfile, O_WRONLY | O_APPEND | O_TRUNC | O_CREAT,
307                    0644)) >= 0)) {
308             printf("Writing ticket to: %s\n", tkfile);
309             code = (write(fd, iob.in, iob.in_size) != iob.in_size);
310             close(fd);
311         } else
312             code = KTC_PIOCTLFAIL;
313     }
314 #else /* NO_AFS_CLIENT */
315     code = PIOCTL(0, VIOCSETTOK, &iob, 0);
316 #endif /* NO_AFS_CLIENT */
317     if (code)
318         return KTC_PIOCTLFAIL;
319     return 0;
320 }
321
322 int
323 ktc_SetTokenEx(struct ktc_setTokenData *token) {
324     struct ViceIoctl iob;
325     afs_int32 code;
326     XDR xdrs;
327
328     xdrlen_create(&xdrs);
329     if (!xdr_ktc_setTokenData(&xdrs, token))
330         return EINVAL;
331     iob.in_size = xdr_getpos(&xdrs);
332     xdr_destroy(&xdrs);
333
334     iob.in = malloc(iob.in_size);
335     if (iob.in == NULL)
336         return ENOMEM;
337
338     xdrmem_create(&xdrs, iob.in, iob.in_size, XDR_ENCODE);
339     if (!xdr_ktc_setTokenData(&xdrs, token))
340         return KTC_INVAL;
341     xdr_destroy(&xdrs);
342
343     iob.out = NULL;
344     iob.out_size = 0;
345
346     code = PIOCTL(0, VIOC_SETTOK2, &iob, 0);
347
348     free(iob.in);
349
350     /* If we can't use the new pioctl, then fallback to using the old
351      * one, with just the rxkad portion of the token we're being asked to
352      * set
353      */
354     if (code == -1 && errno == EINVAL) {
355         struct ktc_principal server, client;
356         struct ktc_token *rxkadToken;
357         afs_int32 flags;
358
359         /* With the growth of ticket sizes, a ktc_token is now 12k. Don't
360          * allocate it on the stack! */
361         rxkadToken = malloc(sizeof(*rxkadToken));
362         if (rxkadToken == NULL)
363             return ENOMEM;
364
365         code = token_extractRxkad(token, rxkadToken, &flags, &client);
366         if (code) {
367             free(rxkadToken);
368             return KTC_INVAL;
369         }
370
371         memset(&server, 0, sizeof(server));
372         strcpy(server.name, "afs");
373         strcpy(server.cell, token->cell);
374         code = ktc_SetToken(&server, rxkadToken, &client, flags);
375         free(rxkadToken);
376         return code;
377     }
378
379     if (code)
380         return KTC_PIOCTLFAIL;
381 #if defined(AFS_LINUX26_ENV) && defined(SYS_keyctl)
382     else
383         /*
384          * If we're using keyring based PAGs and the SESSION_TO_PARENT keyctl
385          * is available, use it to copy the session keyring to the parent process
386          */
387         if (token->flags & AFS_SETTOK_SETPAG)
388             syscall(SYS_keyctl, KEYCTL_SESSION_TO_PARENT);
389 #endif
390
391     return 0;
392 }
393
394 int
395 ktc_SetToken(struct ktc_principal *aserver,
396     struct ktc_token *atoken,
397     struct ktc_principal *aclient,
398     afs_int32 flags)
399 {
400     int code;
401
402     LOCK_GLOBAL_MUTEX;
403 #ifdef AFS_KERBEROS_ENV
404     if (!lcell[0])
405         ktc_LocalCell();
406
407     if (                        /*!strcmp(aclient->cell, lcell) && this would only store local creds */
408            (strcmp(aserver->name, "AuthServer")
409             || strcmp(aserver->instance, "Admin"))) {
410         if (strcmp(aserver->name, "krbtgt") == 0) {
411             static char lrealm[MAXKTCREALMLEN];
412
413             if (!lrealm[0])
414                 ucstring(lrealm, lcell, MAXKTCREALMLEN);
415             if (strcmp(aserver->instance, lrealm) == 0) {
416                 afs_tf_create(aclient->name, aclient->instance);
417             }
418         }
419
420         code = afs_tf_init(ktc_tkt_string(), W_TKT_FIL);
421         if (code == NO_TKT_FIL) {
422             (void)afs_tf_create(aclient->name, aclient->instance);
423             code = afs_tf_init(ktc_tkt_string(), W_TKT_FIL);
424         }
425
426         if (!code) {
427             afs_tf_save_cred(aserver, atoken, aclient);
428         }
429         afs_tf_close();
430 #ifdef NO_AFS_CLIENT
431         UNLOCK_GLOBAL_MUTEX;
432         return code;
433 #endif /* NO_AFS_CLIENT */
434     }
435 #endif
436
437 #ifndef NO_AFS_CLIENT
438     code = SetToken(aserver, atoken, aclient, flags);
439     if (code) {
440         UNLOCK_GLOBAL_MUTEX;
441         if (code == -1)
442             code = errno;
443         else if (code == KTC_PIOCTLFAIL)
444             code = errno;
445         if (code == ESRCH)
446             return KTC_NOCELL;
447         if (code == EINVAL)
448             return KTC_NOPIOCTL;
449         if (code == EIO)
450             return KTC_NOCM;
451         return KTC_PIOCTLFAIL;
452     }
453 #endif /* NO_AFS_CLIENT */
454     UNLOCK_GLOBAL_MUTEX;
455     return 0;
456 }
457
458 /*!
459  * Get a token, given the cell that we need to get information for
460  *
461  * @param cellName
462  *      The name of the cell we're getting the token for - if NULL, we'll
463  *      get information for the primary cell
464  */
465 int
466 ktc_GetTokenEx(char *cellName, struct ktc_setTokenData **tokenSet) {
467     struct ViceIoctl iob;
468     char tbuffer[MAXPIOCTLTOKENLEN];
469     char *tp;
470     afs_int32 code;
471     XDR xdrs;
472
473     tp = tbuffer;
474
475     /* If we have a cellName, write it out here */
476     if (cellName) {
477         memcpy(tp, cellName, strlen(cellName) +1);
478         tp += strlen(cellName)+1;
479     }
480
481     iob.in = tbuffer;
482     iob.in_size = tp - tbuffer;
483     iob.out = tbuffer;
484     iob.out_size = sizeof(tbuffer);
485
486     code = PIOCTL(0, VIOC_GETTOK2, &iob, 0);
487
488     /* If we can't use the new pioctl, the fall back to the old one. We then
489      * need to convert the rxkad token we get back into the new format
490      */
491     if (code == -1 && errno == EINVAL) {
492         struct ktc_principal server;
493         struct ktc_principal client;
494         struct ktc_tokenUnion token;
495         struct ktc_token *ktcToken; /* too huge for the stack */
496
497         memset(&server, 0, sizeof(server));
498         ktcToken = malloc(sizeof(struct ktc_token));
499         if (ktcToken == NULL)
500             return ENOMEM;
501         memset(ktcToken, 0, sizeof(struct ktc_token));
502
503         strcpy(server.name, "afs");
504         strcpy(server.cell, cellName);
505         code = ktc_GetToken(&server, ktcToken, sizeof(struct ktc_token),
506                             &client);
507         if (code == 0) {
508             *tokenSet = token_buildTokenJar(cellName);
509             token.at_type = AFSTOKEN_UNION_KAD;
510             token.ktc_tokenUnion_u.at_kad.rk_kvno = ktcToken->kvno;
511             memcpy(token.ktc_tokenUnion_u.at_kad.rk_key,
512                    ktcToken->sessionKey.data, 8);
513
514             token.ktc_tokenUnion_u.at_kad.rk_begintime = ktcToken->startTime;
515             token.ktc_tokenUnion_u.at_kad.rk_endtime   = ktcToken->endTime;
516             token.ktc_tokenUnion_u.at_kad.rk_ticket.rk_ticket_len
517                 = ktcToken->ticketLen;
518             token.ktc_tokenUnion_u.at_kad.rk_ticket.rk_ticket_val
519                 = ktcToken->ticket;
520
521             token_addToken(*tokenSet, &token);
522
523             memset(ktcToken, 0, sizeof(struct ktc_token));
524         }
525         free(ktcToken);
526     }
527     if (code)
528         return KTC_PIOCTLFAIL;
529
530     *tokenSet = malloc(sizeof(struct ktc_setTokenData));
531     if (*tokenSet == NULL)
532         return ENOMEM;
533     memset(*tokenSet, 0, sizeof(struct ktc_setTokenData));
534
535     xdrmem_create(&xdrs, iob.out, iob.out_size, XDR_DECODE);
536     if (!xdr_ktc_setTokenData(&xdrs, *tokenSet)) {
537         free(*tokenSet);
538         *tokenSet = NULL;
539         xdr_destroy(&xdrs);
540         return EINVAL;
541     }
542     xdr_destroy(&xdrs);
543     return 0;
544 }
545
546 /* get token, given server we need and token buffer.  aclient will eventually
547  * be set to our identity to the server.
548  */
549 int
550 ktc_GetToken(struct ktc_principal *aserver, struct ktc_token *atoken,
551              int atokenLen, struct ktc_principal *aclient)
552 {
553     struct ViceIoctl iob;
554     char tbuffer[MAXPIOCTLTOKENLEN];
555     afs_int32 code = 0;
556     int index;
557     char *stp, *cellp;          /* secret token ptr */
558     struct ClearToken ct;
559     char *tp;
560     afs_int32 temp;
561     int maxLen;                 /* biggest ticket we can copy */
562     int tktLen;                 /* server ticket length */
563 #ifdef AFS_KERBEROS_ENV
564     char found = 0;
565 #endif
566
567     LOCK_GLOBAL_MUTEX;
568
569 #ifdef AFS_KERBEROS_ENV
570     if (!lcell[0])
571         ktc_LocalCell();
572 #endif
573 #ifndef NO_AFS_CLIENT
574     if (strcmp(aserver->name, "afs") != 0)
575 #endif /* NO_AFS_CLIENT */
576     {
577         int i;
578         /* try the local tokens */
579         for (i = 0; i < MAXLOCALTOKENS; i++)
580             if (local_tokens[i].valid
581                 && (strcmp(local_tokens[i].server.name, aserver->name) == 0)
582                 && (strcmp(local_tokens[i].server.instance, aserver->instance)
583                     == 0)
584                 && (strcmp(local_tokens[i].server.cell, aserver->cell) == 0)) {
585                 memcpy(atoken, &local_tokens[i].token,
586                        min(atokenLen, sizeof(struct ktc_token)));
587                 if (aclient)
588                     *aclient = local_tokens[i].client;
589                 UNLOCK_GLOBAL_MUTEX;
590                 return 0;
591             }
592 #ifdef AFS_KERBEROS_ENV
593         if (!afs_tf_init(ktc_tkt_string(), R_TKT_FIL)) {
594             if (aclient) {
595                 if (!afs_tf_get_pname(aclient->name)
596                     && !afs_tf_get_pinst(aclient->instance))
597                     found = 1;
598             } else {
599                 char tmpstring[MAXHOSTCHARS];
600                 afs_tf_get_pname(tmpstring);
601                 afs_tf_get_pinst(tmpstring);
602                 found = 1;
603             }
604         }
605         if (found) {
606             struct ktc_principal cprincipal;
607             struct ktc_token ctoken;
608
609             while (!afs_tf_get_cred(&cprincipal, &ctoken)) {
610                 if (strcmp(cprincipal.name, aserver->name) == 0
611                     && strcmp(cprincipal.instance, aserver->instance) == 0
612                     && strcmp(cprincipal.cell, aserver->cell) == 0) {
613
614                     if (aclient)
615                         strcpy(aclient->cell, lcell);
616                     memcpy(atoken, &ctoken,
617                            min(atokenLen, sizeof(struct ktc_token)));
618
619                     afs_tf_close();
620                     UNLOCK_GLOBAL_MUTEX;
621                     return 0;
622                 }
623             }
624         }
625         afs_tf_close();
626 #endif
627         UNLOCK_GLOBAL_MUTEX;
628         return KTC_NOENT;
629     }
630 #ifndef NO_AFS_CLIENT
631     for (index = 0; index < 200; index++) {     /* sanity check in case pioctl fails */
632         iob.in = (char *)&index;
633         iob.in_size = sizeof(afs_int32);
634         iob.out = tbuffer;
635         iob.out_size = sizeof(tbuffer);
636
637         code = PIOCTL(0, VIOCGETTOK, &iob, 0);
638
639         if (code) {
640             /* failed to retrieve specified token */
641             if (code < 0 && errno == EDOM) {
642                 UNLOCK_GLOBAL_MUTEX;
643                 return KTC_NOENT;
644             }
645         } else {
646             /* token retrieved; parse buffer */
647             tp = tbuffer;
648
649             /* get ticket length */
650             memcpy(&temp, tp, sizeof(afs_int32));
651             tktLen = temp;
652             tp += sizeof(afs_int32);
653
654             /* remember where ticket is and skip over it */
655             stp = tp;
656             tp += tktLen;
657
658             /* get size of clear token and verify */
659             memcpy(&temp, tp, sizeof(afs_int32));
660             if (temp != sizeof(struct ClearToken)) {
661                 UNLOCK_GLOBAL_MUTEX;
662                 return KTC_ERROR;
663             }
664             tp += sizeof(afs_int32);
665
666             /* copy clear token */
667             memcpy(&ct, tp, temp);
668             tp += temp;
669
670             /* skip over primary flag */
671             tp += sizeof(afs_int32);
672
673             /* remember where cell name is */
674             cellp = tp;
675
676             if ((strcmp(cellp, aserver->cell) == 0)
677 #ifdef  AFS_KERBEROS_ENV
678                 || (*aserver->cell == '\0' && strcmp(cellp, lcell) == 0)
679 #endif
680                 ) {
681                 /* got token for cell; check that it will fit */
682                 maxLen =
683                     atokenLen - sizeof(struct ktc_token) + MAXKTCTICKETLEN;
684                 if (maxLen < tktLen) {
685                     UNLOCK_GLOBAL_MUTEX;
686                     return KTC_TOOBIG;
687                 }
688
689                 /* set return values */
690                 memcpy(atoken->ticket, stp, tktLen);
691                 atoken->startTime = ct.BeginTimestamp;
692                 atoken->endTime = ct.EndTimestamp;
693                 if (ct.AuthHandle == -1) {
694                     ct.AuthHandle = 999;
695                 }
696                 atoken->kvno = ct.AuthHandle;
697                 memcpy(&atoken->sessionKey, ct.HandShakeKey,
698                        sizeof(struct ktc_encryptionKey));
699                 atoken->ticketLen = tktLen;
700
701                 if (aclient) {
702                     strcpy(aclient->cell, cellp);
703                     aclient->instance[0] = 0;
704
705                     if ((atoken->kvno == 999) ||        /* old style bcrypt ticket */
706                         (ct.BeginTimestamp &&   /* new w/ prserver lookup */
707                          (((ct.EndTimestamp - ct.BeginTimestamp) & 1) == 1))) {
708                         sprintf(aclient->name, "AFS ID %d", ct.ViceId);
709                     } else {
710                         sprintf(aclient->name, "Unix UID %d", ct.ViceId);
711                     }
712                 }
713                 UNLOCK_GLOBAL_MUTEX;
714                 return 0;
715             }
716         }
717     }
718 #endif /* NO_AFS_CLIENT */
719
720     UNLOCK_GLOBAL_MUTEX;
721     if ((code < 0) && (errno == EINVAL))
722         return KTC_NOPIOCTL;
723     return KTC_PIOCTLFAIL;      /* probable cause */
724 }
725
726 /*
727  * Forget tokens for this server and the calling user.
728  * NOT IMPLEMENTED YET!
729  */
730 #ifndef NO_AFS_CLIENT
731 int
732 ktc_ForgetToken(struct ktc_principal *aserver)
733 {
734     int rc;
735
736     LOCK_GLOBAL_MUTEX;
737     rc = ktc_ForgetAllTokens(); /* bogus, but better */
738     UNLOCK_GLOBAL_MUTEX;
739     return rc;
740 }
741 #endif /* NO_AFS_CLIENT */
742
743 /*!
744  * An iterator which can list all cells with tokens in the cache
745  *
746  * This function may be used to list the names of all cells for which
747  * tokens exist in the current cache. The first time that it is called,
748  * prevIndex should be set to 0. On all subsequent calls, prevIndex
749  * should be set to the value returned in newIndex by the last call
750  * to the function. Note that there is no guarantee that the index value
751  * is monotonically increasing.
752  *
753  * @param prevIndex
754  *      The index returned by the last call, or 0 if this is the first
755  *      call in an iteration
756  * @param newIndex
757  *      A pointer to an int which, upon return, will hold the next value
758  *      to be used.
759  * @param cellName
760  *      A pointer to a char * which, upon return, will hold a cellname.
761  *      This must be freed by the caller using free()
762  */
763
764 int
765 ktc_ListTokensEx(int prevIndex, int *newIndex, char **cellName) {
766     struct ViceIoctl iob;
767     char tbuffer[MAXPIOCTLTOKENLEN];
768     afs_int32 code;
769     afs_int32 index;
770     struct ktc_setTokenData tokenSet;
771     XDR xdrs;
772
773     memset(&tokenSet, 0, sizeof(tokenSet));
774
775     *cellName = NULL;
776     *newIndex = prevIndex;
777
778     index = prevIndex;
779
780     while (index<100) { /* Safety, incase of pioctl failure */
781         memset(tbuffer, 0, sizeof(tbuffer));
782         iob.in = tbuffer;
783         memcpy(tbuffer, &index, sizeof(afs_int32));
784         iob.in_size = sizeof(afs_int32);
785         iob.out = tbuffer;
786         iob.out_size = sizeof(tbuffer);
787
788         code = PIOCTL(0, VIOC_GETTOK2, &iob, 0);
789
790         /* Can't use new pioctl, so must use old one */
791         if (code == -1 && errno == EINVAL) {
792             struct ktc_principal server;
793
794             code = ktc_ListTokens(index, newIndex, &server);
795             if (code == 0)
796                 *cellName = strdup(server.cell);
797             return code;
798         }
799
800         if (code == 0) {
801             /* Got a token from the pioctl. Now we throw it away,
802              * so we can return just a cellname. This is rather wasteful,
803              * but it's what the old API does. Ho hum.  */
804
805             xdrmem_create(&xdrs, iob.out, iob.out_size, XDR_DECODE);
806             if (!xdr_ktc_setTokenData(&xdrs, &tokenSet)) {
807                 xdr_destroy(&xdrs);
808                 return EINVAL;
809             }
810             xdr_destroy(&xdrs);
811             *cellName = strdup(tokenSet.cell);
812             xdr_free((xdrproc_t)xdr_ktc_setTokenData, &tokenSet);
813             *newIndex = index + 1;
814             return 0;
815         }
816         index++;
817     }
818     return KTC_PIOCTLFAIL;
819 }
820
821 /* ktc_ListTokens - list all tokens.  start aprevIndex at 0, it returns the
822  * next rock in (*aindex).  (*aserver) is set to the relevant ticket on
823  * success.  */
824
825 int
826 ktc_ListTokens(int aprevIndex,
827     int *aindex,
828     struct ktc_principal *aserver)
829 {
830     struct ViceIoctl iob;
831     char tbuffer[MAXPIOCTLTOKENLEN];
832     afs_int32 code = 0 ;
833     char *tp;
834     afs_int32 temp, index;
835
836     memset(tbuffer, 0, sizeof(tbuffer));
837
838     LOCK_GLOBAL_MUTEX;
839
840     index = aprevIndex;
841 #ifdef NO_AFS_CLIENT
842     if (index < 214)
843         index = 214;
844 #endif /* NO_AFS_CLIENT */
845 #ifdef AFS_KERBEROS_ENV
846     if (index >= 214) {
847         int i;
848         struct ktc_principal cprincipal;
849         struct ktc_token ctoken;
850
851         if (afs_tf_init(ktc_tkt_string(), R_TKT_FIL)
852             || afs_tf_get_pname(tbuffer) || afs_tf_get_pinst(tbuffer)) {
853             afs_tf_close();
854             UNLOCK_GLOBAL_MUTEX;
855             return KTC_NOENT;
856         }
857
858         for (i = 214; i < index; i++) {
859             if (afs_tf_get_cred(&cprincipal, &ctoken)) {
860                 afs_tf_close();
861                 UNLOCK_GLOBAL_MUTEX;
862                 return KTC_NOENT;
863             }
864         }
865
866       again:
867         if (afs_tf_get_cred(&cprincipal, &ctoken)) {
868             afs_tf_close();
869             UNLOCK_GLOBAL_MUTEX;
870             return KTC_NOENT;
871         }
872         index++;
873
874 #ifndef NO_AFS_CLIENT
875         if (!strcmp(cprincipal.name, "afs") && cprincipal.instance[0] == 0) {
876             goto again;
877         }
878 #endif /* NO_AFS_CLIENT */
879
880         for (i = 0; i < MAXLOCALTOKENS; i++) {
881             if (!strcmp(cprincipal.name, local_tokens[i].server.name)
882                 && !strcmp(cprincipal.instance,
883                            local_tokens[i].server.instance)
884                 && !strcmp(cprincipal.cell, local_tokens[i].server.cell)) {
885                 goto again;
886             }
887         }
888
889         *aserver = cprincipal;
890         *aindex = index;
891         afs_tf_close();
892         UNLOCK_GLOBAL_MUTEX;
893         return 0;
894     }
895 #endif
896
897 #ifndef NO_AFS_CLIENT
898     if (index >= 123) {         /* special hack for returning TCS */
899         while (index - 123 < MAXLOCALTOKENS) {
900             if (local_tokens[index - 123].valid) {
901                 *aserver = local_tokens[index - 123].server;
902                 *aindex = index + 1;
903                 UNLOCK_GLOBAL_MUTEX;
904                 return 0;
905             }
906             index++;
907         }
908         UNLOCK_GLOBAL_MUTEX;
909 #ifdef AFS_KERBEROS_ENV
910         return ktc_ListTokens(214, aindex, aserver);
911 #else
912         return KTC_NOENT;
913 #endif
914     }
915
916     /* get tokens from the kernel */
917     while (index < 200) {       /* sanity check in case pioctl fails */
918         iob.in = (char *)&index;
919         iob.in_size = sizeof(afs_int32);
920         iob.out = tbuffer;
921         iob.out_size = sizeof(tbuffer);
922         code = PIOCTL(0, VIOCGETTOK, &iob, 0);
923         if (code < 0 && errno == EDOM) {
924             if (index < 123) {
925                 int rc;
926                 rc = ktc_ListTokens(123, aindex, aserver);
927                 UNLOCK_GLOBAL_MUTEX;
928                 return rc;
929             } else {
930                 UNLOCK_GLOBAL_MUTEX;
931                 return KTC_NOENT;
932             }
933         }
934         if (code == 0)
935             break;              /* got a ticket */
936         /* otherwise we should skip this ticket slot */
937         index++;
938     }
939     if (code < 0) {
940         UNLOCK_GLOBAL_MUTEX;
941         if (errno == EINVAL)
942             return KTC_NOPIOCTL;
943         return KTC_PIOCTLFAIL;
944     }
945
946     /* parse buffer */
947     tp = tbuffer;
948
949     /* next iterator determined by earlier loop */
950     *aindex = index + 1;
951
952     memcpy(&temp, tp, sizeof(afs_int32));       /* get size of secret token */
953     tp += sizeof(afs_int32);
954     tp += temp;                 /* skip ticket for now */
955     memcpy(&temp, tp, sizeof(afs_int32));       /* get size of clear token */
956     if (temp != sizeof(struct ClearToken)) {
957         UNLOCK_GLOBAL_MUTEX;
958         return KTC_ERROR;
959     }
960     tp += sizeof(afs_int32);    /* skip length */
961     tp += temp;                 /* skip clear token itself */
962     tp += sizeof(afs_int32);    /* skip primary flag */
963     /* tp now points to the cell name */
964     strcpy(aserver->cell, tp);
965     aserver->instance[0] = 0;
966     strcpy(aserver->name, "afs");
967 #endif /* NO_AFS_CLIENT */
968     UNLOCK_GLOBAL_MUTEX;
969     return 0;
970 }
971
972 static int
973 ForgetAll(void)
974 {
975     struct ViceIoctl iob;
976     afs_int32 code;
977     int i;
978
979     for (i = 0; i < MAXLOCALTOKENS; i++)
980         local_tokens[i].valid = 0;
981
982     iob.in = 0;
983     iob.in_size = 0;
984     iob.out = 0;
985     iob.out_size = 0;
986 #ifndef NO_AFS_CLIENT
987     code = PIOCTL(0, VIOCUNPAG, &iob, 0);
988     if (code)
989         return KTC_PIOCTLFAIL;
990 #endif /* NO_AFS_CLIENT */
991     return 0;
992 }
993
994 int
995 ktc_ForgetAllTokens(void)
996 {
997     int ocode;
998
999     LOCK_GLOBAL_MUTEX;
1000 #ifdef AFS_KERBEROS_ENV
1001     (void)afs_tf_dest_tkt();
1002 #endif
1003
1004     ocode = ForgetAll();
1005     if (ocode) {
1006         if (ocode == -1)
1007             ocode = errno;
1008         else if (ocode == KTC_PIOCTLFAIL)
1009             ocode = errno;
1010         UNLOCK_GLOBAL_MUTEX;
1011         if (ocode == EINVAL)
1012             return KTC_NOPIOCTL;
1013         return KTC_PIOCTLFAIL;
1014     }
1015     UNLOCK_GLOBAL_MUTEX;
1016     return 0;
1017 }
1018
1019 /* ktc_OldPioctl - returns a boolean true if the kernel supports only the old
1020  * pioctl interface for delivering AFS tickets to the cache manager. */
1021
1022 int
1023 ktc_OldPioctl(void)
1024 {
1025     return 1;
1026 }
1027
1028 afs_uint32
1029 ktc_curpag(void)
1030 {
1031     int code;
1032     struct ViceIoctl iob;
1033     afs_uint32 pag;
1034
1035     /* now setup for the pioctl */
1036     iob.in = NULL;
1037     iob.in_size = 0;
1038     iob.out = (caddr_t) &pag;
1039     iob.out_size = sizeof(afs_uint32);
1040
1041     code = PIOCTL(0, VIOC_GETPAG, &iob, 0);
1042     if (code < 0) {
1043 #if defined(AFS_AIX52_ENV)
1044         code = getpagvalue("afs");
1045         if (code < 0 && errno == EINVAL)
1046             code = 0;
1047         return code;
1048 #elif defined(AFS_AIX51_ENV)
1049         return -1;
1050 #else
1051         gid_t groups[NGROUPS_MAX];
1052         afs_uint32 g0, g1;
1053         afs_uint32 h, l, ret;
1054         int ngroups;
1055 #ifdef AFS_LINUX26_ENV
1056         int i;
1057 #endif
1058
1059         ngroups = getgroups(sizeof groups / sizeof groups[0], groups);
1060
1061 #ifdef AFS_LINUX26_ENV
1062         /* check for AFS_LINUX26_ONEGROUP_ENV PAGs */
1063         for (i = 0; i < ngroups; i++) {
1064             if (((groups[i] >> 24) & 0xff) == 'A') {
1065                 return groups[i];
1066             }
1067         }
1068 #endif
1069
1070         if (ngroups < 2)
1071             return 0;
1072
1073         g0 = groups[0] & 0xffff;
1074         g1 = groups[1] & 0xffff;
1075         g0 -= 0x3f00;
1076         g1 -= 0x3f00;
1077         if (g0 < 0xc000 && g1 < 0xc000) {
1078             l = ((g0 & 0x3fff) << 14) | (g1 & 0x3fff);
1079             h = (g0 >> 14);
1080             h = (g1 >> 14) + h + h + h;
1081             ret = ((h << 28) | l);
1082             /* Additional testing */
1083             if (((ret >> 24) & 0xff) == 'A')
1084                 return ret;
1085             else
1086                 return -1;
1087         }
1088         return -1;
1089 #endif
1090     }
1091     return pag;
1092 }
1093
1094
1095 #ifdef AFS_KERBEROS_ENV
1096  /*
1097   * Copyright 1987, 1988 by the Massachusetts Institute of Technology.
1098   *
1099   * For copying and distribution information, please see the file
1100   * <mit-copyright.h>.
1101   */
1102
1103 #if 0
1104 #include <stdio.h>
1105 #include <errno.h>
1106 #include <sys/types.h>
1107 #include <sys/stat.h>
1108 #include <sys/file.h>
1109 #include <krb.h>
1110 #endif
1111
1112 #define TOO_BIG -1
1113 #define TF_LCK_RETRY ((unsigned)2)      /* seconds to sleep before
1114                                          * retry if ticket file is
1115                                          * locked */
1116
1117 /*
1118  * fd must be initialized to something that won't ever occur as a real
1119  * file descriptor. Since open(2) returns only non-negative numbers as
1120  * valid file descriptors, and afs_tf_init always stuffs the return value
1121  * from open in here even if it is an error flag, we must
1122  *      a. Initialize fd to a negative number, to indicate that it is
1123  *         not initially valid.
1124  *      b. When checking for a valid fd, assume that negative values
1125  *         are invalid (ie. when deciding whether afs_tf_init has been
1126  *         called.)
1127  *      c. In tf_close, be sure it gets reinitialized to a negative
1128  *         number.
1129  */
1130 static int fd = -1;
1131 static int curpos;                      /* Position in tfbfr */
1132 static int lastpos;                     /* End of tfbfr */
1133 static char tfbfr[BUFSIZ];      /* Buffer for ticket data */
1134
1135 static int tf_gets(char *, int);
1136 static int tf_read(char *, int);
1137
1138 /*
1139  * This file contains routines for manipulating the ticket cache file.
1140  *
1141  * The ticket file is in the following format:
1142  *
1143  *      principal's name        (null-terminated string)
1144  *      principal's instance    (null-terminated string)
1145  *      CREDENTIAL_1
1146  *      CREDENTIAL_2
1147  *      ...
1148  *      CREDENTIAL_n
1149  *      EOF
1150  *
1151  *      Where "CREDENTIAL_x" consists of the following fixed-length
1152  *      fields from the CREDENTIALS structure (see "krb.h"):
1153  *
1154  *              char            service[MAXKTCNAMELEN]
1155  *              char            instance[MAXKTCNAMELEN]
1156  *              char            realm[REALM_SZ]
1157  *              C_Block         session
1158  *              int             lifetime
1159  *              int             kvno
1160  *              KTEXT_ST        ticket_st
1161  *              afs_int32            issue_date
1162  *
1163  * Short description of routines:
1164  *
1165  * afs_tf_init() opens the ticket file and locks it.
1166  *
1167  * afs_tf_get_pname() returns the principal's name.
1168  *
1169  * afs_tf_get_pinst() returns the principal's instance (may be null).
1170  *
1171  * afs_tf_get_cred() returns the next CREDENTIALS record.
1172  *
1173  * afs_tf_save_cred() appends a new CREDENTIAL record to the ticket file.
1174  *
1175  * afs_tf_close() closes the ticket file and releases the lock.
1176  *
1177  * tf_gets() returns the next null-terminated string.  It's an internal
1178  * routine used by afs_tf_get_pname(), afs_tf_get_pinst(), and
1179  * afs_tf_get_cred().
1180  *
1181  * tf_read() reads a given number of bytes.  It's an internal routine
1182  * used by afs_tf_get_cred().
1183  */
1184
1185 /*
1186  * afs_tf_init() should be called before the other ticket file routines.
1187  * It takes the name of the ticket file to use, "tf_name", and a
1188  * read/write flag "rw" as arguments.
1189  *
1190  * It tries to open the ticket file, checks the mode, and if everything
1191  * is okay, locks the file.  If it's opened for reading, the lock is
1192  * shared.  If it's opened for writing, the lock is exclusive.
1193  *
1194  * Returns 0 if all went well, otherwise one of the following:
1195  *
1196  * NO_TKT_FIL   - file wasn't there
1197  * TKT_FIL_ACC  - file was in wrong mode, etc.
1198  * TKT_FIL_LCK  - couldn't lock the file, even after a retry
1199  */
1200
1201 int
1202 afs_tf_init(char *tf_name, int rw)
1203 {
1204     int wflag;
1205     int me;
1206     struct stat stat_buf;
1207
1208     switch (rw) {
1209     case R_TKT_FIL:
1210         wflag = 0;
1211         break;
1212     case W_TKT_FIL:
1213         wflag = 1;
1214         break;
1215     default:
1216         return TKT_FIL_ACC;
1217     }
1218     if (lstat(tf_name, &stat_buf) < 0)
1219         switch (errno) {
1220         case ENOENT:
1221             return NO_TKT_FIL;
1222         default:
1223             return TKT_FIL_ACC;
1224         }
1225     me = getuid();
1226     if ((stat_buf.st_uid != me && me != 0)
1227         || ((stat_buf.st_mode & S_IFMT) != S_IFREG))
1228         return TKT_FIL_ACC;
1229
1230     /*
1231      * If "wflag" is set, open the ticket file in append-writeonly mode
1232      * and lock the ticket file in exclusive mode.  If unable to lock
1233      * the file, sleep and try again.  If we fail again, return with the
1234      * proper error message.
1235      */
1236
1237     curpos = sizeof(tfbfr);
1238
1239     if (wflag) {
1240         fd = open(tf_name, O_RDWR, 0600);
1241         if (fd < 0) {
1242             return TKT_FIL_ACC;
1243         }
1244 #if defined(AFS_AIX_ENV) || defined(AFS_HPUX_ENV) || defined(AFS_SUN5_ENV)
1245         if (fcntl(fd, F_SETLK, &fileWlock) == -1) {
1246             sleep(TF_LCK_RETRY);
1247             if (fcntl(fd, F_SETLK, &fileWlock) == -1) {
1248 #else
1249         if (flock(fd, LOCK_EX | LOCK_NB) < 0) {
1250             sleep(TF_LCK_RETRY);
1251             if (flock(fd, LOCK_EX | LOCK_NB) < 0) {
1252 #endif
1253                 (void)close(fd);
1254                 fd = -1;
1255                 return TKT_FIL_LCK;
1256             }
1257         }
1258         return 0;
1259     }
1260     /*
1261      * Otherwise "wflag" is not set and the ticket file should be opened
1262      * for read-only operations and locked for shared access.
1263      */
1264
1265     fd = open(tf_name, O_RDONLY, 0600);
1266     if (fd < 0) {
1267         return TKT_FIL_ACC;
1268     }
1269 #if defined(AFS_AIX_ENV) || defined(AFS_HPUX_ENV) || defined(AFS_SUN5_ENV)
1270     if (fcntl(fd, F_SETLK, &fileRlock) == -1) {
1271         sleep(TF_LCK_RETRY);
1272         if (fcntl(fd, F_SETLK, &fileRlock) == -1) {
1273 #else
1274     if (flock(fd, LOCK_SH | LOCK_NB) < 0) {
1275         sleep(TF_LCK_RETRY);
1276         if (flock(fd, LOCK_SH | LOCK_NB) < 0) {
1277 #endif
1278             (void)close(fd);
1279             fd = -1;
1280             return TKT_FIL_LCK;
1281         }
1282     }
1283     return 0;
1284 }
1285
1286 /*
1287  * afs_tf_get_pname() reads the principal's name from the ticket file. It
1288  * should only be called after afs_tf_init() has been called.  The
1289  * principal's name is filled into the "p" parameter.  If all goes well,
1290  * 0 is returned.  If afs_tf_init() wasn't called, TKT_FIL_INI is
1291  * returned.  If the name was null, or EOF was encountered, or the name
1292  * was longer than MAXKTCNAMELEN, TKT_FIL_FMT is returned.
1293  */
1294
1295 int
1296 afs_tf_get_pname(char *p)
1297 {
1298     if (fd < 0) {
1299         return TKT_FIL_INI;
1300     }
1301     if (tf_gets(p, MAXKTCNAMELEN) < 2)  /* can't be just a null */
1302         return TKT_FIL_FMT;
1303     return 0;
1304 }
1305
1306 /*
1307  * afs_tf_get_pinst() reads the principal's instance from a ticket file.
1308  * It should only be called after afs_tf_init() and afs_tf_get_pname() have
1309  * been called.  The instance is filled into the "inst" parameter.  If all
1310  * goes well, 0 is returned.  If afs_tf_init() wasn't called,
1311  * TKT_FIL_INI is returned.  If EOF was encountered, or the instance
1312  * was longer than MAXKTCNAMELEN, TKT_FIL_FMT is returned.  Note that the
1313  * instance may be null.
1314  */
1315
1316 int
1317 afs_tf_get_pinst(char *inst)
1318 {
1319     if (fd < 0) {
1320         return TKT_FIL_INI;
1321     }
1322     if (tf_gets(inst, MAXKTCNAMELEN) < 1)
1323         return TKT_FIL_FMT;
1324     return 0;
1325 }
1326
1327 /*
1328  * afs_tf_get_cred() reads a CREDENTIALS record from a ticket file and fills
1329  * in the given structure "c".  It should only be called after afs_tf_init(),
1330  * afs_tf_get_pname(), and afs_tf_get_pinst() have been called. If all goes
1331  * well, 0 is returned.  Possible error codes are:
1332  *
1333  * TKT_FIL_INI  - afs_tf_init wasn't called first
1334  * TKT_FIL_FMT  - bad format
1335  * EOF          - end of file encountered
1336  */
1337
1338 int
1339 afs_tf_get_cred(struct ktc_principal *principal, struct ktc_token *token)
1340 {
1341     int k_errno;
1342     int kvno, lifetime;
1343     long mit_compat;            /* MIT Kerberos 5 with Krb4 uses a "long" for issue_date */
1344
1345     if (fd < 0) {
1346         return TKT_FIL_INI;
1347     }
1348     if ((k_errno = tf_gets(principal->name, MAXKTCNAMELEN)) < 2)
1349         switch (k_errno) {
1350         case TOO_BIG:
1351         case 1:         /* can't be just a null */
1352             return TKT_FIL_FMT;
1353         case 0:
1354             return EOF;
1355         }
1356     if ((k_errno = tf_gets(principal->instance, MAXKTCNAMELEN)) < 1)
1357         switch (k_errno) {
1358         case TOO_BIG:
1359             return TKT_FIL_FMT;
1360         case 0:
1361             return EOF;
1362         }
1363     if ((k_errno = tf_gets(principal->cell, MAXKTCREALMLEN)) < 2)
1364         switch (k_errno) {
1365         case TOO_BIG:
1366         case 1:         /* can't be just a null */
1367             return TKT_FIL_FMT;
1368         case 0:
1369             return EOF;
1370         }
1371     lcstring(principal->cell, principal->cell, MAXKTCREALMLEN);
1372     if (tf_read((char *)&(token->sessionKey), 8) < 1
1373         || tf_read((char *)&(lifetime), sizeof(lifetime)) < 1
1374         || tf_read((char *)&(kvno), sizeof(kvno)) < 1
1375         || tf_read((char *)&(token->ticketLen), sizeof(token->ticketLen))
1376         < 1 ||
1377         /* don't try to read a silly amount into ticket->dat */
1378         token->ticketLen > MAXKTCTICKETLEN
1379         || tf_read((char *)(token->ticket), token->ticketLen) < 1
1380         || tf_read((char *)&mit_compat, sizeof(mit_compat)) < 1) {
1381         return TKT_FIL_FMT;
1382     }
1383     token->startTime = mit_compat;
1384     token->endTime = life_to_time(token->startTime, lifetime);
1385     token->kvno = kvno;
1386     return 0;
1387 }
1388
1389 /*
1390  * tf_close() closes the ticket file and sets "fd" to -1. If "fd" is
1391  * not a valid file descriptor, it just returns.  It also clears the
1392  * buffer used to read tickets.
1393  *
1394  * The return value is not defined.
1395  */
1396
1397 int
1398 afs_tf_close(void)
1399 {
1400     if (!(fd < 0)) {
1401 #if defined(AFS_AIX_ENV) || defined(AFS_HPUX_ENV) || defined(AFS_SUN5_ENV)
1402         (void)fcntl(fd, F_SETLK, &fileUlock);
1403 #else
1404         (void)flock(fd, LOCK_UN);
1405 #endif
1406         (void)close(fd);
1407         fd = -1;                /* see declaration of fd above */
1408     }
1409     memset(tfbfr, 0, sizeof(tfbfr));
1410     return 0;
1411 }
1412
1413 /*
1414  * tf_gets() is an internal routine.  It takes a string "s" and a count
1415  * "n", and reads from the file until either it has read "n" characters,
1416  * or until it reads a null byte. When finished, what has been read exists
1417  * in "s".
1418  *
1419  * Possible return values are:
1420  *
1421  * n            the number of bytes read (including null terminator)
1422  *              when all goes well
1423  *
1424  * 0            end of file or read error
1425  *
1426  * TOO_BIG      if "count" characters are read and no null is
1427  *              encountered. This is an indication that the ticket
1428  *              file is seriously ill.
1429  */
1430
1431 static int
1432 tf_gets(char *s, int n)
1433 {
1434     int count;
1435
1436     if (fd < 0) {
1437         return TKT_FIL_INI;
1438     }
1439     for (count = n - 1; count > 0; --count) {
1440         if (curpos >= sizeof(tfbfr)) {
1441             lastpos = read(fd, tfbfr, sizeof(tfbfr));
1442             curpos = 0;
1443         }
1444         if (curpos == lastpos) {
1445             return 0;
1446         }
1447         *s = tfbfr[curpos++];
1448         if (*s++ == '\0')
1449             return (n - count);
1450     }
1451     return TOO_BIG;
1452 }
1453
1454 /*
1455  * tf_read() is an internal routine.  It takes a string "s" and a count
1456  * "n", and reads from the file until "n" bytes have been read.  When
1457  * finished, what has been read exists in "s".
1458  *
1459  * Possible return values are:
1460  *
1461  * n            the number of bytes read when all goes well
1462  *
1463  * 0            on end of file or read error
1464  */
1465
1466 static int
1467 tf_read(char *s, int n)
1468 {
1469     int count;
1470
1471     for (count = n; count > 0; --count) {
1472         if (curpos >= sizeof(tfbfr)) {
1473             lastpos = read(fd, tfbfr, sizeof(tfbfr));
1474             curpos = 0;
1475         }
1476         if (curpos == lastpos) {
1477             return 0;
1478         }
1479         *s++ = tfbfr[curpos++];
1480     }
1481     return n;
1482 }
1483
1484 /*
1485  * afs_tf_save_cred() appends an incoming ticket to the end of the ticket
1486  * file.  You must call afs_tf_init() before calling afs_tf_save_cred().
1487  *
1488  * The "service", "instance", and "realm" arguments specify the
1489  * server's name; "aticket" contains the credential.
1490  *
1491  * Returns 0 if all goes well, TKT_FIL_INI if afs_tf_init() wasn't
1492  * called previously, and KFAILURE for anything else that went wrong.
1493  */
1494
1495 int
1496 afs_tf_save_cred(struct ktc_principal *aserver,
1497                  struct ktc_token *atoken,
1498                  struct ktc_principal *aclient)
1499 {
1500     char realm[MAXKTCREALMLEN + 1];
1501     char junk[MAXKTCNAMELEN];
1502     struct ktc_principal principal;
1503     struct ktc_token token;
1504     int status;
1505     off_t start;
1506     int lifetime, kvno;
1507     int count;                  /* count for write */
1508     long mit_compat;            /* MIT Kerberos 5 with Krb4 uses a "long" for issue_date */
1509
1510     if (fd < 0) {               /* fd is ticket file as set by afs_tf_init */
1511         return TKT_FIL_INI;
1512     }
1513
1514     ucstring(realm, aserver->cell, MAXKTCREALMLEN);
1515     realm[MAXKTCREALMLEN] = '\0';
1516
1517     /* Look for a duplicate ticket */
1518     (void)lseek(fd, (off_t) 0L, 0);
1519     curpos = sizeof(tfbfr);
1520
1521     if (afs_tf_get_pname(junk) || strcmp(junk, aclient->name)
1522         || afs_tf_get_pinst(junk) || strcmp(junk, aclient->instance))
1523         goto bad;
1524
1525     do {
1526         start = lseek(fd, (off_t) 0L, 1) - lastpos + curpos;
1527         status = afs_tf_get_cred(&principal, &token);
1528     } while (status == 0
1529              && (strcmp(aserver->name, principal.name) != 0
1530                  || strcmp(aserver->instance, principal.instance) != 0
1531                  || strcmp(aserver->cell, principal.cell) != 0));
1532
1533     /*
1534      * Two tickets for the same user authenticating to the same service
1535      * should be the same length, but we check here just to make sure.
1536      */
1537     if (status == 0 && token.ticketLen != atoken->ticketLen)
1538         return KFAILURE;
1539     if (status && status != EOF)
1540         return status;
1541
1542     /* Position over the credential we just matched (or the EOF) */
1543     lseek(fd, start, 0);
1544     curpos = lastpos = sizeof(tfbfr);
1545
1546     /* Write the ticket and associated data */
1547     /* Service */
1548     count = strlen(aserver->name) + 1;
1549     if (write(fd, aserver->name, count) != count)
1550         goto bad;
1551     /* Instance */
1552     count = strlen(aserver->instance) + 1;
1553     if (write(fd, aserver->instance, count) != count)
1554         goto bad;
1555     /* Realm */
1556     count = strlen(realm) + 1;
1557     if (write(fd, realm, count) != count)
1558         goto bad;
1559     /* Session key */
1560     if (write(fd, (char *)&atoken->sessionKey, 8) != 8)
1561         goto bad;
1562     /* Lifetime */
1563     lifetime = time_to_life(atoken->startTime, atoken->endTime);
1564     if (write(fd, (char *)&lifetime, sizeof(int)) != sizeof(int))
1565         goto bad;
1566     /* Key vno */
1567     kvno = atoken->kvno;
1568     if (write(fd, (char *)&kvno, sizeof(int)) != sizeof(int))
1569         goto bad;
1570     /* Tkt length */
1571     if (write(fd, (char *)&(atoken->ticketLen), sizeof(int)) != sizeof(int))
1572         goto bad;
1573     /* Ticket */
1574     count = atoken->ticketLen;
1575     if (write(fd, atoken->ticket, count) != count)
1576         goto bad;
1577     /* Issue date */
1578     mit_compat = atoken->startTime;
1579     if (write(fd, (char *)&mit_compat, sizeof(mit_compat))
1580         != sizeof(mit_compat))
1581         goto bad;
1582
1583     /* Actually, we should check each write for success */
1584     return (0);
1585   bad:
1586     return (KFAILURE);
1587 }
1588
1589 /*
1590  * Copyright 1985, 1986, 1987, 1988 by the Massachusetts Institute
1591  * of Technology.
1592  *
1593  * For copying and distribution information, please see the file
1594  * <mit-copyright.h>.
1595  */
1596
1597 /*
1598  * This routine is used to generate the name of the file that holds
1599  * the user's cache of server tickets and associated session keys.
1600  *
1601  * If it is set, krb_ticket_string contains the ticket file name.
1602  * Otherwise, the filename is constructed as follows:
1603  *
1604  * If it is set, the environment variable "KRBTKFILE" will be used as
1605  * the ticket file name.  Otherwise TKT_ROOT (defined in "krb.h") and
1606  * the user's uid are concatenated to produce the ticket file name
1607  * (e.g., "/tmp/tkt123").  A pointer to the string containing the ticket
1608  * file name is returned.
1609  */
1610
1611 static char krb_ticket_string[4096] = "";
1612
1613 char *
1614 ktc_tkt_string(void)
1615 {
1616     return ktc_tkt_string_uid(getuid());
1617 }
1618
1619 char *
1620 ktc_tkt_string_uid(afs_uint32 uid)
1621 {
1622     char *env;
1623
1624     LOCK_GLOBAL_MUTEX;
1625     if (!*krb_ticket_string) {
1626         if ((env = getenv("KRBTKFILE"))) {
1627             (void)strncpy(krb_ticket_string, env,
1628                           sizeof(krb_ticket_string) - 1);
1629             krb_ticket_string[sizeof(krb_ticket_string) - 1] = '\0';
1630         } else {
1631             /* 32 bits of signed integer will always fit in 11 characters
1632              * (including the sign), so no need to worry about overflow */
1633             (void)sprintf(krb_ticket_string, "%s%d", TKT_ROOT, uid);
1634         }
1635     }
1636     UNLOCK_GLOBAL_MUTEX;
1637     return krb_ticket_string;
1638 }
1639
1640 /*
1641  * This routine is used to set the name of the file that holds the user's
1642  * cache of server tickets and associated session keys.
1643  *
1644  * The value passed in is copied into local storage.
1645  *
1646  * NOTE:  This routine should be called during initialization, before other
1647  * Kerberos routines are called; otherwise tkt_string() above may be called
1648  * and return an undesired ticket file name until this routine is called.
1649  */
1650
1651 void
1652 ktc_set_tkt_string(char * val)
1653 {
1654
1655     LOCK_GLOBAL_MUTEX;
1656     (void)strncpy(krb_ticket_string, val, sizeof(krb_ticket_string) - 1);
1657     krb_ticket_string[sizeof(krb_ticket_string) - 1] = '\0';
1658     UNLOCK_GLOBAL_MUTEX;
1659     return;
1660 }
1661
1662 /*
1663  * tf_create() is used to initialize the ticket store.  It creates the
1664  * file to contain the tickets and writes the given user's name "pname"
1665  * and instance "pinst" in the file.  in_tkt() returns KSUCCESS on
1666  * success, or KFAILURE if something goes wrong.
1667  */
1668
1669 int
1670 afs_tf_create(char *pname, char *pinst)
1671 {
1672     int tktfile;
1673     int me, metoo;
1674     int count;
1675     char *file = ktc_tkt_string();
1676     int fd;
1677     int i;
1678     char zerobuf[1024];
1679     struct stat sbuf;
1680
1681     me = getuid();
1682     metoo = geteuid();
1683
1684     if (lstat(file, &sbuf) == 0) {
1685         if ((sbuf.st_uid != me && me != 0)
1686             || ((sbuf.st_mode & S_IFMT) != S_IFREG) || sbuf.st_mode & 077) {
1687             return KFAILURE;
1688         }
1689         /* file already exists, and permissions appear ok, so nuke it */
1690         if ((fd = open(file, O_RDWR, 0)) < 0)
1691             goto out;           /* can't zero it, but we can still try truncating it */
1692
1693         memset(zerobuf, 0, sizeof(zerobuf));
1694
1695         for (i = 0; i < sbuf.st_size; i += sizeof(zerobuf))
1696             if (write(fd, zerobuf, sizeof(zerobuf)) != sizeof(zerobuf)) {
1697                 (void)fsync(fd);
1698                 (void)close(fd);
1699                 goto out;
1700             }
1701
1702         (void)fsync(fd);
1703         (void)close(fd);
1704     }
1705
1706   out:
1707     /* arrange so the file is owned by the ruid
1708      * (swap real & effective uid if necessary).
1709      * This isn't a security problem, since the ticket file, if it already
1710      * exists, has the right uid (== ruid) and mode. */
1711     if (me != metoo) {
1712         if (setreuid(metoo, me) < 0) {
1713             return (KFAILURE);
1714         }
1715     }
1716     tktfile = creat(file, 0600);
1717     if (me != metoo) {
1718         if (setreuid(me, metoo) < 0) {
1719             /* can't switch??? fail! */
1720             return (KFAILURE);
1721         }
1722     }
1723     if (tktfile < 0) {
1724         return (KFAILURE);
1725     }
1726     count = strlen(pname) + 1;
1727     if (write(tktfile, pname, count) != count) {
1728         (void)close(tktfile);
1729         return (KFAILURE);
1730     }
1731     count = strlen(pinst) + 1;
1732     if (write(tktfile, pinst, count) != count) {
1733         (void)close(tktfile);
1734         return (KFAILURE);
1735     }
1736     (void)close(tktfile);
1737     return (KSUCCESS);
1738 }
1739
1740 /*
1741  * dest_tkt() is used to destroy the ticket store upon logout.
1742  * If the ticket file does not exist, dest_tkt() returns RET_TKFIL.
1743  * Otherwise the function returns 0 on success, KFAILURE on
1744  * failure.
1745  */
1746
1747 int
1748 afs_tf_dest_tkt(void)
1749 {
1750     char *file = ktc_tkt_string();
1751     int i, fd;
1752     struct stat statb;
1753     char buf[BUFSIZ];
1754
1755     errno = 0;
1756     if (lstat(file, &statb) < 0)
1757         goto out;
1758
1759     if (!(statb.st_mode & S_IFREG))
1760         goto out;
1761
1762     if ((fd = open(file, O_RDWR, 0)) < 0)
1763         goto out;
1764
1765     memset(buf, 0, BUFSIZ);
1766
1767     for (i = 0; i < statb.st_size; i += BUFSIZ)
1768         if (write(fd, buf, BUFSIZ) != BUFSIZ) {
1769             (void)fsync(fd);
1770             (void)close(fd);
1771             goto out;
1772         }
1773
1774     (void)fsync(fd);
1775     (void)close(fd);
1776
1777     (void)unlink(file);
1778
1779   out:
1780     if (errno == ENOENT)
1781         return RET_TKFIL;
1782     else if (errno != 0)
1783         return KFAILURE;
1784     return 0;
1785 }
1786
1787 int
1788 ktc_newpag(void)
1789 {
1790 #if !defined(AFS_DARWIN100_ENV) || defined(HAVE_CRT_EXTERNS_H)
1791 # if defined(AFS_DARWIN100_ENV)
1792 #  define environ (*_NSGetEnviron())
1793 # else
1794 extern char **environ;
1795 # endif
1796
1797     afs_uint32 pag;
1798     struct stat sbuf;
1799     char fname[256], *prefix = "/ticket/";
1800     char fname5[256], *prefix5 = "FILE:/ticket/krb5cc_";
1801     int numenv;
1802     char **newenv, **senv, **denv;
1803
1804     LOCK_GLOBAL_MUTEX;
1805     if (stat("/ticket", &sbuf) == -1) {
1806         prefix = "/tmp/tkt";
1807         prefix5 = "FILE:/tmp/krb5cc_";
1808     }
1809
1810     pag = ktc_curpag() & 0xffffffff;
1811     if (pag == -1) {
1812         sprintf(fname, "%s%d", prefix, getuid());
1813         sprintf(fname5, "%s%d", prefix5, getuid());
1814     } else {
1815         sprintf(fname, "%sp%lu", prefix, afs_printable_uint32_lu(pag));
1816         sprintf(fname5, "%sp%lud", prefix5, afs_printable_uint32_lu(pag));
1817     }
1818     ktc_set_tkt_string(fname);
1819
1820     for (senv = environ, numenv = 0; *senv; senv++)
1821         numenv++;
1822     newenv = (char **)malloc((numenv + 2) * sizeof(char *));
1823
1824     for (senv = environ, denv = newenv; *senv; senv++) {
1825         if (strncmp(*senv, "KRBTKFILE=", 10) != 0 &&
1826             strncmp(*senv, "KRB5CCNAME=", 11) != 0)
1827             *denv++ = *senv;
1828     }
1829
1830     *denv = malloc(10+11 + strlen(fname) + strlen(fname5) + 2);
1831     strcpy(*denv, "KRBTKFILE=");
1832     strcat(*denv, fname);
1833     *(denv+1) = *denv + strlen(*denv) + 1;
1834     denv++;
1835     strcpy(*denv, "KRB5CCNAME=");
1836     strcat(*denv, fname5);
1837     *++denv = 0;
1838     environ = newenv;
1839     UNLOCK_GLOBAL_MUTEX;
1840 #endif
1841     return 0;
1842 }
1843
1844 /*
1845  * BLETCH!  We have to invoke the entire afsconf package just to
1846  * find out what the local cell is.
1847  */
1848 static void
1849 ktc_LocalCell(void)
1850 {
1851     int code = 0;
1852     struct afsconf_dir *conf;
1853
1854     if ((conf = afsconf_Open(AFSDIR_CLIENT_ETC_DIRPATH))
1855         || (conf = afsconf_Open(AFSDIR_SERVER_ETC_DIRPATH))) {
1856         code = afsconf_GetLocalCell(conf, lcell, sizeof(lcell));
1857         afsconf_Close(conf);
1858     }
1859     if (!conf || code) {
1860         printf("** Can't determine local cell name!\n");
1861     }
1862 }
1863
1864 #endif