1 /* This modules is based on the params.c module from Samba, written by Karl Auer
2 and much modifed by Christopher Hertel. */
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, visit the http://fsf.org website.
19 /* -------------------------------------------------------------------------- **
23 * -------------------------------------------------------------------------- **
25 * This module performs lexical analysis and initial parsing of a
26 * Windows-like parameter file. It recognizes and handles four token
27 * types: section-name, parameter-name, parameter-value, and
28 * end-of-file. Comments and line continuation are handled
31 * The entry point to the module is function pm_process(). This
32 * function opens the source file, calls the Parse() function to parse
33 * the input, and then closes the file when either the EOF is reached
34 * or a fatal error is encountered.
36 * A sample parameter file might look like this:
39 * parameter one = value string
40 * parameter two = another value
42 * new parameter = some value or t'other
44 * The parameter file is divided into sections by section headers:
45 * section names enclosed in square brackets (eg. [section one]).
46 * Each section contains parameter lines, each of which consist of a
47 * parameter name and value delimited by an equal sign. Roughly, the
50 * <file> :== { <section> } EOF
52 * <section> :== <section header> { <parameter line> }
54 * <section header> :== '[' NAME ']'
56 * <parameter line> :== NAME '=' VALUE '\n'
58 * Blank lines and comment lines are ignored. Comment lines are lines
59 * beginning with either a semicolon (';') or a pound sign ('#').
61 * All whitespace in section names and parameter names is compressed
62 * to single spaces. Leading and trailing whitespace is stipped from
63 * both names and values.
65 * Only the first equals sign in a parameter line is significant.
66 * Parameter values may contain equals signs, square brackets and
67 * semicolons. Internal whitespace is retained in parameter values,
68 * with the exception of the '\r' character, which is stripped for
69 * historic reasons. Parameter names may not start with a left square
70 * bracket, an equal sign, a pound sign, or a semicolon, because these
71 * are used to identify other tokens.
73 * -------------------------------------------------------------------------- **
79 /* -------------------------------------------------------------------------- **
86 /* -------------------------------------------------------------------------- **
89 * bufr - pointer to a global buffer. This is probably a kludge,
90 * but it was the nicest kludge I could think of (for now).
91 * bSize - The size of the global buffer <bufr>.
94 static char *bufr = NULL;
96 static BOOL (*the_sfunc)(char *);
97 static BOOL (*the_pfunc)(char *, char *);
99 /* -------------------------------------------------------------------------- **
103 static int EatWhitespace( FILE *InFile )
104 /* ------------------------------------------------------------------------ **
105 * Scan past whitespace (see ctype(3C)) and return the first non-whitespace
106 * character, or newline, or EOF.
108 * Input: InFile - Input source.
110 * Output: The next non-whitespace character in the input stream.
112 * Notes: Because the config files use a line-oriented grammar, we
113 * explicitly exclude the newline character from the list of
114 * whitespace characters.
115 * - Note that both EOF (-1) and the nul character ('\0') are
116 * considered end-of-file markers.
118 * ------------------------------------------------------------------------ **
123 for( c = getc( InFile ); isspace( c ) && ('\n' != c); c = getc( InFile ) )
126 } /* EatWhitespace */
128 static int EatComment( FILE *InFile )
129 /* ------------------------------------------------------------------------ **
130 * Scan to the end of a comment.
132 * Input: InFile - Input source.
134 * Output: The character that marks the end of the comment. Normally,
135 * this will be a newline, but it *might* be an EOF.
137 * Notes: Because the config files use a line-oriented grammar, we
138 * explicitly exclude the newline character from the list of
139 * whitespace characters.
140 * - Note that both EOF (-1) and the nul character ('\0') are
141 * considered end-of-file markers.
143 * ------------------------------------------------------------------------ **
148 for( c = getc( InFile ); ('\n'!=c) && (EOF!=c) && (c>0); c = getc( InFile ) )
153 static int Continuation( char *line, int pos )
154 /* ------------------------------------------------------------------------ **
155 * Scan backards within a string to discover if the last non-whitespace
156 * character is a line-continuation character ('\\').
158 * Input: line - A pointer to a buffer containing the string to be
160 * pos - This is taken to be the offset of the end of the
161 * string. This position is *not* scanned.
163 * Output: The offset of the '\\' character if it was found, or -1 to
164 * indicate that it was not.
166 * ------------------------------------------------------------------------ **
170 while( pos >= 0 && isSpace(line + pos) )
173 return( ((pos >= 0) && ('\\' == line[pos])) ? pos : -1 );
177 static BOOL Section( FILE *InFile, BOOL (*sfunc)(char *) )
178 /* ------------------------------------------------------------------------ **
179 * Scan a section name, and pass the name to function sfunc().
181 * Input: InFile - Input source.
182 * sfunc - Pointer to the function to be called if the section
183 * name is successfully read.
185 * Output: True if the section name was read and True was returned from
186 * <sfunc>. False if <sfunc> failed or if a lexical error was
189 * ------------------------------------------------------------------------ **
195 char *func = "params.c:Section() -";
197 i = 0; /* <i> is the offset of the next free byte in bufr[] and */
198 end = 0; /* <end> is the current "end of string" offset. In most */
199 /* cases these will be the same, but if the last */
200 /* character written to bufr[] is a space, then <end> */
201 /* will be one less than <i>. */
203 c = EatWhitespace( InFile ); /* We've already got the '['. Scan */
204 /* past initial white space. */
206 while( (EOF != c) && (c > 0) )
209 /* Check that the buffer is big enough for the next character. */
210 if( i > (bSize - 2) )
213 bufr = realloc_array( bufr, char, bSize );
216 rprintf(FLOG, "%s Memory re-allocation failure.", func);
221 /* Handle a single character. */
224 case ']': /* Found the closing bracket. */
226 if( 0 == end ) /* Don't allow an empty name. */
228 rprintf(FLOG, "%s Empty section name in configuration file.\n", func );
231 if( !sfunc( bufr ) ) /* Got a valid name. Deal with it. */
233 (void)EatComment( InFile ); /* Finish off the line. */
236 case '\n': /* Got newline before closing ']'. */
237 i = Continuation( bufr, i ); /* Check for line continuation. */
241 rprintf(FLOG, "%s Badly formed line in configuration file: %s\n",
245 end = ( (i > 0) && (' ' == bufr[i - 1]) ) ? (i - 1) : (i);
246 c = getc( InFile ); /* Continue with next line. */
249 default: /* All else are a valid name chars. */
250 if( isspace( c ) ) /* One space per whitespace region. */
254 c = EatWhitespace( InFile );
256 else /* All others copy verbatim. */
265 /* We arrive here if we've met the EOF before the closing bracket. */
266 rprintf(FLOG, "%s Unexpected EOF in the configuration file: %s\n", func, bufr );
270 static BOOL Parameter( FILE *InFile, BOOL (*pfunc)(char *, char *), int c )
271 /* ------------------------------------------------------------------------ **
272 * Scan a parameter name and value, and pass these two fields to pfunc().
274 * Input: InFile - The input source.
275 * pfunc - A pointer to the function that will be called to
276 * process the parameter, once it has been scanned.
277 * c - The first character of the parameter name, which
278 * would have been read by Parse(). Unlike a comment
279 * line or a section header, there is no lead-in
280 * character that can be discarded.
282 * Output: True if the parameter name and value were scanned and processed
283 * successfully, else False.
285 * Notes: This function is in two parts. The first loop scans the
286 * parameter name. Internal whitespace is compressed, and an
287 * equal sign (=) terminates the token. Leading and trailing
288 * whitespace is discarded. The second loop scans the parameter
289 * value. When both have been successfully identified, they are
290 * passed to pfunc() for processing.
292 * ------------------------------------------------------------------------ **
295 int i = 0; /* Position within bufr. */
296 int end = 0; /* bufr[end] is current end-of-string. */
297 int vstart = 0; /* Starting position of the parameter value. */
298 char *func = "params.c:Parameter() -";
300 /* Read the parameter name. */
301 while( 0 == vstart ) /* Loop until we've found the start of the value. */
304 if( i > (bSize - 2) ) /* Ensure there's space for next char. */
307 bufr = realloc_array( bufr, char, bSize );
310 rprintf(FLOG, "%s Memory re-allocation failure.", func) ;
317 case '=': /* Equal sign marks end of param name. */
318 if( 0 == end ) /* Don't allow an empty name. */
320 rprintf(FLOG, "%s Invalid parameter name in config. file.\n", func );
323 bufr[end++] = '\0'; /* Mark end of string & advance. */
324 i = end; /* New string starts here. */
325 vstart = end; /* New string is parameter value. */
326 bufr[i] = '\0'; /* New string is nul, for now. */
329 case '\n': /* Find continuation char, else error. */
330 i = Continuation( bufr, i );
334 rprintf(FLOG, "%s Ignoring badly formed line in configuration file: %s\n",
338 end = ( (i > 0) && (' ' == bufr[i - 1]) ) ? (i - 1) : (i);
339 c = getc( InFile ); /* Read past eoln. */
342 case '\0': /* Shouldn't have EOF within param name. */
345 rprintf(FLOG, "%s Unexpected end-of-file at: %s\n", func, bufr );
349 if( isspace( c ) ) /* One ' ' per whitespace region. */
353 c = EatWhitespace( InFile );
355 else /* All others verbatim. */
364 /* Now parse the value. */
365 c = EatWhitespace( InFile ); /* Again, trim leading whitespace. */
366 while( (EOF !=c) && (c > 0) )
369 if( i > (bSize - 2) ) /* Make sure there's enough room. */
372 bufr = realloc_array( bufr, char, bSize );
375 rprintf(FLOG, "%s Memory re-allocation failure.", func) ;
382 case '\r': /* Explicitly remove '\r' because the older */
383 c = getc( InFile ); /* version called fgets_slash() which also */
384 break; /* removes them. */
386 case '\n': /* Marks end of value unless there's a '\'. */
387 i = Continuation( bufr, i );
392 for( end = i; end >= 0 && isSpace(bufr + end); end-- )
398 default: /* All others verbatim. Note that spaces do */
399 bufr[i++] = c; /* not advance <end>. This allows trimming */
400 if( !isspace( c ) ) /* of whitespace at the end of the line. */
406 bufr[end] = '\0'; /* End of value. */
408 return( pfunc( bufr, &bufr[vstart] ) ); /* Pass name & value to pfunc(). */
411 static int name_cmp(const void *n1, const void *n2)
413 return strcmp(*(char * const *)n1, *(char * const *)n2);
416 static int include_config(char *include, int manage_globals)
420 char buf[MAXPATHLEN], **bpp;
425 memset(&conf_list, 0, sizeof conf_list);
427 if ((d = opendir(include)) != NULL) {
428 while ((di = readdir(d)) != NULL) {
429 char *dname = d_name(di);
430 if (!wildmatch("*.conf", dname))
432 bpp = EXPAND_ITEM_LIST(&conf_list, char *, 32);
433 pathjoin(buf, sizeof buf, include, dname);
439 if (stat(include, &sb) < 0)
441 bpp = EXPAND_ITEM_LIST(&conf_list, char *, 1);
442 *bpp = strdup(include);
445 if (conf_list.count > 1)
446 qsort(conf_list.items, conf_list.count, sizeof (char *), name_cmp);
448 bpp = conf_list.items;
449 for (j = 0; j < conf_list.count; j++) {
450 if (manage_globals && the_sfunc)
451 the_sfunc(j == 0 ? "]push" : "]reset");
452 if ((ret = pm_process(bpp[j], the_sfunc, the_pfunc)) != 1)
456 if (manage_globals && the_sfunc && conf_list.count)
459 for (j = 0; j < conf_list.count; j++)
465 static int parse_directives(char *name, char *val)
467 if (strcasecmp(name, "include") == 0)
468 return include_config(val, 1);
469 if (strcasecmp(name, "merge") == 0)
470 return include_config(val, 0);
471 rprintf(FLOG, "Unknown directive: &%s.\n", name);
475 static int Parse( FILE *InFile,
476 BOOL (*sfunc)(char *),
477 BOOL (*pfunc)(char *, char *) )
478 /* ------------------------------------------------------------------------ **
479 * Scan & parse the input.
481 * Input: InFile - Input source.
482 * sfunc - Function to be called when a section name is scanned.
484 * pfunc - Function to be called when a parameter is scanned.
487 * Output: 1 if the file was successfully scanned, 2 if the file was
488 * scanned until a section header with no section function, else 0.
490 * Notes: The input can be viewed in terms of 'lines'. There are four
492 * Blank - May contain whitespace, otherwise empty.
493 * Comment - First non-whitespace character is a ';' or '#'.
494 * The remainder of the line is ignored.
495 * Section - First non-whitespace character is a '['.
496 * Parameter - The default case.
498 * ------------------------------------------------------------------------ **
503 c = EatWhitespace( InFile );
504 while( (EOF != c) && (c > 0) )
508 case '\n': /* Blank line. */
509 c = EatWhitespace( InFile );
512 case ';': /* Comment line. */
514 c = EatComment( InFile );
517 case '[': /* Section Header. */
520 if( !Section( InFile, sfunc ) )
522 c = EatWhitespace( InFile );
525 case '\\': /* Bogus backslash. */
526 c = EatWhitespace( InFile );
529 case '&': /* Handle directives */
532 c = EatWhitespace( InFile );
533 c = Parameter( InFile, parse_directives, c );
536 c = EatWhitespace( InFile );
539 default: /* Parameter line. */
540 if( !Parameter( InFile, pfunc, c ) )
542 c = EatWhitespace( InFile );
549 static FILE *OpenConfFile( char *FileName )
550 /* ------------------------------------------------------------------------ **
551 * Open a configuration file.
553 * Input: FileName - The pathname of the config file to be opened.
555 * Output: A pointer of type (FILE *) to the opened file, or NULL if the
556 * file could not be opened.
558 * ------------------------------------------------------------------------ **
562 char *func = "params.c:OpenConfFile() -";
564 if( NULL == FileName || 0 == *FileName )
566 rprintf(FLOG, "%s No configuration filename specified.\n", func);
570 OpenedFile = fopen( FileName, "r" );
571 if( NULL == OpenedFile )
573 rsyserr(FLOG, errno, "unable to open configuration file \"%s\"",
577 return( OpenedFile );
580 int pm_process( char *FileName,
581 BOOL (*sfunc)(char *),
582 BOOL (*pfunc)(char *, char *) )
583 /* ------------------------------------------------------------------------ **
584 * Process the named parameter file.
586 * Input: FileName - The pathname of the parameter file to be opened.
587 * sfunc - A pointer to a function that will be called when
588 * a section name is discovered.
589 * pfunc - A pointer to a function that will be called when
590 * a parameter name and value are discovered.
592 * Output: 1 if the file was successfully parsed, 2 if parsing ended at a
593 * section header w/o a section function, else 0.
595 * ------------------------------------------------------------------------ **
600 char *func = "params.c:pm_process() -";
602 InFile = OpenConfFile( FileName ); /* Open the config file. */
606 if( NULL != bufr ) /* If we already have a buffer */
607 result = Parse( InFile, sfunc, pfunc ); /* (recursive call), then just */
610 else /* If we don't have a buffer */
611 { /* allocate one, then parse, */
612 bSize = BUFR_INC; /* then free. */
613 bufr = new_array( char, bSize );
616 rprintf(FLOG, "%s memory allocation failure.\n", func);
620 result = Parse( InFile, sfunc, pfunc );
628 if( !result ) /* Generic failure. */
630 rprintf(FLOG, "%s Failed. Error returned from params.c:parse().\n", func);
637 /* -------------------------------------------------------------------------- */