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