93afac5c40d4ca3a9af41dd70d8fda0ab9a0731b
[openafs.git] / src / auth / cellconfig.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 #include <afsconfig.h>
11 #include <afs/param.h>
12
13 RCSID
14     ("$Header$");
15
16 #include <afs/stds.h>
17 #include <afs/pthread_glock.h>
18 #ifdef UKERNEL
19 #include "afs/sysincludes.h"
20 #include "afsincludes.h"
21 #include "des/des.h"
22 #include "rx/rxkad.h"
23 #include <netdb.h>
24 #else /* UKERNEL */
25 #include <sys/types.h>
26 #ifdef AFS_NT40_ENV
27 #include <winsock2.h>
28 #include <sys/utime.h>
29 #include <io.h>
30 #include <WINNT/afssw.h>
31 #else
32 #include <sys/socket.h>
33 #include <netinet/in.h>
34 #include <netdb.h>
35 #include <sys/file.h>
36 #include <sys/time.h>
37 #ifdef AFS_AFSDB_ENV
38 #include <arpa/nameser.h>
39 #ifdef HAVE_ARPA_NAMESER_COMPAT_H
40 #include <arpa/nameser_compat.h>
41 #endif
42 #include <resolv.h>
43 #endif /* AFS_AFSDB_ENV */
44 #endif /* AFS_NT40_ENV */
45 #include <afs/afsint.h>
46 #include <errno.h>
47 #include <ctype.h>
48 #include <time.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <sys/stat.h>
52 #include <fcntl.h>
53 #include <string.h>
54 #ifdef HAVE_UNISTD_H
55 #include <unistd.h>
56 #endif
57 #include <rx/rxkad.h>
58 #include <rx/rx.h>
59 #endif /* UKERNEL */
60 #include <afs/afsutil.h>
61 #include "cellconfig.h"
62 #include "keys.h"
63 #ifdef AFS_NT40_ENV
64 #ifdef AFS_AFSDB_ENV
65 #include <cm.h>
66 #include <cm_config.h>
67 /* cm_dns.h depends on cellconfig.h */
68 #include <cm_nls.h>
69 #include <cm_dns.h>
70 #endif /* AFS_AFSDB_ENV */
71 #endif
72 #include <rx/rx.h>
73 #include <rx/rxkad.h>
74
75 static struct afsconf_servPair serviceTable[] = {
76     {"afs", 7000,},
77     {"afscb", 7001,},
78     {"afsprot", 7002,},
79     {"afsvldb", 7003,},
80     {"afskauth", 7004,},
81     {"afsvol", 7005,},
82     {"afserror", 7006,},
83     {"afsnanny", 7007,},
84     {"afsupdate", 7008,},
85     {"afsrmtsys", 7009,},
86     {"afsres", 7010,},          /* residency database for MR-AFS */
87     {"afsremio", 7011,},        /* remote I/O interface for MR-AFS */
88     {0, 0}                      /* insert new services before this spot */
89 };
90
91 /* Prototypes */
92 static afs_int32 afsconf_FindService(register const char *aname);
93 static int TrimLine(char *abuffer);
94 #ifdef AFS_NT40_ENV
95 static int IsClientConfigDirectory(const char *path);
96 static int GetCellNT(struct afsconf_dir *adir);
97 #endif
98 static int afsconf_Check(register struct afsconf_dir *adir);
99 static int afsconf_Touch(register struct afsconf_dir *adir);
100 static int GetCellUnix(struct afsconf_dir *adir);
101 static int afsconf_OpenInternal(register struct afsconf_dir *adir, char *cell,
102                                 char clones[]);
103 static int ParseHostLine(char *aline, register struct sockaddr_in *addr,
104                          char *aname, char *aclone);
105 static int ParseCellLine(register char *aline, register char *aname,
106                          register char *alname);
107 static int afsconf_CloseInternal(register struct afsconf_dir *adir);
108 static int afsconf_Reopen(register struct afsconf_dir *adir);
109 static int SaveKeys(struct afsconf_dir *adir);
110
111 #ifndef T_AFSDB
112 #define T_AFSDB 18              /* per RFC1183 section 1 */
113 #endif
114
115 /*
116  * Basic Rule: we touch "<AFSCONF_DIR>/CellServDB" every time we change anything, so
117  * our code can tell if there is new info in the key files, the cell server db
118  * files or any of the other files (and reopen the thing) if the date on
119  * CellServDB changes.
120  */
121
122 #if defined(AFS_SUN5_ENV) && !defined(__sparcv9)
123 /* Solaris through 10 in 32 bit mode will return EMFILE if fopen can't
124    get an fd <= 255. We allow the fileserver to claim more fds than that.
125    This has always been a problem since pr_Initialize would have the same
126    issue, but hpr_Initialize makes it more likely that we would see this. 
127    Work around it. This is not generic. It's coded with the needs of
128    afsconf_* in mind only.
129
130    http://www.opensolaris.org/os/community/onnv/flag-days/pages/2006042001/
131 */
132
133 #define BUFFER 4096
134
135 struct afsconf_iobuffer {
136     int _file;
137     char *buffer;
138     char *ptr;
139     char *endptr;
140 };
141
142 typedef struct afsconf_iobuffer afsconf_FILE;
143
144 static afsconf_FILE *
145 afsconf_fopen(const char *fname, const char *fmode)
146 {
147     int fd;
148     afsconf_FILE *iop;
149     
150     if ((fd = open(fname, O_RDONLY)) == -1) {
151         return NULL;
152     }
153     
154     iop = malloc(sizeof(struct afsconf_iobuffer));
155     if (iop == NULL) {
156         (void) close(fd);
157         errno = ENOMEM;
158         return NULL;
159     }
160     iop->_file = fd;
161     iop->buffer = malloc(BUFFER);
162     if (iop->buffer == NULL) {
163         (void) close(fd);
164         free((void *) iop);
165         errno = ENOMEM;
166         return NULL;
167     }
168     iop->ptr = iop->buffer;
169     iop->endptr = iop->buffer;
170     return iop;
171 }
172
173 static int
174 afsconf_fclose(afsconf_FILE *iop)
175 {
176     if (iop == NULL) {
177         return 0;
178     }
179     close(iop->_file);
180     free((void *)iop->buffer);
181     free((void *)iop);
182     return 0;
183 }
184
185 static char *
186 afsconf_fgets(char *s, int n, afsconf_FILE *iop)
187 {
188     char *p;
189     
190     p = s;
191     for (;;) {
192         char c;
193         
194         if (iop->ptr == iop->endptr) {
195             ssize_t len;
196             
197             if ((len = read(iop->_file, (void *)iop->buffer, BUFFER)) == -1) {
198                 return NULL;
199             }
200             if (len == 0) {
201                 *p = 0;
202                 if (s == p) {
203                     return NULL;
204                 }
205                 return s;
206             }
207             iop->ptr = iop->buffer;
208             iop->endptr = iop->buffer + len;
209         }
210         c = *iop->ptr++;
211         *p++ = c;
212         if ((p - s) == (n - 1)) {
213             *p = 0;
214             return s;
215         }
216         if (c == '\n') {
217             *p = 0;
218             return s;
219         }
220     }
221 }
222 #define fopen afsconf_fopen
223 #define fclose afsconf_fclose
224 #define fgets afsconf_fgets
225 #else
226 #define afsconf_FILE FILE
227 #endif /* AFS_SUN5_ENV && ! __sparcv9 */
228
229 /* return port number in network byte order in the low 16 bits of a long; return -1 if not found */
230 static afs_int32
231 afsconf_FindService(register const char *aname)
232 {
233     /* lookup a service name */
234     struct servent *ts;
235     register struct afsconf_servPair *tsp;
236
237 #if     defined(AFS_OSF_ENV) 
238     ts = getservbyname(aname, "");
239 #else
240     ts = (struct servent *) getservbyname(aname, NULL);
241 #endif
242     if (ts) {
243         /* we found it in /etc/services, so we use this value */
244         return ts->s_port;      /* already in network byte order */
245     }
246
247     /* not found in /etc/services, see if it is one of ours */
248     for (tsp = serviceTable;; tsp++) {
249         if (tsp->name == NULL)
250             return -1;
251         if (!strcmp(tsp->name, aname))
252             return htons(tsp->port);
253     }
254 }
255
256 static int
257 TrimLine(char *abuffer)
258 {
259     char tbuffer[256];
260     register char *tp;
261     register int tc;
262
263     tp = abuffer;
264     while ((tc = *tp)) {
265         if (!isspace(tc))
266             break;
267         tp++;
268     }
269     strcpy(tbuffer, tp);
270     strcpy(abuffer, tbuffer);
271     return 0;
272 }
273
274 #ifdef AFS_NT40_ENV
275 /*
276  * IsClientConfigDirectory() -- determine if path matches well-known
277  *     client configuration directory.
278  */
279 static int
280 IsClientConfigDirectory(const char *path)
281 {
282     const char *cdir = AFSDIR_CLIENT_ETC_DIRPATH;
283     int i;
284
285     for (i = 0; cdir[i] != '\0' && path[i] != '\0'; i++) {
286         int cc = tolower(cdir[i]);
287         int pc = tolower(path[i]);
288
289         if (cc == '\\') {
290             cc = '/';
291         }
292         if (pc == '\\') {
293             pc = '/';
294         }
295         if (cc != pc) {
296             return 0;
297         }
298     }
299
300     /* hit end of one or both; allow mismatch in existence of trailing slash */
301     if (cdir[i] != '\0') {
302         if ((cdir[i] != '\\' && cdir[i] != '/') || (cdir[i + 1] != '\0')) {
303             return 0;
304         }
305     }
306     if (path[i] != '\0') {
307         if ((path[i] != '\\' && path[i] != '/') || (path[i + 1] != '\0')) {
308             return 0;
309         }
310     }
311     return 1;
312 }
313 #endif /* AFS_NT40_ENV */
314
315
316 static int
317 afsconf_Check(register struct afsconf_dir *adir)
318 {
319     char tbuffer[256];
320 #ifdef AFS_NT40_ENV
321     char *p;
322 #endif
323     struct stat tstat;
324     register afs_int32 code;
325
326 #ifdef AFS_NT40_ENV
327     /* NT client CellServDB has different file name than NT server or Unix */
328     if (IsClientConfigDirectory(adir->name)) {
329         if (!afssw_GetClientCellServDBDir(&p)) {
330             strcompose(tbuffer, sizeof(tbuffer), p, "/",
331                        AFSDIR_CELLSERVDB_FILE_NTCLIENT, NULL);
332             free(p);
333         } else {
334             int len;
335             strncpy(tbuffer, adir->name, sizeof(tbuffer));
336             len = (int)strlen(tbuffer);
337             if (tbuffer[len - 1] != '\\' && tbuffer[len - 1] != '/') {
338                 strncat(tbuffer, "\\", sizeof(tbuffer));
339             }
340             strncat(tbuffer, AFSDIR_CELLSERVDB_FILE_NTCLIENT,
341                     sizeof(tbuffer));
342             tbuffer[sizeof(tbuffer) - 1] = '\0';
343         }
344     } else {
345         strcompose(tbuffer, 256, adir->name, "/", AFSDIR_CELLSERVDB_FILE,
346                    NULL);
347     }
348 #else
349     strcompose(tbuffer, 256, adir->name, "/", AFSDIR_CELLSERVDB_FILE, NULL);
350 #endif /* AFS_NT40_ENV */
351
352     code = stat(tbuffer, &tstat);
353     if (code < 0) {
354         return code;
355     }
356     /* did file change? */
357     if (tstat.st_mtime == adir->timeRead) {
358         return 0;
359     }
360     /* otherwise file has changed, so reopen it */
361     return afsconf_Reopen(adir);
362 }
363
364 /* set modtime on file */
365 static int
366 afsconf_Touch(register struct afsconf_dir *adir)
367 {
368     char tbuffer[256];
369 #ifndef AFS_NT40_ENV
370     struct timeval tvp[2];
371 #else
372     char *p;
373 #endif
374
375     adir->timeRead = 0;         /* just in case */
376
377 #ifdef AFS_NT40_ENV
378     /* NT client CellServDB has different file name than NT server or Unix */
379
380     if (IsClientConfigDirectory(adir->name)) {
381         if (!afssw_GetClientCellServDBDir(&p)) {
382             strcompose(tbuffer, sizeof(tbuffer), p, "/",
383                        AFSDIR_CELLSERVDB_FILE_NTCLIENT, NULL);
384             free(p);
385         } else {
386             int len = (int)strlen(tbuffer);
387             if (tbuffer[len - 1] != '\\' && tbuffer[len - 1] != '/') {
388                 strncat(tbuffer, "\\", sizeof(tbuffer));
389             }
390             strncat(tbuffer, AFSDIR_CELLSERVDB_FILE_NTCLIENT,
391                     sizeof(tbuffer));
392             tbuffer[sizeof(tbuffer) - 1] = '\0';
393         }
394     } else {
395         strcompose(tbuffer, 256, adir->name, "/", AFSDIR_CELLSERVDB_FILE,
396                    NULL);
397     }
398
399     return _utime(tbuffer, NULL);
400
401 #else
402     strcompose(tbuffer, 256, adir->name, "/", AFSDIR_CELLSERVDB_FILE, NULL);
403     gettimeofday(&tvp[0], NULL);
404     tvp[1] = tvp[0];
405     return utimes(tbuffer, tvp);
406 #endif /* AFS_NT40_ENV */
407 }
408
409 struct afsconf_dir *
410 afsconf_Open(register const char *adir)
411 {
412     register struct afsconf_dir *tdir;
413     register afs_int32 code;
414
415     LOCK_GLOBAL_MUTEX;
416     /* zero structure and fill in name; rest is done by internal routine */
417     tdir = (struct afsconf_dir *)malloc(sizeof(struct afsconf_dir));
418     memset(tdir, 0, sizeof(struct afsconf_dir));
419     tdir->name = (char *)malloc(strlen(adir) + 1);
420     strcpy(tdir->name, adir);
421
422     code = afsconf_OpenInternal(tdir, 0, 0);
423     if (code) {
424         char *afsconf_path, afs_confdir[128];
425
426         free(tdir->name);
427         /* Check global place only when local Open failed for whatever reason */
428         if (!(afsconf_path = getenv("AFSCONF"))) {
429             /* The "AFSCONF" environment (or contents of "/.AFSCONF") will be typically set to something like "/afs/<cell>/common/etc" where, by convention, the default files for "ThisCell" and "CellServDB" will reside; note that a major drawback is that a given afs client on that cell may NOT contain the same contents... */
430             char *home_dir;
431             afsconf_FILE *fp;
432             size_t len;
433
434             if (!(home_dir = getenv("HOME"))) {
435                 /* Our last chance is the "/.AFSCONF" file */
436                 fp = fopen("/.AFSCONF", "r");
437                 if (fp == 0) {
438                     free(tdir);
439                     UNLOCK_GLOBAL_MUTEX;
440                     return (struct afsconf_dir *)0;
441                 }
442                 fgets(afs_confdir, 128, fp);
443                 fclose(fp);
444             } else {
445                 char pathname[256];
446
447                 sprintf(pathname, "%s/%s", home_dir, ".AFSCONF");
448                 fp = fopen(pathname, "r");
449                 if (fp == 0) {
450                     /* Our last chance is the "/.AFSCONF" file */
451                     fp = fopen("/.AFSCONF", "r");
452                     if (fp == 0) {
453                         free(tdir);
454                         UNLOCK_GLOBAL_MUTEX;
455                         return (struct afsconf_dir *)0;
456                     }
457                 }
458                 fgets(afs_confdir, 128, fp);
459                 fclose(fp);
460             }
461             len = strlen(afs_confdir);
462             if (len == 0) {
463                 free(tdir);
464                 UNLOCK_GLOBAL_MUTEX;
465                 return (struct afsconf_dir *)0;
466             }
467             if (afs_confdir[len - 1] == '\n') {
468                 afs_confdir[len - 1] = 0;
469             }
470             afsconf_path = afs_confdir;
471         }
472         tdir->name = (char *)malloc(strlen(afsconf_path) + 1);
473         strcpy(tdir->name, afsconf_path);
474         code = afsconf_OpenInternal(tdir, 0, 0);
475         if (code) {
476             free(tdir->name);
477             free(tdir);
478             UNLOCK_GLOBAL_MUTEX;
479             return (struct afsconf_dir *)0;
480         }
481     }
482     UNLOCK_GLOBAL_MUTEX;
483     return tdir;
484 }
485
486 static int
487 GetCellUnix(struct afsconf_dir *adir)
488 {
489     char *rc;
490     char tbuffer[256];
491     char *start, *p;
492     afsconf_FILE *fp;
493     
494     strcompose(tbuffer, 256, adir->name, "/", AFSDIR_THISCELL_FILE, NULL);
495     fp = fopen(tbuffer, "r");
496     if (fp == 0) {
497         return -1;
498     }
499     rc = fgets(tbuffer, 256, fp);
500     fclose(fp);
501     if (rc == NULL)
502         return -1;
503
504     start = tbuffer;
505     while (*start != '\0' && isspace(*start))
506         start++;
507     p = start;
508     while (*p != '\0' && !isspace(*p))
509         p++;
510     *p = '\0';
511     if (*start == '\0')
512         return -1;
513
514     adir->cellName = strdup(start);
515     return 0;
516 }
517
518
519 #ifdef AFS_NT40_ENV
520 static int
521 GetCellNT(struct afsconf_dir *adir)
522 {
523     if (IsClientConfigDirectory(adir->name)) {
524         /* NT client config dir; ThisCell is in registry (no file). */
525         return afssw_GetClientCellName(&adir->cellName);
526     } else {
527         /* NT server config dir; works just like Unix */
528         return GetCellUnix(adir);
529     }
530 }
531
532 /* The following procedures and structs are used on Windows only
533  * to enumerate the Cell information distributed within the 
534  * Windows registry.  (See src/WINNT/afsd/cm_config.c)
535  */
536 typedef struct _cm_enumCellRegistry {
537     afs_uint32 client;  /* non-zero if client query */
538     struct afsconf_dir *adir;
539 } cm_enumCellRegistry_t;
540
541 static long
542 cm_serverConfigProc(void *rockp, struct sockaddr_in *addrp, 
543                     char *hostNamep, unsigned short rank)
544 {
545     struct afsconf_cell *cellInfop = (struct afsconf_cell *)rockp;
546
547     if (cellInfop->numServers == MAXHOSTSPERCELL)
548         return 0;
549
550     cellInfop->hostAddr[cellInfop->numServers] = *addrp;
551     strncpy(cellInfop->hostName[cellInfop->numServers], hostNamep, MAXHOSTCHARS);
552     cellInfop->hostName[cellInfop->numServers][MAXHOSTCHARS-1] = '\0';
553     cellInfop->numServers++;
554
555     return 0;
556 }
557
558 static long
559 cm_enumCellRegistryProc(void *rockp, char * cellNamep)
560 {
561     long code;
562     cm_enumCellRegistry_t *enump = (cm_enumCellRegistry_t *)rockp;
563     char linkedName[256] = "";
564     int timeout = 0;
565     struct afsconf_entry *newEntry;
566
567
568     newEntry = malloc(sizeof(struct afsconf_entry));
569     if (newEntry == NULL)
570         return ENOMEM;
571     newEntry->cellInfo.numServers = 0;
572
573     code = cm_SearchCellRegistry(enump->client, cellNamep, NULL, linkedName, cm_serverConfigProc, &newEntry->cellInfo);
574     if (code == CM_ERROR_FORCE_DNS_LOOKUP)
575         code = cm_SearchCellByDNS(cellNamep, NULL, &timeout, cm_serverConfigProc, &newEntry->cellInfo);
576
577     if (code == 0) {
578         strncpy(newEntry->cellInfo.name, cellNamep, MAXCELLCHARS);
579         newEntry->cellInfo.name[MAXCELLCHARS-1];
580         if (linkedName[0])
581             newEntry->cellInfo.linkedCell = strdup(linkedName);
582         else
583             newEntry->cellInfo.linkedCell = NULL;
584         newEntry->cellInfo.timeout = timeout;
585         newEntry->cellInfo.flags = 0;
586
587         newEntry->next = enump->adir->entries;
588         enump->adir->entries = newEntry;
589     } else {
590         free(newEntry);
591     }
592     return code;
593 }       
594 #endif /* AFS_NT40_ENV */
595
596
597 static int
598 afsconf_OpenInternal(register struct afsconf_dir *adir, char *cell,
599                      char clones[])
600 {
601     afsconf_FILE *tf;
602     register char *tp, *bp;
603     register struct afsconf_entry *curEntry;
604     struct afsconf_aliasentry *curAlias;
605     register afs_int32 code;
606     afs_int32 i;
607     char tbuffer[256], tbuf1[256];
608     struct stat tstat;
609 #ifdef AFS_NT40_ENV
610     cm_enumCellRegistry_t enumCellRegistry = {0, 0};
611 #endif /* AFS_NT40_ENV */
612
613     /* figure out the local cell name */
614 #ifdef AFS_NT40_ENV
615     i = GetCellNT(adir);
616     enumCellRegistry.adir = adir;
617 #else
618     i = GetCellUnix(adir);
619 #endif
620
621 #ifndef AFS_FREELANCE_CLIENT    /* no local cell not fatal in freelance */
622     if (i) {
623         return i;
624     }
625 #endif
626
627     /* now parse the individual lines */
628     curEntry = 0;
629
630 #ifdef AFS_NT40_ENV
631     /* NT client/server have a CellServDB that is the same format as Unix.
632      * However, the NT client uses a different file name
633      */
634     if (IsClientConfigDirectory(adir->name)) {
635         /* NT client config dir */
636         char *p;
637
638         enumCellRegistry.client = 1;
639
640         if (!afssw_GetClientCellServDBDir(&p)) {
641             strcompose(tbuffer, sizeof(tbuffer), p, "/",
642                        AFSDIR_CELLSERVDB_FILE_NTCLIENT, NULL);
643             free(p);
644         } else {
645             int len;
646             strncpy(tbuffer, adir->name, sizeof(tbuffer));
647             len = (int)strlen(tbuffer);
648             if (tbuffer[len - 1] != '\\' && tbuffer[len - 1] != '/') {
649                 strncat(tbuffer, "\\", sizeof(tbuffer));
650             }
651             strncat(tbuffer, AFSDIR_CELLSERVDB_FILE_NTCLIENT,
652                     sizeof(tbuffer));
653             tbuffer[sizeof(tbuffer) - 1] = '\0';
654         }
655     } else {
656         /* NT server config dir */
657         strcompose(tbuffer, 256, adir->name, "/", AFSDIR_CELLSERVDB_FILE,
658                    NULL);
659     }
660 #else
661     strcompose(tbuffer, 256, adir->name, "/", AFSDIR_CELLSERVDB_FILE, NULL);
662 #endif /* AFS_NT40_ENV */
663
664     if (!stat(tbuffer, &tstat)) {
665         adir->timeRead = tstat.st_mtime;
666     } else {
667         adir->timeRead = 0;
668     }
669
670     strcpy(tbuf1, tbuffer);
671     tf = fopen(tbuffer, "r");
672     if (!tf) {
673         return -1;
674     }
675
676     /* The CellServDB file is now open.  
677      * The following code parses the contents of the 
678      * file and creates a list with the first cell entry
679      * in the CellServDB file at the end of the list.
680      * 
681      * No checking is performed for duplicates.
682      * The side effects of this process are that duplicate
683      * entries appended to the end of the CellServDB file
684      * take precedence and are found in a shorter period 
685      * of time.
686      */
687
688     while (1) {
689         tp = fgets(tbuffer, sizeof(tbuffer), tf);
690         if (!tp)
691             break;
692         TrimLine(tbuffer);      /* remove white space */
693         if (tbuffer[0] == 0 || tbuffer[0] == '\n')
694             continue;           /* empty line */
695         if (tbuffer[0] == '>') {
696             char linkedcell[MAXCELLCHARS];
697             /* start new cell item */
698             if (curEntry) {
699                 /* thread this guy on the list */
700                 curEntry->next = adir->entries;
701                 adir->entries = curEntry;
702                 curEntry = 0;
703             }
704             curEntry =
705                 (struct afsconf_entry *)malloc(sizeof(struct afsconf_entry));
706             memset(curEntry, 0, sizeof(struct afsconf_entry));
707             code =
708                 ParseCellLine(tbuffer, curEntry->cellInfo.name, linkedcell);
709             if (code) {
710                 afsconf_CloseInternal(adir);
711                 fclose(tf);
712                 free(curEntry);
713                 return -1;
714             }
715             if (linkedcell[0] != '\0') {
716                 curEntry->cellInfo.linkedCell =
717                     (char *)malloc(strlen(linkedcell) + 1);
718                 strcpy(curEntry->cellInfo.linkedCell, linkedcell);
719             }
720         } else {
721             /* new host in the current cell */
722             if (!curEntry) {
723                 afsconf_CloseInternal(adir);
724                 fclose(tf);
725                 return -1;
726             }
727             i = curEntry->cellInfo.numServers;
728             if (cell && !strcmp(cell, curEntry->cellInfo.name))
729                 code =
730                     ParseHostLine(tbuffer, &curEntry->cellInfo.hostAddr[i],
731                                   curEntry->cellInfo.hostName[i], &clones[i]);
732             else
733                 code =
734                     ParseHostLine(tbuffer, &curEntry->cellInfo.hostAddr[i],
735                                   curEntry->cellInfo.hostName[i], 0);
736             if (code) {
737                 if (code == AFSCONF_SYNTAX) {
738                     for (bp = tbuffer; *bp != '\n'; bp++) {     /* Take out the <cr> from the buffer */
739                         if (!*bp)
740                             break;
741                     }
742                     *bp = '\0';
743                     fprintf(stderr,
744                             "Can't properly parse host line \"%s\" in configuration file %s\n",
745                             tbuffer, tbuf1);
746                 }
747                 free(curEntry);
748                 fclose(tf);
749                 afsconf_CloseInternal(adir);
750                 return -1;
751             }
752             curEntry->cellInfo.numServers = ++i;
753         }
754     }
755     fclose(tf);                 /* close the file now */
756
757     /* end the last partially-completed cell */
758     if (curEntry) {
759         curEntry->next = adir->entries;
760         adir->entries = curEntry;
761     }
762
763 #ifdef AFS_NT40_ENV
764      /* 
765       * Windows maintains a CellServDB list in the Registry
766       * that supercedes the contents of the CellServDB file.
767       * Prepending these entries to the head of the list 
768       * is sufficient to enforce the precedence.
769       */
770      cm_EnumerateCellRegistry( enumCellRegistry.client,
771                                cm_enumCellRegistryProc,
772                                &enumCellRegistry);
773 #endif /* AFS_NT40_ENV */
774
775     /* Read in the alias list */
776     strcompose(tbuffer, 256, adir->name, "/", AFSDIR_CELLALIAS_FILE, NULL);
777
778     tf = fopen(tbuffer, "r");
779     while (tf) {
780         char *aliasPtr;
781
782         tp = fgets(tbuffer, sizeof(tbuffer), tf);
783         if (!tp)
784             break;
785         TrimLine(tbuffer);      /* remove white space */
786
787         if (tbuffer[0] == '\0' || tbuffer[0] == '\n' || tbuffer[0] == '#')
788             continue;           /* empty line */
789
790         tp = tbuffer;
791         while (tp[0] != '\0' && tp[0] != ' ' && tp[0] != '\t')
792             tp++;
793         if (tp[0] == '\0')
794             continue;           /* invalid line */
795
796         while (tp[0] != '\0' && (tp[0] == ' ' || tp[0] == '\t'))
797             0[tp++] = '\0';
798         if (tp[0] == '\0')
799             continue;           /* invalid line */
800
801         aliasPtr = tp;
802         while (tp[0] != '\0' && tp[0] != ' ' && tp[0] != '\t' && tp[0] != '\r'
803                && tp[0] != '\n')
804             tp++;
805         tp[0] = '\0';
806
807         curAlias = malloc(sizeof(*curAlias));
808         memset(curAlias, 0, sizeof(*curAlias));
809
810         strcpy(curAlias->aliasInfo.aliasName, aliasPtr);
811         strcpy(curAlias->aliasInfo.realName, tbuffer);
812
813         curAlias->next = adir->alias_entries;
814         adir->alias_entries = curAlias;
815     }
816
817     if (tf != NULL)
818         fclose(tf);
819     /* now read the fs keys, if possible */
820     adir->keystr = (struct afsconf_keys *)0;
821     afsconf_IntGetKeys(adir);
822
823     return 0;
824 }
825
826 /* parse a line of the form
827  *"128.2.1.3   #hostname" or
828  *"[128.2.1.3]  #hostname" for clones
829  * into the appropriate pieces.  
830  */
831 static int
832 ParseHostLine(char *aline, register struct sockaddr_in *addr, char *aname,
833               char *aclone)
834 {
835     int c1, c2, c3, c4;
836     register afs_int32 code;
837     register char *tp;
838
839     if (*aline == '[') {
840         if (aclone)
841             *aclone = 1;
842         /* FIXME: length of aname unknown here */
843         code = sscanf(aline, "[%d.%d.%d.%d] #%s", &c1, &c2, &c3, &c4, aname);
844     } else {
845         if (aclone)
846             *aclone = 0;
847         /* FIXME: length of aname unknown here */
848         code = sscanf(aline, "%d.%d.%d.%d #%s", &c1, &c2, &c3, &c4, aname);
849     }
850     if (code != 5)
851         return AFSCONF_SYNTAX;
852     addr->sin_family = AF_INET;
853     addr->sin_port = 0;
854 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
855     addr->sin_len = sizeof(struct sockaddr_in);
856 #endif
857     tp = (char *)&addr->sin_addr;
858     *tp++ = c1;
859     *tp++ = c2;
860     *tp++ = c3;
861     *tp++ = c4;
862     return 0;
863 }
864
865 /* parse a line of the form
866  * ">cellname [linkedcellname] [#comments]"
867  * into the appropriate pieces.
868  */
869 static int
870 ParseCellLine(register char *aline, register char *aname,
871               register char *alname)
872 {
873     register int code;
874     /* FIXME: length of aname, alname unknown here */
875     code = sscanf(aline, ">%s %s", aname, alname);
876     if (code == 1)
877         *alname = '\0';
878     if (code == 2) {
879         if (*alname == '#') {
880             *alname = '\0';
881         }
882     }
883     return (code > 0 ? 0 : AFSCONF_SYNTAX);
884 }
885
886 /* call aproc(entry, arock, adir) for all cells.  Proc must return 0, or we'll stop early and return the code it returns */
887 int
888 afsconf_CellApply(struct afsconf_dir *adir,
889                   int (*aproc) (struct afsconf_cell * cell, void *arock,
890                                 struct afsconf_dir * dir), void *arock)
891 {
892     register struct afsconf_entry *tde;
893     register afs_int32 code;
894     LOCK_GLOBAL_MUTEX;
895     for (tde = adir->entries; tde; tde = tde->next) {
896         code = (*aproc) (&tde->cellInfo, arock, adir);
897         if (code) {
898             UNLOCK_GLOBAL_MUTEX;
899             return code;
900         }
901     }
902     UNLOCK_GLOBAL_MUTEX;
903     return 0;
904 }
905
906 /* call aproc(entry, arock, adir) for all cell aliases.
907  * Proc must return 0, or we'll stop early and return the code it returns
908  */
909 int
910 afsconf_CellAliasApply(struct afsconf_dir *adir,
911                        int (*aproc) (struct afsconf_cellalias * alias,
912                                      void *arock, struct afsconf_dir * dir),
913                        void *arock)
914 {
915     register struct afsconf_aliasentry *tde;
916     register afs_int32 code;
917     LOCK_GLOBAL_MUTEX;
918     for (tde = adir->alias_entries; tde; tde = tde->next) {
919         code = (*aproc) (&tde->aliasInfo, arock, adir);
920         if (code) {
921             UNLOCK_GLOBAL_MUTEX;
922             return code;
923         }
924     }
925     UNLOCK_GLOBAL_MUTEX;
926     return 0;
927 }
928
929 afs_int32 afsconf_SawCell = 0;
930
931 int
932 afsconf_GetExtendedCellInfo(struct afsconf_dir *adir, char *acellName,
933                             char *aservice, struct afsconf_cell *acellInfo,
934                             char clones[])
935 {
936     afs_int32 code;
937     char *cell;
938
939     code = afsconf_GetCellInfo(adir, acellName, aservice, acellInfo);
940     if (code)
941         return code;
942
943     if (acellName)
944         cell = acellName;
945     else
946         cell = (char *)&acellInfo->name;
947
948     code = afsconf_OpenInternal(adir, cell, clones);
949     return code;
950 }
951
952 #ifdef AFS_AFSDB_ENV
953 #if !defined(AFS_NT40_ENV)
954 int
955 afsconf_GetAfsdbInfo(char *acellName, char *aservice,
956                      struct afsconf_cell *acellInfo)
957 {
958     afs_int32 code;
959     int tservice, i, len;
960     unsigned char answer[1024];
961     unsigned char *p;
962     char *dotcellname;
963     int cellnamelength;
964     char realCellName[256];
965     char host[256];
966     int server_num = 0;
967     int minttl = 0;
968     int try_init = 0;
969
970     /* The resolver isn't always MT-safe.. Perhaps this ought to be
971      * replaced with a more fine-grained lock just for the resolver
972      * operations.
973      */
974
975  retryafsdb:
976     if ( ! strchr(acellName,'.') ) {
977        cellnamelength=strlen(acellName);
978        dotcellname=malloc(cellnamelength+2);
979        memcpy(dotcellname,acellName,cellnamelength);
980        dotcellname[cellnamelength]='.';
981        dotcellname[cellnamelength+1]=0;
982        LOCK_GLOBAL_MUTEX;
983        len = res_search(dotcellname, C_IN, T_AFSDB, answer, sizeof(answer));
984        if ( len < 0 ) {
985           len = res_search(acellName, C_IN, T_AFSDB, answer, sizeof(answer));
986        }
987        UNLOCK_GLOBAL_MUTEX;
988        free(dotcellname);
989     } else {
990        LOCK_GLOBAL_MUTEX;
991        len = res_search(acellName, C_IN, T_AFSDB, answer, sizeof(answer));
992        UNLOCK_GLOBAL_MUTEX;
993     }
994     if (len < 0) {
995         if (try_init < 1) {
996             try_init++;
997             res_init();
998             goto retryafsdb;
999         }
1000         return AFSCONF_NOTFOUND;
1001     }
1002
1003     p = answer + sizeof(HEADER);        /* Skip header */
1004     code = dn_expand(answer, answer + len, p, host, sizeof(host));
1005     if (code < 0)
1006         return AFSCONF_NOTFOUND;
1007
1008     p += code + QFIXEDSZ;       /* Skip name */
1009
1010     while (p < answer + len) {
1011         int type, ttl, size;
1012
1013         code = dn_expand(answer, answer + len, p, host, sizeof(host));
1014         if (code < 0)
1015             return AFSCONF_NOTFOUND;
1016
1017         p += code;              /* Skip the name */
1018         type = (p[0] << 8) | p[1];
1019         p += 4;                 /* Skip type and class */
1020         ttl = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
1021         p += 4;                 /* Skip the TTL */
1022         size = (p[0] << 8) | p[1];
1023         p += 2;                 /* Skip the size */
1024
1025         if (type == T_AFSDB) {
1026             struct hostent *he;
1027             short afsdb_type;
1028
1029             afsdb_type = (p[0] << 8) | p[1];
1030             if (afsdb_type == 1) {
1031                 /*
1032                  * We know this is an AFSDB record for our cell, of the
1033                  * right AFSDB type.  Write down the true cell name that
1034                  * the resolver gave us above.
1035                  */
1036                 strcpy(realCellName, host);
1037             }
1038
1039             code = dn_expand(answer, answer + len, p + 2, host, sizeof(host));
1040             if (code < 0)
1041                 return AFSCONF_NOTFOUND;
1042
1043             if ((afsdb_type == 1) && (server_num < MAXHOSTSPERCELL) &&
1044                 /* Do we want to get TTL data for the A record as well? */
1045                 (he = gethostbyname(host))) {
1046                 afs_int32 ipaddr;
1047                 memcpy(&ipaddr, he->h_addr, he->h_length);
1048                 acellInfo->hostAddr[server_num].sin_addr.s_addr = ipaddr;
1049                 strncpy(acellInfo->hostName[server_num], host,
1050                         sizeof(acellInfo->hostName[server_num]));
1051                 server_num++;
1052
1053                 if (!minttl || ttl < minttl)
1054                     minttl = ttl;
1055             }
1056         }
1057
1058         p += size;
1059     }
1060
1061     if (server_num == 0)        /* No AFSDB records */
1062         return AFSCONF_NOTFOUND;
1063
1064     /* Convert the real cell name to lowercase */
1065     for (p = (unsigned char *)realCellName; *p; p++)
1066         *p = tolower(*p);
1067
1068     strncpy(acellInfo->name, realCellName, sizeof(acellInfo->name));
1069     acellInfo->numServers = server_num;
1070
1071     if (aservice) {
1072         tservice = afsconf_FindService(aservice);
1073         if (tservice < 0)
1074             return AFSCONF_NOTFOUND;    /* service not found */
1075         for (i = 0; i < acellInfo->numServers; i++) {
1076             acellInfo->hostAddr[i].sin_port = tservice;
1077         }
1078     }
1079
1080     acellInfo->timeout = minttl ? (time(0) + minttl) : 0;
1081
1082     return 0;
1083 }
1084 #else /* windows */
1085 int
1086 afsconf_GetAfsdbInfo(char *acellName, char *aservice,
1087                      struct afsconf_cell *acellInfo)
1088 {
1089     register afs_int32 i;
1090     int tservice;
1091     struct afsconf_entry DNSce;
1092     afs_int32 cellHostAddrs[AFSMAXCELLHOSTS];
1093     char cellHostNames[AFSMAXCELLHOSTS][MAXHOSTCHARS];
1094     unsigned short ipRanks[AFSMAXCELLHOSTS];
1095     int numServers;
1096     int rc;
1097     int ttl;
1098
1099     DNSce.cellInfo.numServers = 0;
1100     DNSce.next = NULL;
1101     rc = getAFSServer(acellName, cellHostAddrs, cellHostNames, ipRanks, &numServers,
1102                       &ttl);
1103     /* ignore the ttl here since this code is only called by transitory programs
1104      * like klog, etc. */
1105     if (rc < 0)
1106         return -1;
1107     if (numServers == 0)
1108         return -1;
1109
1110     for (i = 0; i < numServers; i++) {
1111         memcpy(&acellInfo->hostAddr[i].sin_addr.s_addr, &cellHostAddrs[i],
1112                sizeof(long));
1113         memcpy(acellInfo->hostName[i], cellHostNames[i], MAXHOSTCHARS);
1114         acellInfo->hostAddr[i].sin_family = AF_INET;
1115
1116         /* sin_port supplied by connection code */
1117     }
1118
1119     acellInfo->numServers = numServers;
1120     strcpy(acellInfo->name, acellName);
1121     if (aservice) {
1122         LOCK_GLOBAL_MUTEX;
1123         tservice = afsconf_FindService(aservice);
1124         UNLOCK_GLOBAL_MUTEX;
1125         if (tservice < 0) {
1126             return AFSCONF_NOTFOUND;    /* service not found */
1127         }
1128         for (i = 0; i < acellInfo->numServers; i++) {
1129             acellInfo->hostAddr[i].sin_port = tservice;
1130         }
1131     }
1132     acellInfo->linkedCell = NULL;       /* no linked cell */
1133     acellInfo->flags = 0;
1134     return 0;
1135 }
1136 #endif /* windows */
1137 #endif /* AFS_AFSDB_ENV */
1138
1139 int
1140 afsconf_GetCellInfo(struct afsconf_dir *adir, char *acellName, char *aservice,
1141                     struct afsconf_cell *acellInfo)
1142 {
1143     register struct afsconf_entry *tce;
1144     struct afsconf_aliasentry *tcae;
1145     struct afsconf_entry *bestce;
1146     register afs_int32 i;
1147     int tservice;
1148     char *tcell;
1149     int cnLen;
1150     int ambig;
1151     char tbuffer[64];
1152
1153     LOCK_GLOBAL_MUTEX;
1154     if (adir)
1155         afsconf_Check(adir);
1156     if (acellName) {
1157         tcell = acellName;
1158         cnLen = (int)(strlen(tcell) + 1);
1159         lcstring(tcell, tcell, cnLen);
1160         afsconf_SawCell = 1;    /* will ignore the AFSCELL switch on future */
1161         /* call to afsconf_GetLocalCell: like klog  */
1162     } else {
1163         i = afsconf_GetLocalCell(adir, tbuffer, sizeof(tbuffer));
1164         if (i) {
1165             UNLOCK_GLOBAL_MUTEX;
1166             return i;
1167         }
1168         tcell = tbuffer;
1169     }
1170     cnLen = strlen(tcell);
1171     bestce = (struct afsconf_entry *)0;
1172     ambig = 0;
1173     if (!adir) {
1174         UNLOCK_GLOBAL_MUTEX;
1175         return 0;
1176     }
1177
1178     /* Look through the list of aliases */
1179     for (tcae = adir->alias_entries; tcae; tcae = tcae->next) {
1180         if (strcasecmp(tcae->aliasInfo.aliasName, tcell) == 0) {
1181             tcell = tcae->aliasInfo.realName;
1182             break;
1183         }
1184     }
1185
1186     for (tce = adir->entries; tce; tce = tce->next) {
1187         if (strcasecmp(tce->cellInfo.name, tcell) == 0) {
1188             /* found our cell */
1189             bestce = tce;
1190             ambig = 0;
1191             break;
1192         }
1193         if (strlen(tce->cellInfo.name) < cnLen)
1194             continue;           /* clearly wrong */
1195         if (strncasecmp(tce->cellInfo.name, tcell, cnLen) == 0) {
1196             if (bestce)
1197                 ambig = 1;      /* ambiguous unless we get exact match */
1198             bestce = tce;
1199         }
1200     }
1201     if (!ambig && bestce && bestce->cellInfo.numServers) {
1202         *acellInfo = bestce->cellInfo;  /* structure assignment */
1203         if (aservice) {
1204             tservice = afsconf_FindService(aservice);
1205             if (tservice < 0) {
1206                 UNLOCK_GLOBAL_MUTEX;
1207                 return AFSCONF_NOTFOUND;        /* service not found */
1208             }
1209             for (i = 0; i < acellInfo->numServers; i++) {
1210                 acellInfo->hostAddr[i].sin_port = tservice;
1211             }
1212         }
1213         acellInfo->timeout = 0;
1214         UNLOCK_GLOBAL_MUTEX;
1215         return 0;
1216     } else {
1217         UNLOCK_GLOBAL_MUTEX;
1218 #ifdef AFS_AFSDB_ENV
1219         return afsconf_GetAfsdbInfo(tcell, aservice, acellInfo);
1220 #else
1221         return AFSCONF_NOTFOUND;
1222 #endif /* AFS_AFSDB_ENV */
1223     }
1224 }
1225
1226 int
1227 afsconf_GetLocalCell(register struct afsconf_dir *adir, char *aname,
1228                      afs_int32 alen)
1229 {
1230     static int afsconf_showcell = 0;
1231     char *afscell_path;
1232     afs_int32 code = 0;
1233
1234     LOCK_GLOBAL_MUTEX;
1235     /*
1236      * If a cell switch was specified in a command, then it should override the 
1237      * AFSCELL variable.  If a cell was specified, then the afsconf_SawCell flag
1238      * is set and the cell name in the adir structure is used.
1239      * Read the AFSCELL var each time: in case it changes (unsetenv AFSCELL).
1240      */
1241     if (!afsconf_SawCell && (afscell_path = getenv("AFSCELL"))) {
1242         if (!afsconf_showcell) {
1243             fprintf(stderr, "Note: Operation is performed on cell %s\n",
1244                     afscell_path);
1245             afsconf_showcell = 1;
1246         }
1247         strncpy(aname, afscell_path, alen);
1248     } else {
1249         afsconf_Check(adir);
1250         if (adir->cellName) {
1251             strncpy(aname, adir->cellName, alen);
1252         } else
1253             code = AFSCONF_UNKNOWN;
1254     }
1255
1256     UNLOCK_GLOBAL_MUTEX;
1257     return (code);
1258 }
1259
1260 int
1261 afsconf_Close(struct afsconf_dir *adir)
1262 {
1263     LOCK_GLOBAL_MUTEX;
1264     afsconf_CloseInternal(adir);
1265     if (adir->name)
1266         free(adir->name);
1267     free(adir);
1268     UNLOCK_GLOBAL_MUTEX;
1269     return 0;
1270 }
1271
1272 static int
1273 afsconf_CloseInternal(register struct afsconf_dir *adir)
1274 {
1275     register struct afsconf_entry *td, *nd;
1276     struct afsconf_aliasentry *ta, *na;
1277     register char *tname;
1278
1279     tname = adir->name;         /* remember name, since that's all we preserve */
1280
1281     /* free everything we can find */
1282     if (adir->cellName)
1283         free(adir->cellName);
1284     for (td = adir->entries; td; td = nd) {
1285         nd = td->next;
1286         if (td->cellInfo.linkedCell)
1287             free(td->cellInfo.linkedCell);
1288         free(td);
1289     }
1290     for (ta = adir->alias_entries; ta; ta = na) {
1291         na = ta->next;
1292         free(ta);
1293     }
1294     if (adir->keystr)
1295         free(adir->keystr);
1296
1297     /* reinit */
1298     memset(adir, 0, sizeof(struct afsconf_dir));
1299     adir->name = tname;         /* restore it */
1300     return 0;
1301 }
1302
1303 static int
1304 afsconf_Reopen(register struct afsconf_dir *adir)
1305 {
1306     register afs_int32 code;
1307     code = afsconf_CloseInternal(adir);
1308     if (code)
1309         return code;
1310     code = afsconf_OpenInternal(adir, 0, 0);
1311     return code;
1312 }
1313
1314 /* called during opening of config file */
1315 int
1316 afsconf_IntGetKeys(struct afsconf_dir *adir)
1317 {
1318     char tbuffer[256];
1319     register int fd;
1320     struct afsconf_keys *tstr;
1321     register afs_int32 code;
1322
1323 #ifdef AFS_NT40_ENV
1324     /* NT client config dir has no KeyFile; don't risk attempting open
1325      * because there might be a random file of this name if dir is shared.
1326      */
1327     if (IsClientConfigDirectory(adir->name)) {
1328         adir->keystr = ((struct afsconf_keys *)
1329                         malloc(sizeof(struct afsconf_keys)));
1330         adir->keystr->nkeys = 0;
1331         return 0;
1332     }
1333 #endif /* AFS_NT40_ENV */
1334
1335     LOCK_GLOBAL_MUTEX;
1336     /* compute the key name and other setup */
1337     strcompose(tbuffer, 256, adir->name, "/", AFSDIR_KEY_FILE, NULL);
1338     tstr = (struct afsconf_keys *)malloc(sizeof(struct afsconf_keys));
1339     adir->keystr = tstr;
1340
1341     /* read key file */
1342     fd = open(tbuffer, O_RDONLY);
1343     if (fd < 0) {
1344         tstr->nkeys = 0;
1345         UNLOCK_GLOBAL_MUTEX;
1346         return 0;
1347     }
1348     code = read(fd, tstr, sizeof(struct afsconf_keys));
1349     close(fd);
1350     if (code < sizeof(afs_int32)) {
1351         tstr->nkeys = 0;
1352         UNLOCK_GLOBAL_MUTEX;
1353         return 0;
1354     }
1355
1356     /* convert key structure to host order */
1357     tstr->nkeys = ntohl(tstr->nkeys);
1358
1359     if (code < sizeof(afs_int32) + (tstr->nkeys*sizeof(struct afsconf_key))) {
1360         tstr->nkeys = 0;
1361         UNLOCK_GLOBAL_MUTEX;
1362         return 0;
1363     }
1364
1365     for (fd = 0; fd < tstr->nkeys; fd++)
1366         tstr->key[fd].kvno = ntohl(tstr->key[fd].kvno);
1367
1368     UNLOCK_GLOBAL_MUTEX;
1369     return 0;
1370 }
1371
1372 /* get keys structure */
1373 int
1374 afsconf_GetKeys(struct afsconf_dir *adir, struct afsconf_keys *astr)
1375 {
1376     register afs_int32 code;
1377
1378     LOCK_GLOBAL_MUTEX;
1379     code = afsconf_Check(adir);
1380     if (code) {
1381         UNLOCK_GLOBAL_MUTEX;
1382         return AFSCONF_FAILURE;
1383     }
1384     memcpy(astr, adir->keystr, sizeof(struct afsconf_keys));
1385     UNLOCK_GLOBAL_MUTEX;
1386     return 0;
1387 }
1388
1389 /* get latest key */
1390 afs_int32
1391 afsconf_GetLatestKey(struct afsconf_dir * adir, afs_int32 * avno, 
1392                      struct ktc_encryptionKey *akey)
1393 {
1394     register int i;
1395     int maxa;
1396     register struct afsconf_key *tk;
1397     register afs_int32 best;
1398     struct afsconf_key *bestk;
1399     register afs_int32 code;
1400
1401     LOCK_GLOBAL_MUTEX;
1402     code = afsconf_Check(adir);
1403     if (code) {
1404         UNLOCK_GLOBAL_MUTEX;
1405         return AFSCONF_FAILURE;
1406     }
1407     maxa = adir->keystr->nkeys;
1408
1409     best = -1;                  /* highest kvno we've seen yet */
1410     bestk = (struct afsconf_key *)0;    /* ptr to structure providing best */
1411     for (tk = adir->keystr->key, i = 0; i < maxa; i++, tk++) {
1412         if (tk->kvno == 999)
1413             continue;           /* skip bcrypt keys */
1414         if (tk->kvno > best) {
1415             best = tk->kvno;
1416             bestk = tk;
1417         }
1418     }
1419     if (bestk) {                /* found any  */
1420         if (akey)
1421             memcpy(akey, bestk->key, 8);        /* copy out latest key */
1422         if (avno)
1423             *avno = bestk->kvno;        /* and kvno to caller */
1424         UNLOCK_GLOBAL_MUTEX;
1425         return 0;
1426     }
1427     UNLOCK_GLOBAL_MUTEX;
1428     return AFSCONF_NOTFOUND;    /* didn't find any keys */
1429 }
1430
1431 /* get a particular key */
1432 int
1433 afsconf_GetKey(void *rock, int avno, struct ktc_encryptionKey *akey)
1434 {
1435     struct afsconf_dir *adir = (struct afsconf_dir *) rock;
1436     register int i, maxa;
1437     register struct afsconf_key *tk;
1438     register afs_int32 code;
1439
1440     LOCK_GLOBAL_MUTEX;
1441     code = afsconf_Check(adir);
1442     if (code) {
1443         UNLOCK_GLOBAL_MUTEX;
1444         return AFSCONF_FAILURE;
1445     }
1446     maxa = adir->keystr->nkeys;
1447
1448     for (tk = adir->keystr->key, i = 0; i < maxa; i++, tk++) {
1449         if (tk->kvno == avno) {
1450             memcpy(akey, tk->key, 8);
1451             UNLOCK_GLOBAL_MUTEX;
1452             return 0;
1453         }
1454     }
1455
1456     UNLOCK_GLOBAL_MUTEX;
1457     return AFSCONF_NOTFOUND;
1458 }
1459
1460 /* save the key structure in the appropriate file */
1461 static int
1462 SaveKeys(struct afsconf_dir *adir)
1463 {
1464     struct afsconf_keys tkeys;
1465     register int fd;
1466     register afs_int32 i;
1467     char tbuffer[256];
1468
1469     memcpy(&tkeys, adir->keystr, sizeof(struct afsconf_keys));
1470
1471     /* convert it to net byte order */
1472     for (i = 0; i < tkeys.nkeys; i++)
1473         tkeys.key[i].kvno = htonl(tkeys.key[i].kvno);
1474     tkeys.nkeys = htonl(tkeys.nkeys);
1475
1476     /* rewrite keys file */
1477     strcompose(tbuffer, 256, adir->name, "/", AFSDIR_KEY_FILE, NULL);
1478     fd = open(tbuffer, O_RDWR | O_CREAT | O_TRUNC, 0600);
1479     if (fd < 0)
1480         return AFSCONF_FAILURE;
1481     i = write(fd, &tkeys, sizeof(tkeys));
1482     if (i != sizeof(tkeys)) {
1483         close(fd);
1484         return AFSCONF_FAILURE;
1485     }
1486     if (close(fd) < 0)
1487         return AFSCONF_FAILURE;
1488     return 0;
1489 }
1490
1491 int
1492 afsconf_AddKey(struct afsconf_dir *adir, afs_int32 akvno, char akey[8],
1493                afs_int32 overwrite)
1494 {
1495     register struct afsconf_keys *tk;
1496     register struct afsconf_key *tkey;
1497     register afs_int32 i;
1498     int foundSlot;
1499
1500     LOCK_GLOBAL_MUTEX;
1501     tk = adir->keystr;
1502
1503     if (akvno != 999) {
1504         if (akvno < 0 || akvno > 255) {
1505             UNLOCK_GLOBAL_MUTEX;
1506             return ERANGE;
1507         }
1508     }
1509     foundSlot = 0;
1510     for (i = 0, tkey = tk->key; i < tk->nkeys; i++, tkey++) {
1511         if (tkey->kvno == akvno) {
1512             if (!overwrite) {
1513                 UNLOCK_GLOBAL_MUTEX;
1514                 return AFSCONF_KEYINUSE;
1515             }
1516             foundSlot = 1;
1517             break;
1518         }
1519     }
1520     if (!foundSlot) {
1521         if (tk->nkeys >= AFSCONF_MAXKEYS) {
1522             UNLOCK_GLOBAL_MUTEX;
1523             return AFSCONF_FULL;
1524         }
1525         tkey = &tk->key[tk->nkeys++];
1526     }
1527     tkey->kvno = akvno;
1528     memcpy(tkey->key, akey, 8);
1529     i = SaveKeys(adir);
1530     afsconf_Touch(adir);
1531     UNLOCK_GLOBAL_MUTEX;
1532     return i;
1533 }
1534
1535 /* this proc works by sliding the other guys down, rather than using a funny
1536     kvno value, so that callers can count on getting a good key in key[0].
1537 */
1538 int
1539 afsconf_DeleteKey(struct afsconf_dir *adir, afs_int32 akvno)
1540 {
1541     register struct afsconf_keys *tk;
1542     register struct afsconf_key *tkey;
1543     register int i;
1544     int foundFlag = 0;
1545
1546     LOCK_GLOBAL_MUTEX;
1547     tk = adir->keystr;
1548
1549     for (i = 0, tkey = tk->key; i < tk->nkeys; i++, tkey++) {
1550         if (tkey->kvno == akvno) {
1551             foundFlag = 1;
1552             break;
1553         }
1554     }
1555     if (!foundFlag) {
1556         UNLOCK_GLOBAL_MUTEX;
1557         return AFSCONF_NOTFOUND;
1558     }
1559
1560     /* otherwise slide the others down.  i and tkey point at the guy to delete */
1561     for (; i < tk->nkeys - 1; i++, tkey++) {
1562         tkey->kvno = (tkey + 1)->kvno;
1563         memcpy(tkey->key, (tkey + 1)->key, 8);
1564     }
1565     tk->nkeys--;
1566     i = SaveKeys(adir);
1567     afsconf_Touch(adir);
1568     UNLOCK_GLOBAL_MUTEX;
1569     return i;
1570 }