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