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