]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/configparser.cpp
Close files opened with popen() with pclose() instead of fclose()
[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"), exec);
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                 size_t len = strlen(linebuf);
321                 if (len)
322                 {
323                         if (linebuf[len-1] == '\n')
324                                 len--;
325                         cache.push_back(std::string(linebuf, len));
326                 }
327         }
328 }
329
330 bool ParseStack::ParseFile(const std::string& name, int flags)
331 {
332         ServerInstance->Logs->Log("CONFIG", DEBUG, "Reading file %s", name.c_str());
333         for (unsigned int t = 0; t < reading.size(); t++)
334         {
335                 if (std::string(name) == reading[t])
336                 {
337                         throw CoreException("File " + name + " is included recursively (looped inclusion)");
338                 }
339         }
340
341         /* It's not already included, add it to the list of files we've loaded */
342
343         FileWrapper file(fopen(name.c_str(), "r"));
344         if (!file)
345                 throw CoreException("Could not read \"" + name + "\" for include");
346
347         reading.push_back(name);
348         Parser p(*this, flags, file, name);
349         bool ok = p.outer_parse();
350         reading.pop_back();
351         return ok;
352 }
353
354 bool ParseStack::ParseExec(const std::string& name, int flags)
355 {
356         ServerInstance->Logs->Log("CONFIG", DEBUG, "Reading executable %s", name.c_str());
357         for (unsigned int t = 0; t < reading.size(); t++)
358         {
359                 if (std::string(name) == reading[t])
360                 {
361                         throw CoreException("Executable " + name + " is included recursively (looped inclusion)");
362                 }
363         }
364
365         /* It's not already included, add it to the list of files we've loaded */
366
367         FileWrapper file(popen(name.c_str(), "r"), true);
368         if (!file)
369                 throw CoreException("Could not open executable \"" + name + "\" for include");
370
371         reading.push_back(name);
372         Parser p(*this, flags, file, name);
373         bool ok = p.outer_parse();
374         reading.pop_back();
375         return ok;
376 }
377
378 bool ConfigTag::readString(const std::string& key, std::string& value, bool allow_lf)
379 {
380         if (!this)
381                 return false;
382         for(std::vector<KeyVal>::iterator j = items.begin(); j != items.end(); ++j)
383         {
384                 if(j->first != key)
385                         continue;
386                 value = j->second;
387                 if (!allow_lf && (value.find('\n') != std::string::npos))
388                 {
389                         ServerInstance->Logs->Log("CONFIG",DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
390                                 " contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
391                         for (std::string::iterator n = value.begin(); n != value.end(); n++)
392                                 if (*n == '\n')
393                                         *n = ' ';
394                 }
395                 return true;
396         }
397         return false;
398 }
399
400 std::string ConfigTag::getString(const std::string& key, const std::string& def)
401 {
402         std::string res = def;
403         readString(key, res);
404         return res;
405 }
406
407 long ConfigTag::getInt(const std::string &key, long def)
408 {
409         std::string result;
410         if(!readString(key, result))
411                 return def;
412
413         const char* res_cstr = result.c_str();
414         char* res_tail = NULL;
415         long res = strtol(res_cstr, &res_tail, 0);
416         if (res_tail == res_cstr)
417                 return def;
418         switch (toupper(*res_tail))
419         {
420                 case 'K':
421                         res= res* 1024;
422                         break;
423                 case 'M':
424                         res= res* 1024 * 1024;
425                         break;
426                 case 'G':
427                         res= res* 1024 * 1024 * 1024;
428                         break;
429         }
430         return res;
431 }
432
433 double ConfigTag::getFloat(const std::string &key, double def)
434 {
435         std::string result;
436         if (!readString(key, result))
437                 return def;
438         return strtod(result.c_str(), NULL);
439 }
440
441 bool ConfigTag::getBool(const std::string &key, bool def)
442 {
443         std::string result;
444         if(!readString(key, result))
445                 return def;
446
447         if (result == "yes" || result == "true" || result == "1" || result == "on")
448                 return true;
449         if (result == "no" || result == "false" || result == "0" || result == "off")
450                 return false;
451
452         ServerInstance->Logs->Log("CONFIG",DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
453                 " is not valid, ignoring");
454         return def;
455 }
456
457 std::string ConfigTag::getTagLocation()
458 {
459         return src_name + ":" + ConvToStr(src_line);
460 }
461
462 ConfigTag* ConfigTag::create(const std::string& Tag, const std::string& file, int line, std::vector<KeyVal>*&items)
463 {
464         ConfigTag* rv = new ConfigTag(Tag, file, line);
465         items = &rv->items;
466         return rv;
467 }
468
469 ConfigTag::ConfigTag(const std::string& Tag, const std::string& file, int line)
470         : tag(Tag), src_name(file), src_line(line)
471 {
472 }
473
474 std::string OperInfo::getConfig(const std::string& key)
475 {
476         std::string rv;
477         if (type_block)
478                 type_block->readString(key, rv);
479         if (oper_block)
480                 oper_block->readString(key, rv);
481         return rv;
482 }