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