]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/configparser.cpp
Send ERR_BANNEDFROMCHAN when a user can't create a restricted channel.
[user/henk/code/inspircd.git] / src / configparser.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
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>
11  *
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.
15  *
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
19  * details.
20  *
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/>.
23  */
24
25
26 #include "inspircd.h"
27 #include <fstream>
28 #include "configparser.h"
29
30 enum ParseFlags
31 {
32         // Legacy config parsing should be used.
33         FLAG_USE_COMPAT = 1,
34
35         // Executable includes are disabled.
36         FLAG_NO_EXEC = 2,
37
38         // All includes are disabled.
39         FLAG_NO_INC = 4
40 };
41
42 // Represents the position within a config file.
43 struct FilePosition
44 {
45         // The name of the file which is being read.
46         std::string name;
47
48         // The line of the file that this position points to.
49         unsigned int line;
50
51         // The column of the file that this position points to.
52         unsigned int column;
53
54         FilePosition(const std::string& Name)
55                 : name(Name)
56                 , line(1)
57                 , column(1)
58         {
59         }
60
61         /** Returns a string that represents this file position. */
62         std::string str()
63         {
64                 return name + ":" + ConvToStr(line) + ":" + ConvToStr(column);
65         }
66 };
67
68 // RAII wrapper for FILE* which closes the file when it goes out of scope.
69 class FileWrapper
70 {
71  private:
72         // Whether this file handle should be closed with pclose.
73         bool close_with_pclose;
74
75         // The file handle which is being wrapped.
76         FILE* const file;
77
78  public:
79         FileWrapper(FILE* File, bool CloseWithPClose = false)
80                 : close_with_pclose(CloseWithPClose)
81                 , file(File)
82         {
83         }
84
85         // Operator which determines whether the file is open.
86         operator bool() { return (file != NULL); }
87
88         // Operator which retrieves the underlying FILE pointer.
89         operator FILE*() { return file; }
90
91         ~FileWrapper()
92         {
93                 if (!file)
94                         return;
95
96                 if (close_with_pclose)
97                         pclose(file);
98                 else
99                         fclose(file);
100         }
101 };
102
103
104 struct Parser
105 {
106         ParseStack& stack;
107         int flags;
108         FILE* const file;
109         FilePosition current;
110         FilePosition last_tag;
111         reference<ConfigTag> tag;
112         int ungot;
113         std::string mandatory_tag;
114
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)
117         { }
118
119         int next(bool eof_ok = false)
120         {
121                 if (ungot != -1)
122                 {
123                         int ch = ungot;
124                         ungot = -1;
125                         return ch;
126                 }
127                 int ch = fgetc(file);
128                 if (ch == EOF && !eof_ok)
129                 {
130                         throw CoreException("Unexpected end-of-file");
131                 }
132                 else if (ch == '\n')
133                 {
134                         current.line++;
135                         current.column = 0;
136                 }
137                 else
138                 {
139                         current.column++;
140                 }
141                 return ch;
142         }
143
144         void unget(int ch)
145         {
146                 if (ungot != -1)
147                         throw CoreException("INTERNAL ERROR: cannot unget twice");
148                 ungot = ch;
149         }
150
151         void comment()
152         {
153                 while (1)
154                 {
155                         int ch = next();
156                         if (ch == '\n')
157                                 return;
158                 }
159         }
160
161         bool wordchar(char ch)
162         {
163                 return isalnum(ch)
164                         || ch == '-'
165                         || ch == '.'
166                         || ch == '_';
167         }
168
169         void nextword(std::string& rv)
170         {
171                 int ch = next();
172                 while (isspace(ch))
173                         ch = next();
174                 while (wordchar(ch))
175                 {
176                         rv.push_back(ch);
177                         ch = next();
178                 }
179                 unget(ch);
180         }
181
182         bool kv(ConfigItems* items)
183         {
184                 std::string key;
185                 nextword(key);
186                 int ch = next();
187                 if (ch == '>' && key.empty())
188                 {
189                         return false;
190                 }
191                 else if (ch == '#' && key.empty())
192                 {
193                         comment();
194                         return true;
195                 }
196                 else if (ch != '=')
197                 {
198                         throw CoreException("Invalid character " + std::string(1, ch) + " in key (" + key + ")");
199                 }
200
201                 std::string value;
202                 ch = next();
203                 if (ch != '"')
204                 {
205                         throw CoreException("Invalid character in value of <" + tag->tag + ":" + key + ">");
206                 }
207                 while (1)
208                 {
209                         ch = next();
210                         if (ch == '&' && !(flags & FLAG_USE_COMPAT))
211                         {
212                                 std::string varname;
213                                 while (1)
214                                 {
215                                         ch = next();
216                                         if (wordchar(ch) || (varname.empty() && ch == '#'))
217                                                 varname.push_back(ch);
218                                         else if (ch == ';')
219                                                 break;
220                                         else
221                                         {
222                                                 stack.errstr << "Invalid XML entity name in value of <" + tag->tag + ":" + key + ">\n"
223                                                         << "To include an ampersand or quote, use &amp; or &quot;\n";
224                                                 throw CoreException("Parse error");
225                                         }
226                                 }
227                                 if (varname.empty())
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] == '#')
232                                 {
233                                         const char* cvarname = varname.c_str();
234                                         char* endptr;
235                                         unsigned long lvalue;
236                                         if (cvarname[1] == 'x')
237                                                 lvalue = strtoul(cvarname + 2, &endptr, 16);
238                                         else
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));
243                                 }
244                                 else if (varname.compare(0, 4, "env.") == 0)
245                                 {
246                                         const char* envstr = getenv(varname.c_str() + 4);
247                                         if (!envstr)
248                                                 throw CoreException("Undefined XML environment entity reference '&" + varname + ";'");
249                                         value.append(envstr);
250                                 }
251                                 else
252                                 {
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);
257                                 }
258                         }
259                         else if (ch == '\\' && (flags & FLAG_USE_COMPAT))
260                         {
261                                 int esc = next();
262                                 if (esc == 'n')
263                                         value.push_back('\n');
264                                 else if (isalpha(esc))
265                                         throw CoreException("Unknown escape character \\" + std::string(1, esc));
266                                 else
267                                         value.push_back(esc);
268                         }
269                         else if (ch == '"')
270                                 break;
271                         else if (ch != '\r')
272                                 value.push_back(ch);
273                 }
274
275                 if (items->find(key) != items->end())
276                         throw CoreException("Duplicate key '" + key + "' found");
277
278                 (*items)[key] = value;
279                 return true;
280         }
281
282         void dotag()
283         {
284                 last_tag = current;
285                 std::string name;
286                 nextword(name);
287
288                 int spc = next();
289                 if (spc == '>')
290                         unget(spc);
291                 else if (!isspace(spc))
292                         throw CoreException("Invalid character in tag name");
293
294                 if (name.empty())
295                         throw CoreException("Empty tag name");
296
297                 ConfigItems* items;
298                 tag = ConfigTag::create(name, current.name, current.line, items);
299
300                 while (kv(items))
301                 {
302                         // Do nothing here (silences a GCC warning).
303                 }
304
305                 if (name == mandatory_tag)
306                 {
307                         // Found the mandatory tag
308                         mandatory_tag.clear();
309                 }
310
311                 if (stdalgo::string::equalsci(name, "include"))
312                 {
313                         stack.DoInclude(tag, flags);
314                 }
315                 else if (stdalgo::string::equalsci(name, "files"))
316                 {
317                         for(ConfigItems::iterator i = items->begin(); i != items->end(); i++)
318                         {
319                                 stack.DoReadFile(i->first, i->second, flags, false);
320                         }
321                 }
322                 else if (stdalgo::string::equalsci(name, "execfiles"))
323                 {
324                         for(ConfigItems::iterator i = items->begin(); i != items->end(); i++)
325                         {
326                                 stack.DoReadFile(i->first, i->second, flags, true);
327                         }
328                 }
329                 else if (stdalgo::string::equalsci(name, "define"))
330                 {
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");
335                         if (varname.empty())
336                                 throw CoreException("Variable definition must include variable name");
337                         stack.vars[varname] = value;
338                 }
339                 else if (stdalgo::string::equalsci(name, "config"))
340                 {
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);
348                 }
349                 else
350                 {
351                         stack.output.insert(std::make_pair(name, tag));
352                 }
353                 // this is not a leak; reference<> takes care of the delete
354                 tag = NULL;
355         }
356
357         bool outer_parse()
358         {
359                 try
360                 {
361                         while (1)
362                         {
363                                 int ch = next(true);
364                                 switch (ch)
365                                 {
366                                         case EOF:
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");
370                                                 return true;
371                                         case '#':
372                                                 comment();
373                                                 break;
374                                         case '<':
375                                                 dotag();
376                                                 break;
377                                         case ' ':
378                                         case '\r':
379                                         case '\t':
380                                         case '\n':
381                                                 break;
382                                         case 0xFE:
383                                         case 0xFF:
384                                                 stack.errstr << "Do not save your files as UTF-16 or UTF-32, use UTF-8!\n";
385                                                 /*@fallthrough@*/
386                                         default:
387                                                 throw CoreException("Syntax error - start of tag expected");
388                                 }
389                         }
390                 }
391                 catch (CoreException& err)
392                 {
393                         stack.errstr << err.GetReason() << " at " << current.str();
394                         if (tag)
395                                 stack.errstr << " (inside tag " << tag->tag << " at line " << tag->src_line << ")\n";
396                         else
397                                 stack.errstr << " (last tag was on line " << last_tag.line << ")\n";
398                 }
399                 return false;
400         }
401 };
402
403 void ParseStack::DoInclude(ConfigTag* tag, int flags)
404 {
405         if (flags & FLAG_NO_INC)
406                 throw CoreException("Invalid <include> tag in file included with noinclude=\"yes\"");
407
408         std::string mandatorytag;
409         tag->readString("mandatorytag", mandatorytag);
410
411         std::string name;
412         if (tag->readString("file", name))
413         {
414                 if (tag->getBool("noinclude", false))
415                         flags |= FLAG_NO_INC;
416                 if (tag->getBool("noexec", false))
417                         flags |= FLAG_NO_EXEC;
418
419                 if (!ParseFile(ServerInstance->Config->Paths.PrependConfig(name), flags, mandatorytag))
420                         throw CoreException("Included");
421         }
422         else if (tag->readString("directory", name))
423         {
424                 if (tag->getBool("noinclude", false))
425                         flags |= FLAG_NO_INC;
426                 if (tag->getBool("noexec", false))
427                         flags |= FLAG_NO_EXEC;
428
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);
433
434                 std::sort(files.begin(), files.end());
435                 for (std::vector<std::string>::const_iterator iter = files.begin(); iter != files.end(); ++iter)
436                 {
437                         const std::string path = includedir + '/' + *iter;
438                         if (!ParseFile(path, flags, mandatorytag))
439                                 throw CoreException("Included");
440                 }
441         }
442         else if (tag->readString("executable", name))
443         {
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;
450
451                 if (!ParseFile(name, flags, mandatorytag, true))
452                         throw CoreException("Included");
453         }
454 }
455
456 void ParseStack::DoReadFile(const std::string& key, const std::string& name, int flags, bool exec)
457 {
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\"");
462
463         std::string path = ServerInstance->Config->Paths.PrependConfig(name);
464         FileWrapper file(exec ? popen(name.c_str(), "r") : fopen(path.c_str(), "r"), exec);
465         if (!file)
466                 throw CoreException("Could not read \"" + path + "\" for \"" + key + "\" file");
467
468         file_cache& cache = FilesOutput[key];
469         cache.clear();
470
471         char linebuf[5120];
472         while (fgets(linebuf, sizeof(linebuf), file))
473         {
474                 size_t len = strlen(linebuf);
475                 if (len)
476                 {
477                         if (linebuf[len-1] == '\n')
478                                 len--;
479                         cache.push_back(std::string(linebuf, len));
480                 }
481         }
482 }
483
484 bool ParseStack::ParseFile(const std::string& path, int flags, const std::string& mandatory_tag, bool isexec)
485 {
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)");
489
490         /* It's not already included, add it to the list of files we've loaded */
491
492         FileWrapper file((isexec ? popen(path.c_str(), "r") : fopen(path.c_str(), "r")), isexec);
493         if (!file)
494                 throw CoreException("Could not read \"" + path + "\" for include");
495
496         reading.push_back(path);
497         Parser p(*this, flags, file, path, mandatory_tag);
498         bool ok = p.outer_parse();
499         reading.pop_back();
500         return ok;
501 }
502
503 bool ConfigTag::readString(const std::string& key, std::string& value, bool allow_lf)
504 {
505         for(ConfigItems::iterator j = items.begin(); j != items.end(); ++j)
506         {
507                 if(j->first != key)
508                         continue;
509                 value = j->second;
510                 if (!allow_lf && (value.find('\n') != std::string::npos))
511                 {
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++)
515                                 if (*n == '\n')
516                                         *n = ' ';
517                 }
518                 return true;
519         }
520         return false;
521 }
522
523 std::string ConfigTag::getString(const std::string& key, const std::string& def, const TR1NS::function<bool(const std::string&)>& validator)
524 {
525         std::string res;
526         if (!readString(key, res))
527                 return def;
528
529         if (!validator(res))
530         {
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());
533                 return def;
534         }
535         return res;
536 }
537
538 std::string ConfigTag::getString(const std::string& key, const std::string& def, size_t minlen, size_t maxlen)
539 {
540         std::string res;
541         if (!readString(key, res))
542                 return def;
543
544         if (res.length() < minlen || res.length() > maxlen)
545         {
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());
548                 return def;
549         }
550         return res;
551 }
552
553 namespace
554 {
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.
564          */
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)
567         {
568                 // If this is NULL then no magnitude specifier was given.
569                 if (!*tail)
570                         return;
571
572                 switch (toupper(*tail))
573                 {
574                         case 'K':
575                                 num *= 1024;
576                                 return;
577
578                         case 'M':
579                                 num *= 1024 * 1024;
580                                 return;
581
582                         case 'G':
583                                 num *= 1024 * 1024 * 1024;
584                                 return;
585                 }
586
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);
590                 num = def;
591         }
592
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.
601          */
602         template <typename Numeric>
603         void CheckRange(const std::string& tag, const std::string& key, Numeric& num, Numeric def, Numeric min, Numeric max)
604         {
605                 if (num >= min && num <= max)
606                         return;
607
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);
611                 num = def;
612         }
613 }
614
615 long ConfigTag::getInt(const std::string &key, long def, long min, long max)
616 {
617         std::string result;
618         if(!readString(key, result))
619                 return def;
620
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)
625                 return def;
626
627         CheckMagnitude(tag, key, result, res, def, res_tail);
628         CheckRange(tag, key, res, def, min, max);
629         return res;
630 }
631
632 unsigned long ConfigTag::getUInt(const std::string& key, unsigned long def, unsigned long min, unsigned long max)
633 {
634         std::string result;
635         if (!readString(key, result))
636                 return def;
637
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)
642                 return def;
643
644         CheckMagnitude(tag, key, result, res, def, res_tail);
645         CheckRange(tag, key, res, def, min, max);
646         return res;
647 }
648
649 unsigned long ConfigTag::getDuration(const std::string& key, unsigned long def, unsigned long min, unsigned long max)
650 {
651         std::string duration;
652         if (!readString(key, duration))
653                 return def;
654
655         unsigned long ret;
656         if (!InspIRCd::Duration(duration, ret))
657         {
658                 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
659                         " is not a duration; value set to " + ConvToStr(def) + ".");
660                 return def;
661         }
662
663         CheckRange(tag, key, ret, def, min, max);
664         return ret;
665 }
666
667 double ConfigTag::getFloat(const std::string& key, double def, double min, double max)
668 {
669         std::string result;
670         if (!readString(key, result))
671                 return def;
672
673         double res = strtod(result.c_str(), NULL);
674         CheckRange(tag, key, res, def, min, max);
675         return res;
676 }
677
678 bool ConfigTag::getBool(const std::string &key, bool def)
679 {
680         std::string result;
681         if(!readString(key, result))
682                 return def;
683
684         if (stdalgo::string::equalsci(result, "yes") || stdalgo::string::equalsci(result, "true") || stdalgo::string::equalsci(result, "on") || result == "1")
685                 return true;
686
687         if (stdalgo::string::equalsci(result, "no") || stdalgo::string::equalsci(result, "false") || stdalgo::string::equalsci(result, "off") || result == "0")
688                 return false;
689
690         ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
691                 " is not valid, ignoring");
692         return def;
693 }
694
695 std::string ConfigTag::getTagLocation()
696 {
697         return src_name + ":" + ConvToStr(src_line);
698 }
699
700 ConfigTag* ConfigTag::create(const std::string& Tag, const std::string& file, int line, ConfigItems*& Items)
701 {
702         ConfigTag* rv = new ConfigTag(Tag, file, line);
703         Items = &rv->items;
704         return rv;
705 }
706
707 ConfigTag::ConfigTag(const std::string& Tag, const std::string& file, int line)
708         : tag(Tag), src_name(file), src_line(line)
709 {
710 }
711
712 OperInfo::OperInfo(const std::string& Name)
713         : name(Name)
714 {
715 }
716
717 std::string OperInfo::getConfig(const std::string& key)
718 {
719         std::string rv;
720         if (type_block)
721                 type_block->readString(key, rv);
722         if (oper_block)
723                 oper_block->readString(key, rv);
724         return rv;
725 }