large sync up with 2.2
[Samba/gbeck.git] / source / param / params.c
blobb359b269d4e380a4a669ca985f263ec641c774b8
1 /* -------------------------------------------------------------------------- **
2 * Microsoft Network Services for Unix, AKA., Andrew Tridgell's SAMBA.
4 * This module Copyright (C) 1990-1998 Karl Auer
6 * Rewritten almost completely by Christopher R. Hertel
7 * at the University of Minnesota, September, 1997.
8 * This module Copyright (C) 1997-1998 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 /* we can't use FILE* due to the 256 fd limit - use this cheap hack
107 instead */
108 typedef struct {
109 char *buf;
110 char *p;
111 size_t size;
112 } myFILE;
114 static int mygetc(myFILE *f)
116 if (f->p >= f->buf+f->size) return EOF;
117 /* be sure to return chars >127 as positive values */
118 return (int)( *(f->p++) & 0x00FF );
121 static void myfile_close(myFILE *f)
123 if (!f) return;
124 if (f->buf) free(f->buf);
125 free(f);
128 /* -------------------------------------------------------------------------- **
129 * Functions...
132 static int EatWhitespace( myFILE *InFile )
133 /* ------------------------------------------------------------------------ **
134 * Scan past whitespace (see ctype(3C)) and return the first non-whitespace
135 * character, or newline, or EOF.
137 * Input: InFile - Input source.
139 * Output: The next non-whitespace character in the input stream.
141 * Notes: Because the config files use a line-oriented grammar, we
142 * explicitly exclude the newline character from the list of
143 * whitespace characters.
144 * - Note that both EOF (-1) and the nul character ('\0') are
145 * considered end-of-file markers.
147 * ------------------------------------------------------------------------ **
150 int c;
152 for( c = mygetc( InFile ); isspace( c ) && ('\n' != c); c = mygetc( InFile ) )
154 return( c );
155 } /* EatWhitespace */
157 static int EatComment( myFILE *InFile )
158 /* ------------------------------------------------------------------------ **
159 * Scan to the end of a comment.
161 * Input: InFile - Input source.
163 * Output: The character that marks the end of the comment. Normally,
164 * this will be a newline, but it *might* be an EOF.
166 * Notes: Because the config files use a line-oriented grammar, we
167 * explicitly exclude the newline character from the list of
168 * whitespace characters.
169 * - Note that both EOF (-1) and the nul character ('\0') are
170 * considered end-of-file markers.
172 * ------------------------------------------------------------------------ **
175 int c;
177 for( c = mygetc( InFile ); ('\n'!=c) && (EOF!=c) && (c>0); c = mygetc( InFile ) )
179 return( c );
180 } /* EatComment */
182 /*****************************************************************************
183 * Scan backards within a string to discover if the last non-whitespace
184 * character is a line-continuation character ('\\').
186 * Input: line - A pointer to a buffer containing the string to be
187 * scanned.
188 * pos - This is taken to be the offset of the end of the
189 * string. This position is *not* scanned.
191 * Output: The offset of the '\\' character if it was found, or -1 to
192 * indicate that it was not.
194 *****************************************************************************/
196 static int Continuation( char *line, int pos )
198 int pos2 = 0;
200 pos--;
201 while( (pos >= 0) && isspace(line[pos]) )
202 pos--;
204 /* we should recognize if `\` is part of a multibyte character or not. */
205 while(pos2 <= pos) {
206 size_t skip = 0;
207 skip = get_character_len(line[pos2]);
208 if (skip) {
209 pos2 += skip;
210 } else if (pos == pos2) {
211 return( ((pos >= 0) && ('\\' == line[pos])) ? pos : -1 );
212 } else {
213 pos2++;
216 return (-1);
220 static BOOL Section( myFILE *InFile, BOOL (*sfunc)(char *) )
221 /* ------------------------------------------------------------------------ **
222 * Scan a section name, and pass the name to function sfunc().
224 * Input: InFile - Input source.
225 * sfunc - Pointer to the function to be called if the section
226 * name is successfully read.
228 * Output: True if the section name was read and True was returned from
229 * <sfunc>. False if <sfunc> failed or if a lexical error was
230 * encountered.
232 * ------------------------------------------------------------------------ **
235 int c;
236 int i;
237 int end;
238 char *func = "params.c:Section() -";
240 i = 0; /* <i> is the offset of the next free byte in bufr[] and */
241 end = 0; /* <end> is the current "end of string" offset. In most */
242 /* cases these will be the same, but if the last */
243 /* character written to bufr[] is a space, then <end> */
244 /* will be one less than <i>. */
246 c = EatWhitespace( InFile ); /* We've already got the '['. Scan */
247 /* past initial white space. */
249 while( (EOF != c) && (c > 0) )
252 /* Check that the buffer is big enough for the next character. */
253 if( i > (bSize - 2) )
255 bSize += BUFR_INC;
256 bufr = Realloc( bufr, bSize );
257 if( NULL == bufr )
259 DEBUG(0, ("%s Memory re-allocation failure.", func) );
260 return( False );
264 /* Handle a single character. */
265 switch( c )
267 case ']': /* Found the closing bracket. */
268 bufr[end] = '\0';
269 if( 0 == end ) /* Don't allow an empty name. */
271 DEBUG(0, ("%s Empty section name in configuration file.\n", func ));
272 return( False );
274 if( !sfunc( unix_to_dos(bufr,True) ) ) /* Got a valid name. Deal with it. */
275 return( False );
276 (void)EatComment( InFile ); /* Finish off the line. */
277 return( True );
279 case '\n': /* Got newline before closing ']'. */
280 i = Continuation( bufr, i ); /* Check for line continuation. */
281 if( i < 0 )
283 bufr[end] = '\0';
284 DEBUG(0, ("%s Badly formed line in configuration file: %s\n",
285 func, bufr ));
286 return( False );
288 end = ( (i > 0) && (' ' == bufr[i - 1]) ) ? (i - 1) : (i);
289 c = mygetc( InFile ); /* Continue with next line. */
290 break;
292 default: /* All else are a valid name chars. */
293 if( isspace( c ) ) /* One space per whitespace region. */
295 bufr[end] = ' ';
296 i = end + 1;
297 c = EatWhitespace( InFile );
299 else /* All others copy verbatim. */
301 bufr[i++] = c;
302 end = i;
303 c = mygetc( InFile );
308 /* We arrive here if we've met the EOF before the closing bracket. */
309 DEBUG(0, ("%s Unexpected EOF in the configuration file: %s\n", func, bufr ));
310 return( False );
311 } /* Section */
313 static BOOL Parameter( myFILE *InFile, BOOL (*pfunc)(char *, char *), int c )
314 /* ------------------------------------------------------------------------ **
315 * Scan a parameter name and value, and pass these two fields to pfunc().
317 * Input: InFile - The input source.
318 * pfunc - A pointer to the function that will be called to
319 * process the parameter, once it has been scanned.
320 * c - The first character of the parameter name, which
321 * would have been read by Parse(). Unlike a comment
322 * line or a section header, there is no lead-in
323 * character that can be discarded.
325 * Output: True if the parameter name and value were scanned and processed
326 * successfully, else False.
328 * Notes: This function is in two parts. The first loop scans the
329 * parameter name. Internal whitespace is compressed, and an
330 * equal sign (=) terminates the token. Leading and trailing
331 * whitespace is discarded. The second loop scans the parameter
332 * value. When both have been successfully identified, they are
333 * passed to pfunc() for processing.
335 * ------------------------------------------------------------------------ **
338 int i = 0; /* Position within bufr. */
339 int end = 0; /* bufr[end] is current end-of-string. */
340 int vstart = 0; /* Starting position of the parameter value. */
341 char *func = "params.c:Parameter() -";
343 /* Read the parameter name. */
344 while( 0 == vstart ) /* Loop until we've found the start of the value. */
347 if( i > (bSize - 2) ) /* Ensure there's space for next char. */
349 bSize += BUFR_INC;
350 bufr = Realloc( bufr, bSize );
351 if( NULL == bufr )
353 DEBUG(0, ("%s Memory re-allocation failure.", func) );
354 return( False );
358 switch( c )
360 case '=': /* Equal sign marks end of param name. */
361 if( 0 == end ) /* Don't allow an empty name. */
363 DEBUG(0, ("%s Invalid parameter name in config. file.\n", func ));
364 return( False );
366 bufr[end++] = '\0'; /* Mark end of string & advance. */
367 i = end; /* New string starts here. */
368 vstart = end; /* New string is parameter value. */
369 bufr[i] = '\0'; /* New string is nul, for now. */
370 break;
372 case '\n': /* Find continuation char, else error. */
373 i = Continuation( bufr, i );
374 if( i < 0 )
376 bufr[end] = '\0';
377 DEBUG(1,("%s Ignoring badly formed line in configuration file: %s\n",
378 func, bufr ));
379 return( True );
381 end = ( (i > 0) && (' ' == bufr[i - 1]) ) ? (i - 1) : (i);
382 c = mygetc( InFile ); /* Read past eoln. */
383 break;
385 case '\0': /* Shouldn't have EOF within param name. */
386 case EOF:
387 bufr[i] = '\0';
388 DEBUG(1,("%s Unexpected end-of-file at: %s\n", func, bufr ));
389 return( True );
391 default:
392 if( isspace( c ) ) /* One ' ' per whitespace region. */
394 bufr[end] = ' ';
395 i = end + 1;
396 c = EatWhitespace( InFile );
398 else /* All others verbatim. */
400 bufr[i++] = c;
401 end = i;
402 c = mygetc( InFile );
407 /* Now parse the value. */
408 c = EatWhitespace( InFile ); /* Again, trim leading whitespace. */
409 while( (EOF !=c) && (c > 0) )
412 if( i > (bSize - 2) ) /* Make sure there's enough room. */
414 bSize += BUFR_INC;
415 bufr = Realloc( bufr, bSize );
416 if( NULL == bufr )
418 DEBUG(0, ("%s Memory re-allocation failure.", func) );
419 return( False );
423 switch( c )
425 case '\r': /* Explicitly remove '\r' because the older */
426 c = mygetc( InFile ); /* version called fgets_slash() which also */
427 break; /* removes them. */
429 case '\n': /* Marks end of value unless there's a '\'. */
430 i = Continuation( bufr, i );
431 if( i < 0 )
432 c = 0;
433 else
435 for( end = i; (end >= 0) && isspace(bufr[end]); end-- )
437 c = mygetc( InFile );
439 break;
441 default: /* All others verbatim. Note that spaces do */
442 bufr[i++] = c; /* not advance <end>. This allows trimming */
443 if( !isspace( c ) ) /* of whitespace at the end of the line. */
444 end = i;
445 c = mygetc( InFile );
446 break;
449 bufr[end] = '\0'; /* End of value. */
451 return( pfunc( bufr, &bufr[vstart] ) ); /* Pass name & value to pfunc(). */
452 } /* Parameter */
454 static BOOL Parse( myFILE *InFile,
455 BOOL (*sfunc)(char *),
456 BOOL (*pfunc)(char *, char *) )
457 /* ------------------------------------------------------------------------ **
458 * Scan & parse the input.
460 * Input: InFile - Input source.
461 * sfunc - Function to be called when a section name is scanned.
462 * See Section().
463 * pfunc - Function to be called when a parameter is scanned.
464 * See Parameter().
466 * Output: True if the file was successfully scanned, else False.
468 * Notes: The input can be viewed in terms of 'lines'. There are four
469 * types of lines:
470 * Blank - May contain whitespace, otherwise empty.
471 * Comment - First non-whitespace character is a ';' or '#'.
472 * The remainder of the line is ignored.
473 * Section - First non-whitespace character is a '['.
474 * Parameter - The default case.
476 * ------------------------------------------------------------------------ **
479 int c;
481 c = EatWhitespace( InFile );
482 while( (EOF != c) && (c > 0) )
484 switch( c )
486 case '\n': /* Blank line. */
487 c = EatWhitespace( InFile );
488 break;
490 case ';': /* Comment line. */
491 case '#':
492 c = EatComment( InFile );
493 break;
495 case '[': /* Section Header. */
496 if( !Section( InFile, sfunc ) )
497 return( False );
498 c = EatWhitespace( InFile );
499 break;
501 case '\\': /* Bogus backslash. */
502 c = EatWhitespace( InFile );
503 break;
505 default: /* Parameter line. */
506 if( !Parameter( InFile, pfunc, c ) )
507 return( False );
508 c = EatWhitespace( InFile );
509 break;
512 return( True );
513 } /* Parse */
515 static myFILE *OpenConfFile( char *FileName )
516 /* ------------------------------------------------------------------------ **
517 * Open a configuration file.
519 * Input: FileName - The pathname of the config file to be opened.
521 * Output: A pointer of type (char **) to the lines of the file
523 * ------------------------------------------------------------------------ **
526 char *func = "params.c:OpenConfFile() -";
527 extern BOOL in_client;
528 int lvl = in_client?1:0;
529 myFILE *ret;
531 ret = (myFILE *)malloc(sizeof(*ret));
532 if (!ret) return NULL;
534 ret->buf = file_load(FileName, &ret->size);
535 if( NULL == ret->buf )
537 DEBUG( lvl,
538 ("%s Unable to open configuration file \"%s\":\n\t%s\n",
539 func, FileName, strerror(errno)) );
540 free(ret);
541 return NULL;
544 ret->p = ret->buf;
545 return( ret );
546 } /* OpenConfFile */
548 BOOL pm_process( char *FileName,
549 BOOL (*sfunc)(char *),
550 BOOL (*pfunc)(char *, char *) )
551 /* ------------------------------------------------------------------------ **
552 * Process the named parameter file.
554 * Input: FileName - The pathname of the parameter file to be opened.
555 * sfunc - A pointer to a function that will be called when
556 * a section name is discovered.
557 * pfunc - A pointer to a function that will be called when
558 * a parameter name and value are discovered.
560 * Output: TRUE if the file was successfully parsed, else FALSE.
562 * ------------------------------------------------------------------------ **
565 int result;
566 myFILE *InFile;
567 char *func = "params.c:pm_process() -";
569 InFile = OpenConfFile( FileName ); /* Open the config file. */
570 if( NULL == InFile )
571 return( False );
573 DEBUG( 3, ("%s Processing configuration file \"%s\"\n", func, FileName) );
575 if( NULL != bufr ) /* If we already have a buffer */
576 result = Parse( InFile, sfunc, pfunc ); /* (recursive call), then just */
577 /* use it. */
579 else /* If we don't have a buffer */
580 { /* allocate one, then parse, */
581 bSize = BUFR_INC; /* then free. */
582 bufr = (char *)malloc( bSize );
583 if( NULL == bufr )
585 DEBUG(0,("%s memory allocation failure.\n", func));
586 myfile_close(InFile);
587 return( False );
589 result = Parse( InFile, sfunc, pfunc );
590 free( bufr );
591 bufr = NULL;
592 bSize = 0;
595 myfile_close(InFile);
597 if( !result ) /* Generic failure. */
599 DEBUG(0,("%s Failed. Error returned from params.c:parse().\n", func));
600 return( False );
603 return( True ); /* Generic success. */
604 } /* pm_process */
606 /* -------------------------------------------------------------------------- */