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