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