2 * InspIRCd -- Internet Relay Chat Daemon
4 * Copyright (C) 2018 linuxdaemon <linuxdaemon.irc@gmail.com>
5 * Copyright (C) 2013-2014, 2016-2020 Sadie Powell <sadie@witchery.services>
6 * Copyright (C) 2013 ChrisTX <xpipe@hotmail.de>
7 * Copyright (C) 2012-2014 Attila Molnar <attilamolnar@hush.com>
8 * Copyright (C) 2012 Robby <robby@chatbelgie.be>
9 * Copyright (C) 2010 Craig Edwards <brain@inspircd.org>
10 * Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
12 * This file is part of InspIRCd. InspIRCd is free software: you can
13 * redistribute it and/or modify it under the terms of the GNU General Public
14 * License as published by the Free Software Foundation, version 2.
16 * This program is distributed in the hope that it will be useful, but WITHOUT
17 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
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/>.
28 #include "configparser.h"
32 // Legacy config parsing should be used.
35 // Executable includes are disabled.
38 // All includes are disabled.
41 // &env.FOO; is disabled.
44 // It's okay if an include doesn't exist.
45 FLAG_MISSING_OKAY = 16
48 // Represents the position within a config file.
51 // The name of the file which is being read.
54 // The line of the file that this position points to.
57 // The column of the file that this position points to.
60 FilePosition(const std::string& Name)
67 /** Returns a string that represents this file position. */
70 return name + ":" + ConvToStr(line) + ":" + ConvToStr(column);
74 // RAII wrapper for FILE* which closes the file when it goes out of scope.
78 // Whether this file handle should be closed with pclose.
79 bool close_with_pclose;
81 // The file handle which is being wrapped.
85 FileWrapper(FILE* File, bool CloseWithPClose = false)
86 : close_with_pclose(CloseWithPClose)
91 // Operator which determines whether the file is open.
92 operator bool() { return (file != NULL); }
94 // Operator which retrieves the underlying FILE pointer.
95 operator FILE*() { return file; }
102 if (close_with_pclose)
115 FilePosition current;
116 FilePosition last_tag;
117 reference<ConfigTag> tag;
119 std::string mandatory_tag;
121 Parser(ParseStack& me, int myflags, FILE* conf, const std::string& name, const std::string& mandatorytag)
122 : stack(me), flags(myflags), file(conf), current(name), last_tag(name), ungot(-1), mandatory_tag(mandatorytag)
125 int next(bool eof_ok = false)
133 int ch = fgetc(file);
134 if (ch == EOF && !eof_ok)
136 throw CoreException("Unexpected end-of-file");
153 throw CoreException("INTERNAL ERROR: cannot unget twice");
167 bool wordchar(char ch)
175 void nextword(std::string& rv)
188 bool kv(ConfigItems* items)
193 if (ch == '>' && key.empty())
197 else if (ch == '#' && key.empty())
204 throw CoreException("Invalid character " + std::string(1, ch) + " in key (" + key + ")");
211 throw CoreException("Invalid character in value of <" + tag->tag + ":" + key + ">");
216 if (ch == '&' && !(flags & FLAG_USE_COMPAT))
222 if (wordchar(ch) || (varname.empty() && ch == '#'))
223 varname.push_back(ch);
228 stack.errstr << "Invalid XML entity name in value of <" + tag->tag + ":" + key + ">\n"
229 << "To include an ampersand or quote, use & or "\n";
230 throw CoreException("Parse error");
234 throw CoreException("Empty XML entity reference");
235 else if (varname[0] == '#' && (varname.size() == 1 || (varname.size() == 2 && varname[1] == 'x')))
236 throw CoreException("Empty numeric character reference");
237 else if (varname[0] == '#')
239 const char* cvarname = varname.c_str();
241 unsigned long lvalue;
242 if (cvarname[1] == 'x')
243 lvalue = strtoul(cvarname + 2, &endptr, 16);
245 lvalue = strtoul(cvarname + 1, &endptr, 10);
246 if (*endptr != '\0' || lvalue > 255)
247 throw CoreException("Invalid numeric character reference '&" + varname + ";'");
248 value.push_back(static_cast<char>(lvalue));
250 else if (varname.compare(0, 4, "env.") == 0)
252 if (flags & FLAG_NO_ENV)
253 throw CoreException("XML environment entity reference in file included with noenv=\"yes\"");
255 const char* envstr = getenv(varname.c_str() + 4);
257 throw CoreException("Undefined XML environment entity reference '&" + varname + ";'");
259 value.append(envstr);
263 insp::flat_map<std::string, std::string>::iterator var = stack.vars.find(varname);
264 if (var == stack.vars.end())
265 throw CoreException("Undefined XML entity reference '&" + varname + ";'");
266 value.append(var->second);
269 else if (ch == '\\' && (flags & FLAG_USE_COMPAT))
273 value.push_back('\n');
274 else if (isalpha(esc))
275 throw CoreException("Unknown escape character \\" + std::string(1, esc));
277 value.push_back(esc);
285 if (items->find(key) != items->end())
286 throw CoreException("Duplicate key '" + key + "' found");
288 (*items)[key] = value;
301 else if (!isspace(spc))
302 throw CoreException("Invalid character in tag name");
305 throw CoreException("Empty tag name");
308 tag = ConfigTag::create(name, current.name, current.line, items);
312 // Do nothing here (silences a GCC warning).
315 if (name == mandatory_tag)
317 // Found the mandatory tag
318 mandatory_tag.clear();
321 if (stdalgo::string::equalsci(name, "include"))
323 stack.DoInclude(tag, flags);
325 else if (stdalgo::string::equalsci(name, "files"))
327 for(ConfigItems::iterator i = items->begin(); i != items->end(); i++)
329 stack.DoReadFile(i->first, i->second, flags, false);
332 else if (stdalgo::string::equalsci(name, "execfiles"))
334 for(ConfigItems::iterator i = items->begin(); i != items->end(); i++)
336 stack.DoReadFile(i->first, i->second, flags, true);
339 else if (stdalgo::string::equalsci(name, "define"))
341 if (flags & FLAG_USE_COMPAT)
342 throw CoreException("<define> tags may only be used in XML-style config (add <config format=\"xml\">)");
343 std::string varname = tag->getString("name");
344 std::string value = tag->getString("value");
346 throw CoreException("Variable definition must include variable name");
347 stack.vars[varname] = value;
349 else if (stdalgo::string::equalsci(name, "config"))
351 std::string format = tag->getString("format");
352 if (stdalgo::string::equalsci(format, "xml"))
353 flags &= ~FLAG_USE_COMPAT;
354 else if (stdalgo::string::equalsci(format, "compat"))
355 flags |= FLAG_USE_COMPAT;
356 else if (!format.empty())
357 throw CoreException("Unknown configuration format " + format);
361 stack.output.insert(std::make_pair(name, tag));
363 // this is not a leak; reference<> takes care of the delete
377 // this is the one place where an EOF is not an error
378 if (!mandatory_tag.empty())
379 throw CoreException("Mandatory tag \"" + mandatory_tag + "\" not found");
394 stack.errstr << "Do not save your files as UTF-16 or UTF-32, use UTF-8!\n";
397 throw CoreException("Syntax error - start of tag expected");
401 catch (CoreException& err)
403 stack.errstr << err.GetReason() << " at " << current.str();
405 stack.errstr << " (inside tag " << tag->tag << " at line " << tag->src_line << ")\n";
407 stack.errstr << " (last tag was on line " << last_tag.line << ")\n";
413 void ParseStack::DoInclude(ConfigTag* tag, int flags)
415 if (flags & FLAG_NO_INC)
416 throw CoreException("Invalid <include> tag in file included with noinclude=\"yes\"");
418 std::string mandatorytag;
419 tag->readString("mandatorytag", mandatorytag);
422 if (tag->readString("file", name))
424 if (tag->getBool("noinclude", false))
425 flags |= FLAG_NO_INC;
427 if (tag->getBool("noexec", false))
428 flags |= FLAG_NO_EXEC;
430 if (tag->getBool("noenv", false))
431 flags |= FLAG_NO_ENV;
433 if (tag->getBool("missingokay", false))
434 flags |= FLAG_MISSING_OKAY;
436 flags &= ~FLAG_MISSING_OKAY;
438 if (!ParseFile(ServerInstance->Config->Paths.PrependConfig(name), flags, mandatorytag))
439 throw CoreException("Included");
441 else if (tag->readString("directory", name))
443 if (tag->getBool("noinclude", false))
444 flags |= FLAG_NO_INC;
445 if (tag->getBool("noexec", false))
446 flags |= FLAG_NO_EXEC;
447 if (tag->getBool("noenv", false))
448 flags |= FLAG_NO_ENV;
450 const std::string includedir = ServerInstance->Config->Paths.PrependConfig(name);
451 std::vector<std::string> files;
452 if (!FileSystem::GetFileList(includedir, files, "*.conf"))
453 throw CoreException("Unable to read directory for include: " + includedir);
455 std::sort(files.begin(), files.end());
456 for (std::vector<std::string>::const_iterator iter = files.begin(); iter != files.end(); ++iter)
458 const std::string path = includedir + '/' + *iter;
459 if (!ParseFile(path, flags, mandatorytag))
460 throw CoreException("Included");
463 else if (tag->readString("executable", name))
465 if (flags & FLAG_NO_EXEC)
466 throw CoreException("Invalid <include:executable> tag in file included with noexec=\"yes\"");
467 if (tag->getBool("noinclude", false))
468 flags |= FLAG_NO_INC;
469 if (tag->getBool("noexec", true))
470 flags |= FLAG_NO_EXEC;
471 if (tag->getBool("noenv", true))
472 flags |= FLAG_NO_ENV;
474 if (!ParseFile(name, flags, mandatorytag, true))
475 throw CoreException("Included");
479 void ParseStack::DoReadFile(const std::string& key, const std::string& name, int flags, bool exec)
481 if (flags & FLAG_NO_INC)
482 throw CoreException("Invalid <files> tag in file included with noinclude=\"yes\"");
483 if (exec && (flags & FLAG_NO_EXEC))
484 throw CoreException("Invalid <execfiles> tag in file included with noexec=\"yes\"");
486 std::string path = ServerInstance->Config->Paths.PrependConfig(name);
487 FileWrapper file(exec ? popen(name.c_str(), "r") : fopen(path.c_str(), "r"), exec);
489 throw CoreException("Could not read \"" + path + "\" for \"" + key + "\" file");
491 file_cache& cache = FilesOutput[key];
495 while (fgets(linebuf, sizeof(linebuf), file))
497 size_t len = strlen(linebuf);
500 if (linebuf[len-1] == '\n')
502 cache.push_back(std::string(linebuf, len));
507 bool ParseStack::ParseFile(const std::string& path, int flags, const std::string& mandatory_tag, bool isexec)
509 ServerInstance->Logs->Log("CONFIG", LOG_DEBUG, "Reading (isexec=%d) %s", isexec, path.c_str());
510 if (stdalgo::isin(reading, path))
511 throw CoreException((isexec ? "Executable " : "File ") + path + " is included recursively (looped inclusion)");
513 /* It's not already included, add it to the list of files we've loaded */
515 FileWrapper file((isexec ? popen(path.c_str(), "r") : fopen(path.c_str(), "r")), isexec);
518 if (flags & FLAG_MISSING_OKAY)
521 throw CoreException("Could not read \"" + path + "\" for include");
524 reading.push_back(path);
525 Parser p(*this, flags, file, path, mandatory_tag);
526 bool ok = p.outer_parse();
531 bool ConfigTag::readString(const std::string& key, std::string& value, bool allow_lf)
533 for(ConfigItems::iterator j = items.begin(); j != items.end(); ++j)
538 if (!allow_lf && (value.find('\n') != std::string::npos))
540 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
541 " contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
542 for (std::string::iterator n = value.begin(); n != value.end(); n++)
551 std::string ConfigTag::getString(const std::string& key, const std::string& def, const TR1NS::function<bool(const std::string&)>& validator)
554 if (!readString(key, res))
559 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: The value of <%s:%s> is not valid; value set to %s.",
560 tag.c_str(), key.c_str(), def.c_str());
566 std::string ConfigTag::getString(const std::string& key, const std::string& def, size_t minlen, size_t maxlen)
569 if (!readString(key, res))
572 if (res.length() < minlen || res.length() > maxlen)
574 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: The length of <%s:%s> is not between %ld and %ld; value set to %s.",
575 tag.c_str(), key.c_str(), minlen, maxlen, def.c_str());
583 /** Check for an invalid magnitude specifier. If one is found a warning is logged and the
584 * value is corrected (set to \p def).
585 * @param tag The tag name; used in the warning message.
586 * @param key The key name; used in the warning message.
587 * @param val The full value set in the config as a string.
588 * @param num The value to verify and modify if needed.
589 * @param def The default value, \p res will be set to this if \p tail does not contain a.
590 * valid magnitude specifier.
591 * @param tail The location in the config value at which the magnifier is located.
593 template <typename Numeric>
594 void CheckMagnitude(const std::string& tag, const std::string& key, const std::string& val, Numeric& num, Numeric def, const char* tail)
596 // If this is NULL then no magnitude specifier was given.
600 switch (toupper(*tail))
611 num *= 1024 * 1024 * 1024;
615 const std::string message = "WARNING: <" + tag + ":" + key + "> value of " + val + " contains an invalid magnitude specifier '"
616 + tail + "'; value set to " + ConvToStr(def) + ".";
617 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, message);
621 /** Check for an out of range value. If the value falls outside the boundaries a warning is
622 * logged and the value is corrected (set to \p def).
623 * @param tag The tag name; used in the warning message.
624 * @param key The key name; used in the warning message.
625 * @param num The value to verify and modify if needed.
626 * @param def The default value, \p res will be set to this if (min <= res <= max) doesn't hold true.
627 * @param min Minimum accepted value for \p res.
628 * @param max Maximum accepted value for \p res.
630 template <typename Numeric>
631 void CheckRange(const std::string& tag, const std::string& key, Numeric& num, Numeric def, Numeric min, Numeric max)
633 if (num >= min && num <= max)
636 const std::string message = "WARNING: <" + tag + ":" + key + "> value of " + ConvToStr(num) + " is not between "
637 + ConvToStr(min) + " and " + ConvToStr(max) + "; value set to " + ConvToStr(def) + ".";
638 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, message);
643 long ConfigTag::getInt(const std::string &key, long def, long min, long max)
646 if(!readString(key, result) || result.empty())
649 const char* res_cstr = result.c_str();
650 char* res_tail = NULL;
651 long res = strtol(res_cstr, &res_tail, 0);
652 if (res_tail == res_cstr)
655 CheckMagnitude(tag, key, result, res, def, res_tail);
656 CheckRange(tag, key, res, def, min, max);
660 unsigned long ConfigTag::getUInt(const std::string& key, unsigned long def, unsigned long min, unsigned long max)
663 if (!readString(key, result) || result.empty())
666 const char* res_cstr = result.c_str();
667 char* res_tail = NULL;
668 unsigned long res = strtoul(res_cstr, &res_tail, 0);
669 if (res_tail == res_cstr)
672 CheckMagnitude(tag, key, result, res, def, res_tail);
673 CheckRange(tag, key, res, def, min, max);
677 unsigned long ConfigTag::getDuration(const std::string& key, unsigned long def, unsigned long min, unsigned long max)
679 std::string duration;
680 if (!readString(key, duration) || duration.empty())
684 if (!InspIRCd::Duration(duration, ret))
686 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
687 " is not a duration; value set to " + ConvToStr(def) + ".");
691 CheckRange(tag, key, ret, def, min, max);
695 double ConfigTag::getFloat(const std::string& key, double def, double min, double max)
698 if (!readString(key, result))
701 double res = strtod(result.c_str(), NULL);
702 CheckRange(tag, key, res, def, min, max);
706 bool ConfigTag::getBool(const std::string &key, bool def)
709 if(!readString(key, result) || result.empty())
712 if (stdalgo::string::equalsci(result, "yes") || stdalgo::string::equalsci(result, "true") || stdalgo::string::equalsci(result, "on") || result == "1")
715 if (stdalgo::string::equalsci(result, "no") || stdalgo::string::equalsci(result, "false") || stdalgo::string::equalsci(result, "off") || result == "0")
718 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
719 " is not valid, ignoring");
723 std::string ConfigTag::getTagLocation()
725 return src_name + ":" + ConvToStr(src_line);
728 ConfigTag* ConfigTag::create(const std::string& Tag, const std::string& file, int line, ConfigItems*& Items)
730 ConfigTag* rv = new ConfigTag(Tag, file, line);
735 ConfigTag::ConfigTag(const std::string& Tag, const std::string& file, int line)
736 : tag(Tag), src_name(file), src_line(line)
740 OperInfo::OperInfo(const std::string& Name)
745 std::string OperInfo::getConfig(const std::string& key)
749 type_block->readString(key, rv);
751 oper_block->readString(key, rv);