1 /*  Copyright (C) 2003 Aleksey Krivoshey <krivoshey@users.sourceforge.net>
 
   3 *   This program is free software; you can redistribute it and/or modify
 
   4 *   it under the terms of the GNU General Public License as published by
 
   5 *   the Free Software Foundation; either version 2 of the License, or
 
   6 *   (at your option) any later version.
 
   8 *   This program is distributed in the hope that it will be useful,
 
   9 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 
  10 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
  11 *   GNU General Public License for more details.
 
  13 *   You should have received a copy of the GNU General Public License
 
  14 *   along with this program; if not, write to the Free Software
 
  15 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
  18 #include <libgen.h> // dirname
 
  19 #include <glob.h> // glob
 
  22 #include "dotconfpp.h"
 
  24 DOTCONFDocumentNode::DOTCONFDocumentNode():previousNode(NULL), nextNode(NULL), parentNode(NULL), childNode(NULL),
 
  25     values(NULL), valuesCount(0), 
 
  26     name(NULL), lineNum(0), fileName(NULL), closed(true)
 
  30 DOTCONFDocumentNode::~DOTCONFDocumentNode()
 
  34         for(int i = 0 ; i < valuesCount; i++){
 
  41 void DOTCONFDocumentNode::pushValue(char * _value)
 
  44     values = (char**)realloc(values, valuesCount*sizeof(char*));
 
  45     values[valuesCount-1] = strdup(_value);
 
  48 const char* DOTCONFDocumentNode::getValue(int index) const
 
  50     if(index >= valuesCount){
 
  56 DOTCONFDocument::DOTCONFDocument(DOTCONFDocument::CaseSensitive caseSensitivity):
 
  58     curParent(NULL), curPrev(NULL), errorCallback(NULL), errorCallbackData(NULL),
 
  59     curLine(0), file(NULL), fileName(NULL)
 
  61     if(caseSensitivity == CASESENSITIVE){
 
  64         cmp_func = strcasecmp;
 
  67     mempool = new AsyncDNSMemPool(1024);
 
  68     mempool->initialize();
 
  71 DOTCONFDocument::~DOTCONFDocument()
 
  73     for(std::list<DOTCONFDocumentNode*>::iterator i = nodeTree.begin(); i != nodeTree.end(); i++){
 
  76     for(std::list<char*>::iterator i = requiredOptions.begin(); i != requiredOptions.end(); i++){
 
  79     for(std::list<char*>::iterator i = processedFiles.begin(); i != processedFiles.end(); i++){
 
  86 int DOTCONFDocument::cleanupLine(char * line)
 
  90     bool multiline = false;
 
  94     if(!words.empty() && quoted)
 
  98         if((*line == '#' || *line == ';') && !quoted){
 
 101                 //printf("2start='%s'\n", start);
 
 103                     word = (char*)mempool->alloc(strlen(words.back())+strlen(start)+1);
 
 104                     strcpy(word, words.back());
 
 109                     word = mempool->strdup(start);
 
 111                 words.push_back(word);
 
 115         if(*line == '=' && !quoted){ // 'parameter = value' is the same as 'parameter value' but do not replace with ' ' when used in quoted value
 
 116             *line = ' ';continue;
 
 118         if(*line == '\\' && (*(line+1) == '"' || *(line+1) == '\'')){
 
 122         if(*line == '\\' && *(line+1) == 'n'){
 
 126         if(*line == '\\' && *(line+1) == 'r'){
 
 130         if(*line == '\\' && (*(line+1) == '\n' || *(line+1) == '\r')){ //multiline
 
 133                 //printf("3start='%s'\n", start);
 
 135                     word = (char*)mempool->alloc(strlen(words.back())+strlen(start)+1);
 
 136                     strcpy(word, words.back());
 
 141                     word = mempool->strdup(start);
 
 143                 words.push_back(word);
 
 148         if(*line == '"' || *line == '\''){ //need to handle quotes because of spaces or = that may be between
 
 152         if(isspace(*line) && !quoted){
 
 155                 //printf("start='%s'\n", start);
 
 157                     word = (char*)mempool->alloc(strlen(words.back())+strlen(start)+1);
 
 158                     strcpy(word, words.back());
 
 163                     word = mempool->strdup(start);
 
 165                 words.push_back(word);
 
 168             while(isspace(*++line)) {};
 
 174     if(quoted && !multiline){
 
 175         error(curLine, fileName, "unterminated quote");
 
 179     return multiline?1:0;
 
 182 int DOTCONFDocument::parseLine()
 
 185     char * nodeName = NULL;
 
 186     char * nodeValue = NULL;
 
 187     DOTCONFDocumentNode * tagNode = NULL;
 
 188     bool newNode = false;
 
 190     for(std::list<char*>::iterator i = words.begin(); i != words.end(); i++) {
 
 203         size_t wordLen = strlen(word);
 
 204         if(word[wordLen-1] == '>'){
 
 209         if(nodeName == NULL){
 
 211             bool closed = true; //if this not <> node then it is closed by default
 
 212             if(*nodeName == '<'){
 
 213                 if(*(nodeName+1) != '/'){ //opening tag
 
 216                 } else { //closing tag
 
 218                     std::list<DOTCONFDocumentNode*>::reverse_iterator i=nodeTree.rbegin();
 
 219                     for(; i!=nodeTree.rend(); i++){
 
 220                         if(!cmp_func(nodeName, (*i)->name) && !(*i)->closed){
 
 222                             curParent = (*i)->parentNode;
 
 227                     if(i==nodeTree.rend()){
 
 228                         error(curLine, fileName, "not matched closing tag </%s>", nodeName);
 
 234             tagNode = new DOTCONFDocumentNode;
 
 235             tagNode->name = strdup(nodeName);
 
 236             tagNode->document = this;
 
 237             tagNode->fileName = processedFiles.back();
 
 238             tagNode->lineNum = curLine;
 
 239             tagNode->closed = closed;
 
 240             if(!nodeTree.empty()){
 
 241                 DOTCONFDocumentNode * prev = nodeTree.back();
 
 244                     curPrev->nextNode = tagNode;
 
 245                     tagNode->previousNode = curPrev;
 
 246                     tagNode->parentNode = curParent;
 
 249                     prev->childNode = tagNode;
 
 250                     tagNode->parentNode = prev;
 
 254             nodeTree.push_back(tagNode);
 
 258             tagNode->pushValue(nodeValue);
 
 264 int DOTCONFDocument::parseFile(DOTCONFDocumentNode * _parent)
 
 274     while(fgets(str, 511, file)){
 
 278             error(curLine, fileName, "warning: line too long");
 
 280         if(str[slen-1] != '\n'){
 
 284         if((ret = cleanupLine(str)) == -1){
 
 302 int DOTCONFDocument::checkConfig(const std::list<DOTCONFDocumentNode*>::iterator & from)
 
 306     DOTCONFDocumentNode * tagNode = NULL;
 
 308     for(std::list<DOTCONFDocumentNode*>::iterator i = from; i != nodeTree.end(); i++){
 
 310         if(!tagNode->closed){
 
 311             error(tagNode->lineNum, tagNode->fileName, "unclosed tag %s", tagNode->name);
 
 316         while( vi < tagNode->valuesCount ){
 
 317             //if((tagNode->values[vi])[0] == '$' && (tagNode->values[vi])[1] == '{' && strchr(tagNode->values[vi], '}') ){
 
 318             if(strstr(tagNode->values[vi], "${") && strchr(tagNode->values[vi], '}') ){
 
 319                 ret = macroSubstitute(tagNode, vi );
 
 335 int DOTCONFDocument::setContent(const char * _fileName)
 
 338     char realpathBuf[PATH_MAX];
 
 340     if(realpath(_fileName, realpathBuf) == NULL){
 
 341         error(0, NULL, "realpath(%s) failed: %s", _fileName, strerror(errno));
 
 345     fileName = strdup(realpathBuf);
 
 347     char * forPathName = strdup(realpathBuf);
 
 349     if (forPathName == NULL) {
 
 350         error(0, NULL, "Not enought memory to duplicate realpath");
 
 354     char * _pathName = dirname(forPathName);
 
 356     std::string pathName(_pathName);
 
 358     free(forPathName); // From strdup
 
 360     processedFiles.push_back(strdup(realpathBuf));
 
 362     if(( file = fopen(fileName, "r")) == NULL){
 
 363         error(0, NULL, "failed to open file '%s': %s", fileName, strerror(errno));
 
 373         if( (ret = checkConfig(nodeTree.begin())) == -1){
 
 377         std::list<DOTCONFDocumentNode*>::iterator from;
 
 378         DOTCONFDocumentNode * tagNode = NULL;
 
 380         for(std::list<DOTCONFDocumentNode*>::iterator i = nodeTree.begin(); i!=nodeTree.end(); i++){
 
 382             if(!cmp_func("IncludeFile", tagNode->name)){
 
 384                 while( vi < tagNode->valuesCount ){
 
 386                     std::string nodeFilePath;
 
 387                     if (*tagNode->values[vi] != '/') {
 
 389                         nodeFilePath = pathName + "/" + tagNode->values[vi];
 
 392                        nodeFilePath = tagNode->values[vi];
 
 394                     int res = glob(nodeFilePath.c_str(), 0, NULL, &globBuf);
 
 398                                 error(tagNode->lineNum, tagNode->fileName, "glob call failed for '%s': no free space", nodeFilePath.c_str());
 
 402                                 // printf("Read error\n");
 
 406                                 // printf("No match\n");
 
 411                                 error(tagNode->lineNum, tagNode->fileName, "glob call failed for '%s': unknown error", nodeFilePath.c_str());
 
 416                         for (size_t i = 0; i < globBuf.gl_pathc; ++i) {
 
 417                             std::string nodeFilePath(globBuf.gl_pathv[i]);
 
 418                             if(access(nodeFilePath.c_str(), R_OK) == -1){
 
 419                                 error(tagNode->lineNum, tagNode->fileName, "%s: %s", nodeFilePath.c_str(), strerror(errno));
 
 422                             if(realpath(nodeFilePath.c_str(), realpathBuf) == NULL){
 
 423                                 error(tagNode->lineNum, tagNode->fileName, "realpath(%s) failed: %s", nodeFilePath.c_str(), strerror(errno));
 
 427                             bool processed = false;
 
 428                             for(std::list<char*>::const_iterator itInode = processedFiles.begin(); itInode != processedFiles.end(); itInode++){
 
 429                                 if(!strcmp(*itInode, realpathBuf)){
 
 438                             processedFiles.push_back(strdup(realpathBuf));
 
 440                             file = fopen(nodeFilePath.c_str(), "r");
 
 442                                 error(tagNode->lineNum, fileName, "failed to open file '%s': %s", nodeFilePath.c_str(), strerror(errno));
 
 446                             fileName = strdup(realpathBuf);
 
 447                             from = nodeTree.end(); from--;
 
 449                             if(tagNode->parentNode){
 
 450                                 DOTCONFDocumentNode * nd = tagNode->parentNode->childNode;
 
 459                             ret = parseFile(tagNode->parentNode);
 
 461                             //ret = parseFile(tagNode->parentNode);
 
 465                             if(checkConfig(++from) == -1){
 
 476         if( (ret = checkConfig(nodeTree.begin())) == -1){
 
 481         if(!requiredOptions.empty())
 
 482             ret = checkRequiredOptions();
 
 488 int DOTCONFDocument::checkRequiredOptions()
 
 490     for(std::list<char*>::const_iterator ci = requiredOptions.begin(); ci != requiredOptions.end(); ci++){
 
 491         bool matched = false;
 
 492         for(std::list<DOTCONFDocumentNode*>::iterator i = nodeTree.begin(); i!=nodeTree.end(); i++){            
 
 493             if(!cmp_func((*i)->name, *ci)){
 
 499             error(0, NULL, "required option '%s' not specified", *ci);
 
 506 void DOTCONFDocument::error(int lineNum, const char * fileName, const char * fmt, ...)
 
 511     size_t len = (lineNum!=0?strlen(fileName):0) + strlen(fmt) + 50;
 
 512     char * buf = (char*)mempool->alloc(len);
 
 515         (void) snprintf(buf, len, "DOTCONF++: file '%s', line %d: %s\n", fileName, lineNum, fmt);
 
 517         (void) snprintf(buf, len, "DOTCONF++: %s\n", fmt);
 
 520         errorCallback(errorCallbackData, buf);
 
 522         (void) vfprintf(stderr, buf, args);
 
 528 char * DOTCONFDocument::getSubstitution(char * macro, int lineNum)
 
 531     char * variable = macro+2;
 
 533     char * endBr = strchr(macro, '}');
 
 536         error(lineNum, fileName, "unterminated '{'");
 
 541     char * defaultValue = strchr(variable, ':');
 
 545         if(*defaultValue != '-'){
 
 546             error(lineNum, fileName, "incorrect macro substitution syntax");
 
 550         if(*defaultValue == '"' || *defaultValue == '\''){
 
 552             defaultValue[strlen(defaultValue)-1] = 0;
 
 558     char * subs = getenv(variable);
 
 560         buf = mempool->strdup(subs);
 
 562         std::list<DOTCONFDocumentNode*>::iterator i = nodeTree.begin();
 
 563         DOTCONFDocumentNode * tagNode = NULL;
 
 564         for(; i!=nodeTree.end(); i++){            
 
 566             if(!cmp_func(tagNode->name, variable)){
 
 567                 if(tagNode->valuesCount != 0){
 
 568                     buf = mempool->strdup(tagNode->values[0]);
 
 573         if( i == nodeTree.end() ){
 
 575                 buf = mempool->strdup(defaultValue);
 
 577                 error(lineNum, fileName, "substitution not found and default value not given");
 
 585 int DOTCONFDocument::macroSubstitute(DOTCONFDocumentNode * tagNode, int valueIndex)
 
 588     char * macro = tagNode->values[valueIndex];
 
 589     size_t valueLen = strlen(tagNode->values[valueIndex])+1;
 
 590     char * value = (char*)mempool->alloc(valueLen);
 
 595         if(*macro == '$' && *(macro+1) == '{'){
 
 596             char * m = strchr(macro, '}');
 
 597             subs = getSubstitution(macro, tagNode->lineNum);
 
 604             v = (char*)mempool->alloc(strlen(value)+strlen(subs)+valueLen);
 
 606             value = strcat(v, subs);
 
 607             v = value + strlen(value);
 
 614     free(tagNode->values[valueIndex]);
 
 615     tagNode->values[valueIndex] = strdup(value);
 
 619 const DOTCONFDocumentNode * DOTCONFDocument::getFirstNode() const
 
 621     if ( !nodeTree.empty() ) {
 
 622         return *nodeTree.begin();
 
 628 const DOTCONFDocumentNode * DOTCONFDocument::findNode(const char * nodeName, const DOTCONFDocumentNode * parentNode, const DOTCONFDocumentNode * startNode) const
 
 630     //printf("nodeName=%s, cont=%s, start=%s\n", nodeName, containingNode!=NULL?containingNode->name:"NULL", startNode!=NULL?startNode->name:"NULL");
 
 632     std::list<DOTCONFDocumentNode*>::const_iterator i = nodeTree.begin();
 
 634     if(startNode == NULL)
 
 635         startNode = parentNode;
 
 637     if(startNode != NULL){
 
 638         while( i != nodeTree.end() && (*i) != startNode ){
 
 641         if( i != nodeTree.end() ) i++;
 
 644     for(; i!=nodeTree.end(); i++){
 
 645         //if(parentNode != NULL && (*i)->parentNode != parentNode){
 
 646         if((*i)->parentNode != parentNode){
 
 649         if(!cmp_func(nodeName, (*i)->name)){
 
 656 void DOTCONFDocument::setRequiredOptionNames(const char ** requiredOptionNames)
 
 658     while(*requiredOptionNames){
 
 659         requiredOptions.push_back(strdup( *requiredOptionNames ));
 
 660         requiredOptionNames++;