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 2 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, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
27 #define new_array(type, num) ((type *)_new_array(sizeof(type), (num)))
28 #define realloc_array(ptr, type, num) \
29 ((type *)_realloc_array((ptr), sizeof(type), (num)))
31 #define rprintf(x, ...) do { fprintf(stderr, ##__VA_ARGS__); \
32 fprintf(stderr, "\n"); } while (0)
33 #define rsyserr(x, y, ...) do { fprintf(stderr, ##__VA_ARGS__); \
34 fprintf(stderr, "\n"); } while (0)
36 #define MALLOC_MAX 0x40000000
40 void *_new_array(unsigned int size, unsigned long num)
42 if (num >= MALLOC_MAX/size)
44 return malloc(size * num);
47 void *_realloc_array(void *ptr, unsigned int size, unsigned long num)
49 if (num >= MALLOC_MAX/size)
51 /* No realloc should need this, but just in case... */
53 return malloc(size * num);
54 return realloc(ptr, size * num);
58 /* -------------------------------------------------------------------------- **
62 * -------------------------------------------------------------------------- **
64 * This module performs lexical analysis and initial parsing of a
65 * Windows-like parameter file. It recognizes and handles four token
66 * types: section-name, parameter-name, parameter-value, and
67 * end-of-file. Comments and line continuation are handled
70 * The entry point to the module is function pm_process(). This
71 * function opens the source file, calls the Parse() function to parse
72 * the input, and then closes the file when either the EOF is reached
73 * or a fatal error is encountered.
75 * A sample parameter file might look like this:
78 * parameter one = value string
79 * parameter two = another value
81 * new parameter = some value or t'other
83 * The parameter file is divided into sections by section headers:
84 * section names enclosed in square brackets (eg. [section one]).
85 * Each section contains parameter lines, each of which consist of a
86 * parameter name and value delimited by an equal sign. Roughly, the
89 * <file> :== { <section> } EOF
91 * <section> :== <section header> { <parameter line> }
93 * <section header> :== '[' NAME ']'
95 * <parameter line> :== NAME '=' VALUE '\n'
97 * Blank lines and comment lines are ignored. Comment lines are lines
98 * beginning with either a semicolon (';') or a pound sign ('#').
100 * All whitespace in section names and parameter names is compressed
101 * to single spaces. Leading and trailing whitespace is stipped from
102 * both names and values.
104 * Only the first equals sign in a parameter line is significant.
105 * Parameter values may contain equals signs, square brackets and
106 * semicolons. Internal whitespace is retained in parameter values,
107 * with the exception of the '\r' character, which is stripped for
108 * historic reasons. Parameter names may not start with a left square
109 * bracket, an equal sign, a pound sign, or a semicolon, because these
110 * are used to identify other tokens.
112 * -------------------------------------------------------------------------- **
115 /* -------------------------------------------------------------------------- **
119 #define BUFR_INC 1024
122 /* -------------------------------------------------------------------------- **
125 * bufr - pointer to a global buffer. This is probably a kludge,
126 * but it was the nicest kludge I could think of (for now).
127 * bSize - The size of the global buffer <bufr>.
130 static char *bufr = NULL;
131 static int bSize = 0;
133 /* -------------------------------------------------------------------------- **
137 static int EatWhitespace( FILE *InFile )
138 /* ------------------------------------------------------------------------ **
139 * Scan past whitespace (see ctype(3C)) and return the first non-whitespace
140 * character, or newline, or EOF.
142 * Input: InFile - Input source.
144 * Output: The next non-whitespace character in the input stream.
146 * Notes: Because the config files use a line-oriented grammar, we
147 * explicitly exclude the newline character from the list of
148 * whitespace characters.
149 * - Note that both EOF (-1) and the nul character ('\0') are
150 * considered end-of-file markers.
152 * ------------------------------------------------------------------------ **
157 for( c = getc( InFile ); isspace( c ) && ('\n' != c); c = getc( InFile ) )
160 } /* EatWhitespace */
162 static int EatComment( FILE *InFile )
163 /* ------------------------------------------------------------------------ **
164 * Scan to the end of a comment.
166 * Input: InFile - Input source.
168 * Output: The character that marks the end of the comment. Normally,
169 * this will be a newline, but it *might* be an EOF.
171 * Notes: Because the config files use a line-oriented grammar, we
172 * explicitly exclude the newline character from the list of
173 * whitespace characters.
174 * - Note that both EOF (-1) and the nul character ('\0') are
175 * considered end-of-file markers.
177 * ------------------------------------------------------------------------ **
182 for( c = getc( InFile ); ('\n'!=c) && (EOF!=c) && (c>0); c = getc( InFile ) )
187 static int Continuation( char *line, int pos )
188 /* ------------------------------------------------------------------------ **
189 * Scan backards within a string to discover if the last non-whitespace
190 * character is a line-continuation character ('\\').
192 * Input: line - A pointer to a buffer containing the string to be
194 * pos - This is taken to be the offset of the end of the
195 * string. This position is *not* scanned.
197 * Output: The offset of the '\\' character if it was found, or -1 to
198 * indicate that it was not.
200 * ------------------------------------------------------------------------ **
204 while( (pos >= 0) && isspace(((unsigned char *)line)[pos]) )
207 return( ((pos >= 0) && ('\\' == line[pos])) ? pos : -1 );
211 static BOOL Section( FILE *InFile, BOOL (*sfunc)(char *) )
212 /* ------------------------------------------------------------------------ **
213 * Scan a section name, and pass the name to function sfunc().
215 * Input: InFile - Input source.
216 * sfunc - Pointer to the function to be called if the section
217 * name is successfully read.
219 * Output: True if the section name was read and True was returned from
220 * <sfunc>. False if <sfunc> failed or if a lexical error was
223 * ------------------------------------------------------------------------ **
229 char *func = "params.c:Section() -";
231 i = 0; /* <i> is the offset of the next free byte in bufr[] and */
232 end = 0; /* <end> is the current "end of string" offset. In most */
233 /* cases these will be the same, but if the last */
234 /* character written to bufr[] is a space, then <end> */
235 /* will be one less than <i>. */
237 c = EatWhitespace( InFile ); /* We've already got the '['. Scan */
238 /* past initial white space. */
240 while( (EOF != c) && (c > 0) )
243 /* Check that the buffer is big enough for the next character. */
244 if( i > (bSize - 2) )
247 bufr = realloc_array( bufr, char, bSize );
250 rprintf(FERROR, "%s Memory re-allocation failure.", func);
255 /* Handle a single character. */
258 case ']': /* Found the closing bracket. */
260 if( 0 == end ) /* Don't allow an empty name. */
262 rprintf(FERROR, "%s Empty section name in configuration file.\n", func );
265 if( !sfunc( bufr ) ) /* Got a valid name. Deal with it. */
267 (void)EatComment( InFile ); /* Finish off the line. */
270 case '\n': /* Got newline before closing ']'. */
271 i = Continuation( bufr, i ); /* Check for line continuation. */
275 rprintf(FERROR, "%s Badly formed line in configuration file: %s\n",
279 end = ( (i > 0) && (' ' == bufr[i - 1]) ) ? (i - 1) : (i);
280 c = getc( InFile ); /* Continue with next line. */
283 default: /* All else are a valid name chars. */
284 if( isspace( c ) ) /* One space per whitespace region. */
288 c = EatWhitespace( InFile );
290 else /* All others copy verbatim. */
299 /* We arrive here if we've met the EOF before the closing bracket. */
300 rprintf(FERROR, "%s Unexpected EOF in the configuration file: %s\n", func, bufr );
304 static BOOL Parameter( FILE *InFile, BOOL (*pfunc)(char *, char *), int c )
305 /* ------------------------------------------------------------------------ **
306 * Scan a parameter name and value, and pass these two fields to pfunc().
308 * Input: InFile - The input source.
309 * pfunc - A pointer to the function that will be called to
310 * process the parameter, once it has been scanned.
311 * c - The first character of the parameter name, which
312 * would have been read by Parse(). Unlike a comment
313 * line or a section header, there is no lead-in
314 * character that can be discarded.
316 * Output: True if the parameter name and value were scanned and processed
317 * successfully, else False.
319 * Notes: This function is in two parts. The first loop scans the
320 * parameter name. Internal whitespace is compressed, and an
321 * equal sign (=) terminates the token. Leading and trailing
322 * whitespace is discarded. The second loop scans the parameter
323 * value. When both have been successfully identified, they are
324 * passed to pfunc() for processing.
326 * ------------------------------------------------------------------------ **
329 int i = 0; /* Position within bufr. */
330 int end = 0; /* bufr[end] is current end-of-string. */
331 int vstart = 0; /* Starting position of the parameter value. */
332 char *func = "params.c:Parameter() -";
334 /* Read the parameter name. */
335 while( 0 == vstart ) /* Loop until we've found the start of the value. */
338 if( i > (bSize - 2) ) /* Ensure there's space for next char. */
341 bufr = realloc_array( bufr, char, bSize );
344 rprintf(FERROR, "%s Memory re-allocation failure.", func) ;
351 case '=': /* Equal sign marks end of param name. */
352 if( 0 == end ) /* Don't allow an empty name. */
354 rprintf(FERROR, "%s Invalid parameter name in config. file.\n", func );
357 bufr[end++] = '\0'; /* Mark end of string & advance. */
358 i = end; /* New string starts here. */
359 vstart = end; /* New string is parameter value. */
360 bufr[i] = '\0'; /* New string is nul, for now. */
363 case '\n': /* Find continuation char, else error. */
364 i = Continuation( bufr, i );
368 rprintf(FERROR, "%s Ignoring badly formed line in configuration file: %s\n",
372 end = ( (i > 0) && (' ' == bufr[i - 1]) ) ? (i - 1) : (i);
373 c = getc( InFile ); /* Read past eoln. */
376 case '\0': /* Shouldn't have EOF within param name. */
379 rprintf(FERROR, "%s Unexpected end-of-file at: %s\n", func, bufr );
383 if( isspace( c ) ) /* One ' ' per whitespace region. */
387 c = EatWhitespace( InFile );
389 else /* All others verbatim. */
398 /* Now parse the value. */
399 c = EatWhitespace( InFile ); /* Again, trim leading whitespace. */
400 while( (EOF !=c) && (c > 0) )
403 if( i > (bSize - 2) ) /* Make sure there's enough room. */
406 bufr = realloc_array( bufr, char, bSize );
409 rprintf(FERROR, "%s Memory re-allocation failure.", func) ;
416 case '\r': /* Explicitly remove '\r' because the older */
417 c = getc( InFile ); /* version called fgets_slash() which also */
418 break; /* removes them. */
420 case '\n': /* Marks end of value unless there's a '\'. */
421 i = Continuation( bufr, i );
426 for( end = i; (end >= 0) && isspace(((unsigned char *) bufr)[end]); end-- )
432 default: /* All others verbatim. Note that spaces do */
433 bufr[i++] = c; /* not advance <end>. This allows trimming */
434 if( !isspace( c ) ) /* of whitespace at the end of the line. */
440 bufr[end] = '\0'; /* End of value. */
442 return( pfunc( bufr, &bufr[vstart] ) ); /* Pass name & value to pfunc(). */
445 static BOOL Parse( FILE *InFile,
446 BOOL (*sfunc)(char *),
447 BOOL (*pfunc)(char *, char *) )
448 /* ------------------------------------------------------------------------ **
449 * Scan & parse the input.
451 * Input: InFile - Input source.
452 * sfunc - Function to be called when a section name is scanned.
454 * pfunc - Function to be called when a parameter is scanned.
457 * Output: True if the file was successfully scanned, else False.
459 * Notes: The input can be viewed in terms of 'lines'. There are four
461 * Blank - May contain whitespace, otherwise empty.
462 * Comment - First non-whitespace character is a ';' or '#'.
463 * The remainder of the line is ignored.
464 * Section - First non-whitespace character is a '['.
465 * Parameter - The default case.
467 * ------------------------------------------------------------------------ **
472 c = EatWhitespace( InFile );
473 while( (EOF != c) && (c > 0) )
477 case '\n': /* Blank line. */
478 c = EatWhitespace( InFile );
481 case ';': /* Comment line. */
483 c = EatComment( InFile );
486 case '[': /* Section Header. */
487 if (!sfunc) return True;
488 if( !Section( InFile, sfunc ) )
490 c = EatWhitespace( InFile );
493 case '\\': /* Bogus backslash. */
494 c = EatWhitespace( InFile );
497 default: /* Parameter line. */
498 if( !Parameter( InFile, pfunc, c ) )
500 c = EatWhitespace( InFile );
507 static FILE *OpenConfFile( char *FileName )
508 /* ------------------------------------------------------------------------ **
509 * Open a configuration file.
511 * Input: FileName - The pathname of the config file to be opened.
513 * Output: A pointer of type (FILE *) to the opened file, or NULL if the
514 * file could not be opened.
516 * ------------------------------------------------------------------------ **
520 char *func = "params.c:OpenConfFile() -";
522 if( NULL == FileName || 0 == *FileName )
524 rprintf(FERROR,"%s No configuration filename specified.\n", func);
528 OpenedFile = fopen( FileName, "r" );
529 if( NULL == OpenedFile )
531 rsyserr(FERROR, errno, "unable to open configuration file \"%s\"",
535 return( OpenedFile );
538 BOOL pm_process( char *FileName,
539 BOOL (*sfunc)(char *),
540 BOOL (*pfunc)(char *, char *) )
541 /* ------------------------------------------------------------------------ **
542 * Process the named parameter file.
544 * Input: FileName - The pathname of the parameter file to be opened.
545 * sfunc - A pointer to a function that will be called when
546 * a section name is discovered.
547 * pfunc - A pointer to a function that will be called when
548 * a parameter name and value are discovered.
550 * Output: TRUE if the file was successfully parsed, else FALSE.
552 * ------------------------------------------------------------------------ **
557 char *func = "params.c:pm_process() -";
559 InFile = OpenConfFile( FileName ); /* Open the config file. */
563 if( NULL != bufr ) /* If we already have a buffer */
564 result = Parse( InFile, sfunc, pfunc ); /* (recursive call), then just */
567 else /* If we don't have a buffer */
568 { /* allocate one, then parse, */
569 bSize = BUFR_INC; /* then free. */
570 bufr = new_array( char, bSize );
573 rprintf(FERROR,"%s memory allocation failure.\n", func);
577 result = Parse( InFile, sfunc, pfunc );
585 if( !result ) /* Generic failure. */
587 rprintf(FERROR,"%s Failed. Error returned from params.c:parse().\n", func);
591 return( True ); /* Generic success. */
594 /* -------------------------------------------------------------------------- */