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