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());
401 // printf("Read error\n");
405 // printf("No match\n");
409 error(tagNode->lineNum, tagNode->fileName, "glob call failed for '%s': unknown error", nodeFilePath.c_str());
414 for (size_t i = 0; i < globBuf.gl_pathc; ++i) {
415 std::string nodeFilePath(globBuf.gl_pathv[i]);
416 if(access(nodeFilePath.c_str(), R_OK) == -1){
417 error(tagNode->lineNum, tagNode->fileName, "%s: %s", nodeFilePath.c_str(), strerror(errno));
420 if(realpath(nodeFilePath.c_str(), realpathBuf) == NULL){
421 error(tagNode->lineNum, tagNode->fileName, "realpath(%s) failed: %s", nodeFilePath.c_str(), strerror(errno));
425 bool processed = false;
426 for(std::list<char*>::const_iterator itInode = processedFiles.begin(); itInode != processedFiles.end(); itInode++){
427 if(!strcmp(*itInode, realpathBuf)){
436 processedFiles.push_back(strdup(realpathBuf));
438 file = fopen(nodeFilePath.c_str(), "r");
440 error(tagNode->lineNum, fileName, "failed to open file '%s': %s", nodeFilePath.c_str(), strerror(errno));
444 fileName = strdup(realpathBuf);
445 from = nodeTree.end(); from--;
447 if(tagNode->parentNode){
448 DOTCONFDocumentNode * nd = tagNode->parentNode->childNode;
457 ret = parseFile(tagNode->parentNode);
459 //ret = parseFile(tagNode->parentNode);
463 if(checkConfig(++from) == -1){
474 if( (ret = checkConfig(nodeTree.begin())) == -1){
479 if(!requiredOptions.empty())
480 ret = checkRequiredOptions();
486 int DOTCONFDocument::checkRequiredOptions()
488 for(std::list<char*>::const_iterator ci = requiredOptions.begin(); ci != requiredOptions.end(); ci++){
489 bool matched = false;
490 for(std::list<DOTCONFDocumentNode*>::iterator i = nodeTree.begin(); i!=nodeTree.end(); i++){
491 if(!cmp_func((*i)->name, *ci)){
497 error(0, NULL, "required option '%s' not specified", *ci);
504 void DOTCONFDocument::error(int lineNum, const char * fileName, const char * fmt, ...)
509 size_t len = (lineNum!=0?strlen(fileName):0) + strlen(fmt) + 50;
510 char * buf = (char*)mempool->alloc(len);
513 (void) snprintf(buf, len, "DOTCONF++: file '%s', line %d: %s\n", fileName, lineNum, fmt);
515 (void) snprintf(buf, len, "DOTCONF++: %s\n", fmt);
518 errorCallback(errorCallbackData, buf);
520 (void) vfprintf(stderr, buf, args);
526 char * DOTCONFDocument::getSubstitution(char * macro, int lineNum)
529 char * variable = macro+2;
531 char * endBr = strchr(macro, '}');
534 error(lineNum, fileName, "unterminated '{'");
539 char * defaultValue = strchr(variable, ':');
543 if(*defaultValue != '-'){
544 error(lineNum, fileName, "incorrect macro substitution syntax");
548 if(*defaultValue == '"' || *defaultValue == '\''){
550 defaultValue[strlen(defaultValue)-1] = 0;
556 char * subs = getenv(variable);
558 buf = mempool->strdup(subs);
560 std::list<DOTCONFDocumentNode*>::iterator i = nodeTree.begin();
561 DOTCONFDocumentNode * tagNode = NULL;
562 for(; i!=nodeTree.end(); i++){
564 if(!cmp_func(tagNode->name, variable)){
565 if(tagNode->valuesCount != 0){
566 buf = mempool->strdup(tagNode->values[0]);
571 if( i == nodeTree.end() ){
573 buf = mempool->strdup(defaultValue);
575 error(lineNum, fileName, "substitution not found and default value not given");
583 int DOTCONFDocument::macroSubstitute(DOTCONFDocumentNode * tagNode, int valueIndex)
586 char * macro = tagNode->values[valueIndex];
587 size_t valueLen = strlen(tagNode->values[valueIndex])+1;
588 char * value = (char*)mempool->alloc(valueLen);
593 if(*macro == '$' && *(macro+1) == '{'){
594 char * m = strchr(macro, '}');
595 subs = getSubstitution(macro, tagNode->lineNum);
602 v = (char*)mempool->alloc(strlen(value)+strlen(subs)+valueLen);
604 value = strcat(v, subs);
605 v = value + strlen(value);
612 free(tagNode->values[valueIndex]);
613 tagNode->values[valueIndex] = strdup(value);
617 const DOTCONFDocumentNode * DOTCONFDocument::getFirstNode() const
619 if ( !nodeTree.empty() ) {
620 return *nodeTree.begin();
626 const DOTCONFDocumentNode * DOTCONFDocument::findNode(const char * nodeName, const DOTCONFDocumentNode * parentNode, const DOTCONFDocumentNode * startNode) const
628 //printf("nodeName=%s, cont=%s, start=%s\n", nodeName, containingNode!=NULL?containingNode->name:"NULL", startNode!=NULL?startNode->name:"NULL");
630 std::list<DOTCONFDocumentNode*>::const_iterator i = nodeTree.begin();
632 if(startNode == NULL)
633 startNode = parentNode;
635 if(startNode != NULL){
636 while( i != nodeTree.end() && (*i) != startNode ){
639 if( i != nodeTree.end() ) i++;
642 for(; i!=nodeTree.end(); i++){
643 //if(parentNode != NULL && (*i)->parentNode != parentNode){
644 if((*i)->parentNode != parentNode){
647 if(!cmp_func(nodeName, (*i)->name)){
654 void DOTCONFDocument::setRequiredOptionNames(const char ** requiredOptionNames)
656 while(*requiredOptionNames){
657 requiredOptions.push_back(strdup( *requiredOptionNames ));
658 requiredOptionNames++;