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 void nextword(std::string& rv)
166 while (isalnum(ch) || ch == '_'|| ch == '-')
174 bool kv(ConfigItems* items)
179 if (ch == '>' && key.empty())
183 else if (ch == '#' && key.empty())
190 throw CoreException("Invalid character " + std::string(1, ch) + " in key (" + key + ")");
197 throw CoreException("Invalid character in value of <" + tag->tag + ":" + key + ">");
202 if (ch == '&' && !(flags & FLAG_USE_COMPAT))
208 if (isalnum(ch) || (varname.empty() && ch == '#') || ch == '.')
209 varname.push_back(ch);
214 stack.errstr << "Invalid XML entity name in value of <" + tag->tag + ":" + key + ">\n"
215 << "To include an ampersand or quote, use & or "\n";
216 throw CoreException("Parse error");
220 throw CoreException("Empty XML entity reference");
221 else if (varname[0] == '#' && (varname.size() == 1 || (varname.size() == 2 && varname[1] == 'x')))
222 throw CoreException("Empty numeric character reference");
223 else if (varname[0] == '#')
225 const char* cvarname = varname.c_str();
227 unsigned long lvalue;
228 if (cvarname[1] == 'x')
229 lvalue = strtoul(cvarname + 2, &endptr, 16);
231 lvalue = strtoul(cvarname + 1, &endptr, 10);
232 if (*endptr != '\0' || lvalue > 255)
233 throw CoreException("Invalid numeric character reference '&" + varname + ";'");
234 value.push_back(static_cast<char>(lvalue));
236 else if (varname.compare(0, 4, "env.") == 0)
238 const char* envstr = getenv(varname.c_str() + 4);
240 throw CoreException("Undefined XML environment entity reference '&" + varname + ";'");
241 value.append(envstr);
245 insp::flat_map<std::string, std::string>::iterator var = stack.vars.find(varname);
246 if (var == stack.vars.end())
247 throw CoreException("Undefined XML entity reference '&" + varname + ";'");
248 value.append(var->second);
251 else if (ch == '\\' && (flags & FLAG_USE_COMPAT))
255 value.push_back('\n');
256 else if (isalpha(esc))
257 throw CoreException("Unknown escape character \\" + std::string(1, esc));
259 value.push_back(esc);
267 if (items->find(key) != items->end())
268 throw CoreException("Duplicate key '" + key + "' found");
270 (*items)[key] = value;
283 else if (!isspace(spc))
284 throw CoreException("Invalid character in tag name");
287 throw CoreException("Empty tag name");
290 tag = ConfigTag::create(name, current.name, current.line, items);
294 // Do nothing here (silences a GCC warning).
297 if (name == mandatory_tag)
299 // Found the mandatory tag
300 mandatory_tag.clear();
303 if (stdalgo::string::equalsci(name, "include"))
305 stack.DoInclude(tag, flags);
307 else if (stdalgo::string::equalsci(name, "files"))
309 for(ConfigItems::iterator i = items->begin(); i != items->end(); i++)
311 stack.DoReadFile(i->first, i->second, flags, false);
314 else if (stdalgo::string::equalsci(name, "execfiles"))
316 for(ConfigItems::iterator i = items->begin(); i != items->end(); i++)
318 stack.DoReadFile(i->first, i->second, flags, true);
321 else if (stdalgo::string::equalsci(name, "define"))
323 if (flags & FLAG_USE_COMPAT)
324 throw CoreException("<define> tags may only be used in XML-style config (add <config format=\"xml\">)");
325 std::string varname = tag->getString("name");
326 std::string value = tag->getString("value");
328 throw CoreException("Variable definition must include variable name");
329 stack.vars[varname] = value;
331 else if (stdalgo::string::equalsci(name, "config"))
333 std::string format = tag->getString("format");
334 if (stdalgo::string::equalsci(format, "xml"))
335 flags &= ~FLAG_USE_COMPAT;
336 else if (stdalgo::string::equalsci(format, "compat"))
337 flags |= FLAG_USE_COMPAT;
338 else if (!format.empty())
339 throw CoreException("Unknown configuration format " + format);
343 stack.output.insert(std::make_pair(name, tag));
345 // this is not a leak; reference<> takes care of the delete
359 // this is the one place where an EOF is not an error
360 if (!mandatory_tag.empty())
361 throw CoreException("Mandatory tag \"" + mandatory_tag + "\" not found");
376 stack.errstr << "Do not save your files as UTF-16 or UTF-32, use UTF-8!\n";
379 throw CoreException("Syntax error - start of tag expected");
383 catch (CoreException& err)
385 stack.errstr << err.GetReason() << " at " << current.str();
387 stack.errstr << " (inside tag " << tag->tag << " at line " << tag->src_line << ")\n";
389 stack.errstr << " (last tag was on line " << last_tag.line << ")\n";
395 void ParseStack::DoInclude(ConfigTag* tag, int flags)
397 if (flags & FLAG_NO_INC)
398 throw CoreException("Invalid <include> tag in file included with noinclude=\"yes\"");
400 std::string mandatorytag;
401 tag->readString("mandatorytag", mandatorytag);
404 if (tag->readString("file", name))
406 if (tag->getBool("noinclude", false))
407 flags |= FLAG_NO_INC;
408 if (tag->getBool("noexec", false))
409 flags |= FLAG_NO_EXEC;
411 if (!ParseFile(ServerInstance->Config->Paths.PrependConfig(name), flags, mandatorytag))
412 throw CoreException("Included");
414 else if (tag->readString("directory", name))
416 if (tag->getBool("noinclude", false))
417 flags |= FLAG_NO_INC;
418 if (tag->getBool("noexec", false))
419 flags |= FLAG_NO_EXEC;
421 const std::string includedir = ServerInstance->Config->Paths.PrependConfig(name);
422 std::vector<std::string> files;
423 if (!FileSystem::GetFileList(includedir, files, "*.conf"))
424 throw CoreException("Unable to read directory for include: " + includedir);
426 std::sort(files.begin(), files.end());
427 for (std::vector<std::string>::const_iterator iter = files.begin(); iter != files.end(); ++iter)
429 const std::string path = includedir + '/' + *iter;
430 if (!ParseFile(path, flags, mandatorytag))
431 throw CoreException("Included");
434 else if (tag->readString("executable", name))
436 if (flags & FLAG_NO_EXEC)
437 throw CoreException("Invalid <include:executable> tag in file included with noexec=\"yes\"");
438 if (tag->getBool("noinclude", false))
439 flags |= FLAG_NO_INC;
440 if (tag->getBool("noexec", true))
441 flags |= FLAG_NO_EXEC;
443 if (!ParseFile(name, flags, mandatorytag, true))
444 throw CoreException("Included");
448 void ParseStack::DoReadFile(const std::string& key, const std::string& name, int flags, bool exec)
450 if (flags & FLAG_NO_INC)
451 throw CoreException("Invalid <files> tag in file included with noinclude=\"yes\"");
452 if (exec && (flags & FLAG_NO_EXEC))
453 throw CoreException("Invalid <execfiles> tag in file included with noexec=\"yes\"");
455 std::string path = ServerInstance->Config->Paths.PrependConfig(name);
456 FileWrapper file(exec ? popen(name.c_str(), "r") : fopen(path.c_str(), "r"), exec);
458 throw CoreException("Could not read \"" + path + "\" for \"" + key + "\" file");
460 file_cache& cache = FilesOutput[key];
464 while (fgets(linebuf, sizeof(linebuf), file))
466 size_t len = strlen(linebuf);
469 if (linebuf[len-1] == '\n')
471 cache.push_back(std::string(linebuf, len));
476 bool ParseStack::ParseFile(const std::string& path, int flags, const std::string& mandatory_tag, bool isexec)
478 ServerInstance->Logs->Log("CONFIG", LOG_DEBUG, "Reading (isexec=%d) %s", isexec, path.c_str());
479 if (stdalgo::isin(reading, path))
480 throw CoreException((isexec ? "Executable " : "File ") + path + " is included recursively (looped inclusion)");
482 /* It's not already included, add it to the list of files we've loaded */
484 FileWrapper file((isexec ? popen(path.c_str(), "r") : fopen(path.c_str(), "r")), isexec);
486 throw CoreException("Could not read \"" + path + "\" for include");
488 reading.push_back(path);
489 Parser p(*this, flags, file, path, mandatory_tag);
490 bool ok = p.outer_parse();
495 bool ConfigTag::readString(const std::string& key, std::string& value, bool allow_lf)
497 for(ConfigItems::iterator j = items.begin(); j != items.end(); ++j)
502 if (!allow_lf && (value.find('\n') != std::string::npos))
504 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
505 " contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
506 for (std::string::iterator n = value.begin(); n != value.end(); n++)
515 std::string ConfigTag::getString(const std::string& key, const std::string& def, const TR1NS::function<bool(const std::string&)>& validator)
518 if (!readString(key, res))
523 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: The value of <%s:%s> is not valid; value set to %s.",
524 tag.c_str(), key.c_str(), def.c_str());
530 std::string ConfigTag::getString(const std::string& key, const std::string& def, size_t minlen, size_t maxlen)
533 if (!readString(key, res))
536 if (res.length() < minlen || res.length() > maxlen)
538 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: The length of <%s:%s> is not between %ld and %ld; value set to %s.",
539 tag.c_str(), key.c_str(), minlen, maxlen, def.c_str());
547 /** Check for an invalid magnitude specifier. If one is found a warning is logged and the
548 * value is corrected (set to \p def).
549 * @param tag The tag name; used in the warning message.
550 * @param key The key name; used in the warning message.
551 * @param val The full value set in the config as a string.
552 * @param num The value to verify and modify if needed.
553 * @param def The default value, \p res will be set to this if \p tail does not contain a.
554 * valid magnitude specifier.
555 * @param tail The location in the config value at which the magnifier is located.
557 template <typename Numeric>
558 void CheckMagnitude(const std::string& tag, const std::string& key, const std::string& val, Numeric& num, Numeric def, const char* tail)
560 // If this is NULL then no magnitude specifier was given.
564 switch (toupper(*tail))
575 num *= 1024 * 1024 * 1024;
579 const std::string message = "WARNING: <" + tag + ":" + key + "> value of " + val + " contains an invalid magnitude specifier '"
580 + tail + "'; value set to " + ConvToStr(def) + ".";
581 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, message);
585 /** Check for an out of range value. If the value falls outside the boundaries a warning is
586 * logged and the value is corrected (set to \p def).
587 * @param tag The tag name; used in the warning message.
588 * @param key The key name; used in the warning message.
589 * @param num The value to verify and modify if needed.
590 * @param def The default value, \p res will be set to this if (min <= res <= max) doesn't hold true.
591 * @param min Minimum accepted value for \p res.
592 * @param max Maximum accepted value for \p res.
594 template <typename Numeric>
595 void CheckRange(const std::string& tag, const std::string& key, Numeric& num, Numeric def, Numeric min, Numeric max)
597 if (num >= min && num <= max)
600 const std::string message = "WARNING: <" + tag + ":" + key + "> value of " + ConvToStr(num) + " is not between "
601 + ConvToStr(min) + " and " + ConvToStr(max) + "; value set to " + ConvToStr(def) + ".";
602 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, message);
607 long ConfigTag::getInt(const std::string &key, long def, long min, long max)
610 if(!readString(key, result))
613 const char* res_cstr = result.c_str();
614 char* res_tail = NULL;
615 long res = strtol(res_cstr, &res_tail, 0);
616 if (res_tail == res_cstr)
619 CheckMagnitude(tag, key, result, res, def, res_tail);
620 CheckRange(tag, key, res, def, min, max);
624 unsigned long ConfigTag::getUInt(const std::string& key, unsigned long def, unsigned long min, unsigned long max)
627 if (!readString(key, result))
630 const char* res_cstr = result.c_str();
631 char* res_tail = NULL;
632 unsigned long res = strtoul(res_cstr, &res_tail, 0);
633 if (res_tail == res_cstr)
636 CheckMagnitude(tag, key, result, res, def, res_tail);
637 CheckRange(tag, key, res, def, min, max);
641 unsigned long ConfigTag::getDuration(const std::string& key, unsigned long def, unsigned long min, unsigned long max)
643 std::string duration;
644 if (!readString(key, duration))
648 if (!InspIRCd::Duration(duration, ret))
650 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
651 " is not a duration; value set to " + ConvToStr(def) + ".");
655 CheckRange(tag, key, ret, def, min, max);
659 double ConfigTag::getFloat(const std::string& key, double def, double min, double max)
662 if (!readString(key, result))
665 double res = strtod(result.c_str(), NULL);
666 CheckRange(tag, key, res, def, min, max);
670 bool ConfigTag::getBool(const std::string &key, bool def)
673 if(!readString(key, result))
676 if (stdalgo::string::equalsci(result, "yes") || stdalgo::string::equalsci(result, "true") || stdalgo::string::equalsci(result, "on") || result == "1")
679 if (stdalgo::string::equalsci(result, "no") || stdalgo::string::equalsci(result, "false") || stdalgo::string::equalsci(result, "off") || result == "0")
682 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
683 " is not valid, ignoring");
687 std::string ConfigTag::getTagLocation()
689 return src_name + ":" + ConvToStr(src_line);
692 ConfigTag* ConfigTag::create(const std::string& Tag, const std::string& file, int line, ConfigItems*& Items)
694 ConfigTag* rv = new ConfigTag(Tag, file, line);
699 ConfigTag::ConfigTag(const std::string& Tag, const std::string& file, int line)
700 : tag(Tag), src_name(file), src_line(line)
704 OperInfo::OperInfo(const std::string& Name)
709 std::string OperInfo::getConfig(const std::string& key)
713 type_block->readString(key, rv);
715 oper_block->readString(key, rv);