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