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