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