cellconfig-make-nkeys-littleendian-20051107
[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;
740     size_t len;
741     unsigned char answer[1024];
742     unsigned char *p;
743     char *dotcellname;
744     int cellnamelength;
745     char realCellName[256];
746     char host[256];
747     int server_num = 0;
748     int minttl = 0;
749
750     /* The resolver isn't always MT-safe.. Perhaps this ought to be
751      * replaced with a more fine-grained lock just for the resolver
752      * operations.
753      */
754
755     if ( ! strchr(acellName,'.') ) {
756        cellnamelength=strlen(acellName);
757        dotcellname=malloc(cellnamelength+2);
758        memcpy(dotcellname,acellName,cellnamelength);
759        dotcellname[cellnamelength]='.';
760        dotcellname[cellnamelength+1]=0;
761        LOCK_GLOBAL_MUTEX;
762             len = res_search(dotcellname, C_IN, T_AFSDB, answer, sizeof(answer));
763        if ( len < 0 ) {
764           len = res_search(acellName, C_IN, T_AFSDB, answer, sizeof(answer));
765        }
766        UNLOCK_GLOBAL_MUTEX;
767        free(dotcellname);
768     } else {
769        LOCK_GLOBAL_MUTEX;
770             len = res_search(acellName, C_IN, T_AFSDB, answer, sizeof(answer));
771        UNLOCK_GLOBAL_MUTEX;
772     }
773     if (len < 0)
774         return AFSCONF_NOTFOUND;
775
776     p = answer + sizeof(HEADER);        /* Skip header */
777     code = dn_expand(answer, answer + len, p, host, sizeof(host));
778     if (code < 0)
779         return AFSCONF_NOTFOUND;
780
781     p += code + QFIXEDSZ;       /* Skip name */
782
783     while (p < answer + len) {
784         int type, ttl, size;
785
786         code = dn_expand(answer, answer + len, p, host, sizeof(host));
787         if (code < 0)
788             return AFSCONF_NOTFOUND;
789
790         p += code;              /* Skip the name */
791         type = (p[0] << 8) | p[1];
792         p += 4;                 /* Skip type and class */
793         ttl = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
794         p += 4;                 /* Skip the TTL */
795         size = (p[0] << 8) | p[1];
796         p += 2;                 /* Skip the size */
797
798         if (type == T_AFSDB) {
799             struct hostent *he;
800             short afsdb_type;
801
802             afsdb_type = (p[0] << 8) | p[1];
803             if (afsdb_type == 1) {
804                 /*
805                  * We know this is an AFSDB record for our cell, of the
806                  * right AFSDB type.  Write down the true cell name that
807                  * the resolver gave us above.
808                  */
809                 strcpy(realCellName, host);
810             }
811
812             code = dn_expand(answer, answer + len, p + 2, host, sizeof(host));
813             if (code < 0)
814                 return AFSCONF_NOTFOUND;
815
816             if ((afsdb_type == 1) && (server_num < MAXHOSTSPERCELL) &&
817                 /* Do we want to get TTL data for the A record as well? */
818                 (he = gethostbyname(host))) {
819                 afs_int32 ipaddr;
820                 memcpy(&ipaddr, he->h_addr, he->h_length);
821                 acellInfo->hostAddr[server_num].sin_addr.s_addr = ipaddr;
822                 strncpy(acellInfo->hostName[server_num], host,
823                         sizeof(acellInfo->hostName[server_num]));
824                 server_num++;
825
826                 if (!minttl || ttl < minttl)
827                     minttl = ttl;
828             }
829         }
830
831         p += size;
832     }
833
834     if (server_num == 0)        /* No AFSDB records */
835         return AFSCONF_NOTFOUND;
836
837     /* Convert the real cell name to lowercase */
838     for (p = (unsigned char *)realCellName; *p; p++)
839         *p = tolower(*p);
840
841     strncpy(acellInfo->name, realCellName, sizeof(acellInfo->name));
842     acellInfo->numServers = server_num;
843
844     if (aservice) {
845         tservice = afsconf_FindService(aservice);
846         if (tservice < 0)
847             return AFSCONF_NOTFOUND;    /* service not found */
848         for (i = 0; i < acellInfo->numServers; i++) {
849             acellInfo->hostAddr[i].sin_port = tservice;
850         }
851     }
852
853     acellInfo->timeout = minttl ? (time(0) + minttl) : 0;
854
855     return 0;
856 }
857 #else /* windows */
858 int
859 afsconf_GetAfsdbInfo(char *acellName, char *aservice,
860                      struct afsconf_cell *acellInfo)
861 {
862     register afs_int32 i;
863     int tservice;
864     struct afsconf_entry DNSce;
865     afs_int32 cellHostAddrs[AFSMAXCELLHOSTS];
866     char cellHostNames[AFSMAXCELLHOSTS][MAXHOSTCHARS];
867     int numServers;
868     int rc;
869     int ttl;
870
871     DNSce.cellInfo.numServers = 0;
872     DNSce.next = NULL;
873     rc = getAFSServer(acellName, cellHostAddrs, cellHostNames, &numServers,
874                       &ttl);
875     /* ignore the ttl here since this code is only called by transitory programs
876      * like klog, etc. */
877     if (rc < 0)
878         return -1;
879     if (numServers == 0)
880         return -1;
881
882     for (i = 0; i < numServers; i++) {
883         memcpy(&acellInfo->hostAddr[i].sin_addr.s_addr, &cellHostAddrs[i],
884                sizeof(long));
885         memcpy(acellInfo->hostName[i], cellHostNames[i], MAXHOSTCHARS);
886         acellInfo->hostAddr[i].sin_family = AF_INET;
887
888         /* sin_port supplied by connection code */
889     }
890
891     acellInfo->numServers = numServers;
892     strcpy(acellInfo->name, acellName);
893     if (aservice) {
894         LOCK_GLOBAL_MUTEX;
895         tservice = afsconf_FindService(aservice);
896         UNLOCK_GLOBAL_MUTEX;
897         if (tservice < 0) {
898             return AFSCONF_NOTFOUND;    /* service not found */
899         }
900         for (i = 0; i < acellInfo->numServers; i++) {
901             acellInfo->hostAddr[i].sin_port = tservice;
902         }
903     }
904     acellInfo->linkedCell = NULL;       /* no linked cell */
905     acellInfo->flags = 0;
906     return 0;
907 }
908 #endif /* windows */
909 #endif /* AFS_AFSDB_ENV */
910
911 int
912 afsconf_GetCellInfo(struct afsconf_dir *adir, char *acellName, char *aservice,
913                     struct afsconf_cell *acellInfo)
914 {
915     register struct afsconf_entry *tce;
916     struct afsconf_aliasentry *tcae;
917     struct afsconf_entry *bestce;
918     register afs_int32 i;
919     int tservice;
920     char *tcell;
921     int cnLen;
922     int ambig;
923     char tbuffer[64];
924
925     LOCK_GLOBAL_MUTEX;
926     if (adir)
927         afsconf_Check(adir);
928     if (acellName) {
929         tcell = acellName;
930         cnLen = (int)(strlen(tcell) + 1);
931         lcstring(tcell, tcell, cnLen);
932         afsconf_SawCell = 1;    /* will ignore the AFSCELL switch on future */
933         /* call to afsconf_GetLocalCell: like klog  */
934     } else {
935         i = afsconf_GetLocalCell(adir, tbuffer, sizeof(tbuffer));
936         if (i) {
937             UNLOCK_GLOBAL_MUTEX;
938             return i;
939         }
940         tcell = tbuffer;
941     }
942     cnLen = strlen(tcell);
943     bestce = (struct afsconf_entry *)0;
944     ambig = 0;
945     if (!adir) {
946         UNLOCK_GLOBAL_MUTEX;
947         return 0;
948     }
949
950     /* Look through the list of aliases */
951     for (tcae = adir->alias_entries; tcae; tcae = tcae->next) {
952         if (strcasecmp(tcae->aliasInfo.aliasName, tcell) == 0) {
953             tcell = tcae->aliasInfo.realName;
954             break;
955         }
956     }
957
958     for (tce = adir->entries; tce; tce = tce->next) {
959         if (strcasecmp(tce->cellInfo.name, tcell) == 0) {
960             /* found our cell */
961             bestce = tce;
962             ambig = 0;
963             break;
964         }
965         if (strlen(tce->cellInfo.name) < cnLen)
966             continue;           /* clearly wrong */
967         if (strncasecmp(tce->cellInfo.name, tcell, cnLen) == 0) {
968             if (bestce)
969                 ambig = 1;      /* ambiguous unless we get exact match */
970             bestce = tce;
971         }
972     }
973     if (!ambig && bestce && bestce->cellInfo.numServers) {
974         *acellInfo = bestce->cellInfo;  /* structure assignment */
975         if (aservice) {
976             tservice = afsconf_FindService(aservice);
977             if (tservice < 0) {
978                 UNLOCK_GLOBAL_MUTEX;
979                 return AFSCONF_NOTFOUND;        /* service not found */
980             }
981             for (i = 0; i < acellInfo->numServers; i++) {
982                 acellInfo->hostAddr[i].sin_port = tservice;
983             }
984         }
985         acellInfo->timeout = 0;
986         UNLOCK_GLOBAL_MUTEX;
987         return 0;
988     } else {
989         UNLOCK_GLOBAL_MUTEX;
990 #ifdef AFS_AFSDB_ENV
991         return afsconf_GetAfsdbInfo(tcell, aservice, acellInfo);
992 #else
993         return AFSCONF_NOTFOUND;
994 #endif /* AFS_AFSDB_ENV */
995     }
996 }
997
998 int
999 afsconf_GetLocalCell(register struct afsconf_dir *adir, char *aname,
1000                      afs_int32 alen)
1001 {
1002     static int afsconf_showcell = 0;
1003     char *afscell_path;
1004     afs_int32 code = 0;
1005
1006     LOCK_GLOBAL_MUTEX;
1007     /*
1008      * If a cell switch was specified in a command, then it should override the 
1009      * AFSCELL variable.  If a cell was specified, then the afsconf_SawCell flag
1010      * is set and the cell name in the adir structure is used.
1011      * Read the AFSCELL var each time: in case it changes (unsetenv AFSCELL).
1012      */
1013     if (!afsconf_SawCell && (afscell_path = getenv("AFSCELL"))) {
1014         if (!afsconf_showcell) {
1015             fprintf(stderr, "Note: Operation is performed on cell %s\n",
1016                     afscell_path);
1017             afsconf_showcell = 1;
1018         }
1019         strncpy(aname, afscell_path, alen);
1020     } else {
1021         afsconf_Check(adir);
1022         if (adir->cellName) {
1023             strncpy(aname, adir->cellName, alen);
1024         } else
1025             code = AFSCONF_UNKNOWN;
1026     }
1027
1028     UNLOCK_GLOBAL_MUTEX;
1029     return (code);
1030 }
1031
1032 int
1033 afsconf_Close(struct afsconf_dir *adir)
1034 {
1035     LOCK_GLOBAL_MUTEX;
1036     afsconf_CloseInternal(adir);
1037     if (adir->name)
1038         free(adir->name);
1039     free(adir);
1040     UNLOCK_GLOBAL_MUTEX;
1041     return 0;
1042 }
1043
1044 static int
1045 afsconf_CloseInternal(register struct afsconf_dir *adir)
1046 {
1047     register struct afsconf_entry *td, *nd;
1048     struct afsconf_aliasentry *ta, *na;
1049     register char *tname;
1050
1051     tname = adir->name;         /* remember name, since that's all we preserve */
1052
1053     /* free everything we can find */
1054     if (adir->cellName)
1055         free(adir->cellName);
1056     for (td = adir->entries; td; td = nd) {
1057         nd = td->next;
1058         if (td->cellInfo.linkedCell)
1059             free(td->cellInfo.linkedCell);
1060         free(td);
1061     }
1062     for (ta = adir->alias_entries; ta; ta = na) {
1063         na = ta->next;
1064         free(ta);
1065     }
1066     if (adir->keystr)
1067         free(adir->keystr);
1068
1069     /* reinit */
1070     memset(adir, 0, sizeof(struct afsconf_dir));
1071     adir->name = tname;         /* restore it */
1072     return 0;
1073 }
1074
1075 static int
1076 afsconf_Reopen(register struct afsconf_dir *adir)
1077 {
1078     register afs_int32 code;
1079     code = afsconf_CloseInternal(adir);
1080     if (code)
1081         return code;
1082     code = afsconf_OpenInternal(adir, 0, 0);
1083     return code;
1084 }
1085
1086 /* called during opening of config file */
1087 int
1088 afsconf_IntGetKeys(struct afsconf_dir *adir)
1089 {
1090     char tbuffer[256];
1091     register int fd;
1092     struct afsconf_keys *tstr;
1093     register afs_int32 code;
1094
1095 #ifdef AFS_NT40_ENV
1096     /* NT client config dir has no KeyFile; don't risk attempting open
1097      * because there might be a random file of this name if dir is shared.
1098      */
1099     if (IsClientConfigDirectory(adir->name)) {
1100         adir->keystr = ((struct afsconf_keys *)
1101                         malloc(sizeof(struct afsconf_keys)));
1102         adir->keystr->nkeys = 0;
1103         return 0;
1104     }
1105 #endif /* AFS_NT40_ENV */
1106
1107     LOCK_GLOBAL_MUTEX;
1108     /* compute the key name and other setup */
1109     strcompose(tbuffer, 256, adir->name, "/", AFSDIR_KEY_FILE, NULL);
1110     tstr = (struct afsconf_keys *)malloc(sizeof(struct afsconf_keys));
1111     adir->keystr = tstr;
1112
1113     /* read key file */
1114     fd = open(tbuffer, O_RDONLY);
1115     if (fd < 0) {
1116         tstr->nkeys = 0;
1117         UNLOCK_GLOBAL_MUTEX;
1118         return 0;
1119     }
1120     code = read(fd, tstr, sizeof(struct afsconf_keys));
1121     close(fd);
1122     if (code < sizeof(afs_int32)) {
1123         tstr->nkeys = 0;
1124         UNLOCK_GLOBAL_MUTEX;
1125         return 0;
1126     }
1127
1128     /* convert key structure to host order */
1129     tstr->nkeys = ntohl(tstr->nkeys);
1130
1131     if (code < sizeof(afs_int32) + (tstr->nkeys*sizeof(struct afsconf_key))) {
1132         tstr->nkeys = 0;
1133         UNLOCK_GLOBAL_MUTEX;
1134         return 0;
1135     }
1136
1137     for (fd = 0; fd < tstr->nkeys; fd++)
1138         tstr->key[fd].kvno = ntohl(tstr->key[fd].kvno);
1139
1140     UNLOCK_GLOBAL_MUTEX;
1141     return 0;
1142 }
1143
1144 /* get keys structure */
1145 int
1146 afsconf_GetKeys(struct afsconf_dir *adir, struct afsconf_keys *astr)
1147 {
1148     register afs_int32 code;
1149
1150     LOCK_GLOBAL_MUTEX;
1151     code = afsconf_Check(adir);
1152     if (code) {
1153         UNLOCK_GLOBAL_MUTEX;
1154         return AFSCONF_FAILURE;
1155     }
1156     memcpy(astr, adir->keystr, sizeof(struct afsconf_keys));
1157     UNLOCK_GLOBAL_MUTEX;
1158     return 0;
1159 }
1160
1161 /* get latest key */
1162 afs_int32
1163 afsconf_GetLatestKey(struct afsconf_dir * adir, afs_int32 * avno, char *akey)
1164 {
1165     register int i;
1166     int maxa;
1167     register struct afsconf_key *tk;
1168     register afs_int32 best;
1169     struct afsconf_key *bestk;
1170     register afs_int32 code;
1171
1172     LOCK_GLOBAL_MUTEX;
1173     code = afsconf_Check(adir);
1174     if (code) {
1175         UNLOCK_GLOBAL_MUTEX;
1176         return AFSCONF_FAILURE;
1177     }
1178     maxa = adir->keystr->nkeys;
1179
1180     best = -1;                  /* highest kvno we've seen yet */
1181     bestk = (struct afsconf_key *)0;    /* ptr to structure providing best */
1182     for (tk = adir->keystr->key, i = 0; i < maxa; i++, tk++) {
1183         if (tk->kvno == 999)
1184             continue;           /* skip bcrypt keys */
1185         if (tk->kvno > best) {
1186             best = tk->kvno;
1187             bestk = tk;
1188         }
1189     }
1190     if (bestk) {                /* found any  */
1191         if (akey)
1192             memcpy(akey, bestk->key, 8);        /* copy out latest key */
1193         if (avno)
1194             *avno = bestk->kvno;        /* and kvno to caller */
1195         UNLOCK_GLOBAL_MUTEX;
1196         return 0;
1197     }
1198     UNLOCK_GLOBAL_MUTEX;
1199     return AFSCONF_NOTFOUND;    /* didn't find any keys */
1200 }
1201
1202 /* get a particular key */
1203 int
1204 afsconf_GetKey(struct afsconf_dir *adir, afs_int32 avno, char *akey)
1205 {
1206     register int i, maxa;
1207     register struct afsconf_key *tk;
1208     register afs_int32 code;
1209
1210     LOCK_GLOBAL_MUTEX;
1211     code = afsconf_Check(adir);
1212     if (code) {
1213         UNLOCK_GLOBAL_MUTEX;
1214         return AFSCONF_FAILURE;
1215     }
1216     maxa = adir->keystr->nkeys;
1217
1218     for (tk = adir->keystr->key, i = 0; i < maxa; i++, tk++) {
1219         if (tk->kvno == avno) {
1220             memcpy(akey, tk->key, 8);
1221             UNLOCK_GLOBAL_MUTEX;
1222             return 0;
1223         }
1224     }
1225
1226     UNLOCK_GLOBAL_MUTEX;
1227     return AFSCONF_NOTFOUND;
1228 }
1229
1230 /* save the key structure in the appropriate file */
1231 static int
1232 SaveKeys(struct afsconf_dir *adir)
1233 {
1234     struct afsconf_keys tkeys;
1235     register int fd;
1236     register afs_int32 i;
1237     char tbuffer[256];
1238
1239     memcpy(&tkeys, adir->keystr, sizeof(struct afsconf_keys));
1240
1241     /* convert it to net byte order */
1242     for (i = 0; i < tkeys.nkeys; i++)
1243         tkeys.key[i].kvno = htonl(tkeys.key[i].kvno);
1244     tkeys.nkeys = htonl(tkeys.nkeys);
1245
1246     /* rewrite keys file */
1247     strcompose(tbuffer, 256, adir->name, "/", AFSDIR_KEY_FILE, NULL);
1248     fd = open(tbuffer, O_RDWR | O_CREAT | O_TRUNC, 0600);
1249     if (fd < 0)
1250         return AFSCONF_FAILURE;
1251     i = write(fd, &tkeys, sizeof(tkeys));
1252     if (i != sizeof(tkeys)) {
1253         close(fd);
1254         return AFSCONF_FAILURE;
1255     }
1256     if (close(fd) < 0)
1257         return AFSCONF_FAILURE;
1258     return 0;
1259 }
1260
1261 int
1262 afsconf_AddKey(struct afsconf_dir *adir, afs_int32 akvno, char akey[8],
1263                afs_int32 overwrite)
1264 {
1265     register struct afsconf_keys *tk;
1266     register struct afsconf_key *tkey;
1267     register afs_int32 i;
1268     int foundSlot;
1269
1270     LOCK_GLOBAL_MUTEX;
1271     tk = adir->keystr;
1272
1273     if (akvno != 999) {
1274         if (akvno < 0 || akvno > 255) {
1275             UNLOCK_GLOBAL_MUTEX;
1276             return ERANGE;
1277         }
1278     }
1279     foundSlot = 0;
1280     for (i = 0, tkey = tk->key; i < tk->nkeys; i++, tkey++) {
1281         if (tkey->kvno == akvno) {
1282             if (!overwrite) {
1283                 UNLOCK_GLOBAL_MUTEX;
1284                 return AFSCONF_KEYINUSE;
1285             }
1286             foundSlot = 1;
1287             break;
1288         }
1289     }
1290     if (!foundSlot) {
1291         if (tk->nkeys >= AFSCONF_MAXKEYS) {
1292             UNLOCK_GLOBAL_MUTEX;
1293             return AFSCONF_FULL;
1294         }
1295         tkey = &tk->key[tk->nkeys++];
1296     }
1297     tkey->kvno = akvno;
1298     memcpy(tkey->key, akey, 8);
1299     i = SaveKeys(adir);
1300     afsconf_Touch(adir);
1301     UNLOCK_GLOBAL_MUTEX;
1302     return i;
1303 }
1304
1305 /* this proc works by sliding the other guys down, rather than using a funny
1306     kvno value, so that callers can count on getting a good key in key[0].
1307 */
1308 int
1309 afsconf_DeleteKey(struct afsconf_dir *adir, afs_int32 akvno)
1310 {
1311     register struct afsconf_keys *tk;
1312     register struct afsconf_key *tkey;
1313     register int i;
1314     int foundFlag = 0;
1315
1316     LOCK_GLOBAL_MUTEX;
1317     tk = adir->keystr;
1318
1319     for (i = 0, tkey = tk->key; i < tk->nkeys; i++, tkey++) {
1320         if (tkey->kvno == akvno) {
1321             foundFlag = 1;
1322             break;
1323         }
1324     }
1325     if (!foundFlag) {
1326         UNLOCK_GLOBAL_MUTEX;
1327         return AFSCONF_NOTFOUND;
1328     }
1329
1330     /* otherwise slide the others down.  i and tkey point at the guy to delete */
1331     for (; i < tk->nkeys - 1; i++, tkey++) {
1332         tkey->kvno = (tkey + 1)->kvno;
1333         memcpy(tkey->key, (tkey + 1)->key, 8);
1334     }
1335     tk->nkeys--;
1336     i = SaveKeys(adir);
1337     afsconf_Touch(adir);
1338     UNLOCK_GLOBAL_MUTEX;
1339     return i;
1340 }