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