root/lib/util/params.c

/* [<][>][^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. mygetc
  2. EatWhitespace
  3. EatComment
  4. Continuation
  5. Section
  6. Parameter
  7. Parse
  8. OpenConfFile
  9. pm_process

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

/* [<][>][^][v][top][bottom][index][help] */