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.
45 // Represents the position within a config file.
48 // The name of the file which is being read.
51 // The line of the file that this position points to.
54 // The column of the file that this position points to.
57 FilePosition(const std::string& Name)
64 /** Returns a string that represents this file position. */
67 return name + ":" + ConvToStr(line) + ":" + ConvToStr(column);
71 // RAII wrapper for FILE* which closes the file when it goes out of scope.
75 // Whether this file handle should be closed with pclose.
76 bool close_with_pclose;
78 // The file handle which is being wrapped.
82 FileWrapper(FILE* File, bool CloseWithPClose = false)
83 : close_with_pclose(CloseWithPClose)
88 // Operator which determines whether the file is open.
89 operator bool() { return (file != NULL); }
91 // Operator which retrieves the underlying FILE pointer.
92 operator FILE*() { return file; }
99 if (close_with_pclose)
112 FilePosition current;
113 FilePosition last_tag;
114 reference<ConfigTag> tag;
116 std::string mandatory_tag;
118 Parser(ParseStack& me, int myflags, FILE* conf, const std::string& name, const std::string& mandatorytag)
119 : stack(me), flags(myflags), file(conf), current(name), last_tag(name), ungot(-1), mandatory_tag(mandatorytag)
122 int next(bool eof_ok = false)
130 int ch = fgetc(file);
131 if (ch == EOF && !eof_ok)
133 throw CoreException("Unexpected end-of-file");
150 throw CoreException("INTERNAL ERROR: cannot unget twice");
164 bool wordchar(char ch)
172 void nextword(std::string& rv)
185 bool kv(ConfigItems* items)
190 if (ch == '>' && key.empty())
194 else if (ch == '#' && key.empty())
201 throw CoreException("Invalid character " + std::string(1, ch) + " in key (" + key + ")");
208 throw CoreException("Invalid character in value of <" + tag->tag + ":" + key + ">");
213 if (ch == '&' && !(flags & FLAG_USE_COMPAT))
219 if (wordchar(ch) || (varname.empty() && ch == '#'))
220 varname.push_back(ch);
225 stack.errstr << "Invalid XML entity name in value of <" + tag->tag + ":" + key + ">\n"
226 << "To include an ampersand or quote, use & or "\n";
227 throw CoreException("Parse error");
231 throw CoreException("Empty XML entity reference");
232 else if (varname[0] == '#' && (varname.size() == 1 || (varname.size() == 2 && varname[1] == 'x')))
233 throw CoreException("Empty numeric character reference");
234 else if (varname[0] == '#')
236 const char* cvarname = varname.c_str();
238 unsigned long lvalue;
239 if (cvarname[1] == 'x')
240 lvalue = strtoul(cvarname + 2, &endptr, 16);
242 lvalue = strtoul(cvarname + 1, &endptr, 10);
243 if (*endptr != '\0' || lvalue > 255)
244 throw CoreException("Invalid numeric character reference '&" + varname + ";'");
245 value.push_back(static_cast<char>(lvalue));
247 else if (varname.compare(0, 4, "env.") == 0)
249 if (flags & FLAG_NO_ENV)
250 throw CoreException("XML environment entity reference in file included with noenv=\"yes\"");
252 const char* envstr = getenv(varname.c_str() + 4);
254 throw CoreException("Undefined XML environment entity reference '&" + varname + ";'");
256 value.append(envstr);
260 insp::flat_map<std::string, std::string>::iterator var = stack.vars.find(varname);
261 if (var == stack.vars.end())
262 throw CoreException("Undefined XML entity reference '&" + varname + ";'");
263 value.append(var->second);
266 else if (ch == '\\' && (flags & FLAG_USE_COMPAT))
270 value.push_back('\n');
271 else if (isalpha(esc))
272 throw CoreException("Unknown escape character \\" + std::string(1, esc));
274 value.push_back(esc);
282 if (items->find(key) != items->end())
283 throw CoreException("Duplicate key '" + key + "' found");
285 (*items)[key] = value;
298 else if (!isspace(spc))
299 throw CoreException("Invalid character in tag name");
302 throw CoreException("Empty tag name");
305 tag = ConfigTag::create(name, current.name, current.line, items);
309 // Do nothing here (silences a GCC warning).
312 if (name == mandatory_tag)
314 // Found the mandatory tag
315 mandatory_tag.clear();
318 if (stdalgo::string::equalsci(name, "include"))
320 stack.DoInclude(tag, flags);
322 else if (stdalgo::string::equalsci(name, "files"))
324 for(ConfigItems::iterator i = items->begin(); i != items->end(); i++)
326 stack.DoReadFile(i->first, i->second, flags, false);
329 else if (stdalgo::string::equalsci(name, "execfiles"))
331 for(ConfigItems::iterator i = items->begin(); i != items->end(); i++)
333 stack.DoReadFile(i->first, i->second, flags, true);
336 else if (stdalgo::string::equalsci(name, "define"))
338 if (flags & FLAG_USE_COMPAT)
339 throw CoreException("<define> tags may only be used in XML-style config (add <config format=\"xml\">)");
340 std::string varname = tag->getString("name");
341 std::string value = tag->getString("value");
343 throw CoreException("Variable definition must include variable name");
344 stack.vars[varname] = value;
346 else if (stdalgo::string::equalsci(name, "config"))
348 std::string format = tag->getString("format");
349 if (stdalgo::string::equalsci(format, "xml"))
350 flags &= ~FLAG_USE_COMPAT;
351 else if (stdalgo::string::equalsci(format, "compat"))
352 flags |= FLAG_USE_COMPAT;
353 else if (!format.empty())
354 throw CoreException("Unknown configuration format " + format);
358 stack.output.insert(std::make_pair(name, tag));
360 // this is not a leak; reference<> takes care of the delete
374 // this is the one place where an EOF is not an error
375 if (!mandatory_tag.empty())
376 throw CoreException("Mandatory tag \"" + mandatory_tag + "\" not found");
391 stack.errstr << "Do not save your files as UTF-16 or UTF-32, use UTF-8!\n";
394 throw CoreException("Syntax error - start of tag expected");
398 catch (CoreException& err)
400 stack.errstr << err.GetReason() << " at " << current.str();
402 stack.errstr << " (inside tag " << tag->tag << " at line " << tag->src_line << ")\n";
404 stack.errstr << " (last tag was on line " << last_tag.line << ")\n";
410 void ParseStack::DoInclude(ConfigTag* tag, int flags)
412 if (flags & FLAG_NO_INC)
413 throw CoreException("Invalid <include> tag in file included with noinclude=\"yes\"");
415 std::string mandatorytag;
416 tag->readString("mandatorytag", mandatorytag);
419 if (tag->readString("file", name))
421 if (tag->getBool("noinclude", false))
422 flags |= FLAG_NO_INC;
423 if (tag->getBool("noexec", false))
424 flags |= FLAG_NO_EXEC;
425 if (tag->getBool("noenv", false))
426 flags |= FLAG_NO_ENV;
428 if (!ParseFile(ServerInstance->Config->Paths.PrependConfig(name), flags, mandatorytag))
429 throw CoreException("Included");
431 else if (tag->readString("directory", name))
433 if (tag->getBool("noinclude", false))
434 flags |= FLAG_NO_INC;
435 if (tag->getBool("noexec", false))
436 flags |= FLAG_NO_EXEC;
437 if (tag->getBool("noenv", false))
438 flags |= FLAG_NO_ENV;
440 const std::string includedir = ServerInstance->Config->Paths.PrependConfig(name);
441 std::vector<std::string> files;
442 if (!FileSystem::GetFileList(includedir, files, "*.conf"))
443 throw CoreException("Unable to read directory for include: " + includedir);
445 std::sort(files.begin(), files.end());
446 for (std::vector<std::string>::const_iterator iter = files.begin(); iter != files.end(); ++iter)
448 const std::string path = includedir + '/' + *iter;
449 if (!ParseFile(path, flags, mandatorytag))
450 throw CoreException("Included");
453 else if (tag->readString("executable", name))
455 if (flags & FLAG_NO_EXEC)
456 throw CoreException("Invalid <include:executable> tag in file included with noexec=\"yes\"");
457 if (tag->getBool("noinclude", false))
458 flags |= FLAG_NO_INC;
459 if (tag->getBool("noexec", true))
460 flags |= FLAG_NO_EXEC;
461 if (tag->getBool("noenv", true))
462 flags |= FLAG_NO_ENV;
464 if (!ParseFile(name, flags, mandatorytag, true))
465 throw CoreException("Included");
469 void ParseStack::DoReadFile(const std::string& key, const std::string& name, int flags, bool exec)
471 if (flags & FLAG_NO_INC)
472 throw CoreException("Invalid <files> tag in file included with noinclude=\"yes\"");
473 if (exec && (flags & FLAG_NO_EXEC))
474 throw CoreException("Invalid <execfiles> tag in file included with noexec=\"yes\"");
476 std::string path = ServerInstance->Config->Paths.PrependConfig(name);
477 FileWrapper file(exec ? popen(name.c_str(), "r") : fopen(path.c_str(), "r"), exec);
479 throw CoreException("Could not read \"" + path + "\" for \"" + key + "\" file");
481 file_cache& cache = FilesOutput[key];
485 while (fgets(linebuf, sizeof(linebuf), file))
487 size_t len = strlen(linebuf);
490 if (linebuf[len-1] == '\n')
492 cache.push_back(std::string(linebuf, len));
497 bool ParseStack::ParseFile(const std::string& path, int flags, const std::string& mandatory_tag, bool isexec)
499 ServerInstance->Logs->Log("CONFIG", LOG_DEBUG, "Reading (isexec=%d) %s", isexec, path.c_str());
500 if (stdalgo::isin(reading, path))
501 throw CoreException((isexec ? "Executable " : "File ") + path + " is included recursively (looped inclusion)");
503 /* It's not already included, add it to the list of files we've loaded */
505 FileWrapper file((isexec ? popen(path.c_str(), "r") : fopen(path.c_str(), "r")), isexec);
507 throw CoreException("Could not read \"" + path + "\" for include");
509 reading.push_back(path);
510 Parser p(*this, flags, file, path, mandatory_tag);
511 bool ok = p.outer_parse();
516 bool ConfigTag::readString(const std::string& key, std::string& value, bool allow_lf)
518 for(ConfigItems::iterator j = items.begin(); j != items.end(); ++j)
523 if (!allow_lf && (value.find('\n') != std::string::npos))
525 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
526 " contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
527 for (std::string::iterator n = value.begin(); n != value.end(); n++)
536 std::string ConfigTag::getString(const std::string& key, const std::string& def, const TR1NS::function<bool(const std::string&)>& validator)
539 if (!readString(key, res))
544 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: The value of <%s:%s> is not valid; value set to %s.",
545 tag.c_str(), key.c_str(), def.c_str());
551 std::string ConfigTag::getString(const std::string& key, const std::string& def, size_t minlen, size_t maxlen)
554 if (!readString(key, res))
557 if (res.length() < minlen || res.length() > maxlen)
559 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: The length of <%s:%s> is not between %ld and %ld; value set to %s.",
560 tag.c_str(), key.c_str(), minlen, maxlen, def.c_str());
568 /** Check for an invalid magnitude specifier. If one is found a warning is logged and the
569 * value is corrected (set to \p def).
570 * @param tag The tag name; used in the warning message.
571 * @param key The key name; used in the warning message.
572 * @param val The full value set in the config as a string.
573 * @param num The value to verify and modify if needed.
574 * @param def The default value, \p res will be set to this if \p tail does not contain a.
575 * valid magnitude specifier.
576 * @param tail The location in the config value at which the magnifier is located.
578 template <typename Numeric>
579 void CheckMagnitude(const std::string& tag, const std::string& key, const std::string& val, Numeric& num, Numeric def, const char* tail)
581 // If this is NULL then no magnitude specifier was given.
585 switch (toupper(*tail))
596 num *= 1024 * 1024 * 1024;
600 const std::string message = "WARNING: <" + tag + ":" + key + "> value of " + val + " contains an invalid magnitude specifier '"
601 + tail + "'; value set to " + ConvToStr(def) + ".";
602 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, message);
606 /** Check for an out of range value. If the value falls outside the boundaries a warning is
607 * logged and the value is corrected (set to \p def).
608 * @param tag The tag name; used in the warning message.
609 * @param key The key name; used in the warning message.
610 * @param num The value to verify and modify if needed.
611 * @param def The default value, \p res will be set to this if (min <= res <= max) doesn't hold true.
612 * @param min Minimum accepted value for \p res.
613 * @param max Maximum accepted value for \p res.
615 template <typename Numeric>
616 void CheckRange(const std::string& tag, const std::string& key, Numeric& num, Numeric def, Numeric min, Numeric max)
618 if (num >= min && num <= max)
621 const std::string message = "WARNING: <" + tag + ":" + key + "> value of " + ConvToStr(num) + " is not between "
622 + ConvToStr(min) + " and " + ConvToStr(max) + "; value set to " + ConvToStr(def) + ".";
623 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, message);
628 long ConfigTag::getInt(const std::string &key, long def, long min, long max)
631 if(!readString(key, result))
634 const char* res_cstr = result.c_str();
635 char* res_tail = NULL;
636 long res = strtol(res_cstr, &res_tail, 0);
637 if (res_tail == res_cstr)
640 CheckMagnitude(tag, key, result, res, def, res_tail);
641 CheckRange(tag, key, res, def, min, max);
645 unsigned long ConfigTag::getUInt(const std::string& key, unsigned long def, unsigned long min, unsigned long max)
648 if (!readString(key, result))
651 const char* res_cstr = result.c_str();
652 char* res_tail = NULL;
653 unsigned long res = strtoul(res_cstr, &res_tail, 0);
654 if (res_tail == res_cstr)
657 CheckMagnitude(tag, key, result, res, def, res_tail);
658 CheckRange(tag, key, res, def, min, max);
662 unsigned long ConfigTag::getDuration(const std::string& key, unsigned long def, unsigned long min, unsigned long max)
664 std::string duration;
665 if (!readString(key, duration))
669 if (!InspIRCd::Duration(duration, ret))
671 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
672 " is not a duration; value set to " + ConvToStr(def) + ".");
676 CheckRange(tag, key, ret, def, min, max);
680 double ConfigTag::getFloat(const std::string& key, double def, double min, double max)
683 if (!readString(key, result))
686 double res = strtod(result.c_str(), NULL);
687 CheckRange(tag, key, res, def, min, max);
691 bool ConfigTag::getBool(const std::string &key, bool def)
694 if(!readString(key, result))
697 if (stdalgo::string::equalsci(result, "yes") || stdalgo::string::equalsci(result, "true") || stdalgo::string::equalsci(result, "on") || result == "1")
700 if (stdalgo::string::equalsci(result, "no") || stdalgo::string::equalsci(result, "false") || stdalgo::string::equalsci(result, "off") || result == "0")
703 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
704 " is not valid, ignoring");
708 std::string ConfigTag::getTagLocation()
710 return src_name + ":" + ConvToStr(src_line);
713 ConfigTag* ConfigTag::create(const std::string& Tag, const std::string& file, int line, ConfigItems*& Items)
715 ConfigTag* rv = new ConfigTag(Tag, file, line);
720 ConfigTag::ConfigTag(const std::string& Tag, const std::string& file, int line)
721 : tag(Tag), src_name(file), src_line(line)
725 OperInfo::OperInfo(const std::string& Name)
730 std::string OperInfo::getConfig(const std::string& key)
734 type_block->readString(key, rv);
736 oper_block->readString(key, rv);