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