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