]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/configparser.cpp
Only parse valid durations, don't treat invalid multipliers as seconds (#1538)
[user/henk/code/inspircd.git] / src / configparser.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5  *
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.
9  *
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
13  * details.
14  *
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/>.
17  */
18
19
20 #include "inspircd.h"
21 #include <fstream>
22 #include "configparser.h"
23
24 enum ParseFlags
25 {
26         // Legacy config parsing should be used.
27         FLAG_USE_COMPAT = 1,
28
29         // Executable includes are disabled.
30         FLAG_NO_EXEC = 2,
31
32         // All includes are disabled.
33         FLAG_NO_INC = 4
34 };
35
36 // Represents the position within a config file.
37 struct FilePosition
38 {
39         // The name of the file which is being read.
40         std::string name;
41
42         // The line of the file that this position points to.
43         unsigned int line;
44
45         // The column of the file that this position points to.
46         unsigned int column;
47
48         FilePosition(const std::string& Name)
49                 : name(Name)
50                 , line(1)
51                 , column(1)
52         {
53         }
54
55         /** Returns a string that represents this file position. */
56         std::string str()
57         {
58                 return name + ":" + ConvToStr(line) + ":" + ConvToStr(column);
59         }
60 };
61
62 // RAII wrapper for FILE* which closes the file when it goes out of scope.
63 class FileWrapper
64 {
65  private:
66         // Whether this file handle should be closed with pclose.
67         bool close_with_pclose;
68
69         // The file handle which is being wrapped.
70         FILE* const file;
71
72  public:
73         FileWrapper(FILE* File, bool CloseWithPClose = false)
74                 : close_with_pclose(CloseWithPClose)
75                 , file(File)
76         {
77         }
78
79         // Operator which determines whether the file is open.
80         operator bool() { return (file != NULL); }
81
82         // Operator which retrieves the underlying FILE pointer.
83         operator FILE*() { return file; }
84
85         ~FileWrapper()
86         {
87                 if (!file)
88                         return;
89
90                 if (close_with_pclose)
91                         pclose(file);
92                 else
93                         fclose(file);
94         }
95 };
96
97
98 struct Parser
99 {
100         ParseStack& stack;
101         int flags;
102         FILE* const file;
103         FilePosition current;
104         FilePosition last_tag;
105         reference<ConfigTag> tag;
106         int ungot;
107         std::string mandatory_tag;
108
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)
111         { }
112
113         int next(bool eof_ok = false)
114         {
115                 if (ungot != -1)
116                 {
117                         int ch = ungot;
118                         ungot = -1;
119                         return ch;
120                 }
121                 int ch = fgetc(file);
122                 if (ch == EOF && !eof_ok)
123                 {
124                         throw CoreException("Unexpected end-of-file");
125                 }
126                 else if (ch == '\n')
127                 {
128                         current.line++;
129                         current.column = 0;
130                 }
131                 else
132                 {
133                         current.column++;
134                 }
135                 return ch;
136         }
137
138         void unget(int ch)
139         {
140                 if (ungot != -1)
141                         throw CoreException("INTERNAL ERROR: cannot unget twice");
142                 ungot = ch;
143         }
144
145         void comment()
146         {
147                 while (1)
148                 {
149                         int ch = next();
150                         if (ch == '\n')
151                                 return;
152                 }
153         }
154
155         void nextword(std::string& rv)
156         {
157                 int ch = next();
158                 while (isspace(ch))
159                         ch = next();
160                 while (isalnum(ch) || ch == '_'|| ch == '-')
161                 {
162                         rv.push_back(ch);
163                         ch = next();
164                 }
165                 unget(ch);
166         }
167
168         bool kv(ConfigItems* items)
169         {
170                 std::string key;
171                 nextword(key);
172                 int ch = next();
173                 if (ch == '>' && key.empty())
174                 {
175                         return false;
176                 }
177                 else if (ch == '#' && key.empty())
178                 {
179                         comment();
180                         return true;
181                 }
182                 else if (ch != '=')
183                 {
184                         throw CoreException("Invalid character " + std::string(1, ch) + " in key (" + key + ")");
185                 }
186
187                 std::string value;
188                 ch = next();
189                 if (ch != '"')
190                 {
191                         throw CoreException("Invalid character in value of <" + tag->tag + ":" + key + ">");
192                 }
193                 while (1)
194                 {
195                         ch = next();
196                         if (ch == '&' && !(flags & FLAG_USE_COMPAT))
197                         {
198                                 std::string varname;
199                                 while (1)
200                                 {
201                                         ch = next();
202                                         if (isalnum(ch) || (varname.empty() && ch == '#'))
203                                                 varname.push_back(ch);
204                                         else if (ch == ';')
205                                                 break;
206                                         else
207                                         {
208                                                 stack.errstr << "Invalid XML entity name in value of <" + tag->tag + ":" + key + ">\n"
209                                                         << "To include an ampersand or quote, use &amp; or &quot;\n";
210                                                 throw CoreException("Parse error");
211                                         }
212                                 }
213                                 if (varname.empty())
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] == '#')
218                                 {
219                                         const char* cvarname = varname.c_str();
220                                         char* endptr;
221                                         unsigned long lvalue;
222                                         if (cvarname[1] == 'x')
223                                                 lvalue = strtoul(cvarname + 2, &endptr, 16);
224                                         else
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));
229                                 }
230                                 else
231                                 {
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);
236                                 }
237                         }
238                         else if (ch == '\\' && (flags & FLAG_USE_COMPAT))
239                         {
240                                 int esc = next();
241                                 if (esc == 'n')
242                                         value.push_back('\n');
243                                 else if (isalpha(esc))
244                                         throw CoreException("Unknown escape character \\" + std::string(1, esc));
245                                 else
246                                         value.push_back(esc);
247                         }
248                         else if (ch == '"')
249                                 break;
250                         else if (ch != '\r')
251                                 value.push_back(ch);
252                 }
253
254                 if (items->find(key) != items->end())
255                         throw CoreException("Duplicate key '" + key + "' found");
256
257                 (*items)[key] = value;
258                 return true;
259         }
260
261         void dotag()
262         {
263                 last_tag = current;
264                 std::string name;
265                 nextword(name);
266
267                 int spc = next();
268                 if (spc == '>')
269                         unget(spc);
270                 else if (!isspace(spc))
271                         throw CoreException("Invalid character in tag name");
272
273                 if (name.empty())
274                         throw CoreException("Empty tag name");
275
276                 ConfigItems* items;
277                 tag = ConfigTag::create(name, current.name, current.line, items);
278
279                 while (kv(items))
280                 {
281                         // Do nothing here (silences a GCC warning).
282                 }
283
284                 if (name == mandatory_tag)
285                 {
286                         // Found the mandatory tag
287                         mandatory_tag.clear();
288                 }
289
290                 if (stdalgo::string::equalsci(name, "include"))
291                 {
292                         stack.DoInclude(tag, flags);
293                 }
294                 else if (stdalgo::string::equalsci(name, "files"))
295                 {
296                         for(ConfigItems::iterator i = items->begin(); i != items->end(); i++)
297                         {
298                                 stack.DoReadFile(i->first, i->second, flags, false);
299                         }
300                 }
301                 else if (stdalgo::string::equalsci(name, "execfiles"))
302                 {
303                         for(ConfigItems::iterator i = items->begin(); i != items->end(); i++)
304                         {
305                                 stack.DoReadFile(i->first, i->second, flags, true);
306                         }
307                 }
308                 else if (stdalgo::string::equalsci(name, "define"))
309                 {
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");
314                         if (varname.empty())
315                                 throw CoreException("Variable definition must include variable name");
316                         stack.vars[varname] = value;
317                 }
318                 else if (stdalgo::string::equalsci(name, "config"))
319                 {
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);
327                 }
328                 else
329                 {
330                         stack.output.insert(std::make_pair(name, tag));
331                 }
332                 // this is not a leak; reference<> takes care of the delete
333                 tag = NULL;
334         }
335
336         bool outer_parse()
337         {
338                 try
339                 {
340                         while (1)
341                         {
342                                 int ch = next(true);
343                                 switch (ch)
344                                 {
345                                         case EOF:
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");
349                                                 return true;
350                                         case '#':
351                                                 comment();
352                                                 break;
353                                         case '<':
354                                                 dotag();
355                                                 break;
356                                         case ' ':
357                                         case '\r':
358                                         case '\t':
359                                         case '\n':
360                                                 break;
361                                         case 0xFE:
362                                         case 0xFF:
363                                                 stack.errstr << "Do not save your files as UTF-16 or UTF-32, use UTF-8!\n";
364                                                 /*@fallthrough@*/
365                                         default:
366                                                 throw CoreException("Syntax error - start of tag expected");
367                                 }
368                         }
369                 }
370                 catch (CoreException& err)
371                 {
372                         stack.errstr << err.GetReason() << " at " << current.str();
373                         if (tag)
374                                 stack.errstr << " (inside tag " << tag->tag << " at line " << tag->src_line << ")\n";
375                         else
376                                 stack.errstr << " (last tag was on line " << last_tag.line << ")\n";
377                 }
378                 return false;
379         }
380 };
381
382 void ParseStack::DoInclude(ConfigTag* tag, int flags)
383 {
384         if (flags & FLAG_NO_INC)
385                 throw CoreException("Invalid <include> tag in file included with noinclude=\"yes\"");
386
387         std::string mandatorytag;
388         tag->readString("mandatorytag", mandatorytag);
389
390         std::string name;
391         if (tag->readString("file", name))
392         {
393                 if (tag->getBool("noinclude", false))
394                         flags |= FLAG_NO_INC;
395                 if (tag->getBool("noexec", false))
396                         flags |= FLAG_NO_EXEC;
397                 if (!ParseFile(ServerInstance->Config->Paths.PrependConfig(name), flags, mandatorytag))
398                         throw CoreException("Included");
399         }
400         else if (tag->readString("executable", name))
401         {
402                 if (flags & FLAG_NO_EXEC)
403                         throw CoreException("Invalid <include:executable> tag in file included with noexec=\"yes\"");
404                 if (tag->getBool("noinclude", false))
405                         flags |= FLAG_NO_INC;
406                 if (tag->getBool("noexec", true))
407                         flags |= FLAG_NO_EXEC;
408                 if (!ParseFile(name, flags, mandatorytag, true))
409                         throw CoreException("Included");
410         }
411 }
412
413 void ParseStack::DoReadFile(const std::string& key, const std::string& name, int flags, bool exec)
414 {
415         if (flags & FLAG_NO_INC)
416                 throw CoreException("Invalid <files> tag in file included with noinclude=\"yes\"");
417         if (exec && (flags & FLAG_NO_EXEC))
418                 throw CoreException("Invalid <execfiles> tag in file included with noexec=\"yes\"");
419
420         std::string path = ServerInstance->Config->Paths.PrependConfig(name);
421         FileWrapper file(exec ? popen(name.c_str(), "r") : fopen(path.c_str(), "r"), exec);
422         if (!file)
423                 throw CoreException("Could not read \"" + path + "\" for \"" + key + "\" file");
424
425         file_cache& cache = FilesOutput[key];
426         cache.clear();
427
428         char linebuf[5120];
429         while (fgets(linebuf, sizeof(linebuf), file))
430         {
431                 size_t len = strlen(linebuf);
432                 if (len)
433                 {
434                         if (linebuf[len-1] == '\n')
435                                 len--;
436                         cache.push_back(std::string(linebuf, len));
437                 }
438         }
439 }
440
441 bool ParseStack::ParseFile(const std::string& path, int flags, const std::string& mandatory_tag, bool isexec)
442 {
443         ServerInstance->Logs->Log("CONFIG", LOG_DEBUG, "Reading (isexec=%d) %s", isexec, path.c_str());
444         if (stdalgo::isin(reading, path))
445                 throw CoreException((isexec ? "Executable " : "File ") + path + " is included recursively (looped inclusion)");
446
447         /* It's not already included, add it to the list of files we've loaded */
448
449         FileWrapper file((isexec ? popen(path.c_str(), "r") : fopen(path.c_str(), "r")), isexec);
450         if (!file)
451                 throw CoreException("Could not read \"" + path + "\" for include");
452
453         reading.push_back(path);
454         Parser p(*this, flags, file, path, mandatory_tag);
455         bool ok = p.outer_parse();
456         reading.pop_back();
457         return ok;
458 }
459
460 bool ConfigTag::readString(const std::string& key, std::string& value, bool allow_lf)
461 {
462         for(ConfigItems::iterator j = items.begin(); j != items.end(); ++j)
463         {
464                 if(j->first != key)
465                         continue;
466                 value = j->second;
467                 if (!allow_lf && (value.find('\n') != std::string::npos))
468                 {
469                         ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
470                                 " contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
471                         for (std::string::iterator n = value.begin(); n != value.end(); n++)
472                                 if (*n == '\n')
473                                         *n = ' ';
474                 }
475                 return true;
476         }
477         return false;
478 }
479
480 std::string ConfigTag::getString(const std::string& key, const std::string& def, const TR1NS::function<bool(const std::string&)>& validator)
481 {
482         std::string res;
483         if (!readString(key, res))
484                 return def;
485
486         if (!validator(res))
487         {
488                 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: The value of <%s:%s> is not valid; value set to %s.",
489                         tag.c_str(), key.c_str(), def.c_str());
490                 return def;
491         }
492         return res;
493 }
494
495 std::string ConfigTag::getString(const std::string& key, const std::string& def, size_t minlen, size_t maxlen)
496 {
497         std::string res;
498         if (!readString(key, res))
499                 return def;
500
501         if (res.length() < minlen || res.length() > maxlen)
502         {
503                 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "WARNING: The length of <%s:%s> is not between %ld and %ld; value set to %s.",
504                         tag.c_str(), key.c_str(), minlen, maxlen, def.c_str());
505                 return def;
506         }
507         return res;
508 }
509
510 namespace
511 {
512         /** Check for an invalid magnitude specifier. If one is found a warning is logged and the
513          * value is corrected (set to \p def).
514          * @param tag The tag name; used in the warning message.
515          * @param key The key name; used in the warning message.
516          * @param val The full value set in the config as a string.
517          * @param num The value to verify and modify if needed.
518          * @param def The default value, \p res will be set to this if \p tail does not contain a.
519          *            valid magnitude specifier.
520          * @param tail The location in the config value at which the magnifier is located.
521          */
522         template <typename Numeric>
523         void CheckMagnitude(const std::string& tag, const std::string& key, const std::string& val, Numeric& num, Numeric def, const char* tail)
524         {
525                 // If this is NULL then no magnitude specifier was given.
526                 if (!*tail)
527                         return;
528
529                 switch (toupper(*tail))
530                 {
531                         case 'K':
532                                 num *= 1024;
533                                 return;
534
535                         case 'M':
536                                 num *= 1024 * 1024;
537                                 return;
538
539                         case 'G':
540                                 num *= 1024 * 1024 * 1024;
541                                 return;
542                 }
543
544                 const std::string message = "WARNING: <" + tag + ":" + key + "> value of " + val + " contains an invalid magnitude specifier '"
545                         + tail + "'; value set to " + ConvToStr(def) + ".";
546                 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, message);
547                 num = def;
548         }
549
550         /** Check for an out of range value. If the value falls outside the boundaries a warning is
551          * logged and the value is corrected (set to \p def).
552          * @param tag The tag name; used in the warning message.
553          * @param key The key name; used in the warning message.
554          * @param num The value to verify and modify if needed.
555          * @param def The default value, \p res will be set to this if (min <= res <= max) doesn't hold true.
556          * @param min Minimum accepted value for \p res.
557          * @param max Maximum accepted value for \p res.
558          */
559         template <typename Numeric>
560         void CheckRange(const std::string& tag, const std::string& key, Numeric& num, Numeric def, Numeric min, Numeric max)
561         {
562                 if (num >= min && num <= max)
563                         return;
564
565                 const std::string message = "WARNING: <" + tag + ":" + key + "> value of " + ConvToStr(num) + " is not between "
566                         + ConvToStr(min) + " and " + ConvToStr(max) + "; value set to " + ConvToStr(def) + ".";
567                 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, message);
568                 num = def;
569         }
570 }
571
572 long ConfigTag::getInt(const std::string &key, long def, long min, long max)
573 {
574         std::string result;
575         if(!readString(key, result))
576                 return def;
577
578         const char* res_cstr = result.c_str();
579         char* res_tail = NULL;
580         long res = strtol(res_cstr, &res_tail, 0);
581         if (res_tail == res_cstr)
582                 return def;
583
584         CheckMagnitude(tag, key, result, res, def, res_tail);
585         CheckRange(tag, key, res, def, min, max);
586         return res;
587 }
588
589 unsigned long ConfigTag::getUInt(const std::string& key, unsigned long def, unsigned long min, unsigned long max)
590 {
591         std::string result;
592         if (!readString(key, result))
593                 return def;
594
595         const char* res_cstr = result.c_str();
596         char* res_tail = NULL;
597         unsigned long res = strtoul(res_cstr, &res_tail, 0);
598         if (res_tail == res_cstr)
599                 return def;
600
601         CheckMagnitude(tag, key, result, res, def, res_tail);
602         CheckRange(tag, key, res, def, min, max);
603         return res;
604 }
605
606 unsigned long ConfigTag::getDuration(const std::string& key, unsigned long def, unsigned long min, unsigned long max)
607 {
608         std::string duration;
609         if (!readString(key, duration))
610                 return def;
611
612         unsigned long ret;
613         if (!InspIRCd::Duration(duration, ret))
614         {
615                 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
616                         " is not a duration; value set to " + ConvToStr(def) + ".");
617                 return def;
618         }
619
620         CheckRange(tag, key, ret, def, min, max);
621         return ret;
622 }
623
624 double ConfigTag::getFloat(const std::string& key, double def, double min, double max)
625 {
626         std::string result;
627         if (!readString(key, result))
628                 return def;
629
630         double res = strtod(result.c_str(), NULL);
631         CheckRange(tag, key, res, def, min, max);
632         return res;
633 }
634
635 bool ConfigTag::getBool(const std::string &key, bool def)
636 {
637         std::string result;
638         if(!readString(key, result))
639                 return def;
640
641         if (result == "yes" || result == "true" || result == "1" || result == "on")
642                 return true;
643         if (result == "no" || result == "false" || result == "0" || result == "off")
644                 return false;
645
646         ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
647                 " is not valid, ignoring");
648         return def;
649 }
650
651 std::string ConfigTag::getTagLocation()
652 {
653         return src_name + ":" + ConvToStr(src_line);
654 }
655
656 ConfigTag* ConfigTag::create(const std::string& Tag, const std::string& file, int line, ConfigItems*& Items)
657 {
658         ConfigTag* rv = new ConfigTag(Tag, file, line);
659         Items = &rv->items;
660         return rv;
661 }
662
663 ConfigTag::ConfigTag(const std::string& Tag, const std::string& file, int line)
664         : tag(Tag), src_name(file), src_line(line)
665 {
666 }
667
668 OperInfo::OperInfo(const std::string& Name)
669         : name(Name)
670 {
671 }
672
673 std::string OperInfo::getConfig(const std::string& key)
674 {
675         std::string rv;
676         if (type_block)
677                 type_block->readString(key, rv);
678         if (oper_block)
679                 oper_block->readString(key, rv);
680         return rv;
681 }