2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
6 * This file is part of InspIRCd. InspIRCd is free software: you can
7 * redistribute it and/or modify it under the terms of the GNU General Public
8 * License as published by the Free Software Foundation, version 2.
10 * This program is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
12 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #include "configparser.h"
26 // Legacy config parsing should be used.
29 // Executable includes are disabled.
32 // All includes are disabled.
36 // Represents the position within a config file.
39 // The name of the file which is being read.
42 // The line of the file that this position points to.
45 // The column of the file that this position points to.
48 FilePosition(const std::string& Name)
55 /** Returns a string that represents this file position. */
58 return name + ":" + ConvToStr(line) + ":" + ConvToStr(column);
62 // RAII wrapper for FILE* which closes the file when it goes out of scope.
66 // Whether this file handle should be closed with pclose.
67 bool close_with_pclose;
69 // The file handle which is being wrapped.
73 FileWrapper(FILE* File, bool CloseWithPClose = false)
74 : close_with_pclose(CloseWithPClose)
79 // Operator which determines whether the file is open.
80 operator bool() { return (file != NULL); }
82 // Operator which retrieves the underlying FILE pointer.
83 operator FILE*() { return file; }
90 if (close_with_pclose)
103 FilePosition current;
104 FilePosition last_tag;
105 reference<ConfigTag> tag;
107 std::string mandatory_tag;
109 Parser(ParseStack& me, int myflags, FILE* conf, const std::string& name, const std::string& mandatorytag)
110 : stack(me), flags(myflags), file(conf), current(name), last_tag(name), ungot(-1), mandatory_tag(mandatorytag)
113 int next(bool eof_ok = false)
121 int ch = fgetc(file);
122 if (ch == EOF && !eof_ok)
124 throw CoreException("Unexpected end-of-file");
141 throw CoreException("INTERNAL ERROR: cannot unget twice");
155 void nextword(std::string& rv)
160 while (isalnum(ch) || ch == '_'|| ch == '-')
168 bool kv(ConfigItems* items)
173 if (ch == '>' && key.empty())
177 else if (ch == '#' && key.empty())
184 throw CoreException("Invalid character " + std::string(1, ch) + " in key (" + key + ")");
191 throw CoreException("Invalid character in value of <" + tag->tag + ":" + key + ">");
196 if (ch == '&' && !(flags & FLAG_USE_COMPAT))
202 if (isalnum(ch) || (varname.empty() && ch == '#'))
203 varname.push_back(ch);
208 stack.errstr << "Invalid XML entity name in value of <" + tag->tag + ":" + key + ">\n"
209 << "To include an ampersand or quote, use & or "\n";
210 throw CoreException("Parse error");
214 throw CoreException("Empty XML entity reference");
215 else if (varname[0] == '#' && (varname.size() == 1 || (varname.size() == 2 && varname[1] == 'x')))
216 throw CoreException("Empty numeric character reference");
217 else if (varname[0] == '#')
219 const char* cvarname = varname.c_str();
221 unsigned long lvalue;
222 if (cvarname[1] == 'x')
223 lvalue = strtoul(cvarname + 2, &endptr, 16);
225 lvalue = strtoul(cvarname + 1, &endptr, 10);
226 if (*endptr != '\0' || lvalue > 255)
227 throw CoreException("Invalid numeric character reference '&" + varname + ";'");
228 value.push_back(static_cast<char>(lvalue));
232 insp::flat_map<std::string, std::string>::iterator var = stack.vars.find(varname);
233 if (var == stack.vars.end())
234 throw CoreException("Undefined XML entity reference '&" + varname + ";'");
235 value.append(var->second);
238 else if (ch == '\\' && (flags & FLAG_USE_COMPAT))
242 value.push_back('\n');
243 else if (isalpha(esc))
244 throw CoreException("Unknown escape character \\" + std::string(1, esc));
246 value.push_back(esc);
254 if (items->find(key) != items->end())
255 throw CoreException("Duplicate key '" + key + "' found");
257 (*items)[key] = value;
270 else if (!isspace(spc))
271 throw CoreException("Invalid character in tag name");
274 throw CoreException("Empty tag name");
277 tag = ConfigTag::create(name, current.name, current.line, items);
281 // Do nothing here (silences a GCC warning).
284 if (name == mandatory_tag)
286 // Found the mandatory tag
287 mandatory_tag.clear();
290 if (stdalgo::string::equalsci(name, "include"))
292 stack.DoInclude(tag, flags);
294 else if (stdalgo::string::equalsci(name, "files"))
296 for(ConfigItems::iterator i = items->begin(); i != items->end(); i++)
298 stack.DoReadFile(i->first, i->second, flags, false);
301 else if (stdalgo::string::equalsci(name, "execfiles"))
303 for(ConfigItems::iterator i = items->begin(); i != items->end(); i++)
305 stack.DoReadFile(i->first, i->second, flags, true);
308 else if (stdalgo::string::equalsci(name, "define"))
310 if (flags & FLAG_USE_COMPAT)
311 throw CoreException("<define> tags may only be used in XML-style config (add <config format=\"xml\">)");
312 std::string varname = tag->getString("name");
313 std::string value = tag->getString("value");
315 throw CoreException("Variable definition must include variable name");
316 stack.vars[varname] = value;
318 else if (stdalgo::string::equalsci(name, "config"))
320 std::string format = tag->getString("format");
321 if (stdalgo::string::equalsci(format, "xml"))
322 flags &= ~FLAG_USE_COMPAT;
323 else if (stdalgo::string::equalsci(format, "compat"))
324 flags |= FLAG_USE_COMPAT;
325 else if (!format.empty())
326 throw CoreException("Unknown configuration format " + format);
330 stack.output.insert(std::make_pair(name, tag));
332 // this is not a leak; reference<> takes care of the delete
346 // this is the one place where an EOF is not an error
347 if (!mandatory_tag.empty())
348 throw CoreException("Mandatory tag \"" + mandatory_tag + "\" not found");
363 stack.errstr << "Do not save your files as UTF-16 or UTF-32, use UTF-8!\n";
366 throw CoreException("Syntax error - start of tag expected");
370 catch (CoreException& err)
372 stack.errstr << err.GetReason() << " at " << current.str();
374 stack.errstr << " (inside tag " << tag->tag << " at line " << tag->src_line << ")\n";
376 stack.errstr << " (last tag was on line " << last_tag.line << ")\n";
382 void ParseStack::DoInclude(ConfigTag* tag, int flags)
384 if (flags & FLAG_NO_INC)
385 throw CoreException("Invalid <include> tag in file included with noinclude=\"yes\"");
387 std::string mandatorytag;
388 tag->readString("mandatorytag", mandatorytag);
391 if (tag->readString("file", name))
393 if (tag->getBool("noinclude", false))
394 flags |= FLAG_NO_INC;
395 if (tag->getBool("noexec", false))
396 flags |= FLAG_NO_EXEC;
397 if (!ParseFile(ServerInstance->Config->Paths.PrependConfig(name), flags, mandatorytag))
398 throw CoreException("Included");
400 else if (tag->readString("executable", name))
402 if (flags & FLAG_NO_EXEC)
403 throw CoreException("Invalid <include:executable> tag in file included with noexec=\"yes\"");
404 if (tag->getBool("noinclude", false))
405 flags |= FLAG_NO_INC;
406 if (tag->getBool("noexec", true))
407 flags |= FLAG_NO_EXEC;
408 if (!ParseFile(name, flags, mandatorytag, true))
409 throw CoreException("Included");
413 void ParseStack::DoReadFile(const std::string& key, const std::string& name, int flags, bool exec)
415 if (flags & FLAG_NO_INC)
416 throw CoreException("Invalid <files> tag in file included with noinclude=\"yes\"");
417 if (exec && (flags & FLAG_NO_EXEC))
418 throw CoreException("Invalid <execfiles> tag in file included with noexec=\"yes\"");
420 std::string path = ServerInstance->Config->Paths.PrependConfig(name);
421 FileWrapper file(exec ? popen(name.c_str(), "r") : fopen(path.c_str(), "r"), exec);
423 throw CoreException("Could not read \"" + path + "\" for \"" + key + "\" file");
425 file_cache& cache = FilesOutput[key];
429 while (fgets(linebuf, sizeof(linebuf), file))
431 size_t len = strlen(linebuf);
434 if (linebuf[len-1] == '\n')
436 cache.push_back(std::string(linebuf, len));
441 bool ParseStack::ParseFile(const std::string& path, int flags, const std::string& mandatory_tag, bool isexec)
443 ServerInstance->Logs->Log("CONFIG", LOG_DEBUG, "Reading (isexec=%d) %s", isexec, path.c_str());
444 if (stdalgo::isin(reading, path))
445 throw CoreException((isexec ? "Executable " : "File ") + path + " is included recursively (looped inclusion)");
447 /* It's not already included, add it to the list of files we've loaded */
449 FileWrapper file((isexec ? popen(path.c_str(), "r") : fopen(path.c_str(), "r")), isexec);
451 throw CoreException("Could not read \"" + path + "\" for include");
453 reading.push_back(path);
454 Parser p(*this, flags, file, path, mandatory_tag);
455 bool ok = p.outer_parse();
460 bool ConfigTag::readString(const std::string& key, std::string& value, bool allow_lf)
462 for(ConfigItems::iterator j = items.begin(); j != items.end(); ++j)
467 if (!allow_lf && (value.find('\n') != std::string::npos))
469 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
470 " contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
471 for (std::string::iterator n = value.begin(); n != value.end(); n++)
480 std::string ConfigTag::getString(const std::string& key, const std::string& def, const TR1NS::function<bool(const std::string&)>& validator)
483 if (!readString(key, res))
488 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: The value of <%s:%s> is not valid; value set to %s.",
489 tag.c_str(), key.c_str(), def.c_str());
495 std::string ConfigTag::getString(const std::string& key, const std::string& def, size_t minlen, size_t maxlen)
498 if (!readString(key, res))
501 if (res.length() < minlen || res.length() > maxlen)
503 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: The length of <%s:%s> is not between %ld and %ld; value set to %s.",
504 tag.c_str(), key.c_str(), minlen, maxlen, def.c_str());
512 /** Check for an invalid magnitude specifier. If one is found a warning is logged and the
513 * value is corrected (set to \p def).
514 * @param tag The tag name; used in the warning message.
515 * @param key The key name; used in the warning message.
516 * @param val The full value set in the config as a string.
517 * @param num The value to verify and modify if needed.
518 * @param def The default value, \p res will be set to this if \p tail does not contain a.
519 * valid magnitude specifier.
520 * @param tail The location in the config value at which the magnifier is located.
522 template <typename Numeric>
523 void CheckMagnitude(const std::string& tag, const std::string& key, const std::string& val, Numeric& num, Numeric def, const char* tail)
525 // If this is NULL then no magnitude specifier was given.
529 switch (toupper(*tail))
540 num *= 1024 * 1024 * 1024;
544 const std::string message = "WARNING: <" + tag + ":" + key + "> value of " + val + " contains an invalid magnitude specifier '"
545 + tail + "'; value set to " + ConvToStr(def) + ".";
546 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, message);
550 /** Check for an out of range value. If the value falls outside the boundaries a warning is
551 * logged and the value is corrected (set to \p def).
552 * @param tag The tag name; used in the warning message.
553 * @param key The key name; used in the warning message.
554 * @param num The value to verify and modify if needed.
555 * @param def The default value, \p res will be set to this if (min <= res <= max) doesn't hold true.
556 * @param min Minimum accepted value for \p res.
557 * @param max Maximum accepted value for \p res.
559 template <typename Numeric>
560 void CheckRange(const std::string& tag, const std::string& key, Numeric& num, Numeric def, Numeric min, Numeric max)
562 if (num >= min && num <= max)
565 const std::string message = "WARNING: <" + tag + ":" + key + "> value of " + ConvToStr(num) + " is not between "
566 + ConvToStr(min) + " and " + ConvToStr(max) + "; value set to " + ConvToStr(def) + ".";
567 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, message);
572 long ConfigTag::getInt(const std::string &key, long def, long min, long max)
575 if(!readString(key, result))
578 const char* res_cstr = result.c_str();
579 char* res_tail = NULL;
580 long res = strtol(res_cstr, &res_tail, 0);
581 if (res_tail == res_cstr)
584 CheckMagnitude(tag, key, result, res, def, res_tail);
585 CheckRange(tag, key, res, def, min, max);
589 unsigned long ConfigTag::getUInt(const std::string& key, unsigned long def, unsigned long min, unsigned long max)
592 if (!readString(key, result))
595 const char* res_cstr = result.c_str();
596 char* res_tail = NULL;
597 unsigned long res = strtoul(res_cstr, &res_tail, 0);
598 if (res_tail == res_cstr)
601 CheckMagnitude(tag, key, result, res, def, res_tail);
602 CheckRange(tag, key, res, def, min, max);
606 unsigned long ConfigTag::getDuration(const std::string& key, unsigned long def, unsigned long min, unsigned long max)
608 std::string duration;
609 if (!readString(key, duration))
613 if (!InspIRCd::Duration(duration, ret))
615 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
616 " is not a duration; value set to " + ConvToStr(def) + ".");
620 CheckRange(tag, key, ret, def, min, max);
624 double ConfigTag::getFloat(const std::string& key, double def, double min, double max)
627 if (!readString(key, result))
630 double res = strtod(result.c_str(), NULL);
631 CheckRange(tag, key, res, def, min, max);
635 bool ConfigTag::getBool(const std::string &key, bool def)
638 if(!readString(key, result))
641 if (result == "yes" || result == "true" || result == "1" || result == "on")
643 if (result == "no" || result == "false" || result == "0" || result == "off")
646 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
647 " is not valid, ignoring");
651 std::string ConfigTag::getTagLocation()
653 return src_name + ":" + ConvToStr(src_line);
656 ConfigTag* ConfigTag::create(const std::string& Tag, const std::string& file, int line, ConfigItems*& Items)
658 ConfigTag* rv = new ConfigTag(Tag, file, line);
663 ConfigTag::ConfigTag(const std::string& Tag, const std::string& file, int line)
664 : tag(Tag), src_name(file), src_line(line)
668 OperInfo::OperInfo(const std::string& Name)
673 std::string OperInfo::getConfig(const std::string& key)
677 type_block->readString(key, rv);
679 oper_block->readString(key, rv);