]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/configreader.cpp
9a315fe0b4789eb396a061c278a1649c34f33db8
[user/henk/code/inspircd.git] / src / configreader.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2009 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 /* $Core */
15 /* $CopyInstall: conf/inspircd.quotes.example $(CONPATH) */
16 /* $CopyInstall: conf/inspircd.rules.example $(CONPATH) */
17 /* $CopyInstall: conf/inspircd.motd.example $(CONPATH) */
18 /* $CopyInstall: conf/inspircd.helpop-full.example $(CONPATH) */
19 /* $CopyInstall: conf/inspircd.helpop.example $(CONPATH) */
20 /* $CopyInstall: conf/inspircd.censor.example $(CONPATH) */
21 /* $CopyInstall: conf/inspircd.filter.example $(CONPATH) */
22 /* $CopyInstall: conf/inspircd.conf.example $(CONPATH) */
23 /* $CopyInstall: conf/modules.conf.example $(CONPATH) */
24 /* $CopyInstall: conf/opers.conf.example $(CONPATH) */
25 /* $CopyInstall: conf/links.conf.example $(CONPATH) */
26 /* $CopyInstall: tools/gdbargs $(BASE)/.gdbargs */
27
28 #include "inspircd.h"
29 #include <fstream>
30 #include "xline.h"
31 #include "exitcodes.h"
32 #include "commands/cmd_whowas.h"
33 #include "modes/cmode_h.h"
34
35 struct fpos
36 {
37         std::string filename;
38         int line;
39         int col;
40         fpos(const std::string& name, int l = 1, int c = 1) : filename(name), line(l), col(c) {}
41         std::string str()
42         {
43                 return filename + ":" + ConvToStr(line) + ":" + ConvToStr(col);
44         }
45 };
46
47 enum ParseFlags
48 {
49         FLAG_NO_EXEC = 1,
50         FLAG_NO_INC = 2
51 };
52
53 struct ParseStack
54 {
55         std::vector<std::string> reading;
56         std::map<std::string, std::string> vars;
57         ConfigDataHash& output;
58         std::stringstream& errstr;
59
60         ParseStack(ServerConfig* conf)
61                 : output(conf->config_data), errstr(conf->errstr)
62         {
63                 vars["amp"] = "&";
64                 vars["quot"] = "\"";
65                 vars["newline"] = vars["nl"] = "\n";
66         }
67         bool ParseFile(const std::string& name, int flags);
68         bool ParseExec(const std::string& name, int flags);
69         void DoInclude(ConfigTag* includeTag, int flags);
70 };
71
72 struct Parser
73 {
74         ParseStack& stack;
75         const int flags;
76         FILE* const file;
77         fpos current;
78         fpos last_tag;
79         reference<ConfigTag> tag;
80         int ungot;
81
82         Parser(ParseStack& me, int myflags, FILE* conf, const std::string& name)
83                 : stack(me), flags(myflags), file(conf), current(name), last_tag(name), ungot(-1)
84         { }
85
86         int next(bool eof_ok = false)
87         {
88                 if (ungot != -1)
89                 {
90                         int ch = ungot;
91                         ungot = -1;
92                         return ch;
93                 }
94                 int ch = fgetc(file);
95                 if (ch == EOF && !eof_ok)
96                 {
97                         throw CoreException("Unexpected end-of-file");
98                 }
99                 else if (ch == '\n')
100                 {
101                         current.line++;
102                         current.col = 0;
103                 }
104                 else
105                 {
106                         current.col++;
107                 }
108                 return ch;
109         }
110
111         void unget(int ch)
112         {
113                 if (ungot != -1)
114                         throw CoreException("INTERNAL ERROR: cannot unget twice");
115                 ungot = ch;
116         }
117
118         void comment()
119         {
120                 while (1)
121                 {
122                         int ch = next();
123                         if (ch == '\n')
124                                 return;
125                 }
126         }
127
128         void nextword(std::string& rv)
129         {
130                 int ch = next();
131                 while (isspace(ch))
132                         ch = next();
133                 while (isalnum(ch) || ch == '_')
134                 {
135                         rv.push_back(ch);
136                         ch = next();
137                 }
138                 unget(ch);
139         }
140
141         bool kv()
142         {
143                 std::string key;
144                 nextword(key);
145                 int ch = next();
146                 if (ch == '>' && key.empty())
147                 {
148                         return false;
149                 }
150                 else if (ch == '#' && key.empty())
151                 {
152                         comment();
153                         return true;
154                 }
155                 else if (ch != '=')
156                 {
157                         throw CoreException("Invalid character " + std::string(1, ch) + " in key (" + key + ")");
158                 }
159
160                 std::string value;
161                 ch = next();
162                 if (ch != '"')
163                 {
164                         throw CoreException("Invalid character in value of <" + tag->tag + ":" + key + ">");
165                 }
166                 while (1)
167                 {
168                         ch = next();
169                         if (ch == '&')
170                         {
171                                 std::string varname;
172                                 while (1)
173                                 {
174                                         ch = next();
175                                         if (isalnum(ch))
176                                                 varname.push_back(ch);
177                                         else if (ch == ';')
178                                                 break;
179                                         else
180                                         {
181                                                 stack.errstr << "Invalid XML entity name in value of <" + tag->tag + ":" + key + ">\n"
182                                                         << "To include an ampersand or quote, use &amp; or &quot;\n";
183                                                 throw CoreException("Parse error");
184                                         }
185                                 }
186                                 std::map<std::string, std::string>::iterator var = stack.vars.find(varname);
187                                 if (var == stack.vars.end())
188                                         throw CoreException("Undefined XML entity reference '&" + varname + ";'");
189                                 value.append(var->second);
190                         }
191                         else if (ch == '"')
192                                 break;
193                         value.push_back(ch);
194                 }
195                 tag->items.push_back(KeyVal(key, value));
196                 return true;
197         }
198
199         void dotag()
200         {
201                 last_tag = current;
202                 std::string name;
203                 nextword(name);
204
205                 int spc = next();
206                 if (spc == '>')
207                         unget(spc);
208                 else if (!isspace(spc))
209                         throw CoreException("Invalid character in tag name");
210
211                 if (name.empty())
212                         throw CoreException("Empty tag name");
213
214                 tag = new ConfigTag(name, current.filename, current.line);
215
216                 while (kv());
217
218                 if (name == "include")
219                 {
220                         stack.DoInclude(tag, flags);
221                 }
222                 else if (name == "define")
223                 {
224                         std::string varname = tag->getString("name");
225                         std::string value = tag->getString("value");
226                         if (varname.empty())
227                                 throw CoreException("Variable definition must include variable name");
228                         stack.vars[varname] = value;
229                 }
230                 else
231                 {
232                         stack.output.insert(std::make_pair(name, tag));
233                 }
234                 // this is not a leak; reference<> takes care of the delete
235                 tag = NULL;
236         }
237
238         bool outer_parse()
239         {
240                 try
241                 {
242                         while (1)
243                         {
244                                 int ch = next(true);
245                                 switch (ch)
246                                 {
247                                         case EOF:
248                                                 // this is the one place where an EOF is not an error
249                                                 return true;
250                                         case '#':
251                                                 comment();
252                                                 break;
253                                         case '<':
254                                                 dotag();
255                                                 break;
256                                         case ' ':
257                                         case '\r':
258                                         case '\t':
259                                         case '\n':
260                                                 break;
261                                         case 0xFE:
262                                         case 0xFF:
263                                                 stack.errstr << "Do not save your files as UTF-16; use ASCII!\n";
264                                         default:
265                                                 throw CoreException("Syntax error - start of tag expected");
266                                 }
267                         }
268                 }
269                 catch (CoreException& err)
270                 {
271                         stack.errstr << err.GetReason() << " at " << current.str();
272                         if (tag)
273                                 stack.errstr << " (inside tag " << tag->tag << " at line " << tag->src_line << ")\n";
274                         else
275                                 stack.errstr << " (last tag was on line " << last_tag.line << ")\n";
276                 }
277                 return false;
278         }
279 };
280
281 void ParseStack::DoInclude(ConfigTag* tag, int flags)
282 {
283         if (flags & FLAG_NO_INC)
284                 throw CoreException("Invalid <include> tag in file included with noinclude=\"yes\"");
285         std::string name;
286         if (tag->readString("file", name))
287         {
288                 if (tag->getBool("noinclude", false))
289                         flags |= FLAG_NO_INC;
290                 if (tag->getBool("noexec", false))
291                         flags |= FLAG_NO_EXEC;
292                 if (!ParseFile(name, flags))
293                         throw CoreException("Included");
294         }
295         else if (tag->readString("executable", name))
296         {
297                 if (flags & FLAG_NO_EXEC)
298                         throw CoreException("Invalid <include:executable> tag in file included with noexec=\"yes\"");
299                 if (tag->getBool("noinclude", false))
300                         flags |= FLAG_NO_INC;
301                 if (tag->getBool("noexec", true))
302                         flags |= FLAG_NO_EXEC;
303                 if (!ParseExec(name, flags))
304                         throw CoreException("Included");
305         }
306 }
307
308 /** RAII wrapper on FILE* to close files on exceptions */
309 struct FileWrapper
310 {
311         FILE* const f;
312         FileWrapper(FILE* file) : f(file) {}
313         operator bool() { return f; }
314         operator FILE*() { return f; }
315         ~FileWrapper()
316         {
317                 if (f)
318                         fclose(f);
319         }
320 };
321
322 bool ParseStack::ParseFile(const std::string& name, int flags)
323 {
324         ServerInstance->Logs->Log("CONFIG", DEBUG, "Reading file %s", name.c_str());
325         for (unsigned int t = 0; t < reading.size(); t++)
326         {
327                 if (std::string(name) == reading[t])
328                 {
329                         throw CoreException("File " + name + " is included recursively (looped inclusion)");
330                 }
331         }
332
333         /* It's not already included, add it to the list of files we've loaded */
334
335         FileWrapper file(fopen(name.c_str(), "r"));
336         if (!file)
337                 throw CoreException("Could not read \"" + name + "\" for include");
338
339         reading.push_back(name);
340         Parser p(*this, flags, file, name);
341         bool ok = p.outer_parse();
342         reading.pop_back();
343         return ok;
344 }
345
346 bool ParseStack::ParseExec(const std::string& name, int flags)
347 {
348         ServerInstance->Logs->Log("CONFIG", DEBUG, "Reading executable %s", name.c_str());
349         for (unsigned int t = 0; t < reading.size(); t++)
350         {
351                 if (std::string(name) == reading[t])
352                 {
353                         throw CoreException("Executable " + name + " is included recursively (looped inclusion)");
354                 }
355         }
356
357         /* It's not already included, add it to the list of files we've loaded */
358
359         FileWrapper file(popen(name.c_str(), "r"));
360         if (!file)
361                 throw CoreException("Could not open executable \"" + name + "\" for include");
362
363         reading.push_back(name);
364         Parser p(*this, flags, file, name);
365         bool ok = p.outer_parse();
366         reading.pop_back();
367         return ok;
368 }
369
370 /////////////////////////////////////////////////////////////////////////////
371
372 ServerConfig::ServerConfig()
373 {
374         WhoWasGroupSize = WhoWasMaxGroups = WhoWasMaxKeep = 0;
375         NoUserDns = OperSpyWhois = HideBans = HideSplits = UndernetMsgPrefix = false;
376         CycleHosts = AllowHalfop = InvBypassModes = true;
377         dns_timeout = DieDelay = 5;
378         MaxTargets = 20;
379         NetBufferSize = 10240;
380         SoftLimit = ServerInstance->SE->GetMaxFds();
381         MaxConn = SOMAXCONN;
382         MaxWhoResults = 0;
383         MaxChans = 20;
384         OperMaxChans = 30;
385         c_ipv4_range = 32;
386         c_ipv6_range = 128;
387 }
388
389 void ServerConfig::Update005()
390 {
391         std::stringstream out(data005);
392         std::string token;
393         std::string line5;
394         int token_counter = 0;
395         isupport.clear();
396         while (out >> token)
397         {
398                 line5 = line5 + token + " ";
399                 token_counter++;
400                 if (token_counter >= 13)
401                 {
402                         char buf[MAXBUF];
403                         snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
404                         isupport.push_back(buf);
405                         line5.clear();
406                         token_counter = 0;
407                 }
408         }
409         if (!line5.empty())
410         {
411                 char buf[MAXBUF];
412                 snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
413                 isupport.push_back(buf);
414         }
415 }
416
417 void ServerConfig::Send005(User* user)
418 {
419         for (std::vector<std::string>::iterator line = ServerInstance->Config->isupport.begin(); line != ServerInstance->Config->isupport.end(); line++)
420                 user->WriteNumeric(RPL_ISUPPORT, "%s %s", user->nick.c_str(), line->c_str());
421 }
422
423 static void ReqRead(ServerConfig* src, const std::string& tag, const std::string& key, std::string& dest)
424 {
425         ConfigTag* t = src->ConfValue(tag);
426         if (!t || !t->readString(key, dest))
427                 throw CoreException("You must specify a value for <" + tag + ":" + key + ">");
428 }
429
430 template<typename T, typename V>
431 static void range(T& value, V min, V max, V def, const char* msg)
432 {
433         if (value >= (T)min && value <= (T)max)
434                 return;
435         ServerInstance->Logs->Log("CONFIG", DEFAULT,
436                 "WARNING: %s value of %ld is not between %ld and %ld; set to %ld.",
437                 msg, (long)value, (long)min, (long)max, (long)def);
438         value = def;
439 }
440
441
442 /* NOTE: Before anyone asks why we're not using inet_pton for this, it is because inet_pton and friends do not return so much detail,
443  * even in strerror(errno). They just return 'yes' or 'no' to an address without such detail as to whats WRONG with the address.
444  * Because ircd users arent as technical as they used to be (;)) we are going to give more of a useful error message.
445  */
446 static void ValidIP(const std::string& ip, const std::string& key)
447 {
448         const char* p = ip.c_str();
449         int num_dots = 0;
450         int num_seps = 0;
451         int not_numbers = false;
452         int not_hex = false;
453
454         if (*p)
455         {
456                 if (*p == '.')
457                         throw CoreException("The value of "+key+" is not an IP address");
458
459                 for (const char* ptr = p; *ptr; ++ptr)
460                 {
461                         if (*ptr != ':' && *ptr != '.')
462                         {
463                                 if (*ptr < '0' || *ptr > '9')
464                                         not_numbers = true;
465                                 if ((*ptr < '0' || *ptr > '9') && (toupper(*ptr) < 'A' || toupper(*ptr) > 'F'))
466                                         not_hex = true;
467                         }
468                         switch (*ptr)
469                         {
470                                 case ' ':
471                                         throw CoreException("The value of "+key+" is not an IP address");
472                                 case '.':
473                                         num_dots++;
474                                 break;
475                                 case ':':
476                                         num_seps++;
477                                 break;
478                         }
479                 }
480
481                 if (num_dots > 3)
482                         throw CoreException("The value of "+key+" is an IPv4 address with too many fields!");
483
484                 if (num_seps > 8)
485                         throw CoreException("The value of "+key+" is an IPv6 address with too many fields!");
486
487                 if (num_seps == 0 && num_dots < 3)
488                         throw CoreException("The value of "+key+" looks to be a malformed IPv4 address");
489
490                 if (num_seps == 0 && num_dots == 3 && not_numbers)
491                         throw CoreException("The value of "+key+" contains non-numeric characters in an IPv4 address");
492
493                 if (num_seps != 0 && not_hex)
494                         throw CoreException("The value of "+key+" contains non-hexdecimal characters in an IPv6 address");
495
496                 if (num_seps != 0 && num_dots != 3 && num_dots != 0)
497                         throw CoreException("The value of "+key+" is a malformed IPv6 4in6 address");
498         }
499 }
500
501 static void ValidHost(const std::string& p, const std::string& msg)
502 {
503         int num_dots = 0;
504         if (p.empty() || p[0] == '.')
505                 throw CoreException("The value of "+msg+" is not a valid hostname");
506         for (unsigned int i=0;i < p.length();i++)
507         {
508                 switch (p[i])
509                 {
510                         case ' ':
511                                 throw CoreException("The value of "+msg+" is not a valid hostname");
512                         case '.':
513                                 num_dots++;
514                         break;
515                 }
516         }
517         if (num_dots == 0)
518                 throw CoreException("The value of "+msg+" is not a valid hostname");
519 }
520
521 // Specialized validators
522
523 bool ServerConfig::ApplyDisabledCommands(const std::string& data)
524 {
525         std::stringstream dcmds(data);
526         std::string thiscmd;
527
528         /* Enable everything first */
529         for (Commandtable::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
530                 x->second->Disable(false);
531
532         /* Now disable all the ones which the user wants disabled */
533         while (dcmds >> thiscmd)
534         {
535                 Commandtable::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
536                 if (cm != ServerInstance->Parser->cmdlist.end())
537                 {
538                         cm->second->Disable(true);
539                 }
540         }
541         return true;
542 }
543
544 #ifdef WINDOWS
545 // Note: the windows validator is in win32wrapper.cpp
546 void FindDNS(std::string& server);
547 #else
548 static void FindDNS(std::string& server)
549 {
550         if (!server.empty())
551                 return;
552
553         // attempt to look up their nameserver from /etc/resolv.conf
554         ServerInstance->Logs->Log("CONFIG",DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
555
556         std::ifstream resolv("/etc/resolv.conf");
557
558         while (resolv >> server)
559         {
560                 if (server == "nameserver")
561                 {
562                         resolv >> server;
563                         ServerInstance->Logs->Log("CONFIG",DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",server.c_str());
564                         return;
565                 }
566         }
567
568         ServerInstance->Logs->Log("CONFIG",DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
569         server = "127.0.0.1";
570 }
571 #endif
572
573 static void ReadXLine(ServerConfig* conf, const std::string& tag, const std::string& key, XLineFactory* make)
574 {
575         ConfigTagList tags = conf->ConfTags(tag);
576         for(ConfigIter i = tags.first; i != tags.second; ++i)
577         {
578                 ConfigTag* ctag = i->second;
579                 std::string mask;
580                 if (!ctag->readString(key, mask))
581                         throw CoreException("<"+tag+":"+key+"> missing at " + ctag->getTagLocation());
582                 std::string reason = ctag->getString("reason", "<Config>");
583                 XLine* xl = make->Generate(ServerInstance->Time(), 0, "<Config>", reason, mask);
584                 if (!ServerInstance->XLines->AddLine(xl, NULL))
585                         delete xl;
586         }
587 }
588
589 typedef std::map<std::string, ConfigTag*> LocalIndex;
590 void ServerConfig::CrossCheckOperClassType()
591 {
592         LocalIndex operclass;
593         ConfigTagList tags = ConfTags("class");
594         for(ConfigIter i = tags.first; i != tags.second; ++i)
595         {
596                 ConfigTag* tag = i->second;
597                 std::string name = tag->getString("name");
598                 if (name.empty())
599                         throw CoreException("<class:name> missing from tag at " + tag->getTagLocation());
600                 operclass[name] = tag;
601         }
602         tags = ConfTags("type");
603         for(ConfigIter i = tags.first; i != tags.second; ++i)
604         {
605                 ConfigTag* tag = i->second;
606                 std::string name = tag->getString("name");
607                 if (name.empty())
608                         throw CoreException("<type:name> is missing from tag at " + tag->getTagLocation());
609
610                 if (!ServerInstance->IsNick(name.c_str(), Limits.NickMax))
611                         throw CoreException("<type:name> is invalid (value '" + name + "')");
612
613                 OperInfo* ifo = new OperInfo;
614                 oper_blocks[" " + name] = ifo;
615                 ifo->type_block = tag;
616
617                 std::string classname;
618                 irc::spacesepstream str(tag->getString("classes"));
619                 while (str.GetToken(classname))
620                 {
621                         LocalIndex::iterator cls = operclass.find(classname);
622                         if (cls == operclass.end())
623                                 throw CoreException("Oper type " + name + " has missing class " + classname);
624                         ifo->class_blocks.push_back(cls->second);
625                 }
626         }
627
628         tags = ConfTags("oper");
629         for(ConfigIter i = tags.first; i != tags.second; ++i)
630         {
631                 ConfigTag* tag = i->second;
632
633                 std::string name = tag->getString("name");
634                 if (name.empty())
635                         throw CoreException("<oper:name> missing from tag at " + tag->getTagLocation());
636
637                 std::string type = tag->getString("type");
638                 OperIndex::iterator tblk = oper_blocks.find(" " + type);
639                 if (tblk == oper_blocks.end())
640                         throw CoreException("Oper block " + name + " has missing type " + type);
641                 if (oper_blocks.find(name) != oper_blocks.end())
642                         throw CoreException("Duplicate oper block with name " + name);
643
644                 OperInfo* ifo = new OperInfo;
645                 ifo->name = type;
646                 ifo->oper_block = tag;
647                 ifo->type_block = tblk->second->type_block;
648                 ifo->class_blocks.assign(tblk->second->class_blocks.begin(), tblk->second->class_blocks.end());
649                 oper_blocks[name] = ifo;
650         }
651 }
652
653 void ServerConfig::CrossCheckConnectBlocks(ServerConfig* current)
654 {
655         typedef std::map<std::string, ConnectClass*> ClassMap;
656         ClassMap oldBlocksByMask;
657         if (current)
658         {
659                 for(ClassVector::iterator i = current->Classes.begin(); i != current->Classes.end(); ++i)
660                 {
661                         ConnectClass* c = *i;
662                         std::string typeMask = (c->type == CC_ALLOW) ? "a" : "d";
663                         typeMask += c->host;
664                         oldBlocksByMask[typeMask] = c;
665                 }
666         }
667
668         ClassMap newBlocksByMask;
669         Classes.resize(config_data.count("connect"));
670         std::map<std::string, int> names;
671
672         bool try_again = true;
673         for(int tries=0; try_again; tries++)
674         {
675                 try_again = false;
676                 ConfigTagList tags = ConfTags("connect");
677                 int i=0;
678                 for(ConfigIter it = tags.first; it != tags.second; ++it, ++i)
679                 {
680                         ConfigTag* tag = it->second;
681                         if (Classes[i])
682                                 continue;
683
684                         ConnectClass* parent = NULL;
685                         std::string parentName = tag->getString("parent");
686                         if (!parentName.empty())
687                         {
688                                 std::map<std::string,int>::iterator parentIter = names.find(parentName);
689                                 if (parentIter == names.end())
690                                 {
691                                         try_again = true;
692                                         // couldn't find parent this time. If it's the last time, we'll never find it.
693                                         if (tries == 50)
694                                                 throw CoreException("Could not find parent connect class \"" + parentName + "\" for connect block " + ConvToStr(i));
695                                         continue;
696                                 }
697                                 parent = Classes[parentIter->second];
698                         }
699
700                         std::string name = tag->getString("name");
701                         if (!name.empty())
702                         {
703                                 if (names.find(name) != names.end())
704                                         throw CoreException("Two connect classes with name \"" + name + "\" defined!");
705                                 names[name] = i;
706                         }
707
708                         std::string mask, typeMask;
709                         char type;
710
711                         if (tag->readString("allow", mask, false))
712                         {
713                                 type = CC_ALLOW;
714                                 typeMask = 'a' + mask;
715                         }
716                         else if (tag->readString("deny", mask, false))
717                         {
718                                 type = CC_DENY;
719                                 typeMask = 'd' + mask;
720                         }
721                         else
722                         {
723                                 throw CoreException("Connect class must have an allow or deny mask at " + tag->getTagLocation());
724                         }
725                         ClassMap::iterator dupMask = newBlocksByMask.find(typeMask);
726                         if (dupMask != newBlocksByMask.end())
727                                 throw CoreException("Two connect classes cannot have the same mask (" + mask + ")");
728
729                         ConnectClass* me = parent ? 
730                                 new ConnectClass(tag, type, mask, *parent) :
731                                 new ConnectClass(tag, type, mask);
732
733                         if (!name.empty())
734                                 me->name = name;
735
736                         tag->readString("password", me->pass);
737                         tag->readString("hash", me->hash);
738                         me->registration_timeout = tag->getInt("timeout", me->registration_timeout);
739                         me->pingtime = tag->getInt("pingfreq", me->pingtime);
740                         std::string sendq;
741                         if (tag->readString("sendq", sendq))
742                         {
743                                 // attempt to guess a good hard/soft sendq from a single value
744                                 long value = atol(sendq.c_str());
745                                 if (value > 16384)
746                                         me->softsendqmax = value / 16;
747                                 else
748                                         me->softsendqmax = value;
749                                 me->hardsendqmax = value * 8;
750                         }
751                         me->softsendqmax = tag->getInt("softsendq", me->softsendqmax);
752                         me->hardsendqmax = tag->getInt("hardsendq", me->hardsendqmax);
753                         me->recvqmax = tag->getInt("recvq", me->recvqmax);
754                         me->penaltythreshold = tag->getInt("threshold", me->penaltythreshold);
755                         me->maxlocal = tag->getInt("localmax", me->maxlocal);
756                         me->maxglobal = tag->getInt("globalmax", me->maxglobal);
757                         me->port = tag->getInt("port", me->port);
758                         me->maxchans = tag->getInt("maxchans", me->maxchans);
759                         me->limit = tag->getInt("limit", me->limit);
760
761                         ClassMap::iterator oldMask = oldBlocksByMask.find(typeMask);
762                         if (oldMask != oldBlocksByMask.end())
763                         {
764                                 ConnectClass* old = oldMask->second;
765                                 oldBlocksByMask.erase(oldMask);
766                                 old->Update(me);
767                                 delete me;
768                                 me = old;
769                         }
770                         newBlocksByMask[typeMask] = me;
771                         Classes[i] = me;
772                 }
773         }
774 }
775
776 /** Represents a deprecated configuration tag.
777  */
778 struct Deprecated
779 {
780         /** Tag name
781          */
782         const char* tag;
783         /** Tag value
784          */
785         const char* value;
786         /** Reason for deprecation
787          */
788         const char* reason;
789 };
790
791 static const Deprecated ChangedConfig[] = {
792         {"options", "hidelinks",                "has been moved to <security:hidelinks> as of 1.2a3"},
793         {"options", "hidewhois",                "has been moved to <security:hidewhois> as of 1.2a3"},
794         {"options", "userstats",                "has been moved to <security:userstats> as of 1.2a3"},
795         {"options", "customversion",    "has been moved to <security:customversion> as of 1.2a3"},
796         {"options", "hidesplits",               "has been moved to <security:hidesplits> as of 1.2a3"},
797         {"options", "hidebans",         "has been moved to <security:hidebans> as of 1.2a3"},
798         {"options", "hidekills",                "has been moved to <security:hidekills> as of 1.2a3"},
799         {"options", "operspywhois",             "has been moved to <security:operspywhois> as of 1.2a3"},
800         {"options", "announceinvites",  "has been moved to <security:announceinvites> as of 1.2a3"},
801         {"options", "hidemodes",                "has been moved to <security:hidemodes> as of 1.2a3"},
802         {"options", "maxtargets",               "has been moved to <security:maxtargets> as of 1.2a3"},
803         {"options",     "nouserdns",            "has been moved to <performance:nouserdns> as of 1.2a3"},
804         {"options",     "maxwho",               "has been moved to <performance:maxwho> as of 1.2a3"},
805         {"options",     "softlimit",            "has been moved to <performance:softlimit> as of 1.2a3"},
806         {"options", "somaxconn",                "has been moved to <performance:somaxconn> as of 1.2a3"},
807         {"options", "netbuffersize",    "has been moved to <performance:netbuffersize> as of 1.2a3"},
808         {"options", "maxwho",           "has been moved to <performance:maxwho> as of 1.2a3"},
809         {"options",     "loglevel",             "1.2 does not use the loglevel value. Please define <log> tags instead."},
810         {"die",     "value",            "has always been deprecated"},
811 };
812
813 void ServerConfig::Fill()
814 {
815         ReqRead(this, "server", "name", ServerName);
816         ReqRead(this, "power", "diepass", diepass);
817         ReqRead(this, "power", "restartpass", restartpass);
818
819         ConfigTag* options = ConfValue("options");
820         ConfigTag* security = ConfValue("security");
821         powerhash = ConfValue("power")->getString("hash");
822         DieDelay = ConfValue("power")->getInt("pause");
823         PrefixQuit = options->getString("prefixquit");
824         SuffixQuit = options->getString("suffixquit");
825         FixedQuit = options->getString("fixedquit");
826         PrefixPart = options->getString("prefixpart");
827         SuffixPart = options->getString("suffixpart");
828         FixedPart = options->getString("fixedpart");
829         SoftLimit = ConfValue("performance")->getInt("softlimit", ServerInstance->SE->GetMaxFds());
830         MaxConn = ConfValue("performance")->getInt("somaxconn", SOMAXCONN);
831         MoronBanner = options->getString("moronbanner", "You're banned!");
832         ServerDesc = ConfValue("server")->getString("description", "Configure Me");
833         Network = ConfValue("server")->getString("network", "Network");
834         sid = ConfValue("server")->getString("id", "");
835         AdminName = ConfValue("admin")->getString("name", "");
836         AdminEmail = ConfValue("admin")->getString("email", "null@example.com");
837         AdminNick = ConfValue("admin")->getString("nick", "admin");
838         ModPath = ConfValue("path")->getString("moduledir", MOD_PATH);
839         NetBufferSize = ConfValue("performance")->getInt("netbuffersize", 10240);
840         MaxWhoResults = ConfValue("performance")->getInt("maxwho", 1024);
841         dns_timeout = ConfValue("dns")->getInt("timeout", 5);
842         DisabledCommands = ConfValue("disabled")->getString("commands", "");
843         DisabledDontExist = ConfValue("disabled")->getBool("fakenonexistant");
844         UserStats = security->getString("userstats");
845         CustomVersion = security->getString("customversion");
846         HideSplits = security->getBool("hidesplits");
847         HideBans = security->getBool("hidebans");
848         HideWhoisServer = security->getString("hidewhois");
849         HideKillsServer = security->getString("hidekills");
850         OperSpyWhois = security->getBool("operspywhois");
851         RestrictBannedUsers = security->getBool("restrictbannedusers", true);
852         GenericOper = security->getBool("genericoper");
853         NoUserDns = ConfValue("performance")->getBool("nouserdns");
854         SyntaxHints = options->getBool("syntaxhints");
855         CycleHosts = options->getBool("cyclehosts");
856         UndernetMsgPrefix = options->getBool("ircumsgprefix");
857         FullHostInTopic = options->getBool("hostintopic");
858         MaxTargets = security->getInt("maxtargets", 20);
859         DefaultModes = options->getString("defaultmodes", "nt");
860         PID = ConfValue("pid")->getString("file");
861         WhoWasGroupSize = ConfValue("whowas")->getInt("groupsize");
862         WhoWasMaxGroups = ConfValue("whowas")->getInt("maxgroups");
863         WhoWasMaxKeep = ServerInstance->Duration(ConfValue("whowas")->getString("maxkeep"));
864         DieValue = ConfValue("die")->getString("value");
865         MaxChans = ConfValue("channels")->getInt("users");
866         OperMaxChans = ConfValue("channels")->getInt("opers");
867         c_ipv4_range = ConfValue("cidr")->getInt("ipv4clone");
868         c_ipv6_range = ConfValue("cidr")->getInt("ipv6clone");
869         Limits.NickMax = ConfValue("limits")->getInt("maxnick", 32);
870         Limits.ChanMax = ConfValue("limits")->getInt("maxchan", 64);
871         Limits.MaxModes = ConfValue("limits")->getInt("maxmodes", 20);
872         Limits.IdentMax = ConfValue("limits")->getInt("maxident", 11);
873         Limits.MaxQuit = ConfValue("limits")->getInt("maxquit", 255);
874         Limits.MaxTopic = ConfValue("limits")->getInt("maxtopic", 307);
875         Limits.MaxKick = ConfValue("limits")->getInt("maxkick", 255);
876         Limits.MaxGecos = ConfValue("limits")->getInt("maxgecos", 128);
877         Limits.MaxAway = ConfValue("limits")->getInt("maxaway", 200);
878         InvBypassModes = options->getBool("invitebypassmodes", true);
879
880         range(SoftLimit, 10, ServerInstance->SE->GetMaxFds(), ServerInstance->SE->GetMaxFds(), "<performance:softlimit>");
881         range(MaxConn, 0, SOMAXCONN, SOMAXCONN, "<performance:somaxconn>");
882         range(MaxTargets, 1, 31, 20, "<security:maxtargets>");
883         range(NetBufferSize, 1024, 65534, 10240, "<performance:netbuffersize>");
884         range(MaxWhoResults, 1, 65535, 1024, "<performace:maxwho>");
885         range(WhoWasGroupSize, 0, 10000, 10, "<whowas:groupsize>");
886         range(WhoWasMaxGroups, 0, 1000000, 10240, "<whowas:maxgroups>");
887         range(WhoWasMaxKeep, 3600, INT_MAX, 3600, "<whowas:maxkeep>");
888
889         ValidIP(DNSServer, "<dns:server>");
890         ValidHost(ServerName, "<server:name>");
891         if (!sid.empty() && !ServerInstance->IsSID(sid))
892                 throw CoreException(sid + " is not a valid server ID. A server ID must be 3 characters long, with the first character a digit and the next two characters a digit or letter.");
893
894         ConfigTagList tags = ConfTags("uline");
895         for(ConfigIter i = tags.first; i != tags.second; ++i)
896         {
897                 ConfigTag* tag = i->second;
898                 std::string server;
899                 if (!tag->readString("server", server))
900                         throw CoreException("<uline> tag missing server at " + tag->getTagLocation());
901                 ulines[assign(server)] = tag->getBool("silent");
902         }
903
904         tags = ConfTags("banlist");
905         for(ConfigIter i = tags.first; i != tags.second; ++i)
906         {
907                 ConfigTag* tag = i->second;
908                 std::string chan;
909                 if (!tag->readString("chan", chan))
910                         throw CoreException("<banlist> tag missing chan at " + tag->getTagLocation());
911                 maxbans[chan] = tag->getInt("limit");
912         }
913
914         ReadXLine(this, "badip", "ipmask", ServerInstance->XLines->GetFactory("Z"));
915         ReadXLine(this, "badnick", "nick", ServerInstance->XLines->GetFactory("Q"));
916         ReadXLine(this, "badhost", "host", ServerInstance->XLines->GetFactory("K"));
917         ReadXLine(this, "exception", "host", ServerInstance->XLines->GetFactory("E"));
918
919         memset(DisabledUModes, 0, sizeof(DisabledUModes));
920         for (const unsigned char* p = (const unsigned char*)ConfValue("disabled")->getString("usermodes").c_str(); *p; ++p)
921         {
922                 if (*p < 'A' || *p > ('A' + 64)) throw CoreException(std::string("Invalid usermode ")+(char)*p+" was found.");
923                 DisabledUModes[*p - 'A'] = 1;
924         }
925
926         memset(DisabledCModes, 0, sizeof(DisabledCModes));
927         for (const unsigned char* p = (const unsigned char*)ConfValue("disabled")->getString("chanmodes").c_str(); *p; ++p)
928         {
929                 if (*p < 'A' || *p > ('A' + 64)) throw CoreException(std::string("Invalid chanmode ")+(char)*p+" was found.");
930                 DisabledCModes[*p - 'A'] = 1;
931         }
932
933         memset(HideModeLists, 0, sizeof(HideModeLists));
934         for (const unsigned char* p = (const unsigned char*)ConfValue("security")->getString("hidemodes").c_str(); *p; ++p)
935                 HideModeLists[*p] = true;
936
937         std::string v = security->getString("announceinvites");
938
939         if (v == "ops")
940                 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_OPS;
941         else if (v == "all")
942                 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_ALL;
943         else if (v == "dynamic")
944                 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_DYNAMIC;
945         else
946                 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_NONE;
947
948         Limits.Finalise();
949 }
950
951 /* These tags MUST occur and must ONLY occur once in the config file */
952 static const char* const Once[] = { "server", "admin", "files", "power", "options" };
953
954 // WARNING: it is not safe to use most of the codebase in this function, as it
955 // will run in the config reader thread
956 void ServerConfig::Read()
957 {
958         /* Load and parse the config file, if there are any errors then explode */
959
960         ParseStack stack(this);
961         try
962         {
963                 valid = stack.ParseFile(ServerInstance->ConfigFileName, 0);
964         }
965         catch (CoreException& err)
966         {
967                 valid = false;
968                 errstr << err.GetReason();
969         }
970         if (valid)
971         {
972                 ReadFile(MOTD, ConfValue("files")->getString("motd"));
973                 ReadFile(RULES, ConfValue("files")->getString("rules"));
974                 DNSServer = ConfValue("dns")->getString("server");
975                 FindDNS(DNSServer);
976         }
977 }
978
979 void ServerConfig::Apply(ServerConfig* old, const std::string &useruid)
980 {
981         valid = true;
982
983         /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
984         try
985         {
986                 /* Check we dont have more than one of singular tags, or any of them missing
987                  */
988                 for (int Index = 0; Index * sizeof(*Once) < sizeof(Once); Index++)
989                 {
990                         std::string tag = Once[Index];
991                         ConfigTagList tags = ConfTags(tag);
992                         if (tags.first == tags.second)
993                                 throw CoreException("You have not defined a <"+tag+"> tag, this is required.");
994                         tags.first++;
995                         if (tags.first != tags.second)
996                         {
997                                 errstr << "You have more than one <" << tag << "> tag.\n"
998                                         << "First occurrence at " << ConfValue(tag)->getTagLocation()
999                                         << "; second occurrence at " << tags.first->second->getTagLocation() << std::endl;
1000                         }
1001                 }
1002
1003                 for (int Index = 0; Index * sizeof(Deprecated) < sizeof(ChangedConfig); Index++)
1004                 {
1005                         std::string dummy;
1006                         if (ConfValue(ChangedConfig[Index].tag)->readString(ChangedConfig[Index].value, dummy, true))
1007                                 errstr << "Your configuration contains a deprecated value: <"
1008                                         << ChangedConfig[Index].tag << ":" << ChangedConfig[Index].value << "> - " << ChangedConfig[Index].reason
1009                                         << " (at " << ConfValue(ChangedConfig[Index].tag)->getTagLocation() << ")\n";
1010                 }
1011
1012                 Fill();
1013
1014                 // Handle special items
1015                 CrossCheckOperClassType();
1016                 CrossCheckConnectBlocks(old);
1017         }
1018         catch (CoreException &ce)
1019         {
1020                 errstr << ce.GetReason();
1021         }
1022
1023         // write once here, to try it out and make sure its ok
1024         ServerInstance->WritePID(this->PID);
1025
1026         /*
1027          * These values can only be set on boot. Keep their old values. Do it before we send messages so we actually have a servername.
1028          */
1029         if (old)
1030         {
1031                 this->ServerName = old->ServerName;
1032                 this->sid = old->sid;
1033                 this->cmdline = old->cmdline;
1034
1035                 // Same for ports... they're bound later on first run.
1036                 FailedPortList pl;
1037                 ServerInstance->BindPorts(pl);
1038                 if (pl.size())
1039                 {
1040                         errstr << "Not all your client ports could be bound.\nThe following port(s) failed to bind:\n";
1041
1042                         int j = 1;
1043                         for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
1044                         {
1045                                 char buf[MAXBUF];
1046                                 snprintf(buf, MAXBUF, "%d.   Address: %s   Reason: %s\n", j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
1047                                 errstr << buf;
1048                         }
1049                 }
1050         }
1051
1052         User* user = useruid.empty() ? NULL : ServerInstance->FindNick(useruid);
1053
1054         valid = errstr.str().empty();
1055         if (!valid)
1056                 ServerInstance->Logs->Log("CONFIG",DEFAULT, "There were errors in your configuration file:");
1057
1058         while (errstr.good())
1059         {
1060                 std::string line;
1061                 getline(errstr, line, '\n');
1062                 if (!line.empty())
1063                 {
1064                         if (user)
1065                                 user->WriteServ("NOTICE %s :*** %s", user->nick.c_str(), line.c_str());
1066                         else
1067                                 ServerInstance->SNO->WriteGlobalSno('a', line);
1068                 }
1069
1070                 if (!old)
1071                 {
1072                         // Starting up, so print it out so it's seen. XXX this is a bit of a hack.
1073                         printf("%s\n", line.c_str());
1074                 }
1075         }
1076
1077         errstr.clear();
1078         errstr.str(std::string());
1079
1080         /* No old configuration -> initial boot, nothing more to do here */
1081         if (!old)
1082         {
1083                 if (!valid)
1084                 {
1085                         ServerInstance->Exit(EXIT_STATUS_CONFIG);
1086                 }
1087
1088                 if (ConfValue("options")->getBool("allowhalfop"))
1089                         ServerInstance->Modes->AddMode(new ModeChannelHalfOp);
1090
1091                 return;
1092         }
1093
1094         // If there were errors processing configuration, don't touch modules.
1095         if (!valid)
1096                 return;
1097
1098         ApplyModules(user);
1099
1100         if (user)
1101                 user->WriteServ("NOTICE %s :*** Successfully rehashed server.", user->nick.c_str());
1102         ServerInstance->SNO->WriteGlobalSno('a', "*** Successfully rehashed server.");
1103 }
1104
1105 void ServerConfig::ApplyModules(User* user)
1106 {
1107         bool AllowHalfOp = ConfValue("options")->getBool("allowhalfop");
1108         ModeHandler* mh = ServerInstance->Modes->FindMode('h', MODETYPE_CHANNEL);
1109         if (AllowHalfOp && !mh) {
1110                 ServerInstance->Logs->Log("CONFIG", DEFAULT, "Enabling halfop mode.");
1111                 mh = new ModeChannelHalfOp;
1112                 ServerInstance->Modes->AddMode(mh);
1113         } else if (!AllowHalfOp && mh) {
1114                 ServerInstance->Logs->Log("CONFIG", DEFAULT, "Disabling halfop mode.");
1115                 ServerInstance->Modes->DelMode(mh);
1116                 delete mh;
1117         }
1118
1119         Module* whowas = ServerInstance->Modules->Find("cmd_whowas.so");
1120         if (whowas)
1121                 WhowasRequest(NULL, whowas, WhowasRequest::WHOWAS_PRUNE).Send();
1122
1123         const std::vector<std::string> v = ServerInstance->Modules->GetAllModuleNames(0);
1124         std::vector<std::string> added_modules;
1125         std::set<std::string> removed_modules(v.begin(), v.end());
1126
1127         ConfigTagList tags = ConfTags("module");
1128         for(ConfigIter i = tags.first; i != tags.second; ++i)
1129         {
1130                 ConfigTag* tag = i->second;
1131                 std::string name;
1132                 if (tag->readString("name", name))
1133                 {
1134                         // if this module is already loaded, the erase will succeed, so we need do nothing
1135                         // otherwise, we need to add the module (which will be done later)
1136                         if (removed_modules.erase(name) == 0)
1137                                 added_modules.push_back(name);
1138                 }
1139         }
1140
1141         for (std::set<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
1142         {
1143                 // Don't remove cmd_*.so, just remove m_*.so
1144                 if (removing->c_str()[0] == 'c')
1145                         continue;
1146                 Module* m = ServerInstance->Modules->Find(*removing);
1147                 if (m && ServerInstance->Modules->Unload(m))
1148                 {
1149                         ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH UNLOADED MODULE: %s",removing->c_str());
1150
1151                         if (user)
1152                                 user->WriteNumeric(RPL_UNLOADEDMODULE, "%s %s :Module %s successfully unloaded.",user->nick.c_str(), removing->c_str(), removing->c_str());
1153                         else
1154                                 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully unloaded.", removing->c_str());
1155                 }
1156                 else
1157                 {
1158                         if (user)
1159                                 user->WriteNumeric(ERR_CANTUNLOADMODULE, "%s %s :Failed to unload module %s: %s",user->nick.c_str(), removing->c_str(), removing->c_str(), ServerInstance->Modules->LastError().c_str());
1160                         else
1161                                  ServerInstance->SNO->WriteGlobalSno('a', "Failed to unload module %s: %s", removing->c_str(), ServerInstance->Modules->LastError().c_str());
1162                 }
1163         }
1164
1165         for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
1166         {
1167                 if (ServerInstance->Modules->Load(adding->c_str()))
1168                 {
1169                         ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH LOADED MODULE: %s",adding->c_str());
1170                         if (user)
1171                                 user->WriteNumeric(RPL_LOADEDMODULE, "%s %s :Module %s successfully loaded.",user->nick.c_str(), adding->c_str(), adding->c_str());
1172                         else
1173                                 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully loaded.", adding->c_str());
1174                 }
1175                 else
1176                 {
1177                         if (user)
1178                                 user->WriteNumeric(ERR_CANTLOADMODULE, "%s %s :Failed to load module %s: %s",user->nick.c_str(), adding->c_str(), adding->c_str(), ServerInstance->Modules->LastError().c_str());
1179                         else
1180                                 ServerInstance->SNO->WriteGlobalSno('a', "Failed to load module %s: %s", adding->c_str(), ServerInstance->Modules->LastError().c_str());
1181                 }
1182         }
1183 }
1184
1185 bool ServerConfig::StartsWithWindowsDriveLetter(const std::string &path)
1186 {
1187         return (path.length() > 2 && isalpha(path[0]) && path[1] == ':');
1188 }
1189
1190 ConfigTag* ServerConfig::ConfValue(const std::string &tag)
1191 {
1192         ConfigDataHash::iterator iter = config_data.find(tag);
1193         if (iter == config_data.end())
1194                 return NULL;
1195         return iter->second;
1196 }
1197
1198 ConfigTagList ServerConfig::ConfTags(const std::string& tag)
1199 {
1200         return config_data.equal_range(tag);
1201 }
1202
1203 bool ConfigTag::readString(const std::string& key, std::string& value, bool allow_lf)
1204 {
1205         if (!this)
1206                 return false;
1207         for(std::vector<KeyVal>::iterator j = items.begin(); j != items.end(); ++j)
1208         {
1209                 if(j->first != key)
1210                         continue;
1211                 value = j->second;
1212                 if (!allow_lf && (value.find('\n') != std::string::npos))
1213                 {
1214                         ServerInstance->Logs->Log("CONFIG",DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
1215                                 " contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
1216                         for (std::string::iterator n = value.begin(); n != value.end(); n++)
1217                                 if (*n == '\n')
1218                                         *n = ' ';
1219                 }
1220                 return true;
1221         }
1222         return false;
1223 }
1224
1225 std::string ConfigTag::getString(const std::string& key, const std::string& def)
1226 {
1227         std::string res = def;
1228         readString(key, res);
1229         return res;
1230 }
1231
1232 long ConfigTag::getInt(const std::string &key, long def)
1233 {
1234         std::string result;
1235         if(!readString(key, result))
1236                 return def;
1237
1238         const char* res_cstr = result.c_str();
1239         char* res_tail = NULL;
1240         long res = strtol(res_cstr, &res_tail, 0);
1241         if (res_tail == res_cstr)
1242                 return def;
1243         switch (toupper(*res_tail))
1244         {
1245                 case 'K':
1246                         res= res* 1024;
1247                         break;
1248                 case 'M':
1249                         res= res* 1024 * 1024;
1250                         break;
1251                 case 'G':
1252                         res= res* 1024 * 1024 * 1024;
1253                         break;
1254         }
1255         return res;
1256 }
1257
1258 double ConfigTag::getFloat(const std::string &key, double def)
1259 {
1260         std::string result;
1261         if (!readString(key, result))
1262                 return def;
1263         return strtod(result.c_str(), NULL);
1264 }
1265
1266 bool ConfigTag::getBool(const std::string &key, bool def)
1267 {
1268         std::string result;
1269         if(!readString(key, result))
1270                 return def;
1271
1272         return (result == "yes" || result == "true" || result == "1" || result == "on");
1273 }
1274
1275 std::string ConfigTag::getTagLocation()
1276 {
1277         return src_name + ":" + ConvToStr(src_line);
1278 }
1279
1280 std::string OperInfo::getConfig(const std::string& key)
1281 {
1282         std::string rv;
1283         if (type_block)
1284                 type_block->readString(key, rv);
1285         if (oper_block)
1286                 oper_block->readString(key, rv);
1287         return rv;
1288 }
1289
1290 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1291  */
1292 bool ServerConfig::ReadFile(file_cache &F, const std::string& fname)
1293 {
1294         if (fname.empty())
1295                 return false;
1296
1297         char linebuf[MAXBUF];
1298
1299         F.clear();
1300
1301         FileWrapper file(fopen(fname.c_str(), "r"));
1302
1303         if (!file)
1304                 return false;
1305         while (!feof(file))
1306         {
1307                 if (fgets(linebuf, sizeof(linebuf), file))
1308                         linebuf[strlen(linebuf)-1] = 0;
1309                 else
1310                         *linebuf = 0;
1311
1312                 F.push_back(*linebuf ? linebuf : " ");
1313         }
1314
1315         return true;
1316 }
1317
1318 bool ServerConfig::FileExists(const char* file)
1319 {
1320         struct stat sb;
1321         if (stat(file, &sb) == -1)
1322                 return false;
1323
1324         if ((sb.st_mode & S_IFDIR) > 0)
1325                 return false;
1326
1327         FILE *input = fopen(file, "r");
1328         if (input == NULL)
1329                 return false;
1330         else
1331         {
1332                 fclose(input);
1333                 return true;
1334         }
1335 }
1336
1337 const char* ServerConfig::CleanFilename(const char* name)
1338 {
1339         const char* p = name + strlen(name);
1340         while ((p != name) && (*p != '/') && (*p != '\\')) p--;
1341         return (p != name ? ++p : p);
1342 }
1343
1344 std::string ServerConfig::GetSID()
1345 {
1346         return sid;
1347 }
1348
1349 void ConfigReaderThread::Run()
1350 {
1351         Config = new ServerConfig;
1352         Config->Read();
1353         done = true;
1354 }
1355
1356 void ConfigReaderThread::Finish()
1357 {
1358         ServerConfig* old = ServerInstance->Config;
1359         ServerInstance->Logs->Log("CONFIG",DEBUG,"Switching to new configuration...");
1360         ServerInstance->Logs->CloseLogs();
1361         ServerInstance->Config = this->Config;
1362         ServerInstance->Logs->OpenFileLogs();
1363         Config->Apply(old, TheUserUID);
1364
1365         if (Config->valid)
1366         {
1367                 /*
1368                  * Apply the changed configuration from the rehash.
1369                  *
1370                  * XXX: The order of these is IMPORTANT, do not reorder them without testing
1371                  * thoroughly!!!
1372                  */
1373                 ServerInstance->XLines->CheckELines();
1374                 ServerInstance->XLines->CheckELines();
1375                 ServerInstance->XLines->ApplyLines();
1376                 ServerInstance->Res->Rehash();
1377                 ServerInstance->ResetMaxBans();
1378                 Config->ApplyDisabledCommands(Config->DisabledCommands);
1379                 User* user = TheUserUID.empty() ? ServerInstance->FindNick(TheUserUID) : NULL;
1380                 FOREACH_MOD(I_OnRehash, OnRehash(user));
1381                 ServerInstance->BuildISupport();
1382
1383                 delete old;
1384         }
1385         else
1386         {
1387                 // whoops, abort!
1388                 ServerInstance->Logs->CloseLogs();
1389                 ServerInstance->Config = old;
1390                 ServerInstance->Logs->OpenFileLogs();
1391                 delete this->Config;
1392         }
1393 }