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