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;
398 if (!ParseFile(ServerInstance->Config->Paths.PrependConfig(name), flags, mandatorytag))
399 throw CoreException("Included");
401 else if (tag->readString("directory", name))
403 if (tag->getBool("noinclude", false))
404 flags |= FLAG_NO_INC;
405 if (tag->getBool("noexec", false))
406 flags |= FLAG_NO_EXEC;
408 const std::string includedir = ServerInstance->Config->Paths.PrependConfig(name);
409 std::vector<std::string> files;
410 if (!FileSystem::GetFileList(includedir, files, "*.conf"))
411 throw CoreException("Unable to read directory for include: " + includedir);
413 std::sort(files.begin(), files.end());
414 for (std::vector<std::string>::const_iterator iter = files.begin(); iter != files.end(); ++iter)
416 const std::string path = includedir + '/' + *iter;
417 if (!ParseFile(path, flags, mandatorytag))
418 throw CoreException("Included");
421 else if (tag->readString("executable", name))
423 if (flags & FLAG_NO_EXEC)
424 throw CoreException("Invalid <include:executable> tag in file included with noexec=\"yes\"");
425 if (tag->getBool("noinclude", false))
426 flags |= FLAG_NO_INC;
427 if (tag->getBool("noexec", true))
428 flags |= FLAG_NO_EXEC;
430 if (!ParseFile(name, flags, mandatorytag, true))
431 throw CoreException("Included");
435 void ParseStack::DoReadFile(const std::string& key, const std::string& name, int flags, bool exec)
437 if (flags & FLAG_NO_INC)
438 throw CoreException("Invalid <files> tag in file included with noinclude=\"yes\"");
439 if (exec && (flags & FLAG_NO_EXEC))
440 throw CoreException("Invalid <execfiles> tag in file included with noexec=\"yes\"");
442 std::string path = ServerInstance->Config->Paths.PrependConfig(name);
443 FileWrapper file(exec ? popen(name.c_str(), "r") : fopen(path.c_str(), "r"), exec);
445 throw CoreException("Could not read \"" + path + "\" for \"" + key + "\" file");
447 file_cache& cache = FilesOutput[key];
451 while (fgets(linebuf, sizeof(linebuf), file))
453 size_t len = strlen(linebuf);
456 if (linebuf[len-1] == '\n')
458 cache.push_back(std::string(linebuf, len));
463 bool ParseStack::ParseFile(const std::string& path, int flags, const std::string& mandatory_tag, bool isexec)
465 ServerInstance->Logs->Log("CONFIG", LOG_DEBUG, "Reading (isexec=%d) %s", isexec, path.c_str());
466 if (stdalgo::isin(reading, path))
467 throw CoreException((isexec ? "Executable " : "File ") + path + " is included recursively (looped inclusion)");
469 /* It's not already included, add it to the list of files we've loaded */
471 FileWrapper file((isexec ? popen(path.c_str(), "r") : fopen(path.c_str(), "r")), isexec);
473 throw CoreException("Could not read \"" + path + "\" for include");
475 reading.push_back(path);
476 Parser p(*this, flags, file, path, mandatory_tag);
477 bool ok = p.outer_parse();
482 bool ConfigTag::readString(const std::string& key, std::string& value, bool allow_lf)
484 for(ConfigItems::iterator j = items.begin(); j != items.end(); ++j)
489 if (!allow_lf && (value.find('\n') != std::string::npos))
491 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
492 " contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
493 for (std::string::iterator n = value.begin(); n != value.end(); n++)
502 std::string ConfigTag::getString(const std::string& key, const std::string& def, const TR1NS::function<bool(const std::string&)>& validator)
505 if (!readString(key, res))
510 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: The value of <%s:%s> is not valid; value set to %s.",
511 tag.c_str(), key.c_str(), def.c_str());
517 std::string ConfigTag::getString(const std::string& key, const std::string& def, size_t minlen, size_t maxlen)
520 if (!readString(key, res))
523 if (res.length() < minlen || res.length() > maxlen)
525 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: The length of <%s:%s> is not between %ld and %ld; value set to %s.",
526 tag.c_str(), key.c_str(), minlen, maxlen, def.c_str());
534 /** Check for an invalid magnitude specifier. If one is found a warning is logged and the
535 * value is corrected (set to \p def).
536 * @param tag The tag name; used in the warning message.
537 * @param key The key name; used in the warning message.
538 * @param val The full value set in the config as a string.
539 * @param num The value to verify and modify if needed.
540 * @param def The default value, \p res will be set to this if \p tail does not contain a.
541 * valid magnitude specifier.
542 * @param tail The location in the config value at which the magnifier is located.
544 template <typename Numeric>
545 void CheckMagnitude(const std::string& tag, const std::string& key, const std::string& val, Numeric& num, Numeric def, const char* tail)
547 // If this is NULL then no magnitude specifier was given.
551 switch (toupper(*tail))
562 num *= 1024 * 1024 * 1024;
566 const std::string message = "WARNING: <" + tag + ":" + key + "> value of " + val + " contains an invalid magnitude specifier '"
567 + tail + "'; value set to " + ConvToStr(def) + ".";
568 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, message);
572 /** Check for an out of range value. If the value falls outside the boundaries a warning is
573 * logged and the value is corrected (set to \p def).
574 * @param tag The tag name; used in the warning message.
575 * @param key The key name; used in the warning message.
576 * @param num The value to verify and modify if needed.
577 * @param def The default value, \p res will be set to this if (min <= res <= max) doesn't hold true.
578 * @param min Minimum accepted value for \p res.
579 * @param max Maximum accepted value for \p res.
581 template <typename Numeric>
582 void CheckRange(const std::string& tag, const std::string& key, Numeric& num, Numeric def, Numeric min, Numeric max)
584 if (num >= min && num <= max)
587 const std::string message = "WARNING: <" + tag + ":" + key + "> value of " + ConvToStr(num) + " is not between "
588 + ConvToStr(min) + " and " + ConvToStr(max) + "; value set to " + ConvToStr(def) + ".";
589 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, message);
594 long ConfigTag::getInt(const std::string &key, long def, long min, long max)
597 if(!readString(key, result))
600 const char* res_cstr = result.c_str();
601 char* res_tail = NULL;
602 long res = strtol(res_cstr, &res_tail, 0);
603 if (res_tail == res_cstr)
606 CheckMagnitude(tag, key, result, res, def, res_tail);
607 CheckRange(tag, key, res, def, min, max);
611 unsigned long ConfigTag::getUInt(const std::string& key, unsigned long def, unsigned long min, unsigned long max)
614 if (!readString(key, result))
617 const char* res_cstr = result.c_str();
618 char* res_tail = NULL;
619 unsigned long res = strtoul(res_cstr, &res_tail, 0);
620 if (res_tail == res_cstr)
623 CheckMagnitude(tag, key, result, res, def, res_tail);
624 CheckRange(tag, key, res, def, min, max);
628 unsigned long ConfigTag::getDuration(const std::string& key, unsigned long def, unsigned long min, unsigned long max)
630 std::string duration;
631 if (!readString(key, duration))
635 if (!InspIRCd::Duration(duration, ret))
637 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
638 " is not a duration; value set to " + ConvToStr(def) + ".");
642 CheckRange(tag, key, ret, def, min, max);
646 double ConfigTag::getFloat(const std::string& key, double def, double min, double max)
649 if (!readString(key, result))
652 double res = strtod(result.c_str(), NULL);
653 CheckRange(tag, key, res, def, min, max);
657 bool ConfigTag::getBool(const std::string &key, bool def)
660 if(!readString(key, result))
663 if (result == "yes" || result == "true" || result == "1" || result == "on")
665 if (result == "no" || result == "false" || result == "0" || result == "off")
668 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
669 " is not valid, ignoring");
673 std::string ConfigTag::getTagLocation()
675 return src_name + ":" + ConvToStr(src_line);
678 ConfigTag* ConfigTag::create(const std::string& Tag, const std::string& file, int line, ConfigItems*& Items)
680 ConfigTag* rv = new ConfigTag(Tag, file, line);
685 ConfigTag::ConfigTag(const std::string& Tag, const std::string& file, int line)
686 : tag(Tag), src_name(file), src_line(line)
690 OperInfo::OperInfo(const std::string& Name)
695 std::string OperInfo::getConfig(const std::string& key)
699 type_block->readString(key, rv);
701 oper_block->readString(key, rv);