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