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"
31 reference<ConfigTag> tag;
33 std::string mandatory_tag;
35 Parser(ParseStack& me, int myflags, FILE* conf, const std::string& name, const std::string& mandatorytag)
36 : stack(me), flags(myflags), file(conf), current(name), last_tag(name), ungot(-1), mandatory_tag(mandatorytag)
39 int next(bool eof_ok = false)
48 if (ch == EOF && !eof_ok)
50 throw CoreException("Unexpected end-of-file");
67 throw CoreException("INTERNAL ERROR: cannot unget twice");
81 void nextword(std::string& rv)
86 while (isalnum(ch) || ch == '_'|| ch == '-')
94 bool kv(ConfigItems* items)
99 if (ch == '>' && key.empty())
103 else if (ch == '#' && key.empty())
110 throw CoreException("Invalid character " + std::string(1, ch) + " in key (" + key + ")");
117 throw CoreException("Invalid character in value of <" + tag->tag + ":" + key + ">");
122 if (ch == '&' && !(flags & FLAG_USE_COMPAT))
128 if (isalnum(ch) || (varname.empty() && ch == '#'))
129 varname.push_back(ch);
134 stack.errstr << "Invalid XML entity name in value of <" + tag->tag + ":" + key + ">\n"
135 << "To include an ampersand or quote, use & or "\n";
136 throw CoreException("Parse error");
140 throw CoreException("Empty XML entity reference");
141 else if (varname[0] == '#' && (varname.size() == 1 || (varname.size() == 2 && varname[1] == 'x')))
142 throw CoreException("Empty numeric character reference");
143 else if (varname[0] == '#')
145 const char* cvarname = varname.c_str();
147 unsigned long lvalue;
148 if (cvarname[1] == 'x')
149 lvalue = strtoul(cvarname + 2, &endptr, 16);
151 lvalue = strtoul(cvarname + 1, &endptr, 10);
152 if (*endptr != '\0' || lvalue > 255)
153 throw CoreException("Invalid numeric character reference '&" + varname + ";'");
154 value.push_back(static_cast<char>(lvalue));
158 insp::flat_map<std::string, std::string>::iterator var = stack.vars.find(varname);
159 if (var == stack.vars.end())
160 throw CoreException("Undefined XML entity reference '&" + varname + ";'");
161 value.append(var->second);
164 else if (ch == '\\' && (flags & FLAG_USE_COMPAT))
168 value.push_back('\n');
169 else if (isalpha(esc))
170 throw CoreException("Unknown escape character \\" + std::string(1, esc));
172 value.push_back(esc);
180 if (items->find(key) != items->end())
181 throw CoreException("Duplicate key '" + key + "' found");
183 (*items)[key] = value;
196 else if (!isspace(spc))
197 throw CoreException("Invalid character in tag name");
200 throw CoreException("Empty tag name");
203 tag = ConfigTag::create(name, current.filename, current.line, items);
207 // Do nothing here (silences a GCC warning).
210 if (name == mandatory_tag)
212 // Found the mandatory tag
213 mandatory_tag.clear();
216 if (stdalgo::string::equalsci(name, "include"))
218 stack.DoInclude(tag, flags);
220 else if (stdalgo::string::equalsci(name, "files"))
222 for(ConfigItems::iterator i = items->begin(); i != items->end(); i++)
224 stack.DoReadFile(i->first, i->second, flags, false);
227 else if (stdalgo::string::equalsci(name, "execfiles"))
229 for(ConfigItems::iterator i = items->begin(); i != items->end(); i++)
231 stack.DoReadFile(i->first, i->second, flags, true);
234 else if (stdalgo::string::equalsci(name, "define"))
236 if (flags & FLAG_USE_COMPAT)
237 throw CoreException("<define> tags may only be used in XML-style config (add <config format=\"xml\">)");
238 std::string varname = tag->getString("name");
239 std::string value = tag->getString("value");
241 throw CoreException("Variable definition must include variable name");
242 stack.vars[varname] = value;
244 else if (stdalgo::string::equalsci(name, "config"))
246 std::string format = tag->getString("format");
247 if (stdalgo::string::equalsci(format, "xml"))
248 flags &= ~FLAG_USE_COMPAT;
249 else if (stdalgo::string::equalsci(format, "compat"))
250 flags |= FLAG_USE_COMPAT;
251 else if (!format.empty())
252 throw CoreException("Unknown configuration format " + format);
256 stack.output.insert(std::make_pair(name, tag));
258 // this is not a leak; reference<> takes care of the delete
272 // this is the one place where an EOF is not an error
273 if (!mandatory_tag.empty())
274 throw CoreException("Mandatory tag \"" + mandatory_tag + "\" not found");
289 stack.errstr << "Do not save your files as UTF-16 or UTF-32, use UTF-8!\n";
292 throw CoreException("Syntax error - start of tag expected");
296 catch (CoreException& err)
298 stack.errstr << err.GetReason() << " at " << current.str();
300 stack.errstr << " (inside tag " << tag->tag << " at line " << tag->src_line << ")\n";
302 stack.errstr << " (last tag was on line " << last_tag.line << ")\n";
308 void ParseStack::DoInclude(ConfigTag* tag, int flags)
310 if (flags & FLAG_NO_INC)
311 throw CoreException("Invalid <include> tag in file included with noinclude=\"yes\"");
313 std::string mandatorytag;
314 tag->readString("mandatorytag", mandatorytag);
317 if (tag->readString("file", name))
319 if (tag->getBool("noinclude", false))
320 flags |= FLAG_NO_INC;
321 if (tag->getBool("noexec", false))
322 flags |= FLAG_NO_EXEC;
323 if (!ParseFile(ServerInstance->Config->Paths.PrependConfig(name), flags, mandatorytag))
324 throw CoreException("Included");
326 else if (tag->readString("executable", name))
328 if (flags & FLAG_NO_EXEC)
329 throw CoreException("Invalid <include:executable> tag in file included with noexec=\"yes\"");
330 if (tag->getBool("noinclude", false))
331 flags |= FLAG_NO_INC;
332 if (tag->getBool("noexec", true))
333 flags |= FLAG_NO_EXEC;
334 if (!ParseFile(name, flags, mandatorytag, true))
335 throw CoreException("Included");
339 void ParseStack::DoReadFile(const std::string& key, const std::string& name, int flags, bool exec)
341 if (flags & FLAG_NO_INC)
342 throw CoreException("Invalid <files> tag in file included with noinclude=\"yes\"");
343 if (exec && (flags & FLAG_NO_EXEC))
344 throw CoreException("Invalid <execfiles> tag in file included with noexec=\"yes\"");
346 std::string path = ServerInstance->Config->Paths.PrependConfig(name);
347 FileWrapper file(exec ? popen(name.c_str(), "r") : fopen(path.c_str(), "r"), exec);
349 throw CoreException("Could not read \"" + path + "\" for \"" + key + "\" file");
351 file_cache& cache = FilesOutput[key];
355 while (fgets(linebuf, sizeof(linebuf), file))
357 size_t len = strlen(linebuf);
360 if (linebuf[len-1] == '\n')
362 cache.push_back(std::string(linebuf, len));
367 bool ParseStack::ParseFile(const std::string& path, int flags, const std::string& mandatory_tag, bool isexec)
369 ServerInstance->Logs->Log("CONFIG", LOG_DEBUG, "Reading (isexec=%d) %s", isexec, path.c_str());
370 if (stdalgo::isin(reading, path))
371 throw CoreException((isexec ? "Executable " : "File ") + path + " is included recursively (looped inclusion)");
373 /* It's not already included, add it to the list of files we've loaded */
375 FileWrapper file((isexec ? popen(path.c_str(), "r") : fopen(path.c_str(), "r")), isexec);
377 throw CoreException("Could not read \"" + path + "\" for include");
379 reading.push_back(path);
380 Parser p(*this, flags, file, path, mandatory_tag);
381 bool ok = p.outer_parse();
386 bool ConfigTag::readString(const std::string& key, std::string& value, bool allow_lf)
388 for(ConfigItems::iterator j = items.begin(); j != items.end(); ++j)
393 if (!allow_lf && (value.find('\n') != std::string::npos))
395 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
396 " contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
397 for (std::string::iterator n = value.begin(); n != value.end(); n++)
406 std::string ConfigTag::getString(const std::string& key, const std::string& def, const TR1NS::function<bool(const std::string&)>& validator)
409 if (!readString(key, res))
414 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: The value of <%s:%s> is not valid; value set to %s.",
415 tag.c_str(), key.c_str(), def.c_str());
421 std::string ConfigTag::getString(const std::string& key, const std::string& def, size_t minlen, size_t maxlen)
424 if (!readString(key, res))
427 if (res.length() < minlen || res.length() > maxlen)
429 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: The length of <%s:%s> is not between %ld and %ld; value set to %s.",
430 tag.c_str(), key.c_str(), minlen, maxlen, def.c_str());
438 /** Check for an invalid magnitude specifier. If one is found a warning is logged and the
439 * value is corrected (set to \p def).
440 * @param tag The tag name; used in the warning message.
441 * @param key The key name; used in the warning message.
442 * @param val The full value set in the config as a string.
443 * @param num The value to verify and modify if needed.
444 * @param def The default value, \p res will be set to this if \p tail does not contain a.
445 * valid magnitude specifier.
446 * @param tail The location in the config value at which the magnifier is located.
448 template <typename Numeric>
449 void CheckMagnitude(const std::string& tag, const std::string& key, const std::string& val, Numeric& num, Numeric def, const char* tail)
451 // If this is NULL then no magnitude specifier was given.
455 switch (toupper(*tail))
466 num *= 1024 * 1024 * 1024;
470 const std::string message = "WARNING: <" + tag + ":" + key + "> value of " + val + " contains an invalid magnitude specifier '"
471 + tail + "'; value set to " + ConvToStr(def) + ".";
472 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, message);
476 /** Check for an out of range value. If the value falls outside the boundaries a warning is
477 * logged and the value is corrected (set to \p def).
478 * @param tag The tag name; used in the warning message.
479 * @param key The key name; used in the warning message.
480 * @param num The value to verify and modify if needed.
481 * @param def The default value, \p res will be set to this if (min <= res <= max) doesn't hold true.
482 * @param min Minimum accepted value for \p res.
483 * @param max Maximum accepted value for \p res.
485 template <typename Numeric>
486 void CheckRange(const std::string& tag, const std::string& key, Numeric& num, Numeric def, Numeric min, Numeric max)
488 if (num >= min && num <= max)
491 const std::string message = "WARNING: <" + tag + ":" + key + "> value of " + ConvToStr(num) + " is not between "
492 + ConvToStr(min) + " and " + ConvToStr(max) + "; value set to " + ConvToStr(def) + ".";
493 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, message);
498 long ConfigTag::getInt(const std::string &key, long def, long min, long max)
501 if(!readString(key, result))
504 const char* res_cstr = result.c_str();
505 char* res_tail = NULL;
506 long res = strtol(res_cstr, &res_tail, 0);
507 if (res_tail == res_cstr)
510 CheckMagnitude(tag, key, result, res, def, res_tail);
511 CheckRange(tag, key, res, def, min, max);
515 unsigned long ConfigTag::getUInt(const std::string& key, unsigned long def, unsigned long min, unsigned long max)
518 if (!readString(key, result))
521 const char* res_cstr = result.c_str();
522 char* res_tail = NULL;
523 unsigned long res = strtoul(res_cstr, &res_tail, 0);
524 if (res_tail == res_cstr)
527 CheckMagnitude(tag, key, result, res, def, res_tail);
528 CheckRange(tag, key, res, def, min, max);
532 unsigned long ConfigTag::getDuration(const std::string& key, unsigned long def, unsigned long min, unsigned long max)
534 std::string duration;
535 if (!readString(key, duration))
538 unsigned long ret = InspIRCd::Duration(duration);
539 CheckRange(tag, key, ret, def, min, max);
543 double ConfigTag::getFloat(const std::string& key, double def, double min, double max)
546 if (!readString(key, result))
549 double res = strtod(result.c_str(), NULL);
550 CheckRange(tag, key, res, def, min, max);
554 bool ConfigTag::getBool(const std::string &key, bool def)
557 if(!readString(key, result))
560 if (result == "yes" || result == "true" || result == "1" || result == "on")
562 if (result == "no" || result == "false" || result == "0" || result == "off")
565 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
566 " is not valid, ignoring");
570 std::string ConfigTag::getTagLocation()
572 return src_name + ":" + ConvToStr(src_line);
575 ConfigTag* ConfigTag::create(const std::string& Tag, const std::string& file, int line, ConfigItems*& Items)
577 ConfigTag* rv = new ConfigTag(Tag, file, line);
582 ConfigTag::ConfigTag(const std::string& Tag, const std::string& file, int line)
583 : tag(Tag), src_name(file), src_line(line)
587 OperInfo::OperInfo(const std::string& Name)
592 std::string OperInfo::getConfig(const std::string& key)
596 type_block->readString(key, rv);
598 oper_block->readString(key, rv);