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