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