04e35580d8aa35106dbe41df32e7ab829799eb80
[openafs.git] / src / WINNT / afsd / cm_config.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 <windows.h>
11 #include <winsock2.h>
12 #include <stdlib.h>
13 #include <stdio.h>
14 #include <string.h>
15
16 #include "afsd.h"
17 #include <WINNT\afssw.h>
18 #include <WINNT\afsreg.h>
19
20 #include <afs/param.h>
21 #include <afs/stds.h>
22 #include <afs/cellconfig.h>
23
24 #ifdef AFS_AFSDB_ENV
25 #include "cm_dns.h"
26 #include <afs/afsint.h>
27 #endif
28
29 static long cm_ParsePair(char *lineBufferp, char *leftp, char *rightp)
30 {
31     char *tp;
32     char tc;
33     int sawEquals;
34     int sawBracket;
35         
36     sawEquals = 0;
37     sawBracket = 0;
38     for(tp = lineBufferp; *tp; tp++) {
39         tc = *tp;
40
41         if (sawBracket) {
42             if (tc == ']')
43                 sawBracket = 0;
44             continue;
45         }
46
47         /* comment or line end */
48         if (tc == '#' || tc == '\r' || tc == '\n') 
49             break;
50
51         /* square bracket comment -- look for closing delim */
52         if (tc == '[') {
53             sawBracket = 1; 
54             continue;
55         }       
56
57         /* space or tab */
58         if (tc == ' ' || tc == '\t') 
59             continue;
60
61         if (tc == '=') {
62             sawEquals = 1;
63             continue;
64         }
65
66         /* now we have a real character, put it in the appropriate bucket */
67         if (sawEquals == 0) {
68             *leftp++ = tc;
69         }       
70         else {  
71             *rightp++ = tc;
72         }
73     }
74
75     /* null terminate the strings */
76     *leftp = 0;
77     *rightp = 0;
78
79     return 0;   /* and return success */
80 }
81
82 static int
83 IsWindowsModule(const char * name)
84 {
85     const char * p;
86     int i;
87
88     /* Do not perform searches for probable Windows modules */
89     for (p = name, i=0; *p; p++) {
90         if ( *p == '.' )
91             i++;
92     }
93     p = strrchr(name, '.');
94     if (p) {
95         if (i == 1 && 
96             (!cm_stricmp_utf8N(p,".dll") ||
97              !cm_stricmp_utf8N(p,".exe") ||
98              !cm_stricmp_utf8N(p,".ini") ||
99              !cm_stricmp_utf8N(p,".db") ||
100              !cm_stricmp_utf8N(p,".drv")))
101             return 1;
102     }
103     return 0;
104 }
105
106 /* search for a cell, and either return an error code if we don't find it,
107  * or return 0 if we do, in which case we also fill in the addresses in
108  * the cellp field.
109  *
110  * new feature:  we can handle abbreviations and are insensitive to case.
111  * If the caller wants the "real" cell name, it puts a non-null pointer in
112  * newCellNamep.  Anomaly:  if cellNamep is ambiguous, we may modify
113  * newCellNamep but return an error code.
114  *
115  * Linked Cells: the CellServDB format permits linked cells
116  *   >cell [linked-cell] #Description
117  *
118  * newCellNamep and linkedNamep are required to be CELL_MAXNAMELEN in size.
119  */
120 long cm_SearchCellFile(char *cellNamep, char *newCellNamep,
121                        cm_configProc_t *procp, void *rockp)
122 {
123     return cm_SearchCellFileEx(cellNamep, newCellNamep, NULL, procp, rockp);
124 }
125
126 long cm_SearchCellFileEx(char *cellNamep, char *newCellNamep,
127                          char *linkedNamep,
128                          cm_configProc_t *procp, void *rockp)
129 {
130     char wdir[MAX_PATH]="";
131     FILE *tfilep = NULL, *bestp, *tempp;
132     char *tp, *linkp;
133     char lineBuffer[257];
134     struct hostent *thp;
135     char *valuep;
136     struct sockaddr_in vlSockAddr;
137     int inRightCell = 0;
138     int foundCell = 0;
139     long code;
140     int tracking = 1, partial = 0;
141
142     if ( IsWindowsModule(cellNamep) )
143         return -3;
144
145     cm_GetCellServDB(wdir, sizeof(wdir));
146     if (*wdir)
147         tfilep = fopen(wdir, "r");
148
149     if (!tfilep) 
150         return -2;
151
152     bestp = fopen(wdir, "r");
153     
154 #ifdef CELLSERV_DEBUG
155     osi_Log2(afsd_logp,"cm_searchfile fopen handle[%p], wdir[%s]", bestp, 
156              osi_LogSaveString(afsd_logp,wdir));
157 #endif
158     /* have we seen the cell line for the guy we're looking for? */
159     while (1) {
160         linkp = NULL;
161         tp = fgets(lineBuffer, sizeof(lineBuffer), tfilep);
162         if (tracking)
163             (void) fgets(lineBuffer, sizeof(lineBuffer), bestp);
164         if (tp == NULL) {
165             if (feof(tfilep)) {
166                 /* hit EOF */
167                 if (partial) {
168                     /*
169                      * found partial match earlier;
170                      * now go back to it
171                      */
172                     tempp = bestp;
173                     bestp = tfilep;
174                     tfilep = tempp;
175                     inRightCell = 1;
176                     partial = 0;
177                     continue;
178                 }
179                 else {
180                     fclose(tfilep);
181                     fclose(bestp);
182                     return (foundCell? 0 : -3);
183                 }
184             }
185         }       
186
187         /* turn trailing cr or lf into null */
188         tp = strrchr(lineBuffer, '\r');
189         if (tp) *tp = 0;
190         tp = strrchr(lineBuffer, '\n');
191         if (tp) *tp = 0;
192
193         /* skip blank lines */
194         if (lineBuffer[0] == 0) continue;
195
196         /*
197          * The format is:
198          *   >[cell] [linked-cell] #[Description]
199          * where linked-cell and Description are optional
200          */
201         if (lineBuffer[0] == '>') {
202             if (inRightCell) {
203                 fclose(tfilep);
204                 fclose(bestp);
205                 return(foundCell ? 0 : -6);
206             }
207
208             /* 
209              * terminate the cellname at the first white space
210              * leaving 'tp' pointing to the next string if any
211              */
212             for (tp = &lineBuffer[1]; tp && !isspace(*tp); tp++);
213             if (tp) {
214                 *tp = '\0';
215                 for (tp++ ;tp && isspace(*tp); tp++);
216                 if (*tp != '#') {
217                     linkp = tp;
218                     for (; tp && !isspace(*tp); tp++);
219                     if (tp) 
220                         *tp = '\0';
221                 }
222             }
223
224             /* now see if this is the right cell */
225             if (stricmp(lineBuffer+1, cellNamep) == 0) {
226                 /* found the cell we're looking for */
227                 if (newCellNamep) {
228                     strncpy(newCellNamep, lineBuffer+1,CELL_MAXNAMELEN);
229                     newCellNamep[CELL_MAXNAMELEN-1] = '\0';
230                     strlwr(newCellNamep);
231                 }
232                 if (linkedNamep) {
233                     strncpy(linkedNamep, linkp ? linkp : "", CELL_MAXNAMELEN);
234                     linkedNamep[CELL_MAXNAMELEN-1] = '\0';
235                     strlwr(linkedNamep);
236                 }
237                 inRightCell = 1;
238                 tracking = 0;
239 #ifdef CELLSERV_DEBUG                
240                 osi_Log2(afsd_logp, "cm_searchfile is cell inRightCell[%p], linebuffer[%s]",
241                          inRightCell, osi_LogSaveString(afsd_logp,lineBuffer));
242 #endif
243             }
244             else if (cm_stricmp_utf8(lineBuffer+1, cellNamep) == 0) {
245                 /* partial match */
246                 if (partial) {  /* ambiguous */
247                     fclose(tfilep);
248                     fclose(bestp);
249                     return -5;
250                 }
251                 if (newCellNamep) {
252                     strncpy(newCellNamep, lineBuffer+1,CELL_MAXNAMELEN);
253                     newCellNamep[CELL_MAXNAMELEN-1] = '\0';
254                     strlwr(newCellNamep);
255                 }
256                 if (linkedNamep) {
257                     strncpy(linkedNamep, linkp ? linkp : "", CELL_MAXNAMELEN);
258                     linkedNamep[CELL_MAXNAMELEN-1] = '\0';
259                     strlwr(linkedNamep);
260                 }
261                 inRightCell = 0;
262                 tracking = 0;
263                 partial = 1;
264             }
265             else inRightCell = 0;
266         }
267         else {
268             valuep = strchr(lineBuffer, '#');
269             if (valuep == NULL) {
270                 fclose(tfilep);
271                 fclose(bestp);
272                 return -4;
273             }
274             valuep++;   /* skip the "#" */
275
276             valuep += strspn(valuep, " \t"); /* skip SP & TAB */
277             /* strip spaces and tabs in the end. They should not be there according to CellServDB format
278              * so do this just in case                        
279              */
280             while (valuep[strlen(valuep) - 1] == ' ' || valuep[strlen(valuep) - 1] == '\t') 
281                 valuep[strlen(valuep) - 1] = '\0';
282
283             if (inRightCell) {
284                 /* add the server to the VLDB list */
285                 WSASetLastError(0);
286                 thp = gethostbyname(valuep);
287 #ifdef CELLSERV_DEBUG
288                 osi_Log3(afsd_logp,"cm_searchfile inRightCell thp[%p], valuep[%s], WSAGetLastError[%d]",
289                          thp, osi_LogSaveString(afsd_logp,valuep), WSAGetLastError());
290 #endif
291                 if (thp) {
292                     memcpy(&vlSockAddr.sin_addr.s_addr, thp->h_addr,
293                             sizeof(long));
294                     vlSockAddr.sin_family = AF_INET;
295                     /* sin_port supplied by connection code */
296                     if (procp)
297                         (*procp)(rockp, &vlSockAddr, valuep, 0);
298                     foundCell = 1;
299                 }
300                 if (!thp) {
301                     afs_uint32 ip_addr;
302                     unsigned int c1, c2, c3, c4;
303                     
304                     /* Since there is no gethostbyname() data 
305                      * available we will read the IP address
306                      * stored in the CellServDB file
307                      */
308                     code = sscanf(lineBuffer, " %u.%u.%u.%u",
309                                    &c1, &c2, &c3, &c4);
310                     if (code == 4 && c1<256 && c2<256 && c3<256 && c4<256) {
311                         tp = (unsigned char *) &ip_addr;
312                         *tp++ = c1;
313                         *tp++ = c2;
314                         *tp++ = c3;
315                         *tp++ = c4;
316                         memcpy(&vlSockAddr.sin_addr.s_addr, &ip_addr,
317                                 sizeof(long));
318                         vlSockAddr.sin_family = AF_INET;
319                         /* sin_port supplied by connection code */
320                         if (procp)
321                             (*procp)(rockp, &vlSockAddr, valuep, 0);
322                         foundCell = 1;
323                     }
324                 }
325             }
326         }       /* a vldb line */
327     }           /* while loop processing all lines */
328
329     /* if for some unknown reason cell is not found, return negative code (-11) ??? */
330     return (foundCell) ? 0 : -11;
331 }
332
333 /*
334  * The CellServDB registry schema is as follows:
335  *
336  * HKLM\SOFTWARE\OpenAFS\Client\CellServDB\[cellname]\
337  *   "LinkedCell"    REG_SZ "[cellname]" 
338  *   "Description"   REG_SZ "[comment]"
339  *   "ForceDNS"      DWORD  {0,1}
340  *
341  * HKLM\SOFTWARE\OpenAFS\Client\CellServDB\[cellname]\[servername]\
342  *   "HostName"      REG_SZ "[hostname]" 
343  *   "IPv4Address"   REG_SZ "[address]" 
344  *   "IPv6Address"   REG_SZ "[address]"   <future>
345  *   "Comment"       REG_SZ "[comment]"
346  *   "Rank"          DWORD  "0..65535"
347  *   "Clone"         DWORD  "{0,1}"
348  *   "vlserver"      DWORD  "7003"        <future>
349  *   "ptserver"      DWORD  ...           <future>
350  *
351  * ForceDNS is implied non-zero if there are no [servername]
352  * keys under the [cellname] key.  Otherwise, ForceDNS is zero.
353  * If [servername] keys are specified and none of them evaluate
354  * to a valid server configuration, the return code is success.
355  * This prevents failover to the CellServDB file or DNS.
356  */
357 long cm_SearchCellRegistry(afs_uint32 client, 
358                            char *cellNamep, char *newCellNamep,
359                            char *linkedNamep,
360                            cm_configProc_t *procp, void *rockp)
361 {
362     HKEY hkCellServDB = 0, hkCellName = 0, hkServerName = 0;
363     DWORD dwType, dwSize;
364     DWORD dwCells, dwServers, dwForceDNS;
365     DWORD dwIndex, dwRank;
366     unsigned short ipRank;
367     LONG code;
368     FILETIME ftLastWriteTime;
369     char szCellName[CELL_MAXNAMELEN];
370     char szServerName[MAXHOSTCHARS];
371     char szHostName[MAXHOSTCHARS];
372     char szAddr[64];
373     struct hostent *thp;
374     struct sockaddr_in vlSockAddr;
375     char * s;
376
377     if ( IsWindowsModule(cellNamep) )
378         return -1;
379
380     /* No Server CellServDB list (yet) */
381     if ( !client )
382         return CM_ERROR_NOSUCHCELL;
383
384     if (RegOpenKeyEx( HKEY_LOCAL_MACHINE,
385                       AFSREG_CLT_OPENAFS_SUBKEY "\\CellServDB",
386                       0,
387                       KEY_READ|KEY_WRITE|KEY_QUERY_VALUE,
388                       &hkCellServDB) != ERROR_SUCCESS)
389         return CM_ERROR_NOSUCHCELL;
390
391     if (RegOpenKeyEx( hkCellServDB, 
392                       cellNamep,
393                       0,
394                       KEY_READ|KEY_WRITE|KEY_QUERY_VALUE,
395                       &hkCellName) != ERROR_SUCCESS) {
396         BOOL bFound = 0;
397
398         /* We did not find an exact match.  Much search for partial matches. */
399
400         code = RegQueryInfoKey( hkCellServDB,
401                                 NULL,  /* lpClass */
402                                 NULL,  /* lpcClass */
403                                 NULL,  /* lpReserved */
404                                 &dwCells,  /* lpcSubKeys */
405                                 NULL,  /* lpcMaxSubKeyLen */
406                                 NULL,  /* lpcMaxClassLen */
407                                 NULL,  /* lpcValues */
408                                 NULL,  /* lpcMaxValueNameLen */
409                                 NULL,  /* lpcMaxValueLen */
410                                 NULL,  /* lpcbSecurityDescriptor */
411                                 &ftLastWriteTime /* lpftLastWriteTime */
412                                 );
413         if (code != ERROR_SUCCESS)
414             dwCells = 0;
415
416         /* 
417          * We search the entire list to ensure that there is only
418          * one prefix match.  If there is more than one, we return none.
419          */
420         for ( dwIndex = 0; dwIndex < dwCells; dwIndex++ ) {
421             dwSize = CELL_MAXNAMELEN;
422             code = RegEnumKeyEx( hkCellServDB, dwIndex, szCellName, &dwSize, NULL, 
423                                  NULL, NULL, &ftLastWriteTime);
424             if (code != ERROR_SUCCESS)
425                 continue;
426             szCellName[CELL_MAXNAMELEN-1] = '\0';
427             strlwr(szCellName);
428
429             /* if not a prefix match, try the next key */
430             if (strncmp(cellNamep, szCellName, strlen(cellNamep)))
431                 continue;
432
433             /* If we have a prefix match and we already found another
434              * match, return neither */
435             if (hkCellName) {
436                 bFound = 0;
437                 RegCloseKey( hkCellName);
438                 break;
439             }
440
441             if (RegOpenKeyEx( hkCellServDB, 
442                               szCellName,
443                               0,
444                               KEY_READ|KEY_WRITE|KEY_QUERY_VALUE,
445                               &hkCellName) != ERROR_SUCCESS)
446                 continue;
447
448             if (newCellNamep) {
449                 strncpy(newCellNamep, szCellName, CELL_MAXNAMELEN);
450                 newCellNamep[CELL_MAXNAMELEN-1] = '\0';
451             }
452             bFound = 1;
453         }
454
455         if ( !bFound ) {
456             if (newCellNamep)
457                 newCellNamep[0] = '\0';
458             RegCloseKey(hkCellServDB);
459             return CM_ERROR_NOSUCHCELL;
460         }
461     } else if (newCellNamep) {
462         strncpy(newCellNamep, cellNamep, CELL_MAXNAMELEN);
463         newCellNamep[CELL_MAXNAMELEN-1] = '\0';
464         strlwr(newCellNamep);
465     }
466
467     if (linkedNamep) {
468         dwSize = CELL_MAXNAMELEN;
469         code = RegQueryValueEx(hkCellName, "LinkedCell", NULL, &dwType,
470                                 (BYTE *) linkedNamep, &dwSize);
471         if (code == ERROR_SUCCESS && dwType == REG_SZ) {
472             linkedNamep[CELL_MAXNAMELEN-1] = '\0';
473             strlwr(linkedNamep);
474         } else {
475             linkedNamep[0] = '\0';
476         }
477     }
478
479     /* Check to see if DNS lookups are required */
480     dwSize = sizeof(DWORD);
481     code = RegQueryValueEx(hkCellName, "ForceDNS", NULL, &dwType,
482                             (BYTE *) &dwForceDNS, &dwSize);
483     if (code == ERROR_SUCCESS && dwType == REG_DWORD) {
484         if (dwForceDNS)
485             goto done;
486     } else {
487         dwForceDNS = 0;
488     }
489
490     /* 
491      * Using the defined server list.  Enumerate and populate
492      * the server list for the cell.
493      */
494     code = RegQueryInfoKey( hkCellName,
495                             NULL,  /* lpClass */
496                             NULL,  /* lpcClass */
497                             NULL,  /* lpReserved */
498                             &dwServers,  /* lpcSubKeys */
499                             NULL,  /* lpcMaxSubKeyLen */
500                             NULL,  /* lpcMaxClassLen */
501                             NULL,  /* lpcValues */
502                             NULL,  /* lpcMaxValueNameLen */
503                             NULL,  /* lpcMaxValueLen */
504                             NULL,  /* lpcbSecurityDescriptor */
505                             &ftLastWriteTime /* lpftLastWriteTime */
506                             );
507     if (code != ERROR_SUCCESS)
508         dwServers = 0;
509
510     for ( dwIndex = 0; dwIndex < dwServers; dwIndex++ ) {
511         dwSize = MAXHOSTCHARS;
512         code = RegEnumKeyEx( hkCellName, dwIndex, szServerName, &dwSize, NULL, 
513                              NULL, NULL, &ftLastWriteTime);
514         if (code != ERROR_SUCCESS)
515             continue;
516
517         szServerName[MAXHOSTCHARS-1] = '\0';
518         if (RegOpenKeyEx( hkCellName, 
519                           szServerName,
520                           0,
521                           KEY_READ|KEY_WRITE|KEY_QUERY_VALUE,
522                           &hkServerName) != ERROR_SUCCESS)
523             continue;
524
525         /* We have a handle to a valid server key.  Now we need 
526          * to add the server to the cell */
527         
528         /* First, see if there is an alternate hostname specified */
529         dwSize = MAXHOSTCHARS;
530         code = RegQueryValueEx(hkServerName, "HostName", NULL, &dwType,
531                                 (BYTE *) szHostName, &dwSize);
532         if (code == ERROR_SUCCESS && dwType == REG_SZ) {
533             szHostName[MAXHOSTCHARS-1] = '\0';
534             strlwr(szHostName);
535             s = szHostName;
536         } else {
537             s = szServerName;
538         }
539
540         dwSize = sizeof(DWORD);
541         code = RegQueryValueEx(hkServerName, "Rank", NULL, &dwType,
542                                 (BYTE *) &dwRank, &dwSize);
543         if (code == ERROR_SUCCESS && dwType == REG_DWORD) {
544             ipRank = (unsigned short)(dwRank <= 65535 ? dwRank : 65535);
545         } else {
546             ipRank = 0;
547         }
548
549         dwSize = sizeof(szAddr);
550         code = RegQueryValueEx(hkServerName, "IPv4Address", NULL, &dwType,
551                                 (BYTE *) szAddr, &dwSize);
552         if (code == ERROR_SUCCESS && dwType == REG_SZ) {
553             szAddr[63] = '\0';
554         } else {
555             szAddr[0] = '\0';
556         }
557
558         WSASetLastError(0);
559         thp = gethostbyname(s);
560         if (thp) {
561             memcpy(&vlSockAddr.sin_addr.s_addr, thp->h_addr, sizeof(long));
562             vlSockAddr.sin_family = AF_INET;
563             /* sin_port supplied by connection code */
564             if (procp)
565                 (*procp)(rockp, &vlSockAddr, s, ipRank);
566         } else if (szAddr[0]) {
567             afs_uint32 ip_addr;
568             unsigned int c1, c2, c3, c4;
569
570             /* Since there is no gethostbyname() data 
571              * available we will read the IP address
572              * stored in the CellServDB file
573              */
574             code = sscanf(szAddr, " %u.%u.%u.%u",
575                            &c1, &c2, &c3, &c4);
576             if (code == 4 && c1<256 && c2<256 && c3<256 && c4<256) {
577                 unsigned char * tp = (unsigned char *) &ip_addr;
578                 *tp++ = c1;
579                 *tp++ = c2;
580                 *tp++ = c3;
581                 *tp++ = c4;
582                 memcpy(&vlSockAddr.sin_addr.s_addr, &ip_addr,
583                         sizeof(long));
584                 vlSockAddr.sin_family = AF_INET;
585                 /* sin_port supplied by connection code */
586                 if (procp)
587                     (*procp)(rockp, &vlSockAddr, s, ipRank);
588             }
589         }
590
591         RegCloseKey( hkServerName);
592     }
593
594   done:
595     RegCloseKey(hkCellName);
596     RegCloseKey(hkCellServDB);
597
598     return ((dwForceDNS || dwServers == 0) ? CM_ERROR_FORCE_DNS_LOOKUP : 0);
599 }
600
601 long cm_EnumerateCellRegistry(afs_uint32 client, cm_enumCellRegistryProc_t *procp, void *rockp)
602 {
603     HKEY hkCellServDB = 0;
604     DWORD dwType, dwSize;
605     DWORD dwCells;
606     DWORD dwIndex;
607     LONG code;
608     FILETIME ftLastWriteTime;
609     char szCellName[CELL_MAXNAMELEN];
610
611     /* No server CellServDB in the registry. */
612     if (!client || procp == NULL)
613         return 0;
614
615     if (RegOpenKeyEx( HKEY_LOCAL_MACHINE,
616                       AFSREG_CLT_OPENAFS_SUBKEY "\\CellServDB",
617                       0,
618                       KEY_READ|KEY_WRITE|KEY_QUERY_VALUE,
619                       &hkCellServDB) != ERROR_SUCCESS)
620         return 0;
621
622     code = RegQueryInfoKey( hkCellServDB,
623                             NULL,  /* lpClass */
624                             NULL,  /* lpcClass */
625                             NULL,  /* lpReserved */
626                             &dwCells,  /* lpcSubKeys */
627                             NULL,  /* lpcMaxSubKeyLen */
628                             NULL,  /* lpcMaxClassLen */
629                             NULL,  /* lpcValues */
630                             NULL,  /* lpcMaxValueNameLen */
631                             NULL,  /* lpcMaxValueLen */
632                             NULL,  /* lpcbSecurityDescriptor */
633                             &ftLastWriteTime /* lpftLastWriteTime */
634                             );
635     if (code != ERROR_SUCCESS)
636         dwCells = 0;
637
638     /* 
639      * Enumerate each Cell and 
640      */
641     for ( dwIndex = 0; dwIndex < dwCells; dwIndex++ ) {
642         dwSize = CELL_MAXNAMELEN;
643         code = RegEnumKeyEx( hkCellServDB, dwIndex, szCellName, &dwSize, NULL, 
644                              NULL, NULL, &ftLastWriteTime);
645         if (code != ERROR_SUCCESS)
646             continue;
647         szCellName[CELL_MAXNAMELEN-1] = '\0';
648         strlwr(szCellName);
649
650         (*procp)(rockp, szCellName);
651     }
652
653     RegCloseKey(hkCellServDB);
654     return 0;
655 }
656
657 /* newCellNamep is required to be CELL_MAXNAMELEN in size */
658 long cm_SearchCellByDNS(char *cellNamep, char *newCellNamep, int *ttl,
659                         cm_configProc_t *procp, void *rockp)
660 {
661 #ifdef AFS_AFSDB_ENV
662     int rc;
663     int  cellHostAddrs[AFSMAXCELLHOSTS];
664     char cellHostNames[AFSMAXCELLHOSTS][MAXHOSTCHARS];
665     unsigned short ipRanks[AFSMAXCELLHOSTS];
666     int numServers;
667     int i;
668     struct sockaddr_in vlSockAddr;
669 #ifdef CELLSERV_DEBUG
670     osi_Log1(afsd_logp,"SearchCellDNS-Doing search for [%s]", osi_LogSaveString(afsd_logp,cellNamep));
671 #endif
672     if ( IsWindowsModule(cellNamep) )
673         return -1;
674     rc = getAFSServer(cellNamep, cellHostAddrs, cellHostNames, ipRanks, &numServers, ttl);
675     if (rc == 0 && numServers > 0) {     /* found the cell */
676         for (i = 0; i < numServers; i++) {
677             memcpy(&vlSockAddr.sin_addr.s_addr, &cellHostAddrs[i],
678                    sizeof(long));
679             vlSockAddr.sin_family = AF_INET;
680             /* sin_port supplied by connection code */
681             if (procp)
682                 (*procp)(rockp, &vlSockAddr, cellHostNames[i], ipRanks[i]);
683         }
684         if (newCellNamep) {
685             strncpy(newCellNamep,cellNamep,CELL_MAXNAMELEN);
686             newCellNamep[CELL_MAXNAMELEN-1] = '\0';
687             strlwr(newCellNamep);
688         }
689         return 0;   /* found cell */
690     }
691     else
692        return -1;  /* not found */
693 #else
694     return -1;  /* not found */
695 #endif /* AFS_AFSDB_ENV */
696 }
697
698 /* use cm_GetConfigDir() plus AFS_CELLSERVDB to 
699  * generate the fully qualified name of the CellServDB 
700  * file.
701  */
702 long cm_GetCellServDB(char *cellNamep, afs_uint32 len)
703 {
704     size_t tlen;
705     
706     cm_GetConfigDir(cellNamep, len);
707
708     /* add trailing backslash, if required */
709     tlen = (int)strlen(cellNamep);
710     if (tlen) {
711         if (cellNamep[tlen-1] != '\\') {
712             strncat(cellNamep, "\\", len);
713             cellNamep[len-1] = '\0';
714         }
715         
716         strncat(cellNamep, AFS_CELLSERVDB, len);
717         cellNamep[len-1] = '\0';
718     }
719     return 0;
720 }
721
722 /* look up the root cell's name in the Registry 
723  * Input buffer must be at least CELL_MAXNAMELEN 
724  * in size.  (Defined in cm_cell.h)
725  */
726 long cm_GetRootCellName(char *cellNamep)
727 {
728     DWORD code, dummyLen;
729     HKEY parmKey;
730
731     code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
732                         0, KEY_QUERY_VALUE, &parmKey);
733     if (code != ERROR_SUCCESS)
734         return -1;
735
736     dummyLen = CELL_MAXNAMELEN;
737     code = RegQueryValueEx(parmKey, "Cell", NULL, NULL,
738                                 cellNamep, &dummyLen);
739     RegCloseKey (parmKey);
740     if (code != ERROR_SUCCESS || cellNamep[0] == 0)
741         return -1;
742
743     return 0;
744 }
745
746 cm_configFile_t *cm_CommonOpen(char *namep, char *rwp)
747 {
748     char wdir[MAX_PATH]="";
749     FILE *tfilep = NULL;
750
751     cm_GetConfigDir(wdir, sizeof(wdir));
752     if (*wdir) {
753         strncat(wdir, namep, sizeof(wdir));
754         wdir[sizeof(wdir)-1] = '\0';
755         
756         tfilep = fopen(wdir, rwp);
757     }
758     return ((cm_configFile_t *) tfilep);        
759 }       
760
761 long cm_WriteConfigString(char *labelp, char *valuep)
762 {
763     DWORD code, dummyDisp;
764     HKEY parmKey;
765
766     code = RegCreateKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
767                            0, "container", 0, KEY_SET_VALUE, NULL,
768                            &parmKey, &dummyDisp);
769     if (code != ERROR_SUCCESS)
770         return -1;
771
772     code = RegSetValueEx(parmKey, labelp, 0, REG_SZ,
773                           valuep, (DWORD)strlen(valuep) + 1);
774     RegCloseKey (parmKey);
775     if (code != ERROR_SUCCESS)
776         return (long)-1;
777
778     return (long)0;
779 }
780
781 long cm_WriteConfigInt(char *labelp, long value)
782 {
783     DWORD code, dummyDisp;
784     HKEY parmKey;
785
786     code = RegCreateKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
787                            0, "container", 0, KEY_SET_VALUE, NULL,
788                            &parmKey, &dummyDisp);
789     if (code != ERROR_SUCCESS)
790         return -1;
791
792     code = RegSetValueEx(parmKey, labelp, 0, REG_DWORD,
793                           (LPBYTE)&value, sizeof(value));
794     RegCloseKey (parmKey);
795     if (code != ERROR_SUCCESS)
796         return -1;
797
798     return 0;
799 }
800
801 cm_configFile_t *cm_OpenCellFile(void)
802 {
803     cm_configFile_t *cfp;
804
805     cfp = cm_CommonOpen(AFS_CELLSERVDB ".new", "w");
806     return cfp;
807 }
808
809 long cm_AppendPrunedCellList(cm_configFile_t *ofp, char *cellNamep)
810 {
811     cm_configFile_t *tfilep;    /* input file */
812     char *tp;
813     char lineBuffer[256];
814     char *valuep;
815     int inRightCell;
816     int foundCell;
817
818     tfilep = cm_CommonOpen(AFS_CELLSERVDB, "r");
819     if (!tfilep) 
820         return -1;
821
822     foundCell = 0;
823
824     /* have we seen the cell line for the guy we're looking for? */
825     inRightCell = 0;
826     while (1) {
827         tp = fgets(lineBuffer, sizeof(lineBuffer), (FILE *)tfilep);
828         if (tp == NULL) {
829             if (feof((FILE *)tfilep)) {
830                 /* hit EOF */
831                 fclose((FILE *)tfilep);
832                 return 0;
833             }
834         }
835
836         /* turn trailing cr or lf into null */
837         tp = strchr(lineBuffer, '\r');
838         if (tp) *tp = 0;
839         tp = strchr(lineBuffer, '\n');
840         if (tp) *tp = 0;
841                 
842         /* skip blank lines */
843         if (lineBuffer[0] == 0) {
844             fprintf((FILE *)ofp, "%s\n", lineBuffer);
845             continue;
846         }
847
848         if (lineBuffer[0] == '>') {
849             /* trim off at white space or '#' chars */
850             tp = strchr(lineBuffer, ' ');
851             if (tp) *tp = 0;
852             tp = strchr(lineBuffer, '\t');
853             if (tp) *tp = 0;
854             tp = strchr(lineBuffer, '#');
855             if (tp) *tp = 0;
856
857             /* now see if this is the right cell */
858             if (strcmp(lineBuffer+1, cellNamep) == 0) {
859                 /* found the cell we're looking for */
860                 inRightCell = 1;
861             }
862             else {
863                 inRightCell = 0;
864                 fprintf((FILE *)ofp, "%s\n", lineBuffer);
865             }
866         }
867         else {
868             valuep = strchr(lineBuffer, '#');
869             if (valuep == NULL) return -2;
870             valuep++;   /* skip the "#" */
871             if (!inRightCell) {
872                 fprintf((FILE *)ofp, "%s\n", lineBuffer);
873             }
874         }       /* a vldb line */
875     }           /* while loop processing all lines */
876 }       
877
878 long cm_AppendNewCell(cm_configFile_t *filep, char *cellNamep)
879 {
880     fprintf((FILE *)filep, ">%s\n", cellNamep);
881     return 0;
882 }
883
884 long cm_AppendNewCellLine(cm_configFile_t *filep, char *linep)
885 {
886     fprintf((FILE *)filep, "%s\n", linep);
887     return 0;
888 }
889
890 long cm_CloseCellFile(cm_configFile_t *filep)
891 {
892     char wdir[MAX_PATH];
893     char sdir[MAX_PATH];
894     long code;
895     long closeCode;
896     closeCode = fclose((FILE *)filep);
897
898     cm_GetConfigDir(wdir, sizeof(wdir));
899     strcpy(sdir, wdir);
900
901     if (closeCode != 0) {
902         /* something went wrong, preserve original database */
903         strncat(wdir, AFS_CELLSERVDB ".new", sizeof(wdir));
904         wdir[sizeof(wdir)-1] = '\0';
905         unlink(wdir);
906         return closeCode;
907     }
908
909     strncat(wdir, AFS_CELLSERVDB, sizeof(wdir));
910     wdir[sizeof(wdir)-1] = '\0';
911     strncat(sdir, AFS_CELLSERVDB ".new", sizeof(sdir));/* new file */
912     sdir[sizeof(sdir)-1] = '\0';
913
914     unlink(sdir);                       /* delete old file */
915
916     code = rename(sdir, wdir);  /* do the rename */
917
918     if (code) 
919         code = errno;
920
921     return code;
922 }   
923
924 void cm_GetConfigDir(char *dir, afs_uint32 len)
925 {
926     char * dirp = NULL;
927
928     if (!afssw_GetClientCellServDBDir(&dirp)) {
929         strncpy(dir, dirp, len);
930         dir[len-1] = '\0';
931         free(dirp);
932     } else {
933         dir[0] = '\0';
934     }
935 }