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