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