2b99c0bc6aa0985f15bbfa0479b7e9f6f678f63f
[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             if (asprintf(path, "%s/%s", p, AFSDIR_CELLSERVDB_FILE_NTCLIENT) < 0)
331                 *path = NULL;
332             free(p);
333         } else {
334             if (asprintf(path, "%s/%s", adir->name,
335                          AFSDIR_CELLSERVDB_FILE_NTCLIENT) < 0)
336                 *path = NULL;
337         }
338     } else {
339         if (asprintf(path, "%s/%s", adir->name, AFSDIR_CELLSERVDB_FILE) < 0)
340             *path = NULL;
341     }
342     return;
343 }
344 #else
345 static void
346 _afsconf_CellServDBPath(struct afsconf_dir *adir, char **path)
347 {
348     if (asprintf(path, "%s/%s", adir->name, AFSDIR_CELLSERVDB_FILE) < 0)
349         *path = NULL;
350 }
351 #endif /* AFS_NT40_ENV */
352
353 int
354 _afsconf_UpToDate(struct afsconf_dir *adir)
355 {
356     char *cellservDB;
357     struct stat tstat;
358     int code;
359     time_t now = time(0);
360
361     if (adir->timeRead && (adir->timeCheck == now)) {
362         return 1; /* stat no more than once a second */
363     }
364     adir->timeCheck = now;
365
366     _afsconf_CellServDBPath(adir, &cellservDB);
367     if (cellservDB == NULL)
368         return 0;
369
370     code = stat(cellservDB, &tstat);
371     free(cellservDB);
372     if (code < 0)
373         return 0; /* Can't throw the error, so just say we're not up to date */
374
375     /* did file change? */
376     if (tstat.st_mtime == adir->timeRead)
377         return 1;
378
379     /* otherwise file has changed */
380     return 0;
381 }
382
383 int
384 afsconf_UpToDate(void *rock)
385 {
386     int code;
387
388     LOCK_GLOBAL_MUTEX;
389     code = _afsconf_UpToDate(rock);
390     UNLOCK_GLOBAL_MUTEX;
391
392     return code;
393 }
394
395 int
396 _afsconf_Check(struct afsconf_dir *adir)
397 {
398     /* did configuration change? */
399     if (_afsconf_UpToDate(adir))
400         return 0;
401
402     /* otherwise file has changed, so reopen it */
403     return afsconf_Reopen(adir);
404 }
405
406 /* set modtime on file */
407 int
408 _afsconf_Touch(struct afsconf_dir *adir)
409 {
410     char *cellservDB;
411     int code;
412 #ifndef AFS_NT40_ENV
413     struct timeval tvp[2];
414 #endif
415
416     adir->timeRead = 0;         /* just in case */
417     adir->timeCheck = 0;
418
419     _afsconf_CellServDBPath(adir, &cellservDB);
420     if (cellservDB == NULL)
421         return ENOMEM;
422
423 #ifdef AFS_NT40_ENV
424     code = _utime(cellservDB, NULL);
425 #else
426     gettimeofday(&tvp[0], NULL);
427     tvp[1] = tvp[0];
428     code = utimes(cellservDB, tvp);
429 #endif /* AFS_NT40_ENV */
430     free(cellservDB);
431
432     return code;
433 }
434
435 struct afsconf_dir *
436 afsconf_Open(const char *adir)
437 {
438     struct afsconf_dir *tdir;
439     afs_int32 code;
440
441     LOCK_GLOBAL_MUTEX;
442     /* zero structure and fill in name; rest is done by internal routine */
443     tdir = calloc(1, sizeof(struct afsconf_dir));
444     tdir->name = strdup(adir);
445
446     code = afsconf_OpenInternal(tdir, 0, 0);
447     if (code) {
448         char *afsconf_path, afs_confdir[128];
449
450         free(tdir->name);
451         /* Check global place only when local Open failed for whatever reason */
452         if (!(afsconf_path = getenv("AFSCONF"))) {
453             /* 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... */
454             char *home_dir;
455             afsconf_FILE *fp;
456             size_t len = 0;
457             int r;
458
459             if (!(home_dir = getenv("HOME"))) {
460                 /* Our last chance is the "/.AFSCONF" file */
461                 fp = fopen("/.AFSCONF", "r");
462                 if (fp == 0)
463                     goto fail;
464
465             } else {
466                 char *pathname = NULL;
467
468                 r = asprintf(&pathname, "%s/%s", home_dir, ".AFSCONF");
469                 if (r < 0 || pathname == NULL)
470                     goto fail;
471
472                 fp = fopen(pathname, "r");
473                 free(pathname);
474
475                 if (fp == 0) {
476                     /* Our last chance is the "/.AFSCONF" file */
477                     fp = fopen("/.AFSCONF", "r");
478                     if (fp == 0)
479                         goto fail;
480                 }
481             }
482             if (fgets(afs_confdir, 128, fp) != NULL)
483                 len = strlen(afs_confdir);
484             fclose(fp);
485             if (len == 0)
486                 goto fail;
487
488             if (afs_confdir[len - 1] == '\n') {
489                 afs_confdir[len - 1] = 0;
490             }
491             afsconf_path = afs_confdir;
492         }
493         tdir->name = strdup(afsconf_path);
494         code = afsconf_OpenInternal(tdir, 0, 0);
495         if (code) {
496             free(tdir->name);
497             goto fail;
498         }
499     }
500     UNLOCK_GLOBAL_MUTEX;
501     return tdir;
502
503 fail:
504     free(tdir);
505     UNLOCK_GLOBAL_MUTEX;
506     return NULL;
507 }
508
509 static int
510 GetCellUnix(struct afsconf_dir *adir)
511 {
512     char *rc;
513     char tbuffer[256];
514     char *start, *p;
515     afsconf_FILE *fp;
516
517     strcompose(tbuffer, 256, adir->name, "/", AFSDIR_THISCELL_FILE,
518         (char *)NULL);
519     fp = fopen(tbuffer, "r");
520     if (fp == 0) {
521         return -1;
522     }
523     rc = fgets(tbuffer, 256, fp);
524     fclose(fp);
525     if (rc == NULL)
526         return -1;
527
528     start = tbuffer;
529     while (*start != '\0' && isspace(*start))
530         start++;
531     p = start;
532     while (*p != '\0' && !isspace(*p))
533         p++;
534     *p = '\0';
535     if (*start == '\0')
536         return -1;
537
538     adir->cellName = strdup(start);
539     return 0;
540 }
541
542
543 #ifdef AFS_NT40_ENV
544 static int
545 GetCellNT(struct afsconf_dir *adir)
546 {
547     if (_afsconf_IsClientConfigDirectory(adir->name)) {
548         /* NT client config dir; ThisCell is in registry (no file). */
549         return afssw_GetClientCellName(&adir->cellName);
550     } else {
551         /* NT server config dir; works just like Unix */
552         return GetCellUnix(adir);
553     }
554 }
555
556 /* The following procedures and structs are used on Windows only
557  * to enumerate the Cell information distributed within the
558  * Windows registry.  (See src/WINNT/afsd/cm_config.c)
559  */
560 typedef struct _cm_enumCellRegistry {
561     afs_uint32 client;  /* non-zero if client query */
562     struct afsconf_dir *adir;
563 } cm_enumCellRegistry_t;
564
565 static long
566 cm_serverConfigProc(void *rockp, struct sockaddr_in *addrp,
567                     char *hostNamep, unsigned short rank)
568 {
569     struct afsconf_cell *cellInfop = (struct afsconf_cell *)rockp;
570
571     if (cellInfop->numServers == MAXHOSTSPERCELL)
572         return 0;
573
574     cellInfop->hostAddr[cellInfop->numServers] = *addrp;
575     strncpy(cellInfop->hostName[cellInfop->numServers], hostNamep, MAXHOSTCHARS);
576     cellInfop->hostName[cellInfop->numServers][MAXHOSTCHARS-1] = '\0';
577     cellInfop->numServers++;
578
579     return 0;
580 }
581
582 static long
583 cm_enumCellRegistryProc(void *rockp, char * cellNamep)
584 {
585     long code;
586     cm_enumCellRegistry_t *enump = (cm_enumCellRegistry_t *)rockp;
587     char linkedName[256] = "";
588     int timeout = 0;
589     struct afsconf_entry *newEntry;
590
591
592     newEntry = malloc(sizeof(struct afsconf_entry));
593     if (newEntry == NULL)
594         return ENOMEM;
595     newEntry->cellInfo.numServers = 0;
596
597     code = cm_SearchCellRegistry(enump->client, cellNamep, NULL, linkedName, cm_serverConfigProc, &newEntry->cellInfo);
598     if (code == CM_ERROR_FORCE_DNS_LOOKUP)
599         code = cm_SearchCellByDNS(cellNamep, NULL, &timeout, cm_serverConfigProc, &newEntry->cellInfo);
600
601     if (code == 0) {
602         strncpy(newEntry->cellInfo.name, cellNamep, MAXCELLCHARS);
603         newEntry->cellInfo.name[MAXCELLCHARS-1];
604         if (linkedName[0])
605             newEntry->cellInfo.linkedCell = strdup(linkedName);
606         else
607             newEntry->cellInfo.linkedCell = NULL;
608         newEntry->cellInfo.timeout = timeout;
609         newEntry->cellInfo.flags = 0;
610
611         newEntry->next = enump->adir->entries;
612         enump->adir->entries = newEntry;
613     } else {
614         free(newEntry);
615     }
616     return code;
617 }
618 #endif /* AFS_NT40_ENV */
619
620
621 static int
622 afsconf_OpenInternal(struct afsconf_dir *adir, char *cell,
623                      char clones[])
624 {
625     afsconf_FILE *tf;
626     char *tp, *bp;
627     struct afsconf_entry *curEntry;
628     struct afsconf_aliasentry *curAlias;
629     afs_int32 code;
630     afs_int32 i;
631     char tbuffer[256];
632     struct stat tstat;
633     char *cellservDB;
634
635 #ifdef AFS_NT40_ENV
636     cm_enumCellRegistry_t enumCellRegistry = {0, 0};
637 #endif /* AFS_NT40_ENV */
638
639     /* init the keys queue before any call to afsconf_CloseInternal() */
640     _afsconf_InitKeys(adir);
641
642     /* figure out the local cell name */
643 #ifdef AFS_NT40_ENV
644     i = GetCellNT(adir);
645     enumCellRegistry.adir = adir;
646 #else
647     i = GetCellUnix(adir);
648 #endif
649
650 #ifndef AFS_FREELANCE_CLIENT    /* no local cell not fatal in freelance */
651     if (i) {
652         return i;
653     }
654 #endif
655
656     /* now parse the individual lines */
657     curEntry = 0;
658
659     _afsconf_CellServDBPath(adir, &cellservDB);
660
661 #ifdef AFS_NT40_ENV
662     if (_afsconf_IsClientConfigDirectory(adir->name))
663         enumCellRegistry.client = 1;
664 #endif /* AFS_NT40_ENV */
665
666     if (!stat(cellservDB, &tstat)) {
667         adir->timeRead = tstat.st_mtime;
668     } else {
669         adir->timeRead = 0;
670     }
671
672     tf = fopen(cellservDB, "r");
673     if (!tf) {
674         return -1;
675     }
676
677     /* The CellServDB file is now open.
678      * The following code parses the contents of the
679      * file and creates a list with the first cell entry
680      * in the CellServDB file at the end of the list.
681      *
682      * No checking is performed for duplicates.
683      * The side effects of this process are that duplicate
684      * entries appended to the end of the CellServDB file
685      * take precedence and are found in a shorter period
686      * of time.
687      */
688
689     while (1) {
690         tp = fgets(tbuffer, sizeof(tbuffer), tf);
691         if (!tp)
692             break;
693         TrimLine(tbuffer, sizeof tbuffer);      /* remove white space */
694         if (tbuffer[0] == 0 || tbuffer[0] == '\n')
695             continue;           /* empty line */
696         if (tbuffer[0] == '>') {
697             char linkedcell[MAXCELLCHARS];
698             /* start new cell item */
699             if (curEntry) {
700                 /* thread this guy on the list */
701                 curEntry->next = adir->entries;
702                 adir->entries = curEntry;
703                 curEntry = 0;
704             }
705             curEntry = calloc(1, sizeof(struct afsconf_entry));
706             code =
707                 ParseCellLine(tbuffer, curEntry->cellInfo.name, linkedcell);
708             if (code) {
709                 afsconf_CloseInternal(adir);
710                 fclose(tf);
711                 free(curEntry);
712                 return -1;
713             }
714             if (linkedcell[0] != '\0')
715                 curEntry->cellInfo.linkedCell = strdup(linkedcell);
716         } else {
717             /* new host in the current cell */
718             if (!curEntry) {
719                 afsconf_CloseInternal(adir);
720                 fclose(tf);
721                 return -1;
722             }
723             i = curEntry->cellInfo.numServers;
724             if (i < MAXHOSTSPERCELL) {
725                 if (cell && !strcmp(cell, curEntry->cellInfo.name))
726                     code =
727                         ParseHostLine(tbuffer,
728                                       &curEntry->cellInfo.hostAddr[i],
729                                       curEntry->cellInfo.hostName[i],
730                                       &clones[i]);
731                 else
732                     code =
733                         ParseHostLine(tbuffer,
734                                       &curEntry->cellInfo.hostAddr[i],
735                                       curEntry->cellInfo.hostName[i], 0);
736
737                 if (code) {
738                     if (code == AFSCONF_SYNTAX) {
739                         for (bp = tbuffer; *bp != '\n'; bp++) { /* Take out the <cr> from the buffer */
740                             if (!*bp)
741                                 break;
742                         }
743                         *bp = '\0';
744                         fprintf(stderr,
745                                 "Can't properly parse host line \"%s\" in configuration file %s\n",
746                                 tbuffer, cellservDB);
747                     }
748                     free(curEntry);
749                     fclose(tf);
750                     afsconf_CloseInternal(adir);
751                     return -1;
752                 }
753                 curEntry->cellInfo.numServers = ++i;
754             } else {
755                 fprintf(stderr,
756                         "Too many hosts for cell %s in configuration file %s\n",
757                         curEntry->cellInfo.name, cellservDB);
758             }
759         }
760     }
761     fclose(tf);                 /* close the file now */
762     free(cellservDB);
763
764     /* end the last partially-completed cell */
765     if (curEntry) {
766         curEntry->next = adir->entries;
767         adir->entries = curEntry;
768     }
769
770 #ifdef AFS_NT40_ENV
771      /*
772       * Windows maintains a CellServDB list in the Registry
773       * that supercedes the contents of the CellServDB file.
774       * Prepending these entries to the head of the list
775       * is sufficient to enforce the precedence.
776       */
777      cm_EnumerateCellRegistry( enumCellRegistry.client,
778                                cm_enumCellRegistryProc,
779                                &enumCellRegistry);
780 #endif /* AFS_NT40_ENV */
781
782     /* Read in the alias list */
783     strcompose(tbuffer, 256, adir->name, "/", AFSDIR_CELLALIAS_FILE,
784         (char *)NULL);
785
786     tf = fopen(tbuffer, "r");
787     while (tf) {
788         char *aliasPtr;
789
790         tp = fgets(tbuffer, sizeof(tbuffer), tf);
791         if (!tp)
792             break;
793         TrimLine(tbuffer, sizeof tbuffer);      /* remove white space */
794
795         if (tbuffer[0] == '\0' || tbuffer[0] == '\n' || tbuffer[0] == '#')
796             continue;           /* empty line */
797
798         tp = tbuffer;
799         while (tp[0] != '\0' && tp[0] != ' ' && tp[0] != '\t')
800             tp++;
801         if (tp[0] == '\0')
802             continue;           /* invalid line */
803
804         while (tp[0] != '\0' && (tp[0] == ' ' || tp[0] == '\t'))
805             0[tp++] = '\0';
806         if (tp[0] == '\0')
807             continue;           /* invalid line */
808
809         aliasPtr = tp;
810         while (tp[0] != '\0' && tp[0] != ' ' && tp[0] != '\t' && tp[0] != '\r'
811                && tp[0] != '\n')
812             tp++;
813         tp[0] = '\0';
814
815         curAlias = calloc(1, sizeof(*curAlias));
816
817         strlcpy(curAlias->aliasInfo.aliasName, aliasPtr, sizeof curAlias->aliasInfo.aliasName);
818         strlcpy(curAlias->aliasInfo.realName, tbuffer, sizeof curAlias->aliasInfo.realName);
819
820         curAlias->next = adir->alias_entries;
821         adir->alias_entries = curAlias;
822     }
823
824     if (tf != NULL)
825         fclose(tf);
826
827     /* now read the fs keys, if possible */
828     code = _afsconf_LoadKeys(adir);
829     if (code) {
830         return code;
831     }
832     code = _afsconf_LoadRealms(adir);
833
834     return code;
835 }
836
837 /* parse a line of the form
838  *"128.2.1.3   #hostname" or
839  *"[128.2.1.3]  #hostname" for clones
840  * into the appropriate pieces.
841  */
842 static int
843 ParseHostLine(char *aline, struct sockaddr_in *addr, char *aname,
844               char *aclone)
845 {
846     int c1, c2, c3, c4;
847     afs_int32 code;
848     char *tp;
849
850     if (*aline == '[') {
851         if (aclone)
852             *aclone = 1;
853         /* FIXME: length of aname unknown here */
854         code = sscanf(aline, "[%d.%d.%d.%d] #%s", &c1, &c2, &c3, &c4, aname);
855     } else {
856         if (aclone)
857             *aclone = 0;
858         /* FIXME: length of aname unknown here */
859         code = sscanf(aline, "%d.%d.%d.%d #%s", &c1, &c2, &c3, &c4, aname);
860     }
861     if (code != 5)
862         return AFSCONF_SYNTAX;
863     addr->sin_family = AF_INET;
864     addr->sin_port = 0;
865 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
866     addr->sin_len = sizeof(struct sockaddr_in);
867 #endif
868     tp = (char *)&addr->sin_addr;
869     *tp++ = c1;
870     *tp++ = c2;
871     *tp++ = c3;
872     *tp++ = c4;
873     return 0;
874 }
875
876 /* parse a line of the form
877  * ">cellname [linkedcellname] [#comments]"
878  * into the appropriate pieces.
879  */
880 static int
881 ParseCellLine(char *aline, char *aname,
882               char *alname)
883 {
884     int code;
885     /* FIXME: length of aname, alname unknown here */
886     code = sscanf(aline, ">%s %s", aname, alname);
887     if (code == 1)
888         *alname = '\0';
889     if (code == 2) {
890         if (*alname == '#') {
891             *alname = '\0';
892         }
893     }
894     return (code > 0 ? 0 : AFSCONF_SYNTAX);
895 }
896
897 /* call aproc(entry, arock, adir) for all cells.  Proc must return 0, or we'll stop early and return the code it returns */
898 int
899 afsconf_CellApply(struct afsconf_dir *adir,
900                   int (*aproc) (struct afsconf_cell * cell, void *arock,
901                                 struct afsconf_dir * dir), void *arock)
902 {
903     struct afsconf_entry *tde;
904     afs_int32 code;
905     LOCK_GLOBAL_MUTEX;
906     for (tde = adir->entries; tde; tde = tde->next) {
907         code = (*aproc) (&tde->cellInfo, arock, adir);
908         if (code) {
909             UNLOCK_GLOBAL_MUTEX;
910             return code;
911         }
912     }
913     UNLOCK_GLOBAL_MUTEX;
914     return 0;
915 }
916
917 /* call aproc(entry, arock, adir) for all cell aliases.
918  * Proc must return 0, or we'll stop early and return the code it returns
919  */
920 int
921 afsconf_CellAliasApply(struct afsconf_dir *adir,
922                        int (*aproc) (struct afsconf_cellalias * alias,
923                                      void *arock, struct afsconf_dir * dir),
924                        void *arock)
925 {
926     struct afsconf_aliasentry *tde;
927     afs_int32 code;
928     LOCK_GLOBAL_MUTEX;
929     for (tde = adir->alias_entries; tde; tde = tde->next) {
930         code = (*aproc) (&tde->aliasInfo, arock, adir);
931         if (code) {
932             UNLOCK_GLOBAL_MUTEX;
933             return code;
934         }
935     }
936     UNLOCK_GLOBAL_MUTEX;
937     return 0;
938 }
939
940 afs_int32 afsconf_SawCell = 0;
941
942 int
943 afsconf_GetExtendedCellInfo(struct afsconf_dir *adir, char *acellName,
944                             char *aservice, struct afsconf_cell *acellInfo,
945                             char clones[])
946 {
947     afs_int32 code;
948     char *cell;
949
950     code = afsconf_GetCellInfo(adir, acellName, aservice, acellInfo);
951     if (code)
952         return code;
953
954     if (acellName)
955         cell = acellName;
956     else
957         cell = (char *)&acellInfo->name;
958
959     code = afsconf_OpenInternal(adir, cell, clones);
960     return code;
961 }
962
963 #if !defined(AFS_NT40_ENV)
964 int
965 afsconf_LookupServer(const char *service, const char *protocol,
966                      const char *cellName, unsigned short afsdbPort,
967                      int *cellHostAddrs, char cellHostNames[][MAXHOSTCHARS],
968                      unsigned short ports[], unsigned short ipRanks[],
969                      int *numServers, int *ttl, char **arealCellName)
970 {
971     int code = 0;
972     int r;
973     int len;
974     unsigned char answer[4096];
975     unsigned char *p;
976     char *dotcellname = NULL;
977     char *realCellName;
978     char host[256];
979     int server_num = 0;
980     int minttl = 0;
981     int try_init = 0;
982     int dnstype = 0;
983     int pass = 0;
984     char *IANAname = (char *) afsconf_FindIANAName(service);
985     int tservice = afsconf_FindService(service);
986
987     realCellName = NULL;
988
989     *numServers = 0;
990     *ttl = 0;
991     if (tservice <= 0 || !IANAname)
992         return AFSCONF_NOTFOUND;        /* service not found */
993
994     if (strchr(cellName,'.'))
995         pass += 2;
996
997 #ifdef HAVE_RES_RETRANSRETRY
998     if ((_res.options & RES_INIT) == 0 && res_init() == -1)
999       return (0);
1000
1001     /*
1002      * Rx timeout is typically 56 seconds; limit user experience to
1003      * similar timeout
1004      */
1005     _res.retrans = 18;
1006     _res.retry = 3;
1007 #endif
1008
1009  retryafsdb:
1010     r = -1;
1011     switch (pass) {
1012     case 0:
1013         dnstype = T_SRV;
1014         r = asprintf(&dotcellname, "_%s._%s.%s.", IANAname, protocol, cellName);
1015         break;
1016     case 1:
1017         dnstype = T_AFSDB;
1018         r = asprintf(&dotcellname, "%s.", cellName);
1019         break;
1020     case 2:
1021         dnstype = T_SRV;
1022         r = asprintf(&dotcellname, "_%s._%s.%s", IANAname, protocol, cellName);
1023         break;
1024     case 3:
1025         dnstype = T_AFSDB;
1026         r = asprintf(&dotcellname, "%s", cellName);
1027         break;
1028     }
1029     if (r < 0 || dotcellname == NULL)
1030         goto findservererror;
1031
1032     LOCK_GLOBAL_MUTEX;
1033     len = res_search(dotcellname, C_IN, dnstype, answer, sizeof(answer));
1034     UNLOCK_GLOBAL_MUTEX;
1035
1036     if (dotcellname != NULL) {
1037         free(dotcellname);
1038         dotcellname = NULL;
1039     }
1040
1041     if (len < 0) {
1042         if (try_init < 1) {
1043             try_init++;
1044             res_init();
1045             goto retryafsdb;
1046         }
1047         if (pass < 3) {
1048             pass++;
1049             goto retryafsdb;
1050         } else {
1051             code = AFSCONF_NOTFOUND;
1052             goto findservererror;
1053         }
1054     }
1055
1056     p = answer + sizeof(HEADER);        /* Skip header */
1057     code = dn_expand(answer, answer + len, p, host, sizeof(host));
1058     if (code < 0) {
1059         code = AFSCONF_NOTFOUND;
1060         goto findservererror;
1061     }
1062
1063     p += code + QFIXEDSZ;       /* Skip name */
1064
1065     while (p < answer + len) {
1066         int type, ttl, size;
1067
1068         code = dn_expand(answer, answer + len, p, host, sizeof(host));
1069         if (code < 0) {
1070             code = AFSCONF_NOTFOUND;
1071             goto findservererror;
1072         }
1073
1074         p += code;              /* Skip the name */
1075         type = (p[0] << 8) | p[1];
1076         p += 4;                 /* Skip type and class */
1077         ttl = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
1078         p += 4;                 /* Skip the TTL */
1079         size = (p[0] << 8) | p[1];
1080         p += 2;                 /* Skip the size */
1081
1082         if (type == T_AFSDB) {
1083             struct hostent *he;
1084             short afsdb_type;
1085
1086             afsdb_type = (p[0] << 8) | p[1];
1087             if (afsdb_type == 1) {
1088                 /*
1089                  * We know this is an AFSDB record for our cell, of the
1090                  * right AFSDB type.  Write down the true cell name that
1091                  * the resolver gave us above.
1092                  */
1093                 if (!realCellName)
1094                     realCellName = strdup(host);
1095             }
1096
1097             code = dn_expand(answer, answer + len, p + 2, host, sizeof(host));
1098             if (code < 0) {
1099                 code = AFSCONF_NOTFOUND;
1100                 goto findservererror;
1101             }
1102
1103             if ((afsdb_type == 1) && (server_num < MAXHOSTSPERCELL) &&
1104                 /* Do we want to get TTL data for the A record as well? */
1105                 (he = gethostbyname(host))) {
1106                 if (he->h_addrtype == AF_INET) {
1107                     afs_int32 ipaddr;
1108                     memcpy(&ipaddr, he->h_addr, sizeof(ipaddr));
1109                     cellHostAddrs[server_num] = ipaddr;
1110                     ports[server_num] = afsdbPort;
1111                     ipRanks[server_num] = 0;
1112                     strncpy(cellHostNames[server_num], host,
1113                             sizeof(cellHostNames[server_num]));
1114                     server_num++;
1115                     if (!minttl || ttl < minttl)
1116                         minttl = ttl;
1117                 }
1118             }
1119         }
1120         if (type == T_SRV) {
1121             struct hostent *he;
1122             /* math here: _ is 1, _ ._ is 3, _ ._ . is 4. then the domain. */
1123             if ((strncmp(host + 1, IANAname, strlen(IANAname)) == 0) &&
1124                 (strncmp(host + strlen(IANAname) + 3, protocol,
1125                          strlen(protocol)) == 0)) {
1126                 if (!realCellName)
1127                     realCellName = strdup(host + strlen(IANAname) +
1128                                           strlen(protocol) + 4);
1129             }
1130
1131             code = dn_expand(answer, answer + len, p + 6, host, sizeof(host));
1132             if (code < 0) {
1133                 code = AFSCONF_NOTFOUND;
1134                 goto findservererror;
1135             }
1136
1137             if ((server_num < MAXHOSTSPERCELL) &&
1138                 /* Do we want to get TTL data for the A record as well? */
1139                 (he = gethostbyname(host))) {
1140                 if (he->h_addrtype == AF_INET) {
1141                     afs_int32 ipaddr;
1142
1143                     memcpy(&ipaddr, he->h_addr, sizeof(ipaddr));
1144                     cellHostAddrs[server_num] = ipaddr;
1145                     ipRanks[server_num] = (p[0] << 8) | p[1];
1146                     ports[server_num] = htons((p[4] << 8) | p[5]);
1147                     /* weight = (p[2] << 8) | p[3]; */
1148                     strncpy(cellHostNames[server_num], host,
1149                             sizeof(cellHostNames[server_num]));
1150                     server_num++;
1151
1152                     if (!minttl || ttl < minttl)
1153                         minttl = ttl;
1154                 }
1155             }
1156         }
1157
1158         p += size;
1159     }
1160
1161     if (server_num == 0) {      /* No AFSDB or SRV records */
1162         code = AFSCONF_NOTFOUND;
1163         goto findservererror;
1164     }
1165
1166     if (realCellName) {
1167         /* Convert the real cell name to lowercase */
1168         for (p = (unsigned char *)realCellName; *p; p++)
1169             *p = tolower(*p);
1170     }
1171
1172     *numServers = server_num;
1173     *ttl = minttl ? (time(0) + minttl) : 0;
1174
1175     if ( *numServers > 0 ) {
1176         code =  0;
1177         *arealCellName = realCellName;
1178     } else
1179         code = AFSCONF_NOTFOUND;
1180
1181 findservererror:
1182     if (code && realCellName)
1183         free(realCellName);
1184     return code;
1185 }
1186
1187 int
1188 afsconf_GetAfsdbInfo(char *acellName, char *aservice,
1189                      struct afsconf_cell *acellInfo)
1190 {
1191     afs_int32 cellHostAddrs[AFSMAXCELLHOSTS];
1192     char cellHostNames[AFSMAXCELLHOSTS][MAXHOSTCHARS];
1193     unsigned short ipRanks[AFSMAXCELLHOSTS];
1194     unsigned short ports[AFSMAXCELLHOSTS];
1195     char *realCellName = NULL;
1196     int ttl, numServers, i;
1197     char *service = aservice;
1198     int code;
1199     unsigned short afsdbport;
1200     if (!service) {
1201         service = "afs3-vlserver";
1202         afsdbport = htons(7003);
1203     } else {
1204         service = aservice;
1205         afsdbport = afsconf_FindService(service);
1206     }
1207     code = afsconf_LookupServer((const char *)service, "udp",
1208                                 (const char *)acellName, afsdbport,
1209                                 cellHostAddrs, cellHostNames,
1210                                 ports, ipRanks, &numServers, &ttl,
1211                                 &realCellName);
1212
1213     /* If we couldn't find an entry for the requested service
1214      * and that service happens to be the prservice or kaservice
1215      * then fallback to searching for afs3-vlserver and assigning
1216      * the port number here. */
1217     if (code < 0 && (afsdbport == htons(7002) || afsdbport == htons(7004))) {
1218         code = afsconf_LookupServer("afs3-vlserver", "udp",
1219                                     (const char *)acellName, afsdbport,
1220                                     cellHostAddrs, cellHostNames,
1221                                     ports, ipRanks, &numServers, &ttl,
1222                                     &realCellName);
1223         if (code >= 0) {
1224             for (i = 0; i < numServers; i++)
1225                 ports[i] = afsdbport;
1226         }
1227     }
1228     if (code == 0) {
1229         acellInfo->timeout = ttl;
1230         acellInfo->numServers = numServers;
1231         for (i = 0; i < numServers; i++) {
1232             memcpy(&acellInfo->hostAddr[i].sin_addr.s_addr, &cellHostAddrs[i],
1233                    sizeof(afs_int32));
1234             memcpy(acellInfo->hostName[i], cellHostNames[i], MAXHOSTCHARS);
1235             acellInfo->hostAddr[i].sin_family = AF_INET;
1236             acellInfo->hostAddr[i].sin_port = ports[i];
1237
1238             if (realCellName) {
1239                 strlcpy(acellInfo->name, realCellName,
1240                         sizeof(acellInfo->name));
1241                 free(realCellName);
1242                 realCellName = NULL;
1243             }
1244         }
1245         acellInfo->linkedCell = NULL;       /* no linked cell */
1246         acellInfo->flags = 0;
1247     }
1248     return code;
1249 }
1250 #else /* windows */
1251 int
1252 afsconf_GetAfsdbInfo(char *acellName, char *aservice,
1253                      struct afsconf_cell *acellInfo)
1254 {
1255     afs_int32 i;
1256     int tservice = afsconf_FindService(aservice);   /* network byte order */
1257     const char *ianaName = afsconf_FindIANAName(aservice);
1258     struct afsconf_entry DNSce;
1259     afs_int32 cellHostAddrs[AFSMAXCELLHOSTS];
1260     char cellHostNames[AFSMAXCELLHOSTS][MAXHOSTCHARS];
1261     unsigned short ipRanks[AFSMAXCELLHOSTS];
1262     unsigned short ports[AFSMAXCELLHOSTS];          /* network byte order */
1263     int numServers;
1264     int rc;
1265     int ttl;
1266
1267     if (tservice < 0) {
1268         if (aservice)
1269             return AFSCONF_NOTFOUND;
1270         else
1271             tservice = 0;       /* port will be assigned by caller */
1272     }
1273
1274     if (ianaName == NULL)
1275         ianaName = "afs3-vlserver";
1276
1277     DNSce.cellInfo.numServers = 0;
1278     DNSce.next = NULL;
1279
1280     rc = getAFSServer(ianaName, "udp", acellName, tservice,
1281                       cellHostAddrs, cellHostNames, ports, ipRanks, &numServers,
1282                       &ttl);
1283     /* ignore the ttl here since this code is only called by transitory programs
1284      * like klog, etc. */
1285
1286     /* If we couldn't find an entry for the requested service
1287      * and that service happens to be the prservice or kaservice
1288      * then fallback to searching for afs3-vlserver and assigning
1289      * the port number here. */
1290     if (rc < 0 && (tservice == htons(7002) || tservice == htons(7004))) {
1291         rc = getAFSServer("afs3-vlserver", "udp", acellName, tservice,
1292                            cellHostAddrs, cellHostNames, ports, ipRanks, &numServers,
1293                            &ttl);
1294         if (rc >= 0) {
1295             for (i = 0; i < numServers; i++)
1296                 ports[i] = tservice;
1297         }
1298     }
1299
1300     if (rc < 0 || numServers == 0)
1301         return -1;
1302
1303     for (i = 0; i < numServers; i++) {
1304         memcpy(&acellInfo->hostAddr[i].sin_addr.s_addr, &cellHostAddrs[i],
1305                sizeof(afs_uint32));
1306         memcpy(acellInfo->hostName[i], cellHostNames[i], MAXHOSTCHARS);
1307         acellInfo->hostAddr[i].sin_family = AF_INET;
1308         if (aservice)
1309             acellInfo->hostAddr[i].sin_port = ports[i];
1310         else
1311             acellInfo->hostAddr[i].sin_port = 0;
1312     }
1313
1314     acellInfo->numServers = numServers;
1315     strlcpy(acellInfo->name, acellName, sizeof acellInfo->name);
1316     acellInfo->linkedCell = NULL;       /* no linked cell */
1317     acellInfo->flags = 0;
1318     return 0;
1319 }
1320 #endif /* windows */
1321
1322 int
1323 afsconf_GetCellInfo(struct afsconf_dir *adir, char *acellName, char *aservice,
1324                     struct afsconf_cell *acellInfo)
1325 {
1326     struct afsconf_entry *tce;
1327     struct afsconf_aliasentry *tcae;
1328     struct afsconf_entry *bestce;
1329     afs_int32 i;
1330     int tservice;
1331     char *tcell;
1332     int cnLen;
1333     int ambig;
1334     char tbuffer[64];
1335
1336     LOCK_GLOBAL_MUTEX;
1337     if (adir)
1338         _afsconf_Check(adir);
1339     if (acellName) {
1340         tcell = acellName;
1341         cnLen = (int)(strlen(tcell) + 1);
1342         lcstring(tcell, tcell, cnLen);
1343         afsconf_SawCell = 1;    /* will ignore the AFSCELL switch on future */
1344         /* call to afsconf_GetLocalCell: like klog  */
1345     } else {
1346         i = afsconf_GetLocalCell(adir, tbuffer, sizeof(tbuffer));
1347         if (i) {
1348             UNLOCK_GLOBAL_MUTEX;
1349             return i;
1350         }
1351         tcell = tbuffer;
1352     }
1353     cnLen = strlen(tcell);
1354     bestce = (struct afsconf_entry *)0;
1355     ambig = 0;
1356     if (!adir) {
1357         UNLOCK_GLOBAL_MUTEX;
1358         return 0;
1359     }
1360
1361     /* Look through the list of aliases */
1362     for (tcae = adir->alias_entries; tcae; tcae = tcae->next) {
1363         if (strcasecmp(tcae->aliasInfo.aliasName, tcell) == 0) {
1364             tcell = tcae->aliasInfo.realName;
1365             break;
1366         }
1367     }
1368
1369     for (tce = adir->entries; tce; tce = tce->next) {
1370         if (strcasecmp(tce->cellInfo.name, tcell) == 0) {
1371             /* found our cell */
1372             bestce = tce;
1373             ambig = 0;
1374             break;
1375         }
1376         if (strlen(tce->cellInfo.name) < cnLen)
1377             continue;           /* clearly wrong */
1378         if (strncasecmp(tce->cellInfo.name, tcell, cnLen) == 0) {
1379             if (bestce)
1380                 ambig = 1;      /* ambiguous unless we get exact match */
1381             bestce = tce;
1382         }
1383     }
1384     if (!ambig && bestce && bestce->cellInfo.numServers) {
1385         *acellInfo = bestce->cellInfo;  /* structure assignment */
1386         if (aservice) {
1387             tservice = afsconf_FindService(aservice);
1388             if (tservice < 0) {
1389                 UNLOCK_GLOBAL_MUTEX;
1390                 return AFSCONF_NOTFOUND;        /* service not found */
1391             }
1392             for (i = 0; i < acellInfo->numServers; i++) {
1393                 acellInfo->hostAddr[i].sin_port = tservice;
1394             }
1395         }
1396         acellInfo->timeout = 0;
1397
1398         /*
1399          * Until we figure out how to separate out ubik server
1400          * queries from other server queries, only perform gethostbyname()
1401          * lookup on the specified hostnames for the client CellServDB files.
1402          */
1403         if (_afsconf_IsClientConfigDirectory(adir->name) &&
1404             !(acellInfo->flags & AFSCONF_CELL_FLAG_DNS_QUERIED)) {
1405             int j;
1406             short numServers=0;                                 /*Num active servers for the cell */
1407             struct sockaddr_in hostAddr[MAXHOSTSPERCELL];       /*IP addresses for cell's servers */
1408             char hostName[MAXHOSTSPERCELL][MAXHOSTCHARS];       /*Names for cell's servers */
1409
1410             memset(&hostAddr, 0, sizeof(hostAddr));
1411             memset(&hostName, 0, sizeof(hostName));
1412
1413             for ( j=0; j<acellInfo->numServers && numServers < MAXHOSTSPERCELL; j++ ) {
1414                 struct hostent *he = gethostbyname(acellInfo->hostName[j]);
1415                 int foundAddr = 0;
1416
1417                 if (he && he->h_addrtype == AF_INET) {
1418                     int i;
1419                     /* obtain all the valid address from the list */
1420                     for (i=0 ; he->h_addr_list[i] && numServers < MAXHOSTSPERCELL; i++) {
1421                         /* check to see if this is a new address; if so insert it into the list */
1422                         int k, dup;
1423                         afs_uint32 addr;
1424                         memcpy(&addr, he->h_addr_list[i], sizeof(addr));
1425                         for (k=0, dup=0; !dup && k < numServers; k++) {
1426                             if (hostAddr[k].sin_addr.s_addr == addr) {
1427                                 dup = 1;
1428                             }
1429                         }
1430                         if (dup)
1431                             continue;
1432
1433                         hostAddr[numServers].sin_family = AF_INET;
1434                         hostAddr[numServers].sin_port = acellInfo->hostAddr[0].sin_port;
1435 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
1436                         hostAddr[numServers].sin_len = sizeof(struct sockaddr_in);
1437 #endif
1438                         memcpy(&hostAddr[numServers].sin_addr.s_addr, he->h_addr_list[i], sizeof(afs_uint32));
1439                         strcpy(hostName[numServers], acellInfo->hostName[j]);
1440                         foundAddr = 1;
1441                         numServers++;
1442                     }
1443                 }
1444                 if (!foundAddr) {
1445                     hostAddr[numServers] = acellInfo->hostAddr[j];
1446                     strcpy(hostName[numServers], acellInfo->hostName[j]);
1447                     numServers++;
1448                 }
1449             }
1450
1451             for (i=0; i<numServers; i++) {
1452                 acellInfo->hostAddr[i] = hostAddr[i];
1453                 strcpy(acellInfo->hostName[i], hostName[i]);
1454             }
1455             acellInfo->numServers = numServers;
1456             acellInfo->flags |= AFSCONF_CELL_FLAG_DNS_QUERIED;
1457         }
1458         UNLOCK_GLOBAL_MUTEX;
1459         return 0;
1460     } else {
1461         UNLOCK_GLOBAL_MUTEX;
1462         return afsconf_GetAfsdbInfo(tcell, aservice, acellInfo);
1463     }
1464 }
1465
1466 /**
1467  * Get the current localcell name.
1468  *
1469  * Internal function to get a pointer to the local cell name.
1470  * This function must be called with the global afsconf lock held.
1471  *
1472  * @param[in]  adir    afsconf object
1473  * @param[out] aname   address to a char pointer
1474  * @param[in]  check   always perform a config check, even if the
1475  *                     the AFSCELL name is set.
1476  *
1477  * @return status
1478  *    @retval 0 success
1479  *    @retval AFSCONF_UNKNOWN failed to get cellname
1480  *
1481  * @internal
1482  */
1483 int
1484 _afsconf_GetLocalCell(struct afsconf_dir *adir, char **pname, int check)
1485 {
1486     static int afsconf_showcell = 0;
1487     char *afscell_path;
1488     afs_int32 code = 0;
1489
1490     /*
1491      * If a cell switch was specified in a command, then it should override the
1492      * AFSCELL variable.  If a cell was specified, then the afsconf_SawCell flag
1493      * is set and the cell name in the adir structure is used.
1494      * Read the AFSCELL var each time: in case it changes (unsetenv AFSCELL).
1495      * Optionally, check the configuration, even if using the environment variable.
1496      */
1497     if (!afsconf_SawCell && (afscell_path = getenv("AFSCELL"))) {
1498         if (check) {
1499             _afsconf_Check(adir);
1500         }
1501         if (!afsconf_showcell) {
1502             fprintf(stderr, "Note: Operation is performed on cell %s\n",
1503                     afscell_path);
1504             afsconf_showcell = 1;
1505         }
1506         *pname = afscell_path;
1507     } else {
1508         _afsconf_Check(adir);
1509         if (adir->cellName) {
1510             *pname = adir->cellName;
1511         } else
1512             code = AFSCONF_UNKNOWN;
1513     }
1514     return code;
1515 }
1516
1517 int
1518 afsconf_GetLocalCell(struct afsconf_dir *adir, char *aname, afs_int32 alen)
1519 {
1520     afs_int32 code = 0;
1521     char *cellname = NULL;
1522
1523     LOCK_GLOBAL_MUTEX;
1524     code = _afsconf_GetLocalCell(adir, &cellname, 0);
1525     if (!code && cellname) {
1526         strlcpy(aname, cellname, alen);
1527     }
1528     UNLOCK_GLOBAL_MUTEX;
1529     return (code);
1530 }
1531
1532 int
1533 afsconf_Close(struct afsconf_dir *adir)
1534 {
1535     LOCK_GLOBAL_MUTEX;
1536     afsconf_CloseInternal(adir);
1537     if (adir->name)
1538         free(adir->name);
1539     free(adir);
1540     UNLOCK_GLOBAL_MUTEX;
1541     return 0;
1542 }
1543
1544 static int
1545 afsconf_CloseInternal(struct afsconf_dir *adir)
1546 {
1547     struct afsconf_entry *td, *nd;
1548     struct afsconf_aliasentry *ta, *na;
1549     char *tname;
1550
1551     tname = adir->name;         /* remember name, since that's all we preserve */
1552
1553     /* free everything we can find */
1554     if (adir->cellName)
1555         free(adir->cellName);
1556     for (td = adir->entries; td; td = nd) {
1557         nd = td->next;
1558         if (td->cellInfo.linkedCell)
1559             free(td->cellInfo.linkedCell);
1560         free(td);
1561     }
1562     for (ta = adir->alias_entries; ta; ta = na) {
1563         na = ta->next;
1564         free(ta);
1565     }
1566
1567     _afsconf_FreeAllKeys(adir);
1568     _afsconf_FreeRealms(adir);
1569
1570     /* reinit */
1571     memset(adir, 0, sizeof(struct afsconf_dir));
1572     adir->name = tname;         /* restore it */
1573     return 0;
1574 }
1575
1576 static int
1577 afsconf_Reopen(struct afsconf_dir *adir)
1578 {
1579     afs_int32 code;
1580     code = afsconf_CloseInternal(adir);
1581     if (code)
1582         return code;
1583     code = afsconf_OpenInternal(adir, 0, 0);
1584     return code;
1585 }