removed an unreachable statement
[ira/wip.git] / source3 / param / params.c
1 /* -------------------------------------------------------------------------- **
2  * Microsoft Network Services for Unix, AKA., Andrew Tridgell's SAMBA.
3  *
4  * This module Copyright (C) 1990-1998 Karl Auer
5  *
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  * -------------------------------------------------------------------------- **
10  *
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.
15  *
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.
20  *
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.
24  *
25  * -------------------------------------------------------------------------- **
26  *
27  * Module name: params
28  *
29  * -------------------------------------------------------------------------- **
30  *
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.
36  *
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.
41  *
42  *  A sample parameter file might look like this:
43  *
44  *  [section one]
45  *  parameter one = value string
46  *  parameter two = another value
47  *  [section two]
48  *  new parameter = some value or t'other
49  *
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:
55  *
56  *    <file>            :==  { <section> } EOF
57  *
58  *    <section>         :==  <section header> { <parameter line> }
59  *
60  *    <section header>  :==  '[' NAME ']'
61  *
62  *    <parameter line>  :==  NAME '=' VALUE '\n'
63  *
64  *  Blank lines and comment lines are ignored.  Comment lines are lines
65  *  beginning with either a semicolon (';') or a pound sign ('#').
66  *
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.
70  *
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.
78  *
79  * -------------------------------------------------------------------------- **
80  */
81
82 #include "includes.h"
83
84 /* -------------------------------------------------------------------------- **
85  * Constants...
86  */
87
88 #define BUFR_INC 1024
89
90
91 /* -------------------------------------------------------------------------- **
92  * Variables...
93  *
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>.
99  */
100
101 extern int DEBUGLEVEL;
102
103 static char *bufr  = NULL;
104 static int   bSize = 0;
105
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;
113
114 static int mygetc(myFILE *f)
115 {
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 );
119 }
120
121 static void myfile_close(myFILE *f)
122 {
123         if (!f) return;
124         if (f->buf) free(f->buf);
125         free(f);
126 }
127
128 /* -------------------------------------------------------------------------- **
129  * Functions...
130  */
131
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.
136    *
137    *  Input:  InFile  - Input source.
138    *
139    *  Output: The next non-whitespace character in the input stream.
140    *
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.
146    *
147    * ------------------------------------------------------------------------ **
148    */
149   {
150   int c;
151
152   for( c = mygetc( InFile ); isspace( c ) && ('\n' != c); c = mygetc( InFile ) )
153     ;
154   return( c );
155   } /* EatWhitespace */
156
157 static int EatComment( myFILE *InFile )
158   /* ------------------------------------------------------------------------ **
159    * Scan to the end of a comment.
160    *
161    *  Input:  InFile  - Input source.
162    *
163    *  Output: The character that marks the end of the comment.  Normally,
164    *          this will be a newline, but it *might* be an EOF.
165    *
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.
171    *
172    * ------------------------------------------------------------------------ **
173    */
174   {
175   int c;
176
177   for( c = mygetc( InFile ); ('\n'!=c) && (EOF!=c) && (c>0); c = mygetc( InFile ) )
178     ;
179   return( c );
180   } /* EatComment */
181
182 /*****************************************************************************
183  * Scan backards within a string to discover if the last non-whitespace
184  * character is a line-continuation character ('\\').
185  *
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.
190  *
191  *  Output: The offset of the '\\' character if it was found, or -1 to
192  *          indicate that it was not.
193  *
194  *****************************************************************************/
195
196 static int Continuation( char *line, int pos )
197 {
198         pos--;
199         while( (pos >= 0) && isspace(line[pos]) )
200                 pos--;
201
202         return (((pos >= 0) && ('\\' == line[pos])) ? pos : -1 );
203 }
204
205
206 static BOOL Section( myFILE *InFile, BOOL (*sfunc)(char *) )
207   /* ------------------------------------------------------------------------ **
208    * Scan a section name, and pass the name to function sfunc().
209    *
210    *  Input:  InFile  - Input source.
211    *          sfunc   - Pointer to the function to be called if the section
212    *                    name is successfully read.
213    *
214    *  Output: True if the section name was read and True was returned from
215    *          <sfunc>.  False if <sfunc> failed or if a lexical error was
216    *          encountered.
217    *
218    * ------------------------------------------------------------------------ **
219    */
220   {
221   int   c;
222   int   i;
223   int   end;
224   char *func  = "params.c:Section() -";
225
226   i = 0;      /* <i> is the offset of the next free byte in bufr[] and  */
227   end = 0;    /* <end> is the current "end of string" offset.  In most  */
228               /* cases these will be the same, but if the last          */
229               /* character written to bufr[] is a space, then <end>     */
230               /* will be one less than <i>.                             */
231
232   c = EatWhitespace( InFile );    /* We've already got the '['.  Scan */
233                                   /* past initial white space.        */
234
235   while( (EOF != c) && (c > 0) )
236     {
237
238     /* Check that the buffer is big enough for the next character. */
239     if( i > (bSize - 2) )
240       {
241       bSize += BUFR_INC;
242       bufr   = Realloc( bufr, bSize );
243       if( NULL == bufr )
244         {
245         DEBUG(0, ("%s Memory re-allocation failure.", func) );
246         return( False );
247         }
248       }
249
250     /* Handle a single character. */
251     switch( c )
252       {
253       case ']':                       /* Found the closing bracket.         */
254         bufr[end] = '\0';
255         if( 0 == end )                  /* Don't allow an empty name.       */
256           {
257           DEBUG(0, ("%s Empty section name in configuration file.\n", func ));
258           return( False );
259           }
260         if( !sfunc(bufr) )            /* Got a valid name.  Deal with it. */
261           return( False );
262         (void)EatComment( InFile );     /* Finish off the line.             */
263         return( True );
264
265       case '\n':                      /* Got newline before closing ']'.    */
266         i = Continuation( bufr, i );    /* Check for line continuation.     */
267         if( i < 0 )
268           {
269           bufr[end] = '\0';
270           DEBUG(0, ("%s Badly formed line in configuration file: %s\n",
271                    func, bufr ));
272           return( False );
273           }
274         end = ( (i > 0) && (' ' == bufr[i - 1]) ) ? (i - 1) : (i);
275         c = mygetc( InFile );             /* Continue with next line.         */
276         break;
277
278       default:                        /* All else are a valid name chars.   */
279         if( isspace( c ) )              /* One space per whitespace region. */
280           {
281           bufr[end] = ' ';
282           i = end + 1;
283           c = EatWhitespace( InFile );
284           }
285         else                            /* All others copy verbatim.        */
286           {
287           bufr[i++] = c;
288           end = i;
289           c = mygetc( InFile );
290           }
291       }
292     }
293
294   /* We arrive here if we've met the EOF before the closing bracket. */
295   DEBUG(0, ("%s Unexpected EOF in the configuration file: %s\n", func, bufr ));
296   return( False );
297   } /* Section */
298
299 static BOOL Parameter( myFILE *InFile, BOOL (*pfunc)(char *, char *), int c )
300   /* ------------------------------------------------------------------------ **
301    * Scan a parameter name and value, and pass these two fields to pfunc().
302    *
303    *  Input:  InFile  - The input source.
304    *          pfunc   - A pointer to the function that will be called to
305    *                    process the parameter, once it has been scanned.
306    *          c       - The first character of the parameter name, which
307    *                    would have been read by Parse().  Unlike a comment
308    *                    line or a section header, there is no lead-in
309    *                    character that can be discarded.
310    *
311    *  Output: True if the parameter name and value were scanned and processed
312    *          successfully, else False.
313    *
314    *  Notes:  This function is in two parts.  The first loop scans the
315    *          parameter name.  Internal whitespace is compressed, and an
316    *          equal sign (=) terminates the token.  Leading and trailing
317    *          whitespace is discarded.  The second loop scans the parameter
318    *          value.  When both have been successfully identified, they are
319    *          passed to pfunc() for processing.
320    *
321    * ------------------------------------------------------------------------ **
322    */
323   {
324   int   i       = 0;    /* Position within bufr. */
325   int   end     = 0;    /* bufr[end] is current end-of-string. */
326   int   vstart  = 0;    /* Starting position of the parameter value. */
327   char *func    = "params.c:Parameter() -";
328
329   /* Read the parameter name. */
330   while( 0 == vstart )  /* Loop until we've found the start of the value. */
331     {
332
333     if( i > (bSize - 2) )       /* Ensure there's space for next char.    */
334       {
335       bSize += BUFR_INC;
336       bufr   = Realloc( bufr, bSize );
337       if( NULL == bufr )
338         {
339         DEBUG(0, ("%s Memory re-allocation failure.", func) );
340         return( False );
341         }
342       }
343
344     switch( c )
345       {
346       case '=':                 /* Equal sign marks end of param name. */
347         if( 0 == end )              /* Don't allow an empty name.      */
348           {
349           DEBUG(0, ("%s Invalid parameter name in config. file.\n", func ));
350           return( False );
351           }
352         bufr[end++] = '\0';         /* Mark end of string & advance.   */
353         i       = end;              /* New string starts here.         */
354         vstart  = end;              /* New string is parameter value.  */
355         bufr[i] = '\0';             /* New string is nul, for now.     */
356         break;
357
358       case '\n':                /* Find continuation char, else error. */
359         i = Continuation( bufr, i );
360         if( i < 0 )
361           {
362           bufr[end] = '\0';
363           DEBUG(1,("%s Ignoring badly formed line in configuration file: %s\n",
364                    func, bufr ));
365           return( True );
366           }
367         end = ( (i > 0) && (' ' == bufr[i - 1]) ) ? (i - 1) : (i);
368         c = mygetc( InFile );       /* Read past eoln.                   */
369         break;
370
371       case '\0':                /* Shouldn't have EOF within param name. */
372       case EOF:
373         bufr[i] = '\0';
374         DEBUG(1,("%s Unexpected end-of-file at: %s\n", func, bufr ));
375         return( True );
376
377       default:
378         if( isspace( c ) )     /* One ' ' per whitespace region.       */
379           {
380           bufr[end] = ' ';
381           i = end + 1;
382           c = EatWhitespace( InFile );
383           }
384         else                   /* All others verbatim.                 */
385           {
386           bufr[i++] = c;
387           end = i;
388           c = mygetc( InFile );
389           }
390       }
391     }
392
393   /* Now parse the value. */
394   c = EatWhitespace( InFile );  /* Again, trim leading whitespace. */
395   while( (EOF !=c) && (c > 0) )
396     {
397
398     if( i > (bSize - 2) )       /* Make sure there's enough room. */
399       {
400       bSize += BUFR_INC;
401       bufr   = Realloc( bufr, bSize );
402       if( NULL == bufr )
403         {
404         DEBUG(0, ("%s Memory re-allocation failure.", func) );
405         return( False );
406         }
407       }
408
409     switch( c )
410       {
411       case '\r':              /* Explicitly remove '\r' because the older */
412         c = mygetc( InFile );   /* version called fgets_slash() which also  */
413         break;                /* removes them.                            */
414
415       case '\n':              /* Marks end of value unless there's a '\'. */
416         i = Continuation( bufr, i );
417         if( i < 0 )
418           c = 0;
419         else
420           {
421           for( end = i; (end >= 0) && isspace(bufr[end]); end-- )
422             ;
423           c = mygetc( InFile );
424           }
425         break;
426
427       default:               /* All others verbatim.  Note that spaces do */
428         bufr[i++] = c;       /* not advance <end>.  This allows trimming  */
429         if( !isspace( c ) )  /* of whitespace at the end of the line.     */
430           end = i;
431         c = mygetc( InFile );
432         break;
433       }
434     }
435   bufr[end] = '\0';          /* End of value. */
436
437   return( pfunc( bufr, &bufr[vstart] ) );   /* Pass name & value to pfunc().  */
438   } /* Parameter */
439
440 static BOOL Parse( myFILE *InFile,
441                    BOOL (*sfunc)(char *),
442                    BOOL (*pfunc)(char *, char *) )
443   /* ------------------------------------------------------------------------ **
444    * Scan & parse the input.
445    *
446    *  Input:  InFile  - Input source.
447    *          sfunc   - Function to be called when a section name is scanned.
448    *                    See Section().
449    *          pfunc   - Function to be called when a parameter is scanned.
450    *                    See Parameter().
451    *
452    *  Output: True if the file was successfully scanned, else False.
453    *
454    *  Notes:  The input can be viewed in terms of 'lines'.  There are four
455    *          types of lines:
456    *            Blank      - May contain whitespace, otherwise empty.
457    *            Comment    - First non-whitespace character is a ';' or '#'.
458    *                         The remainder of the line is ignored.
459    *            Section    - First non-whitespace character is a '['.
460    *            Parameter  - The default case.
461    * 
462    * ------------------------------------------------------------------------ **
463    */
464   {
465   int    c;
466
467   c = EatWhitespace( InFile );
468   while( (EOF != c) && (c > 0) )
469     {
470     switch( c )
471       {
472       case '\n':                        /* Blank line. */
473         c = EatWhitespace( InFile );
474         break;
475
476       case ';':                         /* Comment line. */
477       case '#':
478         c = EatComment( InFile );
479         break;
480
481       case '[':                         /* Section Header. */
482         if( !Section( InFile, sfunc ) )
483           return( False );
484         c = EatWhitespace( InFile );
485         break;
486
487       case '\\':                        /* Bogus backslash. */
488         c = EatWhitespace( InFile );
489         break;
490
491       default:                          /* Parameter line. */
492         if( !Parameter( InFile, pfunc, c ) )
493           return( False );
494         c = EatWhitespace( InFile );
495         break;
496       }
497     }
498   return( True );
499   } /* Parse */
500
501 static myFILE *OpenConfFile( char *FileName )
502   /* ------------------------------------------------------------------------ **
503    * Open a configuration file.
504    *
505    *  Input:  FileName  - The pathname of the config file to be opened.
506    *
507    *  Output: A pointer of type (char **) to the lines of the file
508    *
509    * ------------------------------------------------------------------------ **
510    */
511   {
512   char *func = "params.c:OpenConfFile() -";
513   extern BOOL in_client;
514   int lvl = in_client?1:0;
515   myFILE *ret;
516
517   ret = (myFILE *)malloc(sizeof(*ret));
518   if (!ret) return NULL;
519
520   ret->buf = file_load(FileName, &ret->size);
521   if( NULL == ret->buf )
522     {
523     DEBUG( lvl,
524       ("%s Unable to open configuration file \"%s\":\n\t%s\n",
525       func, FileName, strerror(errno)) );
526     free(ret);
527     return NULL;
528     }
529
530   ret->p = ret->buf;
531   return( ret );
532   } /* OpenConfFile */
533
534 BOOL pm_process( char *FileName,
535                  BOOL (*sfunc)(char *),
536                  BOOL (*pfunc)(char *, char *) )
537   /* ------------------------------------------------------------------------ **
538    * Process the named parameter file.
539    *
540    *  Input:  FileName  - The pathname of the parameter file to be opened.
541    *          sfunc     - A pointer to a function that will be called when
542    *                      a section name is discovered.
543    *          pfunc     - A pointer to a function that will be called when
544    *                      a parameter name and value are discovered.
545    *
546    *  Output: TRUE if the file was successfully parsed, else FALSE.
547    *
548    * ------------------------------------------------------------------------ **
549    */
550   {
551   int   result;
552   myFILE *InFile;
553   char *func = "params.c:pm_process() -";
554
555   InFile = OpenConfFile( FileName );          /* Open the config file. */
556   if( NULL == InFile )
557     return( False );
558
559   DEBUG( 3, ("%s Processing configuration file \"%s\"\n", func, FileName) );
560
561   if( NULL != bufr )                          /* If we already have a buffer */
562     result = Parse( InFile, sfunc, pfunc );   /* (recursive call), then just */
563                                               /* use it.                     */
564
565   else                                        /* If we don't have a buffer   */
566     {                                         /* allocate one, then parse,   */
567     bSize = BUFR_INC;                         /* then free.                  */
568     bufr = (char *)malloc( bSize );
569     if( NULL == bufr )
570       {
571       DEBUG(0,("%s memory allocation failure.\n", func));
572       myfile_close(InFile);
573       return( False );
574       }
575     result = Parse( InFile, sfunc, pfunc );
576     free( bufr );
577     bufr  = NULL;
578     bSize = 0;
579     }
580
581   myfile_close(InFile);
582
583   if( !result )                               /* Generic failure. */
584     {
585     DEBUG(0,("%s Failed.  Error returned from params.c:parse().\n", func));
586     return( False );
587     }
588
589   return( True );                             /* Generic success. */
590   } /* pm_process */
591
592 /* -------------------------------------------------------------------------- */