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