This is the ubiqx binary tree and linked list library.
[Samba.git] / source / param / params.c
blob4d1c191b479e22f54ff12b1cf5985acc18689100
1 /* -------------------------------------------------------------------------- **
2 * Microsoft Network Services for Unix, AKA., Andrew Tridgell's SAMBA.
4 * This module Copyright (C) 1990, 1991, 1992, 1993, 1994 Karl Auer
6 * Rewritten almost completely by Christopher R. Hertel
7 * at the University of Minnesota, September, 1997.
8 * This module Copyright (C) 1997 by the University of Minnesota
9 * -------------------------------------------------------------------------- **
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25 * -------------------------------------------------------------------------- **
27 * Module name: params
29 * -------------------------------------------------------------------------- **
31 * This module performs lexical analysis and initial parsing of a
32 * Windows-like parameter file. It recognizes and handles four token
33 * types: section-name, parameter-name, parameter-value, and
34 * end-of-file. Comments and line continuation are handled
35 * internally.
37 * The entry point to the module is function pm_process(). This
38 * function opens the source file, calls the Parse() function to parse
39 * the input, and then closes the file when either the EOF is reached
40 * or a fatal error is encountered.
42 * A sample parameter file might look like this:
44 * [section one]
45 * parameter one = value string
46 * parameter two = another value
47 * [section two]
48 * new parameter = some value or t'other
50 * The parameter file is divided into sections by section headers:
51 * section names enclosed in square brackets (eg. [section one]).
52 * Each section contains parameter lines, each of which consist of a
53 * parameter name and value delimited by an equal sign. Roughly, the
54 * syntax is:
56 * <file> :== { <section> } EOF
58 * <section> :== <section header> { <parameter line> }
60 * <section header> :== '[' NAME ']'
62 * <parameter line> :== NAME '=' VALUE '\n'
64 * Blank lines and comment lines are ignored. Comment lines are lines
65 * beginning with either a semicolon (';') or a pound sign ('#').
67 * All whitespace in section names and parameter names is compressed
68 * to single spaces. Leading and trailing whitespace is stipped from
69 * both names and values.
71 * Only the first equals sign in a parameter line is significant.
72 * Parameter values may contain equals signs, square brackets and
73 * semicolons. Internal whitespace is retained in parameter values,
74 * with the exception of the '\r' character, which is stripped for
75 * historic reasons. Parameter names may not start with a left square
76 * bracket, an equal sign, a pound sign, or a semicolon, because these
77 * are used to identify other tokens.
79 * -------------------------------------------------------------------------- **
82 #include "includes.h"
84 /* -------------------------------------------------------------------------- **
85 * Constants...
88 #define BUFR_INC 1024
91 /* -------------------------------------------------------------------------- **
92 * Variables...
94 * DEBUGLEVEL - The ubiquitous DEBUGLEVEL. This determines which DEBUG()
95 * messages will be produced.
96 * bufr - pointer to a global buffer. This is probably a kludge,
97 * but it was the nicest kludge I could think of (for now).
98 * bSize - The size of the global buffer <bufr>.
101 extern int DEBUGLEVEL;
103 static char *bufr = NULL;
104 static int bSize = 0;
106 /* -------------------------------------------------------------------------- **
107 * Functions...
110 static int EatWhitespace( FILE *InFile )
111 /* ------------------------------------------------------------------------ **
112 * Scan past whitespace (see ctype(3C)) and return the first non-whitespace
113 * character, or newline, or EOF.
115 * Input: InFile - Input source.
117 * Output: The next non-whitespace character in the input stream.
119 * Notes: Because the config files use a line-oriented grammar, we
120 * explicitly exclude the newline character from the list of
121 * whitespace characters.
122 * - Note that both EOF (-1) and the nul character ('\0') are
123 * considered end-of-file markers.
125 * ------------------------------------------------------------------------ **
128 int c;
130 for( c = getc( InFile ); isspace( c ) && ('\n' != c); c = getc( InFile ) )
132 return( c );
133 } /* EatWhitespace */
135 static int EatComment( FILE *InFile )
136 /* ------------------------------------------------------------------------ **
137 * Scan to the end of a comment.
139 * Input: InFile - Input source.
141 * Output: The character that marks the end of the comment. Normally,
142 * this will be a newline, but it *might* be an EOF.
144 * Notes: Because the config files use a line-oriented grammar, we
145 * explicitly exclude the newline character from the list of
146 * whitespace characters.
147 * - Note that both EOF (-1) and the nul character ('\0') are
148 * considered end-of-file markers.
150 * ------------------------------------------------------------------------ **
153 int c;
155 for( c = getc( InFile ); ('\n'!=c) && (EOF!=c) && (c>0); c = getc( InFile ) )
157 return( c );
158 } /* EatComment */
160 static int Continuation( char *line, int pos )
161 /* ------------------------------------------------------------------------ **
162 * Scan backards within a string to discover if the last non-whitespace
163 * character is a line-continuation character ('\\').
165 * Input: line - A pointer to a buffer containing the string to be
166 * scanned.
167 * pos - This is taken to be the offset of the end of the
168 * string. This position is *not* scanned.
170 * Output: The offset of the '\\' character if it was found, or -1 to
171 * indicate that it was not.
173 * ------------------------------------------------------------------------ **
176 pos--;
177 while( (pos >= 0) && isspace(line[pos]) )
178 pos--;
180 return( ((pos >= 0) && ('\\' == line[pos])) ? pos : -1 );
181 } /* Continuation */
184 static BOOL Section( FILE *InFile, BOOL (*sfunc)(char *) )
185 /* ------------------------------------------------------------------------ **
186 * Scan a section name, and pass the name to function sfunc().
188 * Input: InFile - Input source.
189 * sfunc - Pointer to the function to be called if the section
190 * name is successfully read.
192 * Output: True if the section name was read and True was returned from
193 * <sfunc>. False if <sfunc> failed or if a lexical error was
194 * encountered.
196 * ------------------------------------------------------------------------ **
199 int c;
200 int i;
201 int end;
202 char *func = "params.c:Section() -";
204 i = 0; /* <i> is the offset of the next free byte in bufr[] and */
205 end = 0; /* <end> is the current "end of string" offset. In most */
206 /* cases these will be the same, but if the last */
207 /* character written to bufr[] is a space, then <end> */
208 /* will be one less than <i>. */
210 c = EatWhitespace( InFile ); /* We've already got the '['. Scan */
211 /* past initial white space. */
213 while( (EOF != c) && (c > 0) )
216 /* Check that the buffer is big enough for the next character. */
217 if( i > (bSize - 2) )
219 bSize += BUFR_INC;
220 bufr = Realloc( bufr, bSize );
221 if( NULL == bufr )
223 DEBUG(0, ("%s Memory re-allocation failure.", func) );
224 return( False );
228 /* Handle a single character. */
229 switch( c )
231 case ']': /* Found the closing bracket. */
232 bufr[end] = '\0';
233 if( 0 == end ) /* Don't allow an empty name. */
235 DEBUG(0, ("%s Empty section name in configuration file.\n", func ));
236 return( False );
238 if( !sfunc( bufr ) ) /* Got a valid name. Deal with it. */
239 return( False );
240 (void)EatComment( InFile ); /* Finish off the line. */
241 return( True );
243 case '\n': /* Got newline before closing ']'. */
244 i = Continuation( bufr, i ); /* Check for line continuation. */
245 if( i < 0 )
247 bufr[end] = '\0';
248 DEBUG(0, ("%s Badly formed line in configuration file: %s\n",
249 func, bufr ));
250 return( False );
252 end = ( (i > 0) && (' ' == bufr[i - 1]) ) ? (i - 1) : (i);
253 c = getc( InFile ); /* Continue with next line. */
254 break;
256 default: /* All else are a valid name chars. */
257 if( isspace( c ) ) /* One space per whitespace region. */
259 bufr[end] = ' ';
260 i = end + 1;
261 c = EatWhitespace( InFile );
263 else /* All others copy verbatim. */
265 bufr[i++] = c;
266 end = i;
267 c = getc( InFile );
272 /* We arrive here if we've met the EOF before the closing bracket. */
273 DEBUG(0, ("%s Unexpected EOF in the configuration file: %s\n", func, bufr ));
274 return( False );
275 } /* Section */
277 static BOOL Parameter( FILE *InFile, BOOL (*pfunc)(char *, char *), int c )
278 /* ------------------------------------------------------------------------ **
279 * Scan a parameter name and value, and pass these two fields to pfunc().
281 * Input: InFile - The input source.
282 * pfunc - A pointer to the function that will be called to
283 * process the parameter, once it has been scanned.
284 * c - The first character of the parameter name, which
285 * would have been read by Parse(). Unlike a comment
286 * line or a section header, there is no lead-in
287 * character that can be discarded.
289 * Output: True if the parameter name and value were scanned and processed
290 * successfully, else False.
292 * Notes: This function is in two parts. The first loop scans the
293 * parameter name. Internal whitespace is compressed, and an
294 * equal sign (=) terminates the token. Leading and trailing
295 * whitespace is discarded. The second loop scans the parameter
296 * value. When both have been successfully identified, they are
297 * passed to pfunc() for processing.
299 * ------------------------------------------------------------------------ **
302 int i = 0; /* Position within bufr. */
303 int end = 0; /* bufr[end] is current end-of-string. */
304 int vstart = 0; /* Starting position of the parameter value. */
305 char *func = "params.c:Parameter() -";
307 /* Read the parameter name. */
308 while( 0 == vstart ) /* Loop until we've found the start of the value. */
311 if( i > (bSize - 2) ) /* Ensure there's space for next char. */
313 bSize += BUFR_INC;
314 bufr = Realloc( bufr, bSize );
315 if( NULL == bufr )
317 DEBUG(0, ("%s Memory re-allocation failure.", func) );
318 return( False );
322 switch( c )
324 case '=': /* Equal sign marks end of param name. */
325 if( 0 == end ) /* Don't allow an empty name. */
327 DEBUG(0, ("%s Invalid parameter name in config. file.\n", func ));
328 return( False );
330 bufr[end++] = '\0'; /* Mark end of string & advance. */
331 i = end; /* New string starts here. */
332 vstart = end; /* New string is parameter value. */
333 bufr[i] = '\0'; /* New string is nul, for now. */
334 break;
336 case '\n': /* Find continuation char, else error. */
337 i = Continuation( bufr, i );
338 if( i < 0 )
340 bufr[end] = '\0';
341 DEBUG(1,("%s Ignoring badly formed line in configuration file: %s\n",
342 func, bufr ));
343 return( True );
345 end = ( (i > 0) && (' ' == bufr[i - 1]) ) ? (i - 1) : (i);
346 c = getc( InFile ); /* Read past eoln. */
347 break;
349 case '\0': /* Shouldn't have EOF within param name. */
350 case EOF:
351 bufr[i] = '\0';
352 DEBUG(1,("%s Unexpected end-of-file at: %s\n", func, bufr ));
353 return( True );
355 default:
356 if( isspace( c ) ) /* One ' ' per whitespace region. */
358 bufr[end] = ' ';
359 i = end + 1;
360 c = EatWhitespace( InFile );
362 else /* All others verbatim. */
364 bufr[i++] = c;
365 end = i;
366 c = getc( InFile );
371 /* Now parse the value. */
372 c = EatWhitespace( InFile ); /* Again, trim leading whitespace. */
373 while( (EOF !=c) && (c > 0) )
376 if( i > (bSize - 2) ) /* Make sure there's enough room. */
378 bSize += BUFR_INC;
379 bufr = Realloc( bufr, bSize );
380 if( NULL == bufr )
382 DEBUG(0, ("%s Memory re-allocation failure.", func) );
383 return( False );
387 switch( c )
389 case '\r': /* Explicitly remove '\r' because the older */
390 c = getc( InFile ); /* version called fgets_slash() which also */
391 break; /* removes them. */
393 case '\n': /* Marks end of value unless there's a '\'. */
394 i = Continuation( bufr, i );
395 if( i < 0 )
396 c = 0;
397 else
399 for( end = i; (end >= 0) && isspace(bufr[end]); end-- )
401 c = getc( InFile );
403 break;
405 default: /* All others verbatim. Note that spaces do */
406 bufr[i++] = c; /* not advance <end>. This allows trimming */
407 if( !isspace( c ) ) /* of whitespace at the end of the line. */
408 end = i;
409 c = getc( InFile );
410 break;
413 bufr[end] = '\0'; /* End of value. */
415 return( pfunc( bufr, &bufr[vstart] ) ); /* Pass name & value to pfunc(). */
416 } /* Parameter */
418 static BOOL Parse( FILE *InFile,
419 BOOL (*sfunc)(char *),
420 BOOL (*pfunc)(char *, char *) )
421 /* ------------------------------------------------------------------------ **
422 * Scan & parse the input.
424 * Input: InFile - Input source.
425 * sfunc - Function to be called when a section name is scanned.
426 * See Section().
427 * pfunc - Function to be called when a parameter is scanned.
428 * See Parameter().
430 * Output: True if the file was successfully scanned, else False.
432 * Notes: The input can be viewed in terms of 'lines'. There are four
433 * types of lines:
434 * Blank - May contain whitespace, otherwise empty.
435 * Comment - First non-whitespace character is a ';' or '#'.
436 * The remainder of the line is ignored.
437 * Section - First non-whitespace character is a '['.
438 * Parameter - The default case.
440 * ------------------------------------------------------------------------ **
443 int c;
445 c = EatWhitespace( InFile );
446 while( (EOF != c) && (c > 0) )
448 switch( c )
450 case '\n': /* Blank line. */
451 c = EatWhitespace( InFile );
452 break;
454 case ';': /* Comment line. */
455 case '#':
456 c = EatComment( InFile );
457 break;
459 case '[': /* Section Header. */
460 if( !Section( InFile, sfunc ) )
461 return( False );
462 c = EatWhitespace( InFile );
463 break;
465 case '\\': /* Bogus backslash. */
466 c = EatWhitespace( InFile );
467 break;
469 default: /* Parameter line. */
470 if( !Parameter( InFile, pfunc, c ) )
471 return( False );
472 c = EatWhitespace( InFile );
473 break;
476 return( True );
477 } /* Parse */
479 static FILE *OpenConfFile( char *FileName )
480 /* ------------------------------------------------------------------------ **
481 * Open a configuration file.
483 * Input: FileName - The pathname of the config file to be opened.
485 * Output: A pointer of type (FILE *) to the opened file, or NULL if the
486 * file could not be opened.
488 * ------------------------------------------------------------------------ **
491 FILE *OpenedFile;
492 char *func = "params.c:OpenConfFile() -";
494 if( NULL == FileName || 0 == *FileName )
496 DEBUG( 0, ("%s No configuration filename specified.\n", func) );
497 return( NULL );
500 OpenedFile = fopen( FileName, "r" );
501 if( NULL == OpenedFile )
503 DEBUG( 0,
504 ("%s Unable to open configuration file \"%s\":\n\t%s\n",
505 func, FileName, strerror(errno)) );
508 return( OpenedFile );
509 } /* OpenConfFile */
511 BOOL pm_process( char *FileName,
512 BOOL (*sfunc)(char *),
513 BOOL (*pfunc)(char *, char *) )
514 /* ------------------------------------------------------------------------ **
515 * Process the named parameter file.
517 * Input: FileName - The pathname of the parameter file to be opened.
518 * sfunc - A pointer to a function that will be called when
519 * a section name is discovered.
520 * pfunc - A pointer to a function that will be called when
521 * a parameter name and value are discovered.
523 * Output: TRUE if the file was successfully parsed, else FALSE.
525 * ------------------------------------------------------------------------ **
528 int result;
529 FILE *InFile;
530 char *func = "params.c:pm_process() -";
532 InFile = OpenConfFile( FileName ); /* Open the config file. */
533 if( NULL == InFile )
534 return( False );
536 DEBUG( 3, ("%s Processing configuration file \"%s\"\n", func, FileName) );
538 if( NULL != bufr ) /* If we already have a buffer */
539 result = Parse( InFile, sfunc, pfunc ); /* (recursive call), then just */
540 /* use it. */
542 else /* If we don't have a buffer */
543 { /* allocate one, then parse, */
544 bSize = BUFR_INC; /* then free. */
545 bufr = (char *)malloc( bSize );
546 if( NULL == bufr )
548 DEBUG(0,("%s memory allocation failure.\n", func));
549 return( False );
551 result = Parse( InFile, sfunc, pfunc );
552 free( bufr );
553 bufr = NULL;
554 bSize = 0;
557 if( !result ) /* Generic failure. */
559 DEBUG(0,("%s Failed. Error returned from params.c:parse().\n", func));
560 return( False );
563 return( True ); /* Generic success. */
564 } /* pm_process */
566 /* -------------------------------------------------------------------------- */