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