34e6117d49cd2ccf461a596424db795b46ce8370
[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 #if defined(UKERNEL)
13
14 #include "../afs/param.h"
15 #include "../afs/sysincludes.h"
16 #include "../afs/afsincludes.h"
17 #include "../afs/stds.h"
18 #include "../afs/pthread_glock.h"
19 #include "../afs/vice.h"
20 #include "../afs/auth.h"
21 #include "../afs/venus.h"
22 #include "../afs/pthread_glock.h"
23 #include "../afs/dirpath.h"
24
25 #if !defined(min)
26 #define min(a,b) ((a)<(b)?(a):(b))
27 #endif /* !defined(min) */
28
29 #else /* defined(UKERNEL) */
30
31 #ifdef  AFS_SUN5_ENV
32 #include <unistd.h>
33 #endif
34 #include <afs/param.h>
35 #include <stdio.h>
36 #include <afs/stds.h>
37 #include <afs/pthread_glock.h>
38 #include <sys/types.h>
39 #include <ctype.h>
40 #include <sys/stat.h>
41 #include <signal.h>
42 #include <errno.h>
43 #include <sys/ioctl.h>
44 #include <netinet/in.h>
45 #include <afs/vice.h>
46 #ifdef  AFS_AIX_ENV
47 #include <sys/lockf.h>
48 #endif
49 #include "auth.h"
50 #include <afs/venus.h>
51 #include <afs/afsutil.h>
52
53 #endif /* defined(UKERNEL) */
54
55 /* For malloc() */
56 #include <stdlib.h>
57
58
59 #ifdef  notdef
60 /* AFS_KERBEROS_ENV is now conditionally defined in the Makefile */
61 #define AFS_KERBEROS_ENV
62 #endif
63
64 #ifdef AFS_KERBEROS_ENV 
65 #include <fcntl.h>
66 #include <sys/file.h>
67 extern afs_uint32 life_to_time();
68 extern unsigned char time_to_life();
69 #include "cellconfig.h"
70 static char lcell[MAXCELLCHARS];
71  
72 #define TKT_ROOT "/tmp/tkt"
73  
74 #define KSUCCESS 0
75 #define KFAILURE 255
76  
77 /* Definitions for ticket file utilities */
78 #define R_TKT_FIL       0
79 #define W_TKT_FIL       1
80  
81 /* Error codes returned by ticket file utilities */
82 #define         NO_TKT_FIL      76      /* No ticket file found */
83 #define         TKT_FIL_ACC     77      /* Couldn't access tkt file */
84 #define         TKT_FIL_LCK     78      /* Couldn't lock ticket file */
85 #define         TKT_FIL_FMT     79      /* Bad ticket file format */
86 #define         TKT_FIL_INI     80      /* tf_init not called first */
87   
88 /* Values returned by get_credentials */
89 #define         RET_TKFIL      21       /* Can't read ticket file */
90  
91 #ifndef BUFSIZ
92 #define BUFSIZ 4096
93 #endif
94
95 #ifdef  AFS_HPUX_ENV
96 #include <unistd.h>
97 #endif
98 #if     defined(AFS_AIX_ENV) || defined(AFS_SUN5_ENV)
99 static struct flock fileWlock = { F_WRLCK, 0, 0, 0, 0, 0 };
100 static struct flock fileRlock = { F_RDLCK, 0, 0, 0, 0, 0 };
101 static struct flock fileUlock = { F_UNLCK, 0, 0, 0, 0, 0 };
102 #endif
103 #ifdef AFS_HPUX_ENV
104 static struct flock fileWlock = { F_WRLCK, 0, 0, 0, 0 };
105 static struct flock fileRlock = { F_RDLCK, 0, 0, 0, 0 };
106 static struct flock fileUlock = { F_UNLCK, 0, 0, 0, 0 };
107 #endif
108
109 #ifndef EOF
110 #define EOF (-1)
111 #endif
112  
113 static int tf_init(), tf_get_pname(), tf_get_pinst(), tf_get_cred(), tf_save_cred();
114 static int tf_close();
115 static int tf_create(), tf_dest_tkt(), ktc_LocalCell();
116 char *ktc_tkt_string();
117 #endif  /* AFS_KERBEROS_ENV */
118
119 #ifdef AFS_DUX40_ENV
120 #define PIOCTL afs_pioctl
121 #elif defined(UKERNEL)
122 #define PIOCTL(A,B,C,D) call_syscall(AFSCALL_PIOCTL,A,B,C,D)
123 #else
124 #define PIOCTL pioctl
125 #endif
126
127
128 #ifdef KERNEL_KTC_COMPAT
129
130 /* In case there is no include file. */
131 #ifdef MAYBE_NO_KTC
132
133 #ifndef KTC_SYSCALL
134 #define KTC_SYSCALL     32
135 #endif
136
137 /* Kernel call opcode definitions */
138 #define KTC_OPCODE_BASE         4300
139 #define KTC_NO_OP               (0+KTC_OPCODE_BASE)
140 #define KTC_SETTOKEN_OP         (1+KTC_OPCODE_BASE)
141 #define KTC_GETTOKEN_OP         (2+KTC_OPCODE_BASE)
142 #define KTC_LISTTOKENS_OP       (3+KTC_OPCODE_BASE)
143 #define KTC_FORGETTOKEN_OP      (4+KTC_OPCODE_BASE)
144 #define KTC_FORGETALLTOKENS_OP  (5+KTC_OPCODE_BASE)
145 #define KTC_STATUS_OP           (6+KTC_OPCODE_BASE)
146 #define KTC_GC_OP               (7+KTC_OPCODE_BASE)
147
148 #define KTC_INTERFACE_VERSION 3
149
150 #else
151 #include <afs/ktc.h>
152 #endif
153
154 /* We have to determine if the kernel supports the ktc system call.  To do so
155  * we attempt to execute its noop function.  If this is successful we use the
156  * kernel calls in the future otherwise we let the old code run. */
157
158 /* To safely check to see whether a system call exists we have to intercept the
159  * SIGSYS signal which is caused by executing a non-existant system call.  If
160  * it is ignored the syscall routine returns EINVAL.  The SIGSYS is reset to
161  * its old value after the return from syscall.  */
162
163 static int kernelKTC = 0;
164
165 #ifdef  AFS_DECOSF_ENV
166 /*
167  * SIGSYS semantics are broken on Dec AXP OSF/1 v1.2 systems.  You need
168  * to ignore SIGTRAP too.  It is claimed to be fixed under v1.3, but...
169  */
170
171 #define CHECK_KERNEL                                                    \
172     if (kernelKTC == 0) {                                               \
173         int code, ecode;                                                \
174         int (*old)();                                                   \
175         int (*old_t)();                                                 \
176         old = (int (*)())signal(SIGSYS, SIG_IGN);                       \
177         old_t = (int (*)())signal(SIGTRAP, SIG_IGN);                    \
178         code = syscall (KTC_SYSCALL, KTC_NO_OP, 0,0,0,0,0);             \
179         ecode = errno;                                                  \
180         signal(SIGSYS, old);                                            \
181         signal(SIGTRAP, old_t);                                         \
182         if (code == 0) kernelKTC = 1;                                   \
183         else kernelKTC = 2;                                             \
184 /* printf ("returned from KTC_NO_OP kernelKTC <= %d; code=%d, errno=%d\n", kernelKTC, code, errno); */\
185     }
186
187 #else   /* AFS_DECOSF_ENV */
188
189 #define CHECK_KERNEL                                                    \
190     if (kernelKTC == 0) {                                               \
191         int code, ecode;                                                \
192         int (*old)();                                                   \
193         old = (int (*)())signal(SIGSYS, SIG_IGN);                       \
194         code = syscall (KTC_SYSCALL, KTC_NO_OP, 0,0,0,0,0);             \
195         ecode = errno;                                                  \
196         signal(SIGSYS, old);                                            \
197         if (code == 0) kernelKTC = 1;                                   \
198         else kernelKTC = 2;                                             \
199 /* printf ("returned from KTC_NO_OP kernelKTC <= %d; code=%d, errno=%d\n", kernelKTC, code, errno); */\
200     }
201 #endif  /* AFS_DECOSF_ENV */
202
203 #define TRY_KERNEL(cmd,a1,a2,a3,a4)                                     \
204 {   CHECK_KERNEL;                                                       \
205     if (kernelKTC == 1)                                                 \
206         return syscall (KTC_SYSCALL, cmd,                               \
207                         KTC_INTERFACE_VERSION, a1,a2,a3,a4);            \
208 }
209
210 #else
211 #define TRY_KERNEL(cmd,a1,a2,a3,a4)
212 #endif /* KERNEL_KTC_COMPAT */
213
214 #if !defined(UKERNEL)
215 /* this is a structure used to communicate with the afs cache mgr, but is
216  * otherwise irrelevant */
217 struct ClearToken {
218         afs_int32 AuthHandle;
219         char HandShakeKey[8];
220         afs_int32 ViceId;
221         afs_int32 BeginTimestamp;
222         afs_int32 EndTimestamp;
223 };
224 #endif /* !defined(UKERNEL) */
225
226 #define MAXLOCALTOKENS 4
227
228 static struct {
229     int valid;
230     struct ktc_principal server;
231     struct ktc_principal client;
232     struct ktc_token     token;
233 } local_tokens[MAXLOCALTOKENS] = {{0}, {0}, {0}, {0}};
234
235 /* new interface routines to the ticket cache.  Only handle afs service right
236  * now. */
237
238 static int NewSetToken (aserver, atoken, aclient, flags)
239   struct ktc_principal *aserver;
240   struct ktc_principal *aclient;
241   struct ktc_token *atoken;
242   afs_int32 flags;
243 {
244     TRY_KERNEL (KTC_SETTOKEN_OP,
245                 aserver, aclient, atoken, sizeof(struct ktc_token));
246     /* no kernel ticket cache */
247     return EINVAL;
248 }
249
250 static int OldSetToken (aserver, atoken, aclient, flags)
251 struct ktc_principal *aserver, *aclient;
252 struct ktc_token *atoken; 
253 afs_int32 flags;
254 {
255     struct ViceIoctl iob;
256     char tbuffer[1024];
257     register char *tp;
258     struct ClearToken ct;
259     register afs_int32 code;
260     afs_int32 temp;
261
262     if (strcmp(aserver->name, "afs") != 0) {
263         int found = -1;
264         int i;
265         for (i=0; i<MAXLOCALTOKENS; i++)
266             if (local_tokens[i].valid) {
267                 if ((strcmp (local_tokens[i].server.name, aserver->name) == 0) &&
268                     (strcmp (local_tokens[i].server.instance, aserver->instance) == 0) &&
269                     (strcmp (local_tokens[i].server.cell, aserver->cell) == 0)) {
270                     found = i;          /* replace existing entry */
271                     break;
272                 }
273                 else /* valid, but no match */ ;
274             } else found = i;           /* remember this empty slot */
275         if (found == -1) return KTC_NOENT;
276         bcopy (atoken, &local_tokens[found].token, sizeof(struct ktc_token));
277         local_tokens[found].server = *aserver;
278         local_tokens[found].client = *aclient;
279         local_tokens[found].valid = 1;
280         return 0;
281     }
282     tp = tbuffer;   /* start copying here */
283     if ((atoken->ticketLen < MINKTCTICKETLEN) ||
284         (atoken->ticketLen > MAXKTCTICKETLEN)) return KTC_TOOBIG;
285     bcopy(&atoken->ticketLen, tp, sizeof(afs_int32));    /* copy in ticket length */
286     tp += sizeof(afs_int32);
287     bcopy(atoken->ticket, tp, atoken->ticketLen);   /* copy in ticket */
288     tp += atoken->ticketLen;
289     /* next, copy in the "clear token", describing who we are */
290     ct.AuthHandle = atoken->kvno;       /* hide auth handle here */
291     bcopy(&atoken->sessionKey, ct.HandShakeKey, 8);
292
293     ct.BeginTimestamp = atoken->startTime;
294     ct.EndTimestamp = atoken->endTime;
295     if (ct.BeginTimestamp == 0) ct.BeginTimestamp = 1;
296
297     if ((strlen(aclient->name) > strlen ("AFS ID ")) &&
298         (aclient->instance[0] == 0)) {
299         int sign = 1;
300         afs_int32 viceId = 0;
301         char *cp = aclient->name + strlen ("AFS ID ");
302         if (*cp == '-') { sign = -1; cp++; }
303         while (*cp) {
304             if (isdigit(*cp)) viceId = viceId*10 + (int)(*cp - '0');
305             else goto not_vice_id;
306             cp++;
307         }
308         ct.ViceId = viceId * sign;      /* OK to let any value here? */
309         if (((ct.EndTimestamp - ct.BeginTimestamp) & 1) == 0)
310             ct.BeginTimestamp++;        /* force lifetime to be odd */
311     } else {
312 not_vice_id:
313         ct.ViceId = getuid();           /* wrong, but works in primary cell */
314         if (((ct.EndTimestamp - ct.BeginTimestamp) & 1) == 1)
315             ct.BeginTimestamp++;        /* force lifetime to be even */
316     }
317
318 #ifdef UKERNEL
319     /*
320      * Information needed by the user space cache manager
321      */
322     u.u_expiration = ct.EndTimestamp;
323     u.u_viceid = ct.ViceId;
324 #endif
325
326     temp = sizeof(struct ClearToken);
327     bcopy(&temp, tp, sizeof(afs_int32));
328     tp += sizeof(afs_int32);
329     bcopy(&ct, tp, sizeof(struct ClearToken));
330     tp += sizeof(struct ClearToken);
331
332     /* next copy in primary flag */
333     temp = 0;
334
335     /*
336      * The following means that setpag will happen inside afs just before
337      * the authentication to prevent the setpag/klog race condition.
338      *
339      * The following means that setpag will affect the parent process as
340      * well as the current process.
341      */
342     if (flags & AFS_SETTOK_SETPAG)      
343         temp |= 0x8000;
344
345     bcopy(&temp, tp, sizeof(afs_int32));
346     tp += sizeof(afs_int32);
347
348     /* finally copy in the cell name */
349     temp = strlen(aserver->cell);
350     if (temp >= MAXKTCREALMLEN) return KTC_TOOBIG;
351     strcpy(tp, aserver->cell);
352     tp += temp+1;
353
354     /* now setup for the pioctl */
355     iob.in = tbuffer;
356     iob.in_size = tp-tbuffer;
357     iob.out = tbuffer;
358     iob.out_size = sizeof(tbuffer);
359
360     code = PIOCTL(0, VIOCSETTOK, &iob, 0);
361     if (code) return KTC_PIOCTLFAIL;
362     return 0;
363 }
364
365
366 ktc_SetToken (aserver, atoken, aclient, flags)
367   struct ktc_principal *aserver;
368   struct ktc_principal *aclient;
369   struct ktc_token *atoken;
370   afs_int32 flags;
371 {
372     int ncode, ocode;
373
374     LOCK_GLOBAL_MUTEX
375 #ifdef AFS_KERBEROS_ENV
376     if (!lcell[0]) ktc_LocalCell();
377  
378     if (/*!strcmp(aclient->cell, lcell) && this would only store local creds*/
379         (strcmp(aserver->name, "AuthServer") ||
380                                           strcmp(aserver->instance, "Admin"))){
381         if (strcmp(aserver->name, "krbtgt") == 0) {
382             static char lrealm[MAXKTCREALMLEN];
383  
384             if (!lrealm[0]) ucstring(lrealm, lcell, MAXKTCREALMLEN);
385             if (strcmp(aserver->instance, lrealm) == 0) {
386                 tf_create(aclient->name, aclient->instance);
387             }
388         }
389  
390         ncode = tf_init(ktc_tkt_string(), W_TKT_FIL);
391         if (ncode == NO_TKT_FIL) {
392             (void) tf_create(aclient->name, aclient->instance);
393             ncode = tf_init(ktc_tkt_string(), W_TKT_FIL);
394         }
395  
396         if (!ncode) {
397             tf_save_cred(aserver, atoken, aclient);
398         }
399         tf_close();
400      }
401 #endif
402
403     ncode = NewSetToken (aserver, atoken, aclient, flags);
404     if (ncode ||                        /* new style failed */
405         (strcmp (aserver->name, "afs") == 0)) { /* for afs tokens do both */
406         ocode = OldSetToken (aserver, atoken, aclient, flags);
407     } else ocode = 0;
408     if (ncode && ocode) {
409         UNLOCK_GLOBAL_MUTEX
410         if (ocode == -1) ocode = errno;
411         else if (ocode == KTC_PIOCTLFAIL) ocode = errno;
412         if (ocode == ESRCH) return KTC_NOCELL;
413         if (ocode == EINVAL) return KTC_NOPIOCTL;
414         if (ocode == EIO) return KTC_NOCM;
415         return KTC_PIOCTLFAIL;
416     }
417     UNLOCK_GLOBAL_MUTEX
418     return 0;
419 }
420
421 /* get token, given server we need and token buffer.  aclient will eventually
422  * be set to our identity to the server.
423  */
424 ktc_GetToken(aserver, atoken, atokenLen, aclient)
425 struct ktc_principal *aserver, *aclient;
426 int atokenLen;
427 struct ktc_token *atoken; {
428     struct ViceIoctl iob;
429     char tbuffer[1024];
430     register afs_int32 code;
431     int index;
432     char *stp, *cellp; /* secret token ptr */
433     struct ClearToken ct;
434     register char *tp;
435     afs_int32 temp;
436     int maxLen; /* biggest ticket we can copy */
437     int tktLen; /* server ticket length */
438     
439     LOCK_GLOBAL_MUTEX
440     TRY_KERNEL (KTC_GETTOKEN_OP, aserver, aclient, atoken, atokenLen);
441
442 #ifdef AFS_KERBEROS_ENV
443     if (!lcell[0]) ktc_LocalCell();
444 #endif
445     if (strcmp(aserver->name, "afs") != 0) {
446         int i;
447         /* try the local tokens */
448         for (i=0; i<MAXLOCALTOKENS; i++)
449             if (local_tokens[i].valid &&
450                 (strcmp (local_tokens[i].server.name, aserver->name) == 0) &&
451                 (strcmp (local_tokens[i].server.instance, aserver->instance) == 0) &&
452                 (strcmp (local_tokens[i].server.cell, aserver->cell) == 0)) {
453                 bcopy (&local_tokens[i].token, atoken, min (atokenLen, sizeof(struct ktc_token)));
454                 *aclient = local_tokens[i].client;
455                 UNLOCK_GLOBAL_MUTEX
456                 return 0;
457             }
458 #ifdef AFS_KERBEROS_ENV
459         if (!tf_init(ktc_tkt_string(), R_TKT_FIL) && !tf_get_pname(aclient->name) &&
460             !tf_get_pinst(aclient->instance)) {
461             struct ktc_principal cprincipal;
462             struct ktc_token ctoken;
463  
464             while (!tf_get_cred(&cprincipal, &ctoken)) {
465                 if (strcmp(cprincipal.name, aserver->name) == 0 &&
466                     strcmp(cprincipal.instance, aserver->instance) == 0 &&
467                     strcmp(cprincipal.cell, aserver->cell) == 0) {
468  
469                     strcpy(aclient->cell, lcell);
470                     bcopy(&ctoken, atoken,
471                           min (atokenLen, sizeof(struct ktc_token)));
472                     
473                     tf_close();
474                     UNLOCK_GLOBAL_MUTEX
475                     return 0;
476                 }
477             }
478         }
479         tf_close();
480 #endif
481         UNLOCK_GLOBAL_MUTEX
482         return KTC_NOENT;
483     }
484
485     for (index=0; index<200; index++) { /* sanity check in case pioctl fails */
486         iob.in = (char *) &index;
487         iob.in_size = sizeof(afs_int32);
488         iob.out = tbuffer;
489         iob.out_size = sizeof(tbuffer);
490
491         code = PIOCTL(0, VIOCGETTOK, &iob, 0);
492
493         if (code) {
494             /* failed to retrieve specified token */
495             if (code < 0 && errno == EDOM) {
496                 UNLOCK_GLOBAL_MUTEX
497                 return KTC_NOENT;
498             }
499         } else {
500             /* token retrieved; parse buffer */
501             tp = tbuffer;
502
503             /* get ticket length */
504             memcpy(&temp, tp, sizeof(afs_int32));
505             tktLen = temp;
506             tp += sizeof(afs_int32);
507
508             /* remember where ticket is and skip over it */
509             stp = tp;
510             tp += tktLen;
511
512             /* get size of clear token and verify */
513             memcpy(&temp, tp, sizeof(afs_int32));
514             if (temp != sizeof(struct ClearToken)) {
515                 UNLOCK_GLOBAL_MUTEX
516                 return KTC_ERROR;
517             }
518             tp += sizeof(afs_int32);
519
520             /* copy clear token */
521             memcpy(&ct, tp, temp);
522             tp += temp;
523
524             /* skip over primary flag */
525             tp += sizeof(afs_int32);
526
527             /* remember where cell name is */
528             cellp = tp;
529
530             if ((strcmp(cellp, aserver->cell) == 0)
531 #ifdef  AFS_KERBEROS_ENV
532                 || (*aserver->cell == '\0' && strcmp(cellp, lcell) == 0)
533 #endif
534                 ) {
535                 /* got token for cell; check that it will fit */
536                 maxLen = atokenLen - sizeof(struct ktc_token) + MAXKTCTICKETLEN;
537                 if (maxLen < tktLen) {
538                     UNLOCK_GLOBAL_MUTEX
539                     return KTC_TOOBIG;
540                 }
541
542                 /* set return values */
543                 memcpy(atoken->ticket, stp, tktLen);
544                 atoken->startTime = ct.BeginTimestamp;
545                 atoken->endTime = ct.EndTimestamp;
546                 if (ct.AuthHandle == -1) {
547                     ct.AuthHandle = 999;
548                 }
549                 atoken->kvno = ct.AuthHandle;
550                 memcpy(&atoken->sessionKey, ct.HandShakeKey, sizeof(struct ktc_encryptionKey));
551                 atoken->ticketLen = tktLen;
552
553                 if (aclient) {
554                     strcpy(aclient->cell, cellp);
555                     aclient->instance[0] = 0;
556
557                     if ((atoken->kvno == 999) || /* old style bcrypt ticket */
558                         (ct.BeginTimestamp &&    /* new w/ prserver lookup */
559                          (((ct.EndTimestamp - ct.BeginTimestamp) & 1) == 1))) {
560                         sprintf(aclient->name, "AFS ID %d", ct.ViceId);
561                     } else {
562                         sprintf(aclient->name, "Unix UID %d", ct.ViceId);
563                     }
564                 }
565                 UNLOCK_GLOBAL_MUTEX
566                 return 0;
567             }
568         }
569     }
570
571     UNLOCK_GLOBAL_MUTEX
572     if ((code < 0) && (errno == EINVAL)) return KTC_NOPIOCTL;
573     return KTC_PIOCTLFAIL;      /* probable cause */
574 }
575
576 /*
577  * Forget tokens for this server and the calling user.
578  * NOT IMPLEMENTED YET!
579  */
580 ktc_ForgetToken(aserver)
581 struct ktc_principal *aserver; {
582     int rc;
583
584     LOCK_GLOBAL_MUTEX
585     TRY_KERNEL (KTC_FORGETTOKEN_OP, aserver, 0,0,0);
586
587     rc = ktc_ForgetAllTokens(); /* bogus, but better */
588     UNLOCK_GLOBAL_MUTEX
589     return rc;
590 }
591
592 /* ktc_ListTokens - list all tokens.  start aprevIndex at 0, it returns the
593  * next rock in (*aindex).  (*aserver) is set to the relevant ticket on
594  * success.  */
595
596 ktc_ListTokens(aprevIndex, aindex, aserver)
597 int aprevIndex, *aindex;
598 struct ktc_principal *aserver; {
599     struct ViceIoctl iob;
600     char tbuffer[1024];
601     register afs_int32 code;
602     register char *tp;
603     afs_int32 temp, index;
604
605     LOCK_GLOBAL_MUTEX
606     TRY_KERNEL (KTC_LISTTOKENS_OP, aserver, aprevIndex, aindex, 0);
607
608     index = aprevIndex;
609 #ifdef AFS_KERBEROS_ENV
610      if (index >= 214) {
611         int i;
612         struct ktc_principal cprincipal;
613         struct ktc_token ctoken;
614  
615         if (tf_init(ktc_tkt_string(), R_TKT_FIL) ||
616             tf_get_pname(tbuffer) ||
617             tf_get_pinst(tbuffer)) {
618             tf_close();
619             UNLOCK_GLOBAL_MUTEX
620             return KTC_NOENT;
621         }
622  
623         for (i=214; i<index; i++) {
624             if (tf_get_cred(&cprincipal, &ctoken)) {
625                 tf_close();
626                 UNLOCK_GLOBAL_MUTEX
627                 return KTC_NOENT;
628             }
629         }
630  
631      again:
632         if (tf_get_cred(&cprincipal, &ctoken)) {
633             tf_close();
634             UNLOCK_GLOBAL_MUTEX
635             return KTC_NOENT;
636         }           
637         index++;
638  
639         if (!strcmp(cprincipal.name, "afs") && cprincipal.instance[0]==0) {
640             goto again;
641         }
642  
643         for (i=0; i < MAXLOCALTOKENS; i++) {
644             if (!strcmp(cprincipal.name, local_tokens[i].server.name) &&
645                 !strcmp(cprincipal.instance, local_tokens[i].server.instance) &&
646                 !strcmp(cprincipal.cell, local_tokens[i].server.cell)) {
647                 goto again;
648                 }
649         }
650  
651         *aserver = cprincipal;
652         *aindex = index;
653         tf_close();
654         UNLOCK_GLOBAL_MUTEX
655         return 0;
656      }
657 #endif
658
659     if (index >= 123) {                 /* special hack for returning TCS */
660         while (index-123 < MAXLOCALTOKENS) {
661             if (local_tokens[index-123].valid) {
662                 *aserver = local_tokens[index-123].server;
663                 *aindex = index+1;
664                 UNLOCK_GLOBAL_MUTEX
665                 return 0;
666             }
667             index++;
668         }
669         UNLOCK_GLOBAL_MUTEX
670 #ifdef AFS_KERBEROS_ENV
671         return ktc_ListTokens(214, aindex, aserver);
672 #else
673         return KTC_NOENT;
674 #endif
675     }
676
677     /* get tokens from the kernel */
678     while (index<200) {                 /* sanity check in case pioctl fails */
679         iob.in = (char *) &index;
680         iob.in_size = sizeof(afs_int32);
681         iob.out = tbuffer;
682         iob.out_size = sizeof(tbuffer);
683         code = PIOCTL(0, VIOCGETTOK, &iob, 0);
684         if (code < 0 && errno == EDOM) {
685             if (index < 123) {
686                 int rc;
687                 rc = ktc_ListTokens (123, aindex, aserver);
688                 UNLOCK_GLOBAL_MUTEX
689                 return rc;
690             }
691             else {
692                 UNLOCK_GLOBAL_MUTEX
693                 return KTC_NOENT;
694             }
695         }
696         if (code == 0) break;   /* got a ticket */
697         /* otherwise we should skip this ticket slot */
698         index++;
699     }
700     if (code < 0) {
701         UNLOCK_GLOBAL_MUTEX
702         if (errno == EINVAL) return KTC_NOPIOCTL;
703         return KTC_PIOCTLFAIL;
704     }
705
706     /* parse buffer */
707     tp = tbuffer;
708
709     /* next iterator determined by earlier loop */
710     *aindex = index+1;
711
712     bcopy(tp, &temp, sizeof(afs_int32)); /* get size of secret token */
713     tp += sizeof(afs_int32);
714     tp += temp; /* skip ticket for now */
715     bcopy(tp, &temp, sizeof(afs_int32)); /* get size of clear token */
716     if (temp != sizeof(struct ClearToken)) {
717         UNLOCK_GLOBAL_MUTEX
718         return KTC_ERROR;
719     }
720     tp += sizeof(afs_int32);        /* skip length */
721     tp += temp;             /* skip clear token itself */
722     tp += sizeof(afs_int32);        /* skip primary flag */
723     /* tp now points to the cell name */
724     strcpy(aserver->cell, tp);
725     aserver->instance[0] = 0;
726     strcpy(aserver->name, "afs");
727     UNLOCK_GLOBAL_MUTEX
728     return 0;
729 }
730
731 /* discard all tokens from this user's cache */
732
733 static int NewForgetAll ()
734 {
735     TRY_KERNEL (KTC_FORGETALLTOKENS_OP, 0,0,0,0);
736     return EINVAL;
737 }
738
739 static int OldForgetAll ()
740 {
741     struct ViceIoctl iob;
742     register afs_int32 code;
743     int i;
744
745     for (i=0; i<MAXLOCALTOKENS; i++) local_tokens[i].valid = 0;
746
747     iob.in = 0;
748     iob.in_size = 0;
749     iob.out = 0;
750     iob.out_size = 0;
751     code = PIOCTL(0, VIOCUNPAG, &iob, 0);
752     if (code) return KTC_PIOCTLFAIL;
753     return 0;
754 }
755
756 int ktc_ForgetAllTokens()
757 {
758     int ncode, ocode;
759
760     LOCK_GLOBAL_MUTEX
761 #ifdef AFS_KERBEROS_ENV
762      (void) tf_dest_tkt();
763 #endif
764
765     ncode = NewForgetAll ();
766     ocode = OldForgetAll ();
767     if (ncode && ocode) {
768         if (ocode == -1) ocode = errno;
769         else if (ocode == KTC_PIOCTLFAIL) ocode = errno;
770         UNLOCK_GLOBAL_MUTEX
771         if (ocode == EINVAL) return KTC_NOPIOCTL;
772         return KTC_PIOCTLFAIL;
773     }
774     UNLOCK_GLOBAL_MUTEX
775     return 0;
776 }
777
778 /* ktc_OldPioctl - returns a boolean true if the kernel supports only the old
779  * pioctl interface for delivering AFS tickets to the cache manager. */
780
781 ktc_OldPioctl ()
782 {
783     int rc;
784     LOCK_GLOBAL_MUTEX
785 #ifdef  KERNEL_KTC_COMPAT
786     CHECK_KERNEL;
787     rc = (kernelKTC != 1);              /* old style interface */
788 #else
789     rc = 1;
790 #endif
791     UNLOCK_GLOBAL_MUTEX
792     return rc;
793 }
794
795
796 #ifdef AFS_KERBEROS_ENV
797  /*
798   * Copyright 1987, 1988 by the Massachusetts Institute of Technology.
799   *
800   * For copying and distribution information, please see the file
801   * <mit-copyright.h>.
802   */
803  
804 #if 0
805 #include <stdio.h>
806 #include <errno.h>
807 #include <sys/types.h>
808 #include <sys/stat.h>
809 #include <sys/file.h>
810 #include <krb.h>
811 #endif
812  
813 #define TOO_BIG -1
814 #define TF_LCK_RETRY ((unsigned)2)      /* seconds to sleep before
815                                          * retry if ticket file is
816                                          * locked */
817  
818 /*
819  * fd must be initialized to something that won't ever occur as a real
820  * file descriptor. Since open(2) returns only non-negative numbers as
821  * valid file descriptors, and tf_init always stuffs the return value
822  * from open in here even if it is an error flag, we must
823  *      a. Initialize fd to a negative number, to indicate that it is
824  *         not initially valid.
825  *      b. When checking for a valid fd, assume that negative values
826  *         are invalid (ie. when deciding whether tf_init has been
827  *         called.)
828  *      c. In tf_close, be sure it gets reinitialized to a negative
829  *         number. 
830  */
831 static  fd = -1;
832 static  curpos;                         /* Position in tfbfr */
833 static  lastpos;                        /* End of tfbfr */
834 static  char tfbfr[BUFSIZ];             /* Buffer for ticket data */
835  
836 static tf_gets(), tf_read();
837  
838 /*
839  * This file contains routines for manipulating the ticket cache file.
840  *
841  * The ticket file is in the following format:
842  *
843  *      principal's name        (null-terminated string)
844  *      principal's instance    (null-terminated string)
845  *      CREDENTIAL_1
846  *      CREDENTIAL_2
847  *      ...
848  *      CREDENTIAL_n
849  *      EOF
850  *
851  *      Where "CREDENTIAL_x" consists of the following fixed-length
852  *      fields from the CREDENTIALS structure (see "krb.h"):
853  *
854  *              char            service[MAXKTCNAMELEN]
855  *              char            instance[MAXKTCNAMELEN]
856  *              char            realm[REALM_SZ]
857  *              C_Block         session
858  *              int             lifetime
859  *              int             kvno
860  *              KTEXT_ST        ticket_st
861  *              afs_int32            issue_date
862  *
863  * Short description of routines:
864  *
865  * tf_init() opens the ticket file and locks it.
866  *
867  * tf_get_pname() returns the principal's name.
868  *
869  * tf_get_pinst() returns the principal's instance (may be null).
870  *
871  * tf_get_cred() returns the next CREDENTIALS record.
872  *
873  * tf_save_cred() appends a new CREDENTIAL record to the ticket file.
874  *
875  * tf_close() closes the ticket file and releases the lock.
876  *
877  * tf_gets() returns the next null-terminated string.  It's an internal
878  * routine used by tf_get_pname(), tf_get_pinst(), and tf_get_cred().
879  *
880  * tf_read() reads a given number of bytes.  It's an internal routine
881  * used by tf_get_cred().
882  */
883
884 /*
885  * tf_init() should be called before the other ticket file routines.
886  * It takes the name of the ticket file to use, "tf_name", and a
887  * read/write flag "rw" as arguments. 
888  *
889  * It tries to open the ticket file, checks the mode, and if everything
890  * is okay, locks the file.  If it's opened for reading, the lock is
891  * shared.  If it's opened for writing, the lock is exclusive. 
892  *
893  * Returns 0 if all went well, otherwise one of the following: 
894  *
895  * NO_TKT_FIL   - file wasn't there
896  * TKT_FIL_ACC  - file was in wrong mode, etc.
897  * TKT_FIL_LCK  - couldn't lock the file, even after a retry
898  */
899  
900 static tf_init(tf_name, rw)
901     char   *tf_name;
902 {
903     int     wflag;
904     int   me;
905      struct stat stat_buf;
906
907      switch (rw) {
908      case R_TKT_FIL:
909         wflag = 0;
910         break;
911      case W_TKT_FIL:
912         wflag = 1;
913         break;
914      default:
915         return TKT_FIL_ACC;
916      }
917      if (lstat(tf_name, &stat_buf) < 0)
918         switch (errno) {
919         case ENOENT:
920             return NO_TKT_FIL;
921         default:
922             return TKT_FIL_ACC;
923         }
924      me = getuid();
925      if ((stat_buf.st_uid != me && me != 0) ||
926         ((stat_buf.st_mode & S_IFMT) != S_IFREG))
927         return TKT_FIL_ACC;
928  
929      /*
930       * If "wflag" is set, open the ticket file in append-writeonly mode
931       * and lock the ticket file in exclusive mode.  If unable to lock
932      * the file, sleep and try again.  If we fail again, return with the
933      * proper error message. 
934      */
935
936     curpos = sizeof(tfbfr);
937
938     if (wflag) {
939         fd = open(tf_name, O_RDWR, 0600);
940         if (fd < 0) {
941             return TKT_FIL_ACC;
942         }
943 #if defined(AFS_AIX_ENV) || defined(AFS_HPUX_ENV) || defined(AFS_SUN5_ENV)
944         if  (fcntl(fd, F_SETLK, &fileWlock) == -1) {
945             sleep(TF_LCK_RETRY);
946             if  (fcntl(fd, F_SETLK, &fileWlock) == -1) {
947 #else
948         if (flock(fd, LOCK_EX | LOCK_NB) < 0) {
949             sleep(TF_LCK_RETRY);
950             if (flock(fd, LOCK_EX | LOCK_NB) < 0) {
951 #endif
952                 (void) close(fd);
953                 fd = -1;
954                 return TKT_FIL_LCK;
955             }
956         }
957         return 0;
958     }
959     /*
960      * Otherwise "wflag" is not set and the ticket file should be opened
961      * for read-only operations and locked for shared access. 
962      */
963
964     fd = open(tf_name, O_RDONLY, 0600);
965     if (fd < 0) {
966         return TKT_FIL_ACC;
967     }
968 #if defined(AFS_AIX_ENV) || defined(AFS_HPUX_ENV) || defined(AFS_SUN5_ENV)
969     if  (fcntl(fd, F_SETLK, &fileRlock) == -1) {
970         sleep(TF_LCK_RETRY);
971         if  (fcntl(fd, F_SETLK, &fileRlock) == -1) {
972 #else
973     if (flock(fd, LOCK_SH | LOCK_NB) < 0) {
974         sleep(TF_LCK_RETRY);
975         if (flock(fd, LOCK_SH | LOCK_NB) < 0) {
976 #endif
977             (void) close(fd);
978             fd = -1;
979             return TKT_FIL_LCK;
980         }
981     }
982     return 0;
983 }
984
985 /*
986  * tf_get_pname() reads the principal's name from the ticket file. It
987  * should only be called after tf_init() has been called.  The
988  * principal's name is filled into the "p" parameter.  If all goes well,
989  * 0 is returned.  If tf_init() wasn't called, TKT_FIL_INI is
990  * returned.  If the name was null, or EOF was encountered, or the name
991  * was longer than MAXKTCNAMELEN, TKT_FIL_FMT is returned. 
992  */
993
994 static tf_get_pname(p)
995     char   *p;
996 {
997     if (fd < 0) {
998         return TKT_FIL_INI;
999     }
1000     if (tf_gets(p, MAXKTCNAMELEN) < 2)  /* can't be just a null */
1001         return TKT_FIL_FMT;
1002     return 0;
1003 }
1004
1005 /*
1006  * tf_get_pinst() reads the principal's instance from a ticket file.
1007  * It should only be called after tf_init() and tf_get_pname() have been
1008  * called.  The instance is filled into the "inst" parameter.  If all
1009  * goes well, 0 is returned.  If tf_init() wasn't called,
1010  * TKT_FIL_INI is returned.  If EOF was encountered, or the instance
1011  * was longer than MAXKTCNAMELEN, TKT_FIL_FMT is returned.  Note that the
1012  * instance may be null. 
1013  */
1014
1015 static tf_get_pinst(inst)
1016     char   *inst;
1017 {
1018     if (fd < 0) {
1019         return TKT_FIL_INI;
1020     }
1021     if (tf_gets(inst, MAXKTCNAMELEN) < 1)
1022         return TKT_FIL_FMT;
1023     return 0;
1024 }
1025
1026 /*
1027  * tf_get_cred() reads a CREDENTIALS record from a ticket file and fills
1028  * in the given structure "c".  It should only be called after tf_init(),
1029  * tf_get_pname(), and tf_get_pinst() have been called. If all goes well,
1030  * 0 is returned.  Possible error codes are: 
1031  *
1032  * TKT_FIL_INI  - tf_init wasn't called first
1033  * TKT_FIL_FMT  - bad format
1034  * EOF          - end of file encountered
1035  */
1036
1037 static tf_get_cred(principal, token)
1038     struct ktc_principal *principal;
1039     struct ktc_token *token;
1040 {
1041     int     k_errno;
1042     int     kvno, lifetime;
1043
1044     if (fd < 0) {
1045         return TKT_FIL_INI;
1046     }
1047     if ((k_errno = tf_gets(principal->name, MAXKTCNAMELEN)) < 2)
1048         switch (k_errno) {
1049         case TOO_BIG:
1050         case 1:         /* can't be just a null */
1051             return TKT_FIL_FMT;
1052         case 0:
1053             return EOF;
1054         }
1055     if ((k_errno = tf_gets(principal->instance, MAXKTCNAMELEN)) < 1)
1056         switch (k_errno) {
1057         case TOO_BIG:
1058             return TKT_FIL_FMT;
1059         case 0:
1060             return EOF;
1061         }
1062     if ((k_errno = tf_gets(principal->cell, MAXKTCREALMLEN)) < 2)
1063         switch (k_errno) {
1064         case TOO_BIG:
1065         case 1:         /* can't be just a null */
1066             return TKT_FIL_FMT;
1067         case 0:
1068             return EOF;
1069         }
1070     lcstring(principal->cell, principal->cell, MAXKTCREALMLEN);
1071     if (
1072         tf_read((char *) &(token->sessionKey), 8) < 1 ||
1073         tf_read((char *) &(lifetime), sizeof(lifetime)) < 1 ||
1074         tf_read((char *) &(kvno), sizeof(kvno)) < 1 ||
1075         tf_read((char *) &(token->ticketLen), sizeof(token->ticketLen))
1076         < 1 ||
1077     /* don't try to read a silly amount into ticket->dat */
1078         token->ticketLen > MAXKTCTICKETLEN ||
1079         tf_read((char *) (token->ticket), token->ticketLen) < 1 ||
1080         tf_read((char *) &(token->startTime), sizeof(token->startTime)) < 1
1081         ) {
1082         return TKT_FIL_FMT;
1083     }
1084     token->endTime = life_to_time(token->startTime, lifetime);
1085     token->kvno = kvno;
1086     return 0;
1087 }
1088
1089 /*
1090  * tf_close() closes the ticket file and sets "fd" to -1. If "fd" is
1091  * not a valid file descriptor, it just returns.  It also clears the
1092  * buffer used to read tickets.
1093  *
1094  * The return value is not defined.
1095  */
1096
1097 static tf_close()
1098 {
1099     if (!(fd < 0)) {
1100 #if defined(AFS_AIX_ENV) || defined(AFS_HPUX_ENV) || defined(AFS_SUN5_ENV)
1101         (void) fcntl(fd, F_SETLK, &fileUlock);
1102 #else
1103         (void) flock(fd, LOCK_UN);
1104 #endif 
1105         (void) close(fd);
1106         fd = -1;                /* see declaration of fd above */
1107     }
1108     bzero(tfbfr, sizeof(tfbfr));
1109 }
1110
1111 /*
1112  * tf_gets() is an internal routine.  It takes a string "s" and a count
1113  * "n", and reads from the file until either it has read "n" characters,
1114  * or until it reads a null byte. When finished, what has been read exists
1115  * in "s".
1116  *
1117  * Possible return values are:
1118  *
1119  * n            the number of bytes read (including null terminator)
1120  *              when all goes well
1121  *
1122  * 0            end of file or read error
1123  *
1124  * TOO_BIG      if "count" characters are read and no null is
1125  *              encountered. This is an indication that the ticket
1126  *              file is seriously ill.
1127  */
1128
1129 static 
1130 tf_gets(s, n)
1131     register char *s;
1132 {
1133     register count;
1134
1135     if (fd < 0) {
1136         return TKT_FIL_INI;
1137     }
1138     for (count = n - 1; count > 0; --count) {
1139         if (curpos >= sizeof(tfbfr)) {
1140             lastpos = read(fd, tfbfr, sizeof(tfbfr));
1141             curpos = 0;
1142         }
1143         if (curpos == lastpos) {
1144             return 0;
1145         }
1146         *s = tfbfr[curpos++];
1147         if (*s++== '\0')
1148             return (n - count);
1149     }
1150     return TOO_BIG;
1151 }
1152
1153 /*
1154  * tf_read() is an internal routine.  It takes a string "s" and a count
1155  * "n", and reads from the file until "n" bytes have been read.  When
1156  * finished, what has been read exists in "s".
1157  *
1158  * Possible return values are:
1159  *
1160  * n            the number of bytes read when all goes well
1161  *
1162  * 0            on end of file or read error
1163  */
1164
1165 static
1166 tf_read(s, n)
1167     register char *s;
1168     register n;
1169 {
1170     register count;
1171     
1172     for (count = n; count > 0; --count) {
1173         if (curpos >= sizeof(tfbfr)) {
1174             lastpos = read(fd, tfbfr, sizeof(tfbfr));
1175             curpos = 0;
1176         }
1177         if (curpos == lastpos) {
1178             return 0;
1179         }
1180         *s++ = tfbfr[curpos++];
1181     }
1182     return n;
1183 }
1184      
1185 char   *tkt_string();
1186
1187 /*
1188  * tf_save_cred() appends an incoming ticket to the end of the ticket
1189  * file.  You must call tf_init() before calling tf_save_cred().
1190  *
1191  * The "service", "instance", and "realm" arguments specify the
1192  * server's name; "aticket" contains the credential.
1193  *
1194  * Returns 0 if all goes well, TKT_FIL_INI if tf_init() wasn't
1195  * called previously, and KFAILURE for anything else that went wrong.
1196  */
1197
1198 static tf_save_cred(aserver, atoken, aclient)
1199     struct ktc_principal *aserver;
1200     struct ktc_principal *aclient;
1201     struct ktc_token *atoken;   /* Token */
1202 {
1203     char realm[MAXKTCREALMLEN+1];
1204     char junk[MAXKTCNAMELEN];
1205     struct ktc_principal principal;
1206     struct ktc_token token;
1207     int     status;
1208     off_t   start, lseek();
1209     int     lifetime, kvno;
1210     int     count;              /* count for write */
1211
1212     if (fd < 0) {               /* fd is ticket file as set by tf_init */
1213           return TKT_FIL_INI;
1214     }
1215
1216     ucstring(realm, aserver->cell, MAXKTCREALMLEN);
1217     realm[MAXKTCREALMLEN] = '\0';
1218
1219     /* Look for a duplicate ticket */
1220     (void) lseek(fd, (off_t) 0L, 0);
1221     curpos = sizeof(tfbfr);
1222
1223     if (tf_get_pname(junk) || strcmp(junk, aclient->name) ||
1224         tf_get_pinst(junk) || strcmp(junk, aclient->instance)) goto bad;
1225
1226     do {
1227         start = lseek(fd, (off_t) 0L, 1) - lastpos + curpos;
1228         status = tf_get_cred(&principal, &token);
1229     } while (status == 0 &&
1230              (strcmp(aserver->name, principal.name) != 0 ||
1231               strcmp(aserver->instance, principal.instance) != 0 ||
1232               strcmp(aserver->cell, principal.cell) != 0));
1233
1234     /*
1235      * Two tickets for the same user authenticating to the same service
1236      * should be the same length, but we check here just to make sure.
1237      */
1238     if (status == 0 && token.ticketLen != atoken->ticketLen) return KFAILURE;
1239     if (status && status != EOF) return status;
1240
1241     /* Position over the credential we just matched (or the EOF) */
1242     lseek(fd, start, 0);
1243     curpos = lastpos = sizeof(tfbfr);
1244
1245     /* Write the ticket and associated data */
1246     /* Service */
1247     count = strlen(aserver->name) + 1;
1248     if (write(fd, aserver->name, count) != count)
1249         goto bad;
1250     /* Instance */
1251     count = strlen(aserver->instance) + 1;
1252     if (write(fd, aserver->instance, count) != count)
1253         goto bad;
1254     /* Realm */
1255     count = strlen(realm) + 1;
1256     if (write(fd, realm, count) != count)
1257         goto bad;
1258     /* Session key */
1259     if (write(fd, (char *) &atoken->sessionKey, 8) != 8)
1260         goto bad;
1261     /* Lifetime */
1262     lifetime = time_to_life(atoken->startTime, atoken->endTime);
1263     if (write(fd, (char *) &lifetime, sizeof(int)) != sizeof(int))
1264         goto bad;
1265     /* Key vno */
1266     kvno = atoken->kvno;
1267     if (write(fd, (char *) &kvno, sizeof(int)) != sizeof(int))
1268         goto bad;
1269     /* Tkt length */
1270     if (write(fd, (char *) &(atoken->ticketLen), sizeof(int)) !=
1271         sizeof(int))
1272         goto bad;
1273     /* Ticket */
1274     count = atoken->ticketLen;
1275     if (write(fd, atoken->ticket, count) != count)
1276         goto bad;
1277     /* Issue date */
1278     if (write(fd, (char *) &atoken->startTime, sizeof(afs_int32))
1279         != sizeof(afs_int32))
1280         goto bad;
1281
1282     /* Actually, we should check each write for success */
1283     return (0);
1284 bad:
1285     return (KFAILURE);
1286 }
1287
1288 /*
1289  * Copyright 1985, 1986, 1987, 1988 by the Massachusetts Institute
1290  * of Technology.
1291  *
1292  * For copying and distribution information, please see the file
1293  * <mit-copyright.h>.
1294  */
1295
1296 char *getenv();
1297
1298 /*
1299  * This routine is used to generate the name of the file that holds
1300  * the user's cache of server tickets and associated session keys.
1301  *
1302  * If it is set, krb_ticket_string contains the ticket file name.
1303  * Otherwise, the filename is constructed as follows:
1304  *
1305  * If it is set, the environment variable "KRBTKFILE" will be used as
1306  * the ticket file name.  Otherwise TKT_ROOT (defined in "krb.h") and
1307  * the user's uid are concatenated to produce the ticket file name
1308  * (e.g., "/tmp/tkt123").  A pointer to the string containing the ticket
1309  * file name is returned.
1310  */
1311
1312 static char krb_ticket_string[4096] = "";
1313
1314 char *ktc_tkt_string()
1315 {
1316     char *env;
1317
1318     LOCK_GLOBAL_MUTEX
1319     if (!*krb_ticket_string) {
1320         if (env = getenv("KRBTKFILE")) {
1321             (void) strncpy(krb_ticket_string, env,
1322                            sizeof(krb_ticket_string)-1);
1323             krb_ticket_string[sizeof(krb_ticket_string)-1] = '\0';
1324         } else {
1325             /* 32 bits of signed integer will always fit in 11 characters
1326              (including the sign), so no need to worry about overflow */
1327             (void) sprintf(krb_ticket_string, "%s%d",TKT_ROOT,getuid());
1328         }
1329     }
1330     UNLOCK_GLOBAL_MUTEX
1331     return krb_ticket_string;
1332 }
1333
1334 /*
1335  * This routine is used to set the name of the file that holds the user's
1336  * cache of server tickets and associated session keys.
1337  *
1338  * The value passed in is copied into local storage.
1339  *
1340  * NOTE:  This routine should be called during initialization, before other
1341  * Kerberos routines are called; otherwise tkt_string() above may be called
1342  * and return an undesired ticket file name until this routine is called.
1343  */
1344
1345 void
1346 ktc_set_tkt_string(val)
1347 char *val;
1348 {
1349
1350     LOCK_GLOBAL_MUTEX
1351     (void) strncpy(krb_ticket_string, val, sizeof(krb_ticket_string)-1);
1352     krb_ticket_string[sizeof(krb_ticket_string)-1] = '\0';
1353     UNLOCK_GLOBAL_MUTEX
1354
1355     return;
1356 }
1357
1358 /*
1359  * tf_create() is used to initialize the ticket store.  It creates the
1360  * file to contain the tickets and writes the given user's name "pname"
1361  * and instance "pinst" in the file.  in_tkt() returns KSUCCESS on
1362  * success, or KFAILURE if something goes wrong.
1363  */
1364
1365 static tf_create(pname,pinst)
1366     char *pname;
1367     char *pinst;
1368 {
1369     int tktfile;
1370     int me, metoo;
1371     int count;
1372     char *file = ktc_tkt_string();
1373     int fd;
1374     register int i;
1375     char zerobuf[1024];
1376     struct stat sbuf;
1377
1378     me = getuid ();
1379     metoo = geteuid();
1380
1381     if (lstat(file,&sbuf) == 0) {
1382         if ((sbuf.st_uid != me && me != 0) || ((sbuf.st_mode & S_IFMT) != S_IFREG) ||
1383             sbuf.st_mode & 077) {
1384             return KFAILURE;
1385         }
1386         /* file already exists, and permissions appear ok, so nuke it */
1387         if ((fd = open(file, O_RDWR, 0)) < 0)
1388             goto out; /* can't zero it, but we can still try truncating it */
1389
1390         bzero(zerobuf, sizeof(zerobuf));
1391
1392         for (i = 0; i < sbuf.st_size; i += sizeof(zerobuf))
1393             if (write(fd, zerobuf, sizeof(zerobuf)) != sizeof(zerobuf)) {
1394                 (void) fsync(fd);
1395                 (void) close(fd);
1396                 goto out;
1397             }
1398         
1399         (void) fsync(fd);
1400         (void) close(fd);
1401     }
1402
1403  out:
1404     /* arrange so the file is owned by the ruid
1405        (swap real & effective uid if necessary).
1406        This isn't a security problem, since the ticket file, if it already
1407        exists, has the right uid (== ruid) and mode. */
1408     if (me != metoo) {
1409         if (setreuid(metoo, me) < 0) {
1410             return(KFAILURE);
1411         }
1412     }
1413     tktfile = creat(file, 0600);
1414     if (me != metoo) {
1415         if (setreuid(me, metoo) < 0) {
1416             /* can't switch??? fail! */
1417             return(KFAILURE);
1418         }
1419     }
1420     if (tktfile < 0) {
1421         return(KFAILURE);
1422     }
1423     count = strlen(pname)+1;
1424     if (write(tktfile,pname,count) != count) {
1425         (void) close(tktfile);
1426         return(KFAILURE);
1427     }
1428     count = strlen(pinst)+1;
1429     if (write(tktfile,pinst,count) != count) {
1430         (void) close(tktfile);
1431         return(KFAILURE);
1432     }
1433     (void) close(tktfile);
1434     return(KSUCCESS);
1435 }
1436
1437 /*
1438  * dest_tkt() is used to destroy the ticket store upon logout.
1439  * If the ticket file does not exist, dest_tkt() returns RET_TKFIL.
1440  * Otherwise the function returns 0 on success, KFAILURE on
1441  * failure.
1442  */
1443
1444 static tf_dest_tkt()
1445 {
1446     char *file = ktc_tkt_string();
1447     int i,fd;
1448     struct stat statb;
1449     char buf[BUFSIZ];
1450
1451     errno = 0;
1452     if (lstat(file,&statb) < 0)
1453         goto out;
1454
1455     if (!(statb.st_mode & S_IFREG))
1456         goto out;
1457
1458     if ((fd = open(file, O_RDWR, 0)) < 0)
1459         goto out;
1460
1461     bzero(buf, BUFSIZ);
1462
1463     for (i = 0; i < statb.st_size; i += BUFSIZ)
1464         if (write(fd, buf, BUFSIZ) != BUFSIZ) {
1465             (void) fsync(fd);
1466             (void) close(fd);
1467             goto out;
1468         }
1469
1470     (void) fsync(fd);
1471     (void) close(fd);
1472
1473     (void) unlink(file);
1474
1475 out:
1476     if (errno == ENOENT) return RET_TKFIL;
1477     else if (errno != 0) return KFAILURE;
1478     return 0;
1479 }
1480
1481 static afs_uint32 curpag()
1482 {
1483     gid_t groups[NGROUPS_MAX];
1484     afs_uint32 g0, g1;
1485     afs_uint32 h, l, ret;
1486
1487     if (getgroups(sizeof groups/sizeof groups[0], groups) < 2) return 0;
1488
1489     g0 = groups[0]  & 0xffff;
1490     g1 = groups[1]  & 0xffff;
1491     g0 -= 0x3f00;
1492     g1 -= 0x3f00;
1493     if (g0 < 0xc000 && g1 < 0xc000) {
1494         l = ((g0 & 0x3fff) << 14) | (g1 & 0x3fff);
1495         h = (g0 >> 14);
1496         h = (g1 >> 14) + h + h + h;
1497         ret = ((h << 28) | l);
1498         /* Additional testing */
1499         if (((ret >> 24) & 0xff) == 'A')
1500             return ret;
1501         else
1502             return -1;
1503     }
1504     return -1;
1505 }
1506   
1507
1508 ktc_newpag()
1509 {
1510     extern char **environ;
1511
1512     afs_uint32 pag;
1513     struct stat sbuf;
1514     char fname[256], *prefix = "/ticket/";
1515     int numenv;
1516     char **newenv, **senv, **denv;
1517
1518     LOCK_GLOBAL_MUTEX
1519     if (stat("/ticket", &sbuf) == -1) {
1520         prefix = "/tmp/tkt";
1521     }
1522
1523     pag = curpag() & 0xffffffff;
1524     if (pag == -1) {
1525         sprintf(fname, "%s%d", prefix, getuid());
1526     }
1527     else {
1528         sprintf(fname, "%sp%ld", prefix, pag);
1529     }
1530     ktc_set_tkt_string(fname);
1531
1532     for (senv=environ, numenv=0; *senv; senv++) numenv++;
1533     newenv = (char **)malloc((numenv+2) * sizeof(char *));
1534
1535     for (senv=environ, denv=newenv; *senv; *senv++) {
1536         if (strncmp(*senv, "KRBTKFILE=", 10) != 0) *denv++ = *senv;
1537     }
1538
1539     *denv = (char *)malloc(10 + strlen(fname) + 1);
1540     strcpy(*denv, "KRBTKFILE=");
1541     strcat(*denv, fname);
1542     *++denv = 0;
1543     environ = newenv;
1544     UNLOCK_GLOBAL_MUTEX
1545 }
1546
1547 /*
1548  * BLETCH!  We have to invoke the entire afsconf package just to
1549  * find out what the local cell is.
1550  */
1551 static ktc_LocalCell()
1552 {
1553     int code;
1554     struct afsconf_dir *conf;
1555
1556     if ((conf = afsconf_Open (AFSDIR_CLIENT_ETC_DIRPATH)) ||
1557         (conf = afsconf_Open (AFSDIR_SERVER_ETC_DIRPATH ))) {
1558         code = afsconf_GetLocalCell (conf, lcell, sizeof(lcell));
1559         afsconf_Close (conf);
1560     }
1561     if (!conf || code) {
1562         printf("** Can't determine local cell name!\n");
1563     }
1564 }
1565
1566 #endif