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