joe-beuhler-patches-20031122
[openafs.git] / src / auth / cellconfig.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  * 
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 #include <afsconfig.h>
11 #include <afs/param.h>
12
13 RCSID
14     ("$Header$");
15
16 #include <afs/stds.h>
17 #include <afs/pthread_glock.h>
18 #ifdef UKERNEL
19 #include "afs/sysincludes.h"
20 #include "afsincludes.h"
21 #else /* UKERNEL */
22 #include <sys/types.h>
23 #ifdef AFS_NT40_ENV
24 #include <winsock2.h>
25 #include <sys/utime.h>
26 #include <io.h>
27 #include <WINNT/afssw.h>
28 #ifdef AFS_AFSDB_ENV
29 #include <cm_dns.h>
30 #endif /* AFS_AFSDB_ENV */
31 #else
32 #include <sys/socket.h>
33 #include <netinet/in.h>
34 #include <netdb.h>
35 #include <sys/file.h>
36 #include <sys/time.h>
37 #ifdef AFS_AFSDB_ENV
38 #include <arpa/nameser.h>
39 #include <resolv.h>
40 #endif /* AFS_AFSDB_ENV */
41 #endif /* AFS_NT40_ENV */
42 #include <afs/afsint.h>
43 #include <errno.h>
44 #include <ctype.h>
45 #include <time.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <sys/stat.h>
49 #include <fcntl.h>
50 #ifdef HAVE_STRING_H
51 #include <string.h>
52 #else
53 #ifdef HAVE_STRINGS_H
54 #include <strings.h>
55 #endif
56 #endif
57 #ifdef HAVE_UNISTD_H
58 #include <unistd.h>
59 #endif
60 #endif /* UKERNEL */
61 #include <afs/afsutil.h>
62 #include "cellconfig.h"
63 #include "keys.h"
64
65 static struct afsconf_servPair serviceTable[] = {
66     {"afs", 7000,},
67     {"afscb", 7001,},
68     {"afsprot", 7002,},
69     {"afsvldb", 7003,},
70     {"afskauth", 7004,},
71     {"afsvol", 7005,},
72     {"afserror", 7006,},
73     {"afsnanny", 7007,},
74     {"afsupdate", 7008,},
75     {"afsrmtsys", 7009,},
76     {"afsres", 7010,},          /* residency database for MR-AFS */
77     {"afsremio", 7011,},        /* remote I/O interface for MR-AFS */
78     {0, 0}                      /* insert new services before this spot */
79 };
80
81 /* Prototypes */
82 static afs_int32 afsconf_FindService(register const char *aname);
83 static int TrimLine(char *abuffer);
84 #ifdef AFS_NT40_ENV
85 static int IsClientConfigDirectory(const char *path);
86 static int GetCellNT(struct afsconf_dir *adir);
87 #endif
88 static int afsconf_Check(register struct afsconf_dir *adir);
89 static int afsconf_Touch(register struct afsconf_dir *adir);
90 static int GetCellUnix(struct afsconf_dir *adir);
91 static int afsconf_OpenInternal(register struct afsconf_dir *adir, char *cell,
92                                 char clones[]);
93 static int ParseHostLine(char *aline, register struct sockaddr_in *addr,
94                          char *aname, char *aclone);
95 static int ParseCellLine(register char *aline, register char *aname,
96                          register char *alname);
97 static int afsconf_CloseInternal(register struct afsconf_dir *adir);
98 static int afsconf_Reopen(register struct afsconf_dir *adir);
99 static int SaveKeys(struct afsconf_dir *adir);
100
101 #ifndef T_AFSDB
102 #define T_AFSDB 18              /* per RFC1183 section 1 */
103 #endif
104
105 /*
106  * Basic Rule: we touch "<AFSCONF_DIR>/CellServDB" every time we change anything, so
107  * our code can tell if there is new info in the key files, the cell server db
108  * files or any of the other files (and reopen the thing) if the date on
109  * CellServDB changes.
110  */
111
112 /* return port number in network byte order in the low 16 bits of a long; return -1 if not found */
113 static afs_int32
114 afsconf_FindService(register const char *aname)
115 {
116     /* lookup a service name */
117     struct servent *ts;
118     register struct afsconf_servPair *tsp;
119
120 #if     defined(AFS_OSF_ENV) || defined(AFS_DEC_ENV)
121     ts = getservbyname(aname, "");
122 #else
123     ts = getservbyname(aname, NULL);
124 #endif
125     if (ts) {
126         /* we found it in /etc/services, so we use this value */
127         return ts->s_port;      /* already in network byte order */
128     }
129
130     /* not found in /etc/services, see if it is one of ours */
131     for (tsp = serviceTable;; tsp++) {
132         if (tsp->name == NULL)
133             return -1;
134         if (!strcmp(tsp->name, aname))
135             return htons(tsp->port);
136     }
137 }
138
139 static int
140 TrimLine(char *abuffer)
141 {
142     char tbuffer[256];
143     register char *tp;
144     register int tc;
145
146     tp = abuffer;
147     while ((tc = *tp)) {
148         if (!isspace(tc))
149             break;
150         tp++;
151     }
152     strcpy(tbuffer, tp);
153     strcpy(abuffer, tbuffer);
154     return 0;
155 }
156
157 #ifdef AFS_NT40_ENV
158 /*
159  * IsClientConfigDirectory() -- determine if path matches well-known
160  *     client configuration directory.
161  */
162 static int
163 IsClientConfigDirectory(const char *path)
164 {
165     const char *cdir = AFSDIR_CLIENT_ETC_DIRPATH;
166     int i;
167
168     for (i = 0; cdir[i] != '\0' && path[i] != '\0'; i++) {
169         int cc = tolower(cdir[i]);
170         int pc = tolower(path[i]);
171
172         if (cc == '\\') {
173             cc = '/';
174         }
175         if (pc == '\\') {
176             pc = '/';
177         }
178         if (cc != pc) {
179             return 0;
180         }
181     }
182
183     /* hit end of one or both; allow mismatch in existence of trailing slash */
184     if (cdir[i] != '\0') {
185         if ((cdir[i] != '\\' && cdir[i] != '/') || (cdir[i + 1] != '\0')) {
186             return 0;
187         }
188     }
189     if (path[i] != '\0') {
190         if ((path[i] != '\\' && path[i] != '/') || (path[i + 1] != '\0')) {
191             return 0;
192         }
193     }
194     return 1;
195 }
196 #endif /* AFS_NT40_ENV */
197
198
199 static int
200 afsconf_Check(register struct afsconf_dir *adir)
201 {
202     char tbuffer[256];
203     struct stat tstat;
204     register afs_int32 code;
205
206 #ifdef AFS_NT40_ENV
207     /* NT client CellServDB has different file name than NT server or Unix */
208     if (IsClientConfigDirectory(adir->name)) {
209         strcompose(tbuffer, 256, adir->name, "/",
210                    AFSDIR_CELLSERVDB_FILE_NTCLIENT, NULL);
211     } else {
212         strcompose(tbuffer, 256, adir->name, "/", AFSDIR_CELLSERVDB_FILE,
213                    NULL);
214     }
215 #else
216     strcompose(tbuffer, 256, adir->name, "/", AFSDIR_CELLSERVDB_FILE, NULL);
217 #endif /* AFS_NT40_ENV */
218
219     code = stat(tbuffer, &tstat);
220     if (code < 0) {
221         return code;
222     }
223     /* did file change? */
224     if (tstat.st_mtime == adir->timeRead) {
225         return 0;
226     }
227     /* otherwise file has changed, so reopen it */
228     return afsconf_Reopen(adir);
229 }
230
231 /* set modtime on file */
232 static int
233 afsconf_Touch(register struct afsconf_dir *adir)
234 {
235     char tbuffer[256];
236 #ifndef AFS_NT40_ENV
237     struct timeval tvp[2];
238 #endif
239
240     adir->timeRead = 0;         /* just in case */
241
242 #ifdef AFS_NT40_ENV
243     /* NT client CellServDB has different file name than NT server or Unix */
244
245     if (IsClientConfigDirectory(adir->name)) {
246         strcompose(tbuffer, 256, adir->name, "/",
247                    AFSDIR_CELLSERVDB_FILE_NTCLIENT, NULL);
248     } else {
249         strcompose(tbuffer, 256, adir->name, "/", AFSDIR_CELLSERVDB_FILE,
250                    NULL);
251     }
252
253     return _utime(tbuffer, NULL);
254
255 #else
256     strcompose(tbuffer, 256, adir->name, "/", AFSDIR_CELLSERVDB_FILE, NULL);
257     gettimeofday(&tvp[0], NULL);
258     tvp[1] = tvp[0];
259     return utimes(tbuffer, tvp);
260 #endif /* AFS_NT40_ENV */
261 }
262
263 struct afsconf_dir *
264 afsconf_Open(register const char *adir)
265 {
266     register struct afsconf_dir *tdir;
267     register afs_int32 code;
268
269     LOCK_GLOBAL_MUTEX
270         /* zero structure and fill in name; rest is done by internal routine */
271         tdir = (struct afsconf_dir *)malloc(sizeof(struct afsconf_dir));
272     memset(tdir, 0, sizeof(struct afsconf_dir));
273     tdir->name = (char *)malloc(strlen(adir) + 1);
274     strcpy(tdir->name, adir);
275
276     code = afsconf_OpenInternal(tdir, 0, 0);
277     if (code) {
278         char *afsconf_path, afs_confdir[128];
279
280         free(tdir->name);
281         /* Check global place only when local Open failed for whatever reason */
282         if (!(afsconf_path = getenv("AFSCONF"))) {
283             /* 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... */
284             char *home_dir;
285             FILE *fp;
286             size_t len;
287
288             if (!(home_dir = getenv("HOME"))) {
289                 /* Our last chance is the "/.AFSCONF" file */
290                 fp = fopen("/.AFSCONF", "r");
291                 if (fp == 0) {
292                     free(tdir);
293                     UNLOCK_GLOBAL_MUTEX return (struct afsconf_dir *)0;
294                 }
295                 fgets(afs_confdir, 128, fp);
296                 fclose(fp);
297             } else {
298                 char pathname[256];
299
300                 sprintf(pathname, "%s/%s", home_dir, ".AFSCONF");
301                 fp = fopen(pathname, "r");
302                 if (fp == 0) {
303                     /* Our last chance is the "/.AFSCONF" file */
304                     fp = fopen("/.AFSCONF", "r");
305                     if (fp == 0) {
306                         free(tdir);
307                         UNLOCK_GLOBAL_MUTEX return (struct afsconf_dir *)0;
308                     }
309                     fgets(afs_confdir, 128, fp);
310                     fclose(fp);
311                 }
312                 fgets(afs_confdir, 128, fp);
313                 fclose(fp);
314             }
315             len = strlen(afs_confdir);
316             if (len == 0) {
317                 free(tdir);
318                 UNLOCK_GLOBAL_MUTEX return (struct afsconf_dir *)0;
319             }
320             if (afs_confdir[len - 1] == '\n') {
321                 afs_confdir[len - 1] = 0;
322             }
323             afsconf_path = afs_confdir;
324         }
325         tdir->name = (char *)malloc(strlen(afsconf_path) + 1);
326         strcpy(tdir->name, afsconf_path);
327         code = afsconf_OpenInternal(tdir, 0, 0);
328         if (code) {
329             free(tdir->name);
330             free(tdir);
331             UNLOCK_GLOBAL_MUTEX return (struct afsconf_dir *)0;
332         }
333     }
334     UNLOCK_GLOBAL_MUTEX return tdir;
335 }
336
337
338 static int
339 GetCellUnix(struct afsconf_dir *adir)
340 {
341     int rc;
342     char tbuffer[256];
343     FILE *tf;
344
345     strcompose(tbuffer, 256, adir->name, "/", AFSDIR_THISCELL_FILE, NULL);
346     tf = fopen(tbuffer, "r");
347     if (tf) {
348         rc = fscanf(tf, "%s", tbuffer);
349         if (rc == 1) {
350             adir->cellName = (char *)malloc(strlen(tbuffer) + 1);
351             strcpy(adir->cellName, tbuffer);
352         }
353         fclose(tf);
354     } else {
355         return -1;
356     }
357     return 0;
358 }
359
360
361 #ifdef AFS_NT40_ENV
362 static int
363 GetCellNT(struct afsconf_dir *adir)
364 {
365     if (IsClientConfigDirectory(adir->name)) {
366         /* NT client config dir; ThisCell is in registry (no file). */
367         return afssw_GetClientCellName(&adir->cellName);
368     } else {
369         /* NT server config dir; works just like Unix */
370         return GetCellUnix(adir);
371     }
372 }
373 #endif /* AFS_NT40_ENV */
374
375
376 static int
377 afsconf_OpenInternal(register struct afsconf_dir *adir, char *cell,
378                      char clones[])
379 {
380     FILE *tf;
381     register char *tp, *bp;
382     register struct afsconf_entry *curEntry;
383     struct afsconf_aliasentry *curAlias;
384     register afs_int32 code;
385     afs_int32 i;
386     char tbuffer[256], tbuf1[256];
387     struct stat tstat;
388
389     /* figure out the cell name */
390 #ifdef AFS_NT40_ENV
391     i = GetCellNT(adir);
392 #else
393     i = GetCellUnix(adir);
394 #endif
395
396 #ifndef AFS_FREELANCE_CLIENT    /* no local cell not fatal in freelance */
397     if (i) {
398         return i;
399     }
400 #endif
401
402     /* now parse the individual lines */
403     curEntry = 0;
404
405 #ifdef AFS_NT40_ENV
406     /* NT client/server have a CellServDB that is the same format as Unix.
407      * However, the NT client uses a different file name
408      */
409     if (IsClientConfigDirectory(adir->name)) {
410         /* NT client config dir */
411         strcompose(tbuffer, 256, adir->name, "/",
412                    AFSDIR_CELLSERVDB_FILE_NTCLIENT, NULL);
413     } else {
414         /* NT server config dir */
415         strcompose(tbuffer, 256, adir->name, "/", AFSDIR_CELLSERVDB_FILE,
416                    NULL);
417     }
418 #else
419     strcompose(tbuffer, 256, adir->name, "/", AFSDIR_CELLSERVDB_FILE, NULL);
420 #endif /* AFS_NT40_ENV */
421
422     if (!stat(tbuffer, &tstat)) {
423         adir->timeRead = tstat.st_mtime;
424     } else {
425         adir->timeRead = 0;
426     }
427
428     strcpy(tbuf1, tbuffer);
429     tf = fopen(tbuffer, "r");
430     if (!tf) {
431         return -1;
432     }
433     while (1) {
434         tp = fgets(tbuffer, sizeof(tbuffer), tf);
435         if (!tp)
436             break;
437         TrimLine(tbuffer);      /* remove white space */
438         if (tbuffer[0] == 0 || tbuffer[0] == '\n')
439             continue;           /* empty line */
440         if (tbuffer[0] == '>') {
441             char linkedcell[MAXCELLCHARS];
442             /* start new cell item */
443             if (curEntry) {
444                 /* thread this guy on the list */
445                 curEntry->next = adir->entries;
446                 adir->entries = curEntry;
447                 curEntry = 0;
448             }
449             curEntry =
450                 (struct afsconf_entry *)malloc(sizeof(struct afsconf_entry));
451             memset(curEntry, 0, sizeof(struct afsconf_entry));
452             code =
453                 ParseCellLine(tbuffer, curEntry->cellInfo.name, linkedcell);
454             if (code) {
455                 afsconf_CloseInternal(adir);
456                 fclose(tf);
457                 return -1;
458             }
459             if (linkedcell[0] != '\0') {
460                 curEntry->cellInfo.linkedCell =
461                     (char *)malloc(strlen(linkedcell) + 1);
462                 strcpy(curEntry->cellInfo.linkedCell, linkedcell);
463             }
464         } else {
465             /* new host in the current cell */
466             if (!curEntry) {
467                 afsconf_CloseInternal(adir);
468                 fclose(tf);
469                 return -1;
470             }
471             i = curEntry->cellInfo.numServers;
472             if (cell && !strcmp(cell, curEntry->cellInfo.name))
473                 code =
474                     ParseHostLine(tbuffer, &curEntry->cellInfo.hostAddr[i],
475                                   curEntry->cellInfo.hostName[i], &clones[i]);
476             else
477                 code =
478                     ParseHostLine(tbuffer, &curEntry->cellInfo.hostAddr[i],
479                                   curEntry->cellInfo.hostName[i], 0);
480             if (code) {
481                 if (code == AFSCONF_SYNTAX) {
482                     for (bp = tbuffer; *bp != '\n'; bp++) {     /* Take out the <cr> from the buffer */
483                         if (!*bp)
484                             break;
485                     }
486                     *bp = '\0';
487                     fprintf(stderr,
488                             "Can't properly parse host line \"%s\" in configuration file %s\n",
489                             tbuffer, tbuf1);
490                 }
491                 free(curEntry);
492                 fclose(tf);
493                 afsconf_CloseInternal(adir);
494                 return -1;
495             }
496             curEntry->cellInfo.numServers = ++i;
497         }
498     }
499     fclose(tf);                 /* close the file now */
500
501     /* end the last partially-completed cell */
502     if (curEntry) {
503         curEntry->next = adir->entries;
504         adir->entries = curEntry;
505     }
506
507     /* Read in the alias list */
508     strcompose(tbuffer, 256, adir->name, "/", AFSDIR_CELLALIAS_FILE, NULL);
509
510     tf = fopen(tbuffer, "r");
511     while (tf) {
512         char *aliasPtr;
513
514         tp = fgets(tbuffer, sizeof(tbuffer), tf);
515         if (!tp)
516             break;
517         TrimLine(tbuffer);      /* remove white space */
518
519         if (tbuffer[0] == '\0' || tbuffer[0] == '\n' || tbuffer[0] == '#')
520             continue;           /* empty line */
521
522         tp = tbuffer;
523         while (tp[0] != '\0' && tp[0] != ' ' && tp[0] != '\t')
524             tp++;
525         if (tp[0] == '\0')
526             continue;           /* invalid line */
527
528         while (tp[0] != '\0' && (tp[0] == ' ' || tp[0] == '\t'))
529             0[tp++] = '\0';
530         if (tp[0] == '\0')
531             continue;           /* invalid line */
532
533         aliasPtr = tp;
534         while (tp[0] != '\0' && tp[0] != ' ' && tp[0] != '\t' && tp[0] != '\r'
535                && tp[0] != '\n')
536             tp++;
537         tp[0] = '\0';
538
539         curAlias = malloc(sizeof(*curAlias));
540         memset(curAlias, 0, sizeof(*curAlias));
541
542         strcpy(curAlias->aliasInfo.aliasName, aliasPtr);
543         strcpy(curAlias->aliasInfo.realName, tbuffer);
544
545         curAlias->next = adir->alias_entries;
546         adir->alias_entries = curAlias;
547     }
548
549     if (tf != NULL)
550         fclose(tf);
551     /* now read the fs keys, if possible */
552     adir->keystr = (struct afsconf_keys *)0;
553     afsconf_IntGetKeys(adir);
554
555     return 0;
556 }
557
558 /* parse a line of the form
559  *"128.2.1.3   #hostname" or
560  *"[128.2.1.3]  #hostname" for clones
561  * into the appropriate pieces.  
562  */
563 static int
564 ParseHostLine(char *aline, register struct sockaddr_in *addr, char *aname,
565               char *aclone)
566 {
567     int c1, c2, c3, c4;
568     register afs_int32 code;
569     register char *tp;
570
571     if (*aline == '[') {
572         if (aclone)
573             *aclone = 1;
574         code = sscanf(aline, "[%d.%d.%d.%d] #%s", &c1, &c2, &c3, &c4, aname);
575     } else {
576         if (aclone)
577             *aclone = 0;
578         code = sscanf(aline, "%d.%d.%d.%d #%s", &c1, &c2, &c3, &c4, aname);
579     }
580     if (code != 5)
581         return AFSCONF_SYNTAX;
582     addr->sin_family = AF_INET;
583     addr->sin_port = 0;
584 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
585     addr->sin_len = sizeof(struct sockaddr_in);
586 #endif
587     tp = (char *)&addr->sin_addr;
588     *tp++ = c1;
589     *tp++ = c2;
590     *tp++ = c3;
591     *tp++ = c4;
592     return 0;
593 }
594
595 /* parse a line of the form
596  * ">cellname [linkedcellname] [#comments]"
597  * into the appropriate pieces.
598  */
599 static int
600 ParseCellLine(register char *aline, register char *aname,
601               register char *alname)
602 {
603     register int code;
604     code = sscanf(aline, ">%s %s", aname, alname);
605     if (code == 1)
606         *alname = '\0';
607     if (code == 2) {
608         if (*alname == '#') {
609             *alname = '\0';
610         }
611     }
612     return (code > 0 ? 0 : AFSCONF_SYNTAX);
613 }
614
615 /* call aproc(entry, arock, adir) for all cells.  Proc must return 0, or we'll stop early and return the code it returns */
616 int
617 afsconf_CellApply(struct afsconf_dir *adir,
618                   int (*aproc) (struct afsconf_cell * cell, char *arock,
619                                 struct afsconf_dir * dir), char *arock)
620 {
621     register struct afsconf_entry *tde;
622     register afs_int32 code;
623     LOCK_GLOBAL_MUTEX for (tde = adir->entries; tde; tde = tde->next) {
624         code = (*aproc) (&tde->cellInfo, arock, adir);
625         if (code) {
626             UNLOCK_GLOBAL_MUTEX return code;
627         }
628     }
629     UNLOCK_GLOBAL_MUTEX return 0;
630 }
631
632 /* call aproc(entry, arock, adir) for all cell aliases.
633  * Proc must return 0, or we'll stop early and return the code it returns
634  */
635 int
636 afsconf_CellAliasApply(struct afsconf_dir *adir,
637                        int (*aproc) (struct afsconf_cellalias * alias,
638                                      char *arock, struct afsconf_dir * dir),
639                        char *arock)
640 {
641     register struct afsconf_aliasentry *tde;
642     register afs_int32 code;
643     LOCK_GLOBAL_MUTEX for (tde = adir->alias_entries; tde; tde = tde->next) {
644         code = (*aproc) (&tde->aliasInfo, arock, adir);
645         if (code) {
646             UNLOCK_GLOBAL_MUTEX return code;
647         }
648     }
649     UNLOCK_GLOBAL_MUTEX return 0;
650 }
651
652 afs_int32 afsconf_SawCell = 0;
653
654 int
655 afsconf_GetExtendedCellInfo(struct afsconf_dir *adir, char *acellName,
656                             char *aservice, struct afsconf_cell *acellInfo,
657                             char clones[])
658 {
659     afs_int32 code;
660     char *cell;
661
662     code = afsconf_GetCellInfo(adir, acellName, aservice, acellInfo);
663     if (code)
664         return code;
665
666     if (acellName)
667         cell = acellName;
668     else
669         cell = (char *)&acellInfo->name;
670
671     code = afsconf_OpenInternal(adir, cell, clones);
672     return code;
673 }
674
675 #ifdef AFS_AFSDB_ENV
676 #if !defined(AFS_NT40_ENV)
677 int
678 afsconf_GetAfsdbInfo(char *acellName, char *aservice,
679                      struct afsconf_cell *acellInfo)
680 {
681     afs_int32 code;
682     int tservice, i;
683     size_t len;
684     unsigned char answer[1024];
685     unsigned char *p;
686     char realCellName[256];
687     char host[256];
688     int server_num = 0;
689     int minttl = 0;
690
691     /* The resolver isn't always MT-safe.. Perhaps this ought to be
692      * replaced with a more fine-grained lock just for the resolver
693      * operations.
694      */
695     LOCK_GLOBAL_MUTEX len =
696         res_search(acellName, C_IN, T_AFSDB, answer, sizeof(answer));
697     UNLOCK_GLOBAL_MUTEX if (len < 0)
698           return AFSCONF_NOTFOUND;
699
700     p = answer + sizeof(HEADER);        /* Skip header */
701     code = dn_expand(answer, answer + len, p, host, sizeof(host));
702     if (code < 0)
703         return AFSCONF_NOTFOUND;
704
705     p += code + QFIXEDSZ;       /* Skip name */
706
707     while (p < answer + len) {
708         int type, ttl, size;
709
710         code = dn_expand(answer, answer + len, p, host, sizeof(host));
711         if (code < 0)
712             return AFSCONF_NOTFOUND;
713
714         p += code;              /* Skip the name */
715         type = (p[0] << 8) | p[1];
716         p += 4;                 /* Skip type and class */
717         ttl = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
718         p += 4;                 /* Skip the TTL */
719         size = (p[0] << 8) | p[1];
720         p += 2;                 /* Skip the size */
721
722         if (type == T_AFSDB) {
723             struct hostent *he;
724             short afsdb_type;
725
726             afsdb_type = (p[0] << 8) | p[1];
727             if (afsdb_type == 1) {
728                 /*
729                  * We know this is an AFSDB record for our cell, of the
730                  * right AFSDB type.  Write down the true cell name that
731                  * the resolver gave us above.
732                  */
733                 strcpy(realCellName, host);
734             }
735
736             code = dn_expand(answer, answer + len, p + 2, host, sizeof(host));
737             if (code < 0)
738                 return AFSCONF_NOTFOUND;
739
740             if ((afsdb_type == 1) && (server_num < MAXHOSTSPERCELL) &&
741                 /* Do we want to get TTL data for the A record as well? */
742                 (he = gethostbyname(host))) {
743                 afs_int32 ipaddr;
744                 memcpy(&ipaddr, he->h_addr, he->h_length);
745                 acellInfo->hostAddr[server_num].sin_addr.s_addr = ipaddr;
746                 strncpy(acellInfo->hostName[server_num], host,
747                         sizeof(acellInfo->hostName[server_num]));
748                 server_num++;
749
750                 if (!minttl || ttl < minttl)
751                     minttl = ttl;
752             }
753         }
754
755         p += size;
756     }
757
758     if (server_num == 0)        /* No AFSDB records */
759         return AFSCONF_NOTFOUND;
760
761     /* Convert the real cell name to lowercase */
762     for (p = (unsigned char *)realCellName; *p; p++)
763         *p = tolower(*p);
764
765     strncpy(acellInfo->name, realCellName, sizeof(acellInfo->name));
766     acellInfo->numServers = server_num;
767
768     if (aservice) {
769         tservice = afsconf_FindService(aservice);
770         if (tservice < 0)
771             return AFSCONF_NOTFOUND;    /* service not found */
772         for (i = 0; i < acellInfo->numServers; i++) {
773             acellInfo->hostAddr[i].sin_port = tservice;
774         }
775     }
776
777     acellInfo->timeout = minttl ? (time(0) + minttl) : 0;
778
779     return 0;
780 }
781 #else /* windows */
782 int
783 afsconf_GetAfsdbInfo(char *acellName, char *aservice,
784                      struct afsconf_cell *acellInfo)
785 {
786     register afs_int32 i;
787     int tservice;
788     struct afsconf_entry DNSce;
789     afs_int32 cellHosts[AFSMAXCELLHOSTS];
790     int numServers;
791     int rc;
792     int ttl;
793
794     DNSce.cellInfo.numServers = 0;
795     DNSce.next = NULL;
796     rc = getAFSServer(acellName, cellHosts, &numServers, &ttl);
797     /* ignore the ttl here since this code is only called by transitory programs
798      * like klog, etc. */
799     if (rc < 0)
800         return -1;
801     if (numServers == 0)
802         return -1;
803
804     for (i = 0; i < numServers; i++) {
805         memcpy(&acellInfo->hostAddr[i].sin_addr.s_addr, &cellHosts[i],
806                sizeof(long));
807         acellInfo->hostAddr[i].sin_family = AF_INET;
808
809         /* sin_port supplied by connection code */
810     }
811
812     acellInfo->numServers = numServers;
813     strcpy(acellInfo->name, acellName);
814     if (aservice) {
815         LOCK_GLOBAL_MUTEX tservice = afsconf_FindService(aservice);
816         UNLOCK_GLOBAL_MUTEX if (tservice < 0) {
817             return AFSCONF_NOTFOUND;    /* service not found */
818         }
819         for (i = 0; i < acellInfo->numServers; i++) {
820             acellInfo->hostAddr[i].sin_port = tservice;
821         }
822     }
823     acellInfo->linkedCell = NULL;       /* no linked cell */
824     acellInfo->flags = 0;
825     return 0;
826 }
827 #endif /* windows */
828 #endif /* AFS_AFSDB_ENV */
829
830 int
831 afsconf_GetCellInfo(struct afsconf_dir *adir, char *acellName, char *aservice,
832                     struct afsconf_cell *acellInfo)
833 {
834     register struct afsconf_entry *tce;
835     struct afsconf_aliasentry *tcae;
836     struct afsconf_entry *bestce;
837     register afs_int32 i;
838     int tservice;
839     char *tcell;
840     size_t cnLen;
841     int ambig;
842     char tbuffer[64];
843
844     LOCK_GLOBAL_MUTEX if (adir)
845           afsconf_Check(adir);
846     if (acellName) {
847         tcell = acellName;
848         cnLen = strlen(tcell) + 1;
849         lcstring(tcell, tcell, cnLen);
850         afsconf_SawCell = 1;    /* will ignore the AFSCELL switch on future */
851         /* call to afsconf_GetLocalCell: like klog  */
852     } else {
853         i = afsconf_GetLocalCell(adir, tbuffer, sizeof(tbuffer));
854         if (i) {
855             UNLOCK_GLOBAL_MUTEX return i;
856         }
857         tcell = tbuffer;
858     }
859     cnLen = strlen(tcell);
860     bestce = (struct afsconf_entry *)0;
861     ambig = 0;
862     if (!adir) {
863         UNLOCK_GLOBAL_MUTEX return 0;
864     }
865
866     /* Look through the list of aliases */
867     for (tcae = adir->alias_entries; tcae; tcae = tcae->next) {
868         if (strcasecmp(tcae->aliasInfo.aliasName, tcell) == 0) {
869             tcell = tcae->aliasInfo.realName;
870             break;
871         }
872     }
873
874     for (tce = adir->entries; tce; tce = tce->next) {
875         if (strcasecmp(tce->cellInfo.name, tcell) == 0) {
876             /* found our cell */
877             bestce = tce;
878             ambig = 0;
879             break;
880         }
881         if (strlen(tce->cellInfo.name) < cnLen)
882             continue;           /* clearly wrong */
883         if (strncasecmp(tce->cellInfo.name, tcell, cnLen) == 0) {
884             if (bestce)
885                 ambig = 1;      /* ambiguous unless we get exact match */
886             bestce = tce;
887         }
888     }
889     if (!ambig && bestce && bestce->cellInfo.numServers) {
890         *acellInfo = bestce->cellInfo;  /* structure assignment */
891         if (aservice) {
892             tservice = afsconf_FindService(aservice);
893             if (tservice < 0) {
894                 UNLOCK_GLOBAL_MUTEX return AFSCONF_NOTFOUND;    /* service not found */
895             }
896             for (i = 0; i < acellInfo->numServers; i++) {
897                 acellInfo->hostAddr[i].sin_port = tservice;
898             }
899         }
900         acellInfo->timeout = 0;
901         UNLOCK_GLOBAL_MUTEX return 0;
902     } else {
903         UNLOCK_GLOBAL_MUTEX
904 #ifdef AFS_AFSDB_ENV
905             return afsconf_GetAfsdbInfo(tcell, aservice, acellInfo);
906 #else
907             return AFSCONF_NOTFOUND;
908 #endif /* AFS_AFSDB_ENV */
909     }
910 }
911
912 int
913 afsconf_GetLocalCell(register struct afsconf_dir *adir, char *aname,
914                      afs_int32 alen)
915 {
916     static int afsconf_showcell = 0;
917     char *afscell_path;
918     afs_int32 code = 0;
919
920     LOCK_GLOBAL_MUTEX
921         /*
922          * If a cell switch was specified in a command, then it should override the 
923          * AFSCELL variable.  If a cell was specified, then the afsconf_SawCell flag
924          * is set and the cell name in the adir structure is used.
925          * Read the AFSCELL var each time: in case it changes (unsetenv AFSCELL).
926          */
927         if (!afsconf_SawCell && (afscell_path = getenv("AFSCELL"))) {
928         if (!afsconf_showcell) {
929             fprintf(stderr, "Note: Operation is performed on cell %s\n",
930                     afscell_path);
931             afsconf_showcell = 1;
932         }
933         strncpy(aname, afscell_path, alen);
934     } else {
935         afsconf_Check(adir);
936         if (adir->cellName) {
937             strncpy(aname, adir->cellName, alen);
938         } else
939             code = AFSCONF_UNKNOWN;
940     }
941
942     UNLOCK_GLOBAL_MUTEX return (code);
943 }
944
945 int
946 afsconf_Close(struct afsconf_dir *adir)
947 {
948     LOCK_GLOBAL_MUTEX afsconf_CloseInternal(adir);
949     if (adir->name)
950         free(adir->name);
951     free(adir);
952     UNLOCK_GLOBAL_MUTEX return 0;
953 }
954
955 static int
956 afsconf_CloseInternal(register struct afsconf_dir *adir)
957 {
958     register struct afsconf_entry *td, *nd;
959     struct afsconf_aliasentry *ta, *na;
960     register char *tname;
961
962     tname = adir->name;         /* remember name, since that's all we preserve */
963
964     /* free everything we can find */
965     if (adir->cellName)
966         free(adir->cellName);
967     for (td = adir->entries; td; td = nd) {
968         nd = td->next;
969         if (td->cellInfo.linkedCell)
970             free(td->cellInfo.linkedCell);
971         free(td);
972     }
973     for (ta = adir->alias_entries; ta; ta = na) {
974         na = ta->next;
975         free(ta);
976     }
977     if (adir->keystr)
978         free(adir->keystr);
979
980     /* reinit */
981     memset(adir, 0, sizeof(struct afsconf_dir));
982     adir->name = tname;         /* restore it */
983     return 0;
984 }
985
986 static int
987 afsconf_Reopen(register struct afsconf_dir *adir)
988 {
989     register afs_int32 code;
990     code = afsconf_CloseInternal(adir);
991     if (code)
992         return code;
993     code = afsconf_OpenInternal(adir, 0, 0);
994     return code;
995 }
996
997 /* called during opening of config file */
998 int
999 afsconf_IntGetKeys(struct afsconf_dir *adir)
1000 {
1001     char tbuffer[256];
1002     register int fd;
1003     struct afsconf_keys *tstr;
1004     register afs_int32 code;
1005
1006 #ifdef AFS_NT40_ENV
1007     /* NT client config dir has no KeyFile; don't risk attempting open
1008      * because there might be a random file of this name if dir is shared.
1009      */
1010     if (IsClientConfigDirectory(adir->name)) {
1011         adir->keystr = ((struct afsconf_keys *)
1012                         malloc(sizeof(struct afsconf_keys)));
1013         adir->keystr->nkeys = 0;
1014         return 0;
1015     }
1016 #endif /* AFS_NT40_ENV */
1017
1018     LOCK_GLOBAL_MUTEX
1019         /* compute the key name and other setup */
1020         strcompose(tbuffer, 256, adir->name, "/", AFSDIR_KEY_FILE, NULL);
1021     tstr = (struct afsconf_keys *)malloc(sizeof(struct afsconf_keys));
1022     adir->keystr = tstr;
1023
1024     /* read key file */
1025     fd = open(tbuffer, O_RDONLY);
1026     if (fd < 0) {
1027         tstr->nkeys = 0;
1028         UNLOCK_GLOBAL_MUTEX return 0;
1029     }
1030     code = read(fd, tstr, sizeof(struct afsconf_keys));
1031     close(fd);
1032     if (code < sizeof(afs_int32)) {
1033         tstr->nkeys = 0;
1034         UNLOCK_GLOBAL_MUTEX return 0;
1035     }
1036
1037     /* convert key structure to host order */
1038     tstr->nkeys = ntohl(tstr->nkeys);
1039     for (fd = 0; fd < tstr->nkeys; fd++)
1040         tstr->key[fd].kvno = ntohl(tstr->key[fd].kvno);
1041
1042     UNLOCK_GLOBAL_MUTEX return 0;
1043 }
1044
1045 /* get keys structure */
1046 int
1047 afsconf_GetKeys(struct afsconf_dir *adir, struct afsconf_keys *astr)
1048 {
1049     register afs_int32 code;
1050
1051     LOCK_GLOBAL_MUTEX code = afsconf_Check(adir);
1052     if (code) {
1053         UNLOCK_GLOBAL_MUTEX return AFSCONF_FAILURE;
1054     }
1055     memcpy(astr, adir->keystr, sizeof(struct afsconf_keys));
1056     UNLOCK_GLOBAL_MUTEX return 0;
1057 }
1058
1059 /* get latest key */
1060 afs_int32
1061 afsconf_GetLatestKey(struct afsconf_dir * adir, afs_int32 * avno, char *akey)
1062 {
1063     register int i;
1064     int maxa;
1065     register struct afsconf_key *tk;
1066     register afs_int32 best;
1067     struct afsconf_key *bestk;
1068     register afs_int32 code;
1069
1070     LOCK_GLOBAL_MUTEX code = afsconf_Check(adir);
1071     if (code) {
1072         UNLOCK_GLOBAL_MUTEX return AFSCONF_FAILURE;
1073     }
1074     maxa = adir->keystr->nkeys;
1075
1076     best = -1;                  /* highest kvno we've seen yet */
1077     bestk = (struct afsconf_key *)0;    /* ptr to structure providing best */
1078     for (tk = adir->keystr->key, i = 0; i < maxa; i++, tk++) {
1079         if (tk->kvno == 999)
1080             continue;           /* skip bcrypt keys */
1081         if (tk->kvno > best) {
1082             best = tk->kvno;
1083             bestk = tk;
1084         }
1085     }
1086     if (bestk) {                /* found any  */
1087         if (akey)
1088             memcpy(akey, bestk->key, 8);        /* copy out latest key */
1089         if (avno)
1090             *avno = bestk->kvno;        /* and kvno to caller */
1091         UNLOCK_GLOBAL_MUTEX return 0;
1092     }
1093     UNLOCK_GLOBAL_MUTEX return AFSCONF_NOTFOUND;        /* didn't find any keys */
1094 }
1095
1096 /* get a particular key */
1097 int
1098 afsconf_GetKey(struct afsconf_dir *adir, afs_int32 avno, char *akey)
1099 {
1100     register int i, maxa;
1101     register struct afsconf_key *tk;
1102     register afs_int32 code;
1103
1104     LOCK_GLOBAL_MUTEX code = afsconf_Check(adir);
1105     if (code) {
1106         UNLOCK_GLOBAL_MUTEX return AFSCONF_FAILURE;
1107     }
1108     maxa = adir->keystr->nkeys;
1109
1110     for (tk = adir->keystr->key, i = 0; i < maxa; i++, tk++) {
1111         if (tk->kvno == avno) {
1112             memcpy(akey, tk->key, 8);
1113             UNLOCK_GLOBAL_MUTEX return 0;
1114         }
1115     }
1116
1117     UNLOCK_GLOBAL_MUTEX return AFSCONF_NOTFOUND;
1118 }
1119
1120 /* save the key structure in the appropriate file */
1121 static int
1122 SaveKeys(struct afsconf_dir *adir)
1123 {
1124     struct afsconf_keys tkeys;
1125     register int fd;
1126     register afs_int32 i;
1127     char tbuffer[256];
1128
1129     memcpy(&tkeys, adir->keystr, sizeof(struct afsconf_keys));
1130
1131     /* convert it to net byte order */
1132     for (i = 0; i < tkeys.nkeys; i++)
1133         tkeys.key[i].kvno = htonl(tkeys.key[i].kvno);
1134     tkeys.nkeys = htonl(tkeys.nkeys);
1135
1136     /* rewrite keys file */
1137     strcompose(tbuffer, 256, adir->name, "/", AFSDIR_KEY_FILE, NULL);
1138     fd = open(tbuffer, O_RDWR | O_CREAT | O_TRUNC, 0600);
1139     if (fd < 0)
1140         return AFSCONF_FAILURE;
1141     i = write(fd, &tkeys, sizeof(tkeys));
1142     if (i != sizeof(tkeys)) {
1143         close(fd);
1144         return AFSCONF_FAILURE;
1145     }
1146     if (close(fd) < 0)
1147         return AFSCONF_FAILURE;
1148     return 0;
1149 }
1150
1151 int
1152 afsconf_AddKey(struct afsconf_dir *adir, afs_int32 akvno, char akey[8],
1153                afs_int32 overwrite)
1154 {
1155     register struct afsconf_keys *tk;
1156     register struct afsconf_key *tkey;
1157     register afs_int32 i;
1158     int foundSlot;
1159
1160     LOCK_GLOBAL_MUTEX tk = adir->keystr;
1161
1162     if (akvno != 999) {
1163         if (akvno < 0 || akvno > 255) {
1164             UNLOCK_GLOBAL_MUTEX return ERANGE;
1165         }
1166     }
1167     foundSlot = 0;
1168     for (i = 0, tkey = tk->key; i < tk->nkeys; i++, tkey++) {
1169         if (tkey->kvno == akvno) {
1170             if (!overwrite) {
1171                 UNLOCK_GLOBAL_MUTEX return AFSCONF_KEYINUSE;
1172             }
1173             foundSlot = 1;
1174             break;
1175         }
1176     }
1177     if (!foundSlot) {
1178         if (tk->nkeys >= AFSCONF_MAXKEYS) {
1179             UNLOCK_GLOBAL_MUTEX return AFSCONF_FULL;
1180         }
1181         tkey = &tk->key[tk->nkeys++];
1182     }
1183     tkey->kvno = akvno;
1184     memcpy(tkey->key, akey, 8);
1185     i = SaveKeys(adir);
1186     afsconf_Touch(adir);
1187     UNLOCK_GLOBAL_MUTEX return i;
1188 }
1189
1190 /* this proc works by sliding the other guys down, rather than using a funny
1191     kvno value, so that callers can count on getting a good key in key[0].
1192 */
1193 int
1194 afsconf_DeleteKey(struct afsconf_dir *adir, afs_int32 akvno)
1195 {
1196     register struct afsconf_keys *tk;
1197     register struct afsconf_key *tkey;
1198     register int i;
1199     int foundFlag = 0;
1200
1201     LOCK_GLOBAL_MUTEX tk = adir->keystr;
1202
1203     for (i = 0, tkey = tk->key; i < tk->nkeys; i++, tkey++) {
1204         if (tkey->kvno == akvno) {
1205             foundFlag = 1;
1206             break;
1207         }
1208     }
1209     if (!foundFlag) {
1210         UNLOCK_GLOBAL_MUTEX return AFSCONF_NOTFOUND;
1211     }
1212
1213     /* otherwise slide the others down.  i and tkey point at the guy to delete */
1214     for (; i < tk->nkeys - 1; i++, tkey++) {
1215         tkey->kvno = (tkey + 1)->kvno;
1216         memcpy(tkey->key, (tkey + 1)->key, 8);
1217     }
1218     tk->nkeys--;
1219     i = SaveKeys(adir);
1220     afsconf_Touch(adir);
1221     UNLOCK_GLOBAL_MUTEX return i;
1222 }