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