]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/configparser.cpp
Merge pull request #109 from Justasic/insp20
[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 struct Parser
25 {
26         ParseStack& stack;
27         int flags;
28         FILE* const file;
29         fpos current;
30         fpos last_tag;
31         reference<ConfigTag> tag;
32         int ungot;
33
34         Parser(ParseStack& me, int myflags, FILE* conf, const std::string& name)
35                 : stack(me), flags(myflags), file(conf), current(name), last_tag(name), ungot(-1)
36         { }
37
38         int next(bool eof_ok = false)
39         {
40                 if (ungot != -1)
41                 {
42                         int ch = ungot;
43                         ungot = -1;
44                         return ch;
45                 }
46                 int ch = fgetc(file);
47                 if (ch == EOF && !eof_ok)
48                 {
49                         throw CoreException("Unexpected end-of-file");
50                 }
51                 else if (ch == '\n')
52                 {
53                         current.line++;
54                         current.col = 0;
55                 }
56                 else
57                 {
58                         current.col++;
59                 }
60                 return ch;
61         }
62
63         void unget(int ch)
64         {
65                 if (ungot != -1)
66                         throw CoreException("INTERNAL ERROR: cannot unget twice");
67                 ungot = ch;
68         }
69
70         void comment()
71         {
72                 while (1)
73                 {
74                         int ch = next();
75                         if (ch == '\n')
76                                 return;
77                 }
78         }
79
80         void nextword(std::string& rv)
81         {
82                 int ch = next();
83                 while (isspace(ch))
84                         ch = next();
85                 while (isalnum(ch) || ch == '_'|| ch == '-')
86                 {
87                         rv.push_back(ch);
88                         ch = next();
89                 }
90                 unget(ch);
91         }
92
93         bool kv(std::vector<KeyVal>* items, std::set<std::string>& seen)
94         {
95                 std::string key;
96                 nextword(key);
97                 int ch = next();
98                 if (ch == '>' && key.empty())
99                 {
100                         return false;
101                 }
102                 else if (ch == '#' && key.empty())
103                 {
104                         comment();
105                         return true;
106                 }
107                 else if (ch != '=')
108                 {
109                         throw CoreException("Invalid character " + std::string(1, ch) + " in key (" + key + ")");
110                 }
111
112                 std::string value;
113                 ch = next();
114                 if (ch != '"')
115                 {
116                         throw CoreException("Invalid character in value of <" + tag->tag + ":" + key + ">");
117                 }
118                 while (1)
119                 {
120                         ch = next();
121                         if (ch == '&' && (flags & FLAG_USE_XML))
122                         {
123                                 std::string varname;
124                                 while (1)
125                                 {
126                                         ch = next();
127                                         if (isalnum(ch))
128                                                 varname.push_back(ch);
129                                         else if (ch == ';')
130                                                 break;
131                                         else
132                                         {
133                                                 stack.errstr << "Invalid XML entity name in value of <" + tag->tag + ":" + key + ">\n"
134                                                         << "To include an ampersand or quote, use &amp; or &quot;\n";
135                                                 throw CoreException("Parse error");
136                                         }
137                                 }
138                                 std::map<std::string, std::string>::iterator var = stack.vars.find(varname);
139                                 if (var == stack.vars.end())
140                                         throw CoreException("Undefined XML entity reference '&" + varname + ";'");
141                                 value.append(var->second);
142                         }
143                         else if (ch == '\\' && !(flags & FLAG_USE_XML))
144                         {
145                                 int esc = next();
146                                 if (esc == 'n')
147                                         value.push_back('\n');
148                                 else if (isalpha(esc))
149                                         throw CoreException("Unknown escape character \\" + std::string(1, esc));
150                                 else
151                                         value.push_back(esc);
152                         }
153                         else if (ch == '"')
154                                 break;
155                         else
156                                 value.push_back(ch);
157                 }
158
159                 if (!seen.insert(key).second)
160                         throw CoreException("Duplicate key '" + key + "' found");
161
162                 items->push_back(KeyVal(key, value));
163                 return true;
164         }
165
166         void dotag()
167         {
168                 last_tag = current;
169                 std::string name;
170                 nextword(name);
171
172                 int spc = next();
173                 if (spc == '>')
174                         unget(spc);
175                 else if (!isspace(spc))
176                         throw CoreException("Invalid character in tag name");
177
178                 if (name.empty())
179                         throw CoreException("Empty tag name");
180
181                 std::vector<KeyVal>* items;
182                 std::set<std::string> seen;
183                 tag = ConfigTag::create(name, current.filename, current.line, items);
184
185                 while (kv(items, seen));
186
187                 if (name == "include")
188                 {
189                         stack.DoInclude(tag, flags);
190                 }
191                 else if (name == "files")
192                 {
193                         for(std::vector<KeyVal>::iterator i = items->begin(); i != items->end(); i++)
194                         {
195                                 stack.DoReadFile(i->first, i->second, flags, false);
196                         }
197                 }
198                 else if (name == "execfiles")
199                 {
200                         for(std::vector<KeyVal>::iterator i = items->begin(); i != items->end(); i++)
201                         {
202                                 stack.DoReadFile(i->first, i->second, flags, true);
203                         }
204                 }
205                 else if (name == "define")
206                 {
207                         if (!(flags & FLAG_USE_XML))
208                                 throw CoreException("<define> tags may only be used in XML-style config (add <config format=\"xml\">)");
209                         std::string varname = tag->getString("name");
210                         std::string value = tag->getString("value");
211                         if (varname.empty())
212                                 throw CoreException("Variable definition must include variable name");
213                         stack.vars[varname] = value;
214                 }
215                 else if (name == "config")
216                 {
217                         std::string format = tag->getString("format");
218                         if (format == "xml")
219                                 flags |= FLAG_USE_XML;
220                         else if (format == "compat")
221                                 flags &= ~FLAG_USE_XML;
222                         else if (!format.empty())
223                                 throw CoreException("Unknown configuration format " + format);
224                 }
225                 else
226                 {
227                         stack.output.insert(std::make_pair(name, tag));
228                 }
229                 // this is not a leak; reference<> takes care of the delete
230                 tag = NULL;
231         }
232
233         bool outer_parse()
234         {
235                 try
236                 {
237                         while (1)
238                         {
239                                 int ch = next(true);
240                                 switch (ch)
241                                 {
242                                         case EOF:
243                                                 // this is the one place where an EOF is not an error
244                                                 return true;
245                                         case '#':
246                                                 comment();
247                                                 break;
248                                         case '<':
249                                                 dotag();
250                                                 break;
251                                         case ' ':
252                                         case '\r':
253                                         case '\t':
254                                         case '\n':
255                                                 break;
256                                         case 0xFE:
257                                         case 0xFF:
258                                                 stack.errstr << "Do not save your files as UTF-16; use ASCII!\n";
259                                         default:
260                                                 throw CoreException("Syntax error - start of tag expected");
261                                 }
262                         }
263                 }
264                 catch (CoreException& err)
265                 {
266                         stack.errstr << err.GetReason() << " at " << current.str();
267                         if (tag)
268                                 stack.errstr << " (inside tag " << tag->tag << " at line " << tag->src_line << ")\n";
269                         else
270                                 stack.errstr << " (last tag was on line " << last_tag.line << ")\n";
271                 }
272                 return false;
273         }
274 };
275
276 void ParseStack::DoInclude(ConfigTag* tag, int flags)
277 {
278         if (flags & FLAG_NO_INC)
279                 throw CoreException("Invalid <include> tag in file included with noinclude=\"yes\"");
280         std::string name;
281         if (tag->readString("file", name))
282         {
283                 if (tag->getBool("noinclude", false))
284                         flags |= FLAG_NO_INC;
285                 if (tag->getBool("noexec", false))
286                         flags |= FLAG_NO_EXEC;
287                 if (!ParseFile(name, flags))
288                         throw CoreException("Included");
289         }
290         else if (tag->readString("executable", name))
291         {
292                 if (flags & FLAG_NO_EXEC)
293                         throw CoreException("Invalid <include:executable> tag in file included with noexec=\"yes\"");
294                 if (tag->getBool("noinclude", false))
295                         flags |= FLAG_NO_INC;
296                 if (tag->getBool("noexec", true))
297                         flags |= FLAG_NO_EXEC;
298                 if (!ParseExec(name, flags))
299                         throw CoreException("Included");
300         }
301 }
302
303 void ParseStack::DoReadFile(const std::string& key, const std::string& name, int flags, bool exec)
304 {
305         if (flags & FLAG_NO_INC)
306                 throw CoreException("Invalid <files> tag in file included with noinclude=\"yes\"");
307         if (exec && (flags & FLAG_NO_EXEC))
308                 throw CoreException("Invalid <execfiles> tag in file included with noexec=\"yes\"");
309
310         FileWrapper file(exec ? popen(name.c_str(), "r") : fopen(name.c_str(), "r"));
311         if (!file)
312                 throw CoreException("Could not read \"" + name + "\" for \"" + key + "\" file");
313
314         file_cache& cache = FilesOutput[key];
315         cache.clear();
316
317         char linebuf[MAXBUF*10];
318         while (fgets(linebuf, sizeof(linebuf), file))
319         {
320                 int len = strlen(linebuf);
321                 if (len)
322                         cache.push_back(std::string(linebuf, len - 1));
323         }
324 }
325
326 bool ParseStack::ParseFile(const std::string& name, int flags)
327 {
328         ServerInstance->Logs->Log("CONFIG", DEBUG, "Reading file %s", name.c_str());
329         for (unsigned int t = 0; t < reading.size(); t++)
330         {
331                 if (std::string(name) == reading[t])
332                 {
333                         throw CoreException("File " + name + " is included recursively (looped inclusion)");
334                 }
335         }
336
337         /* It's not already included, add it to the list of files we've loaded */
338
339         FileWrapper file(fopen(name.c_str(), "r"));
340         if (!file)
341                 throw CoreException("Could not read \"" + name + "\" for include");
342
343         reading.push_back(name);
344         Parser p(*this, flags, file, name);
345         bool ok = p.outer_parse();
346         reading.pop_back();
347         return ok;
348 }
349
350 bool ParseStack::ParseExec(const std::string& name, int flags)
351 {
352         ServerInstance->Logs->Log("CONFIG", DEBUG, "Reading executable %s", name.c_str());
353         for (unsigned int t = 0; t < reading.size(); t++)
354         {
355                 if (std::string(name) == reading[t])
356                 {
357                         throw CoreException("Executable " + name + " is included recursively (looped inclusion)");
358                 }
359         }
360
361         /* It's not already included, add it to the list of files we've loaded */
362
363         FileWrapper file(popen(name.c_str(), "r"));
364         if (!file)
365                 throw CoreException("Could not open executable \"" + name + "\" for include");
366
367         reading.push_back(name);
368         Parser p(*this, flags, file, name);
369         bool ok = p.outer_parse();
370         reading.pop_back();
371         return ok;
372 }
373
374 bool ConfigTag::readString(const std::string& key, std::string& value, bool allow_lf)
375 {
376         if (!this)
377                 return false;
378         for(std::vector<KeyVal>::iterator j = items.begin(); j != items.end(); ++j)
379         {
380                 if(j->first != key)
381                         continue;
382                 value = j->second;
383                 if (!allow_lf && (value.find('\n') != std::string::npos))
384                 {
385                         ServerInstance->Logs->Log("CONFIG",DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
386                                 " contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
387                         for (std::string::iterator n = value.begin(); n != value.end(); n++)
388                                 if (*n == '\n')
389                                         *n = ' ';
390                 }
391                 return true;
392         }
393         return false;
394 }
395
396 std::string ConfigTag::getString(const std::string& key, const std::string& def)
397 {
398         std::string res = def;
399         readString(key, res);
400         return res;
401 }
402
403 long ConfigTag::getInt(const std::string &key, long def)
404 {
405         std::string result;
406         if(!readString(key, result))
407                 return def;
408
409         const char* res_cstr = result.c_str();
410         char* res_tail = NULL;
411         long res = strtol(res_cstr, &res_tail, 0);
412         if (res_tail == res_cstr)
413                 return def;
414         switch (toupper(*res_tail))
415         {
416                 case 'K':
417                         res= res* 1024;
418                         break;
419                 case 'M':
420                         res= res* 1024 * 1024;
421                         break;
422                 case 'G':
423                         res= res* 1024 * 1024 * 1024;
424                         break;
425         }
426         return res;
427 }
428
429 double ConfigTag::getFloat(const std::string &key, double def)
430 {
431         std::string result;
432         if (!readString(key, result))
433                 return def;
434         return strtod(result.c_str(), NULL);
435 }
436
437 bool ConfigTag::getBool(const std::string &key, bool def)
438 {
439         std::string result;
440         if(!readString(key, result))
441                 return def;
442
443         if (result == "yes" || result == "true" || result == "1" || result == "on")
444                 return true;
445         if (result == "no" || result == "false" || result == "0" || result == "off")
446                 return false;
447
448         ServerInstance->Logs->Log("CONFIG",DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
449                 " is not valid, ignoring");
450         return def;
451 }
452
453 std::string ConfigTag::getTagLocation()
454 {
455         return src_name + ":" + ConvToStr(src_line);
456 }
457
458 ConfigTag* ConfigTag::create(const std::string& Tag, const std::string& file, int line, std::vector<KeyVal>*&items)
459 {
460         ConfigTag* rv = new ConfigTag(Tag, file, line);
461         items = &rv->items;
462         return rv;
463 }
464
465 ConfigTag::ConfigTag(const std::string& Tag, const std::string& file, int line)
466         : tag(Tag), src_name(file), src_line(line)
467 {
468 }
469
470 std::string OperInfo::getConfig(const std::string& key)
471 {
472         std::string rv;
473         if (type_block)
474                 type_block->readString(key, rv);
475         if (oper_block)
476                 oper_block->readString(key, rv);
477         return rv;
478 }