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.
42 // Represents the position within a config file.
45 // The name of the file which is being read.
48 // The line of the file that this position points to.
51 // The column of the file that this position points to.
54 FilePosition(const std::string& Name)
61 /** Returns a string that represents this file position. */
64 return name + ":" + ConvToStr(line) + ":" + ConvToStr(column);
68 // RAII wrapper for FILE* which closes the file when it goes out of scope.
72 // Whether this file handle should be closed with pclose.
73 bool close_with_pclose;
75 // The file handle which is being wrapped.
79 FileWrapper(FILE* File, bool CloseWithPClose = false)
80 : close_with_pclose(CloseWithPClose)
85 // Operator which determines whether the file is open.
86 operator bool() { return (file != NULL); }
88 // Operator which retrieves the underlying FILE pointer.
89 operator FILE*() { return file; }
96 if (close_with_pclose)
109 FilePosition current;
110 FilePosition last_tag;
111 reference<ConfigTag> tag;
113 std::string mandatory_tag;
115 Parser(ParseStack& me, int myflags, FILE* conf, const std::string& name, const std::string& mandatorytag)
116 : stack(me), flags(myflags), file(conf), current(name), last_tag(name), ungot(-1), mandatory_tag(mandatorytag)
119 int next(bool eof_ok = false)
127 int ch = fgetc(file);
128 if (ch == EOF && !eof_ok)
130 throw CoreException("Unexpected end-of-file");
147 throw CoreException("INTERNAL ERROR: cannot unget twice");
161 bool wordchar(char ch)
169 void nextword(std::string& rv)
182 bool kv(ConfigItems* items)
187 if (ch == '>' && key.empty())
191 else if (ch == '#' && key.empty())
198 throw CoreException("Invalid character " + std::string(1, ch) + " in key (" + key + ")");
205 throw CoreException("Invalid character in value of <" + tag->tag + ":" + key + ">");
210 if (ch == '&' && !(flags & FLAG_USE_COMPAT))
216 if (wordchar(ch) || (varname.empty() && ch == '#'))
217 varname.push_back(ch);
222 stack.errstr << "Invalid XML entity name in value of <" + tag->tag + ":" + key + ">\n"
223 << "To include an ampersand or quote, use & or "\n";
224 throw CoreException("Parse error");
228 throw CoreException("Empty XML entity reference");
229 else if (varname[0] == '#' && (varname.size() == 1 || (varname.size() == 2 && varname[1] == 'x')))
230 throw CoreException("Empty numeric character reference");
231 else if (varname[0] == '#')
233 const char* cvarname = varname.c_str();
235 unsigned long lvalue;
236 if (cvarname[1] == 'x')
237 lvalue = strtoul(cvarname + 2, &endptr, 16);
239 lvalue = strtoul(cvarname + 1, &endptr, 10);
240 if (*endptr != '\0' || lvalue > 255)
241 throw CoreException("Invalid numeric character reference '&" + varname + ";'");
242 value.push_back(static_cast<char>(lvalue));
244 else if (varname.compare(0, 4, "env.") == 0)
246 const char* envstr = getenv(varname.c_str() + 4);
248 throw CoreException("Undefined XML environment entity reference '&" + varname + ";'");
249 value.append(envstr);
253 insp::flat_map<std::string, std::string>::iterator var = stack.vars.find(varname);
254 if (var == stack.vars.end())
255 throw CoreException("Undefined XML entity reference '&" + varname + ";'");
256 value.append(var->second);
259 else if (ch == '\\' && (flags & FLAG_USE_COMPAT))
263 value.push_back('\n');
264 else if (isalpha(esc))
265 throw CoreException("Unknown escape character \\" + std::string(1, esc));
267 value.push_back(esc);
275 if (items->find(key) != items->end())
276 throw CoreException("Duplicate key '" + key + "' found");
278 (*items)[key] = value;
291 else if (!isspace(spc))
292 throw CoreException("Invalid character in tag name");
295 throw CoreException("Empty tag name");
298 tag = ConfigTag::create(name, current.name, current.line, items);
302 // Do nothing here (silences a GCC warning).
305 if (name == mandatory_tag)
307 // Found the mandatory tag
308 mandatory_tag.clear();
311 if (stdalgo::string::equalsci(name, "include"))
313 stack.DoInclude(tag, flags);
315 else if (stdalgo::string::equalsci(name, "files"))
317 for(ConfigItems::iterator i = items->begin(); i != items->end(); i++)
319 stack.DoReadFile(i->first, i->second, flags, false);
322 else if (stdalgo::string::equalsci(name, "execfiles"))
324 for(ConfigItems::iterator i = items->begin(); i != items->end(); i++)
326 stack.DoReadFile(i->first, i->second, flags, true);
329 else if (stdalgo::string::equalsci(name, "define"))
331 if (flags & FLAG_USE_COMPAT)
332 throw CoreException("<define> tags may only be used in XML-style config (add <config format=\"xml\">)");
333 std::string varname = tag->getString("name");
334 std::string value = tag->getString("value");
336 throw CoreException("Variable definition must include variable name");
337 stack.vars[varname] = value;
339 else if (stdalgo::string::equalsci(name, "config"))
341 std::string format = tag->getString("format");
342 if (stdalgo::string::equalsci(format, "xml"))
343 flags &= ~FLAG_USE_COMPAT;
344 else if (stdalgo::string::equalsci(format, "compat"))
345 flags |= FLAG_USE_COMPAT;
346 else if (!format.empty())
347 throw CoreException("Unknown configuration format " + format);
351 stack.output.insert(std::make_pair(name, tag));
353 // this is not a leak; reference<> takes care of the delete
367 // this is the one place where an EOF is not an error
368 if (!mandatory_tag.empty())
369 throw CoreException("Mandatory tag \"" + mandatory_tag + "\" not found");
384 stack.errstr << "Do not save your files as UTF-16 or UTF-32, use UTF-8!\n";
387 throw CoreException("Syntax error - start of tag expected");
391 catch (CoreException& err)
393 stack.errstr << err.GetReason() << " at " << current.str();
395 stack.errstr << " (inside tag " << tag->tag << " at line " << tag->src_line << ")\n";
397 stack.errstr << " (last tag was on line " << last_tag.line << ")\n";
403 void ParseStack::DoInclude(ConfigTag* tag, int flags)
405 if (flags & FLAG_NO_INC)
406 throw CoreException("Invalid <include> tag in file included with noinclude=\"yes\"");
408 std::string mandatorytag;
409 tag->readString("mandatorytag", mandatorytag);
412 if (tag->readString("file", name))
414 if (tag->getBool("noinclude", false))
415 flags |= FLAG_NO_INC;
416 if (tag->getBool("noexec", false))
417 flags |= FLAG_NO_EXEC;
419 if (!ParseFile(ServerInstance->Config->Paths.PrependConfig(name), flags, mandatorytag))
420 throw CoreException("Included");
422 else if (tag->readString("directory", name))
424 if (tag->getBool("noinclude", false))
425 flags |= FLAG_NO_INC;
426 if (tag->getBool("noexec", false))
427 flags |= FLAG_NO_EXEC;
429 const std::string includedir = ServerInstance->Config->Paths.PrependConfig(name);
430 std::vector<std::string> files;
431 if (!FileSystem::GetFileList(includedir, files, "*.conf"))
432 throw CoreException("Unable to read directory for include: " + includedir);
434 std::sort(files.begin(), files.end());
435 for (std::vector<std::string>::const_iterator iter = files.begin(); iter != files.end(); ++iter)
437 const std::string path = includedir + '/' + *iter;
438 if (!ParseFile(path, flags, mandatorytag))
439 throw CoreException("Included");
442 else if (tag->readString("executable", name))
444 if (flags & FLAG_NO_EXEC)
445 throw CoreException("Invalid <include:executable> tag in file included with noexec=\"yes\"");
446 if (tag->getBool("noinclude", false))
447 flags |= FLAG_NO_INC;
448 if (tag->getBool("noexec", true))
449 flags |= FLAG_NO_EXEC;
451 if (!ParseFile(name, flags, mandatorytag, true))
452 throw CoreException("Included");
456 void ParseStack::DoReadFile(const std::string& key, const std::string& name, int flags, bool exec)
458 if (flags & FLAG_NO_INC)
459 throw CoreException("Invalid <files> tag in file included with noinclude=\"yes\"");
460 if (exec && (flags & FLAG_NO_EXEC))
461 throw CoreException("Invalid <execfiles> tag in file included with noexec=\"yes\"");
463 std::string path = ServerInstance->Config->Paths.PrependConfig(name);
464 FileWrapper file(exec ? popen(name.c_str(), "r") : fopen(path.c_str(), "r"), exec);
466 throw CoreException("Could not read \"" + path + "\" for \"" + key + "\" file");
468 file_cache& cache = FilesOutput[key];
472 while (fgets(linebuf, sizeof(linebuf), file))
474 size_t len = strlen(linebuf);
477 if (linebuf[len-1] == '\n')
479 cache.push_back(std::string(linebuf, len));
484 bool ParseStack::ParseFile(const std::string& path, int flags, const std::string& mandatory_tag, bool isexec)
486 ServerInstance->Logs->Log("CONFIG", LOG_DEBUG, "Reading (isexec=%d) %s", isexec, path.c_str());
487 if (stdalgo::isin(reading, path))
488 throw CoreException((isexec ? "Executable " : "File ") + path + " is included recursively (looped inclusion)");
490 /* It's not already included, add it to the list of files we've loaded */
492 FileWrapper file((isexec ? popen(path.c_str(), "r") : fopen(path.c_str(), "r")), isexec);
494 throw CoreException("Could not read \"" + path + "\" for include");
496 reading.push_back(path);
497 Parser p(*this, flags, file, path, mandatory_tag);
498 bool ok = p.outer_parse();
503 bool ConfigTag::readString(const std::string& key, std::string& value, bool allow_lf)
505 for(ConfigItems::iterator j = items.begin(); j != items.end(); ++j)
510 if (!allow_lf && (value.find('\n') != std::string::npos))
512 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
513 " contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
514 for (std::string::iterator n = value.begin(); n != value.end(); n++)
523 std::string ConfigTag::getString(const std::string& key, const std::string& def, const TR1NS::function<bool(const std::string&)>& validator)
526 if (!readString(key, res))
531 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: The value of <%s:%s> is not valid; value set to %s.",
532 tag.c_str(), key.c_str(), def.c_str());
538 std::string ConfigTag::getString(const std::string& key, const std::string& def, size_t minlen, size_t maxlen)
541 if (!readString(key, res))
544 if (res.length() < minlen || res.length() > maxlen)
546 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: The length of <%s:%s> is not between %ld and %ld; value set to %s.",
547 tag.c_str(), key.c_str(), minlen, maxlen, def.c_str());
555 /** Check for an invalid magnitude specifier. If one is found a warning is logged and the
556 * value is corrected (set to \p def).
557 * @param tag The tag name; used in the warning message.
558 * @param key The key name; used in the warning message.
559 * @param val The full value set in the config as a string.
560 * @param num The value to verify and modify if needed.
561 * @param def The default value, \p res will be set to this if \p tail does not contain a.
562 * valid magnitude specifier.
563 * @param tail The location in the config value at which the magnifier is located.
565 template <typename Numeric>
566 void CheckMagnitude(const std::string& tag, const std::string& key, const std::string& val, Numeric& num, Numeric def, const char* tail)
568 // If this is NULL then no magnitude specifier was given.
572 switch (toupper(*tail))
583 num *= 1024 * 1024 * 1024;
587 const std::string message = "WARNING: <" + tag + ":" + key + "> value of " + val + " contains an invalid magnitude specifier '"
588 + tail + "'; value set to " + ConvToStr(def) + ".";
589 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, message);
593 /** Check for an out of range value. If the value falls outside the boundaries a warning is
594 * logged and the value is corrected (set to \p def).
595 * @param tag The tag name; used in the warning message.
596 * @param key The key name; used in the warning message.
597 * @param num The value to verify and modify if needed.
598 * @param def The default value, \p res will be set to this if (min <= res <= max) doesn't hold true.
599 * @param min Minimum accepted value for \p res.
600 * @param max Maximum accepted value for \p res.
602 template <typename Numeric>
603 void CheckRange(const std::string& tag, const std::string& key, Numeric& num, Numeric def, Numeric min, Numeric max)
605 if (num >= min && num <= max)
608 const std::string message = "WARNING: <" + tag + ":" + key + "> value of " + ConvToStr(num) + " is not between "
609 + ConvToStr(min) + " and " + ConvToStr(max) + "; value set to " + ConvToStr(def) + ".";
610 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, message);
615 long ConfigTag::getInt(const std::string &key, long def, long min, long max)
618 if(!readString(key, result))
621 const char* res_cstr = result.c_str();
622 char* res_tail = NULL;
623 long res = strtol(res_cstr, &res_tail, 0);
624 if (res_tail == res_cstr)
627 CheckMagnitude(tag, key, result, res, def, res_tail);
628 CheckRange(tag, key, res, def, min, max);
632 unsigned long ConfigTag::getUInt(const std::string& key, unsigned long def, unsigned long min, unsigned long max)
635 if (!readString(key, result))
638 const char* res_cstr = result.c_str();
639 char* res_tail = NULL;
640 unsigned long res = strtoul(res_cstr, &res_tail, 0);
641 if (res_tail == res_cstr)
644 CheckMagnitude(tag, key, result, res, def, res_tail);
645 CheckRange(tag, key, res, def, min, max);
649 unsigned long ConfigTag::getDuration(const std::string& key, unsigned long def, unsigned long min, unsigned long max)
651 std::string duration;
652 if (!readString(key, duration))
656 if (!InspIRCd::Duration(duration, ret))
658 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
659 " is not a duration; value set to " + ConvToStr(def) + ".");
663 CheckRange(tag, key, ret, def, min, max);
667 double ConfigTag::getFloat(const std::string& key, double def, double min, double max)
670 if (!readString(key, result))
673 double res = strtod(result.c_str(), NULL);
674 CheckRange(tag, key, res, def, min, max);
678 bool ConfigTag::getBool(const std::string &key, bool def)
681 if(!readString(key, result))
684 if (stdalgo::string::equalsci(result, "yes") || stdalgo::string::equalsci(result, "true") || stdalgo::string::equalsci(result, "on") || result == "1")
687 if (stdalgo::string::equalsci(result, "no") || stdalgo::string::equalsci(result, "false") || stdalgo::string::equalsci(result, "off") || result == "0")
690 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
691 " is not valid, ignoring");
695 std::string ConfigTag::getTagLocation()
697 return src_name + ":" + ConvToStr(src_line);
700 ConfigTag* ConfigTag::create(const std::string& Tag, const std::string& file, int line, ConfigItems*& Items)
702 ConfigTag* rv = new ConfigTag(Tag, file, line);
707 ConfigTag::ConfigTag(const std::string& Tag, const std::string& file, int line)
708 : tag(Tag), src_name(file), src_line(line)
712 OperInfo::OperInfo(const std::string& Name)
717 std::string OperInfo::getConfig(const std::string& key)
721 type_block->readString(key, rv);
723 oper_block->readString(key, rv);