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"
25 DOTCONFDocumentNode::DOTCONFDocumentNode():previousNode(NULL), nextNode(NULL), parentNode(NULL), childNode(NULL),
26 values(NULL), valuesCount(0),
27 name(NULL), lineNum(0), fileName(NULL), closed(true)
31 DOTCONFDocumentNode::~DOTCONFDocumentNode()
35 for(int i = 0 ; i < valuesCount; i++){
42 void DOTCONFDocumentNode::pushValue(char * _value)
45 values = (char**)realloc(values, valuesCount*sizeof(char*));
46 values[valuesCount-1] = strdup(_value);
49 const char* DOTCONFDocumentNode::getValue(int index) const
51 if(index >= valuesCount){
57 DOTCONFDocument::DOTCONFDocument(DOTCONFDocument::CaseSensitive caseSensitivity):
59 curParent(NULL), curPrev(NULL), errorCallback(NULL), errorCallbackData(NULL),
60 curLine(0), file(NULL), fileName(NULL)
62 if(caseSensitivity == CASESENSITIVE){
65 cmp_func = strcasecmp;
68 mempool = new AsyncDNSMemPool(1024);
69 mempool->initialize();
72 DOTCONFDocument::~DOTCONFDocument()
74 for(std::list<DOTCONFDocumentNode*>::iterator i = nodeTree.begin(); i != nodeTree.end(); i++){
77 for(std::list<char*>::iterator i = requiredOptions.begin(); i != requiredOptions.end(); i++){
80 for(std::list<char*>::iterator i = processedFiles.begin(); i != processedFiles.end(); i++){
87 int DOTCONFDocument::cleanupLine(char * line)
91 bool multiline = false;
95 if(!words.empty() && quoted)
99 if((*line == '#' || *line == ';') && !quoted){
102 //printf("2start='%s'\n", start);
104 word = (char*)mempool->alloc(strlen(words.back())+strlen(start)+1);
105 strcpy(word, words.back());
110 word = mempool->strdup(start);
112 words.push_back(word);
116 if(*line == '=' && !quoted){ // 'parameter = value' is the same as 'parameter value' but do not replace with ' ' when used in quoted value
117 *line = ' ';continue;
119 if(*line == '\\' && (*(line+1) == '"' || *(line+1) == '\'')){
123 if(*line == '\\' && *(line+1) == 'n'){
127 if(*line == '\\' && *(line+1) == 'r'){
131 if(*line == '\\' && (*(line+1) == '\n' || *(line+1) == '\r')){ //multiline
134 //printf("3start='%s'\n", start);
136 word = (char*)mempool->alloc(strlen(words.back())+strlen(start)+1);
137 strcpy(word, words.back());
142 word = mempool->strdup(start);
144 words.push_back(word);
149 if(*line == '"' || *line == '\''){ //need to handle quotes because of spaces or = that may be between
153 if(isspace(*line) && !quoted){
156 //printf("start='%s'\n", start);
158 word = (char*)mempool->alloc(strlen(words.back())+strlen(start)+1);
159 strcpy(word, words.back());
164 word = mempool->strdup(start);
166 words.push_back(word);
169 while(isspace(*++line)) {};
175 if(quoted && !multiline){
176 error(curLine, fileName, "unterminated quote");
180 return multiline?1:0;
183 int DOTCONFDocument::parseLine()
186 char * nodeName = NULL;
187 char * nodeValue = NULL;
188 DOTCONFDocumentNode * tagNode = NULL;
189 bool newNode = false;
191 for(std::list<char*>::iterator i = words.begin(); i != words.end(); i++) {
204 size_t wordLen = strlen(word);
205 if(word[wordLen-1] == '>'){
210 if(nodeName == NULL){
212 bool closed = true; //if this not <> node then it is closed by default
213 if(*nodeName == '<'){
214 if(*(nodeName+1) != '/'){ //opening tag
217 } else { //closing tag
219 std::list<DOTCONFDocumentNode*>::reverse_iterator i=nodeTree.rbegin();
220 for(; i!=nodeTree.rend(); i++){
221 if(!cmp_func(nodeName, (*i)->name) && !(*i)->closed){
223 curParent = (*i)->parentNode;
228 if(i==nodeTree.rend()){
229 error(curLine, fileName, "not matched closing tag </%s>", nodeName);
235 tagNode = new DOTCONFDocumentNode;
236 tagNode->name = strdup(nodeName);
237 tagNode->document = this;
238 tagNode->fileName = processedFiles.back();
239 tagNode->lineNum = curLine;
240 tagNode->closed = closed;
241 if(!nodeTree.empty()){
242 DOTCONFDocumentNode * prev = nodeTree.back();
245 curPrev->nextNode = tagNode;
246 tagNode->previousNode = curPrev;
247 tagNode->parentNode = curParent;
250 prev->childNode = tagNode;
251 tagNode->parentNode = prev;
255 nodeTree.push_back(tagNode);
259 tagNode->pushValue(nodeValue);
265 int DOTCONFDocument::parseFile(DOTCONFDocumentNode * _parent)
275 while(fgets(str, 511, file)){
279 error(curLine, fileName, "warning: line too long");
281 if(str[slen-1] != '\n'){
285 if((ret = cleanupLine(str)) == -1){
303 int DOTCONFDocument::checkConfig(const std::list<DOTCONFDocumentNode*>::iterator & from)
307 DOTCONFDocumentNode * tagNode = NULL;
309 for(std::list<DOTCONFDocumentNode*>::iterator i = from; i != nodeTree.end(); i++){
311 if(!tagNode->closed){
312 error(tagNode->lineNum, tagNode->fileName, "unclosed tag %s", tagNode->name);
317 while( vi < tagNode->valuesCount ){
318 //if((tagNode->values[vi])[0] == '$' && (tagNode->values[vi])[1] == '{' && strchr(tagNode->values[vi], '}') ){
319 if(strstr(tagNode->values[vi], "${") && strchr(tagNode->values[vi], '}') ){
320 ret = macroSubstitute(tagNode, vi );
336 int DOTCONFDocument::setContent(const char * _fileName)
339 char realpathBuf[PATH_MAX];
341 if(realpath(_fileName, realpathBuf) == NULL){
342 error(0, _fileName, "realpath('%s') failed: %s", _fileName, strerror(errno));
346 fileName = strdup(realpathBuf);
348 char * forPathName = strdup(realpathBuf);
350 if (forPathName == NULL) {
351 error(0, NULL, "Not enought memory to duplicate realpath");
355 char * _pathName = dirname(forPathName);
357 std::string pathName(_pathName);
359 free(forPathName); // From strdup
361 processedFiles.push_back(strdup(realpathBuf));
363 if(( file = fopen(fileName, "r")) == NULL){
364 error(0, NULL, "failed to open file '%s': %s", fileName, strerror(errno));
374 if( (ret = checkConfig(nodeTree.begin())) == -1){
378 std::list<DOTCONFDocumentNode*>::iterator from;
379 DOTCONFDocumentNode * tagNode = NULL;
381 for(std::list<DOTCONFDocumentNode*>::iterator i = nodeTree.begin(); i!=nodeTree.end(); i++){
383 if(!cmp_func("IncludeFile", tagNode->name)){
385 while( vi < tagNode->valuesCount ){
387 std::string nodeFilePath;
388 if (*tagNode->values[vi] != '/') {
390 nodeFilePath = pathName + "/" + tagNode->values[vi];
393 nodeFilePath = tagNode->values[vi];
395 int res = glob(nodeFilePath.c_str(), 0, NULL, &globBuf);
399 error(tagNode->lineNum, tagNode->fileName, "glob call failed for '%s': no free space", nodeFilePath.c_str());
403 // printf("Read error\n");
407 // printf("No match\n");
412 error(tagNode->lineNum, tagNode->fileName, "glob call failed for '%s': unknown error", nodeFilePath.c_str());
417 for (size_t i = 0; i < globBuf.gl_pathc; ++i) {
418 std::string nodeFilePath(globBuf.gl_pathv[i]);
419 if(access(nodeFilePath.c_str(), R_OK) == -1){
420 error(tagNode->lineNum, tagNode->fileName, "%s: %s", nodeFilePath.c_str(), strerror(errno));
423 if(realpath(nodeFilePath.c_str(), realpathBuf) == NULL){
424 error(tagNode->lineNum, tagNode->fileName, "realpath(%s) failed: %s", nodeFilePath.c_str(), strerror(errno));
428 bool processed = false;
429 for(std::list<char*>::const_iterator itInode = processedFiles.begin(); itInode != processedFiles.end(); itInode++){
430 if(!strcmp(*itInode, realpathBuf)){
439 processedFiles.push_back(strdup(realpathBuf));
441 file = fopen(nodeFilePath.c_str(), "r");
443 error(tagNode->lineNum, fileName, "failed to open file '%s': %s", nodeFilePath.c_str(), strerror(errno));
447 fileName = strdup(realpathBuf);
448 from = nodeTree.end(); from--;
450 if(tagNode->parentNode){
451 DOTCONFDocumentNode * nd = tagNode->parentNode->childNode;
460 ret = parseFile(tagNode->parentNode);
462 //ret = parseFile(tagNode->parentNode);
466 if(checkConfig(++from) == -1){
477 if( (ret = checkConfig(nodeTree.begin())) == -1){
482 if(!requiredOptions.empty())
483 ret = checkRequiredOptions();
489 int DOTCONFDocument::checkRequiredOptions()
491 for(std::list<char*>::const_iterator ci = requiredOptions.begin(); ci != requiredOptions.end(); ci++){
492 bool matched = false;
493 for(std::list<DOTCONFDocumentNode*>::iterator i = nodeTree.begin(); i!=nodeTree.end(); i++){
494 if(!cmp_func((*i)->name, *ci)){
500 error(0, NULL, "required option '%s' not specified", *ci);
507 void DOTCONFDocument::error(int lineNum, const char * fileName, const char * fmt, ...)
514 vsnprintf(msg, 256, fmt, args);
516 size_t len = (lineNum!=0?strlen(fileName):0) + strlen(msg) + 50;
517 char * buf = (char*)mempool->alloc(len);
520 (void) snprintf(buf, len, "DOTCONF++: file '%s', line %d: %s\n", fileName, lineNum, msg);
522 (void) snprintf(buf, len, "DOTCONF++: file '%s': %s\n", fileName, msg);
525 errorCallback(errorCallbackData, buf);
527 (void) vfprintf(stderr, buf, args);
533 char * DOTCONFDocument::getSubstitution(char * macro, int lineNum)
536 char * variable = macro+2;
538 char * endBr = strchr(macro, '}');
541 error(lineNum, fileName, "unterminated '{'");
546 char * defaultValue = strchr(variable, ':');
550 if(*defaultValue != '-'){
551 error(lineNum, fileName, "incorrect macro substitution syntax");
555 if(*defaultValue == '"' || *defaultValue == '\''){
557 defaultValue[strlen(defaultValue)-1] = 0;
563 char * subs = getenv(variable);
565 buf = mempool->strdup(subs);
567 std::list<DOTCONFDocumentNode*>::iterator i = nodeTree.begin();
568 DOTCONFDocumentNode * tagNode = NULL;
569 for(; i!=nodeTree.end(); i++){
571 if(!cmp_func(tagNode->name, variable)){
572 if(tagNode->valuesCount != 0){
573 buf = mempool->strdup(tagNode->values[0]);
578 if( i == nodeTree.end() ){
580 buf = mempool->strdup(defaultValue);
582 error(lineNum, fileName, "substitution not found and default value not given");
590 int DOTCONFDocument::macroSubstitute(DOTCONFDocumentNode * tagNode, int valueIndex)
593 char * macro = tagNode->values[valueIndex];
594 size_t valueLen = strlen(tagNode->values[valueIndex])+1;
595 char * value = (char*)mempool->alloc(valueLen);
600 if(*macro == '$' && *(macro+1) == '{'){
601 char * m = strchr(macro, '}');
602 subs = getSubstitution(macro, tagNode->lineNum);
609 v = (char*)mempool->alloc(strlen(value)+strlen(subs)+valueLen);
611 value = strcat(v, subs);
612 v = value + strlen(value);
619 free(tagNode->values[valueIndex]);
620 tagNode->values[valueIndex] = strdup(value);
624 const DOTCONFDocumentNode * DOTCONFDocument::getFirstNode() const
626 if ( !nodeTree.empty() ) {
627 return *nodeTree.begin();
633 const DOTCONFDocumentNode * DOTCONFDocument::findNode(const char * nodeName, const DOTCONFDocumentNode * parentNode, const DOTCONFDocumentNode * startNode) const
635 //printf("nodeName=%s, cont=%s, start=%s\n", nodeName, containingNode!=NULL?containingNode->name:"NULL", startNode!=NULL?startNode->name:"NULL");
637 std::list<DOTCONFDocumentNode*>::const_iterator i = nodeTree.begin();
639 if(startNode == NULL)
640 startNode = parentNode;
642 if(startNode != NULL){
643 while( i != nodeTree.end() && (*i) != startNode ){
646 if( i != nodeTree.end() ) i++;
649 for(; i!=nodeTree.end(); i++){
650 //if(parentNode != NULL && (*i)->parentNode != parentNode){
651 if((*i)->parentNode != parentNode){
654 if(!cmp_func(nodeName, (*i)->name)){
661 void DOTCONFDocument::setRequiredOptionNames(const char ** requiredOptionNames)
663 while(*requiredOptionNames){
664 requiredOptions.push_back(strdup( *requiredOptionNames ));
665 requiredOptionNames++;