]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/configreader.cpp
Change User::oper to an OperInfo reference
[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         log_file = NULL;
376         NoUserDns = forcedebug = OperSpyWhois = nofork = HideBans = HideSplits = UndernetMsgPrefix = false;
377         CycleHosts = writelog = AllowHalfop = InvBypassModes = true;
378         dns_timeout = DieDelay = 5;
379         MaxTargets = 20;
380         NetBufferSize = 10240;
381         SoftLimit = ServerInstance->SE->GetMaxFds();
382         MaxConn = SOMAXCONN;
383         MaxWhoResults = 0;
384         debugging = 0;
385         MaxChans = 20;
386         OperMaxChans = 30;
387         c_ipv4_range = 32;
388         c_ipv6_range = 128;
389 }
390
391 void ServerConfig::Update005()
392 {
393         std::stringstream out(data005);
394         std::string token;
395         std::string line5;
396         int token_counter = 0;
397         isupport.clear();
398         while (out >> token)
399         {
400                 line5 = line5 + token + " ";
401                 token_counter++;
402                 if (token_counter >= 13)
403                 {
404                         char buf[MAXBUF];
405                         snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
406                         isupport.push_back(buf);
407                         line5.clear();
408                         token_counter = 0;
409                 }
410         }
411         if (!line5.empty())
412         {
413                 char buf[MAXBUF];
414                 snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
415                 isupport.push_back(buf);
416         }
417 }
418
419 void ServerConfig::Send005(User* user)
420 {
421         for (std::vector<std::string>::iterator line = ServerInstance->Config->isupport.begin(); line != ServerInstance->Config->isupport.end(); line++)
422                 user->WriteNumeric(RPL_ISUPPORT, "%s %s", user->nick.c_str(), line->c_str());
423 }
424
425 static void ReqRead(ServerConfig* src, const std::string& tag, const std::string& key, std::string& dest)
426 {
427         ConfigTag* t = src->ConfValue(tag);
428         if (!t || !t->readString(key, dest))
429                 throw CoreException("You must specify a value for <" + tag + ":" + key + ">");
430 }
431
432 template<typename T, typename V>
433 static void range(T& value, V min, V max, V def, const char* msg)
434 {
435         if (value >= (T)min && value <= (T)max)
436                 return;
437         ServerInstance->Logs->Log("CONFIG", DEFAULT,
438                 "WARNING: %s value of %ld is not between %ld and %ld; set to %ld.",
439                 msg, (long)value, (long)min, (long)max, (long)def);
440         value = def;
441 }
442
443
444 /* 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,
445  * even in strerror(errno). They just return 'yes' or 'no' to an address without such detail as to whats WRONG with the address.
446  * Because ircd users arent as technical as they used to be (;)) we are going to give more of a useful error message.
447  */
448 static void ValidIP(const std::string& ip, const std::string& key)
449 {
450         const char* p = ip.c_str();
451         int num_dots = 0;
452         int num_seps = 0;
453         int not_numbers = false;
454         int not_hex = false;
455
456         if (*p)
457         {
458                 if (*p == '.')
459                         throw CoreException("The value of "+key+" is not an IP address");
460
461                 for (const char* ptr = p; *ptr; ++ptr)
462                 {
463                         if (*ptr != ':' && *ptr != '.')
464                         {
465                                 if (*ptr < '0' || *ptr > '9')
466                                         not_numbers = true;
467                                 if ((*ptr < '0' || *ptr > '9') && (toupper(*ptr) < 'A' || toupper(*ptr) > 'F'))
468                                         not_hex = true;
469                         }
470                         switch (*ptr)
471                         {
472                                 case ' ':
473                                         throw CoreException("The value of "+key+" is not an IP address");
474                                 case '.':
475                                         num_dots++;
476                                 break;
477                                 case ':':
478                                         num_seps++;
479                                 break;
480                         }
481                 }
482
483                 if (num_dots > 3)
484                         throw CoreException("The value of "+key+" is an IPv4 address with too many fields!");
485
486                 if (num_seps > 8)
487                         throw CoreException("The value of "+key+" is an IPv6 address with too many fields!");
488
489                 if (num_seps == 0 && num_dots < 3)
490                         throw CoreException("The value of "+key+" looks to be a malformed IPv4 address");
491
492                 if (num_seps == 0 && num_dots == 3 && not_numbers)
493                         throw CoreException("The value of "+key+" contains non-numeric characters in an IPv4 address");
494
495                 if (num_seps != 0 && not_hex)
496                         throw CoreException("The value of "+key+" contains non-hexdecimal characters in an IPv6 address");
497
498                 if (num_seps != 0 && num_dots != 3 && num_dots != 0)
499                         throw CoreException("The value of "+key+" is a malformed IPv6 4in6 address");
500         }
501 }
502
503 static void ValidHost(const std::string& p, const std::string& msg)
504 {
505         int num_dots = 0;
506         if (p.empty() || p[0] == '.')
507                 throw CoreException("The value of "+msg+" is not a valid hostname");
508         for (unsigned int i=0;i < p.length();i++)
509         {
510                 switch (p[i])
511                 {
512                         case ' ':
513                                 throw CoreException("The value of "+msg+" is not a valid hostname");
514                         case '.':
515                                 num_dots++;
516                         break;
517                 }
518         }
519         if (num_dots == 0)
520                 throw CoreException("The value of "+msg+" is not a valid hostname");
521 }
522
523 // Specialized validators
524
525 bool ServerConfig::ApplyDisabledCommands(const std::string& data)
526 {
527         std::stringstream dcmds(data);
528         std::string thiscmd;
529
530         /* Enable everything first */
531         for (Commandtable::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
532                 x->second->Disable(false);
533
534         /* Now disable all the ones which the user wants disabled */
535         while (dcmds >> thiscmd)
536         {
537                 Commandtable::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
538                 if (cm != ServerInstance->Parser->cmdlist.end())
539                 {
540                         cm->second->Disable(true);
541                 }
542         }
543         return true;
544 }
545
546 #ifdef WINDOWS
547 // Note: the windows validator is in win32wrapper.cpp
548 void FindDNS(std::string& server);
549 #else
550 static void FindDNS(std::string& server)
551 {
552         if (!server.empty())
553                 return;
554
555         // attempt to look up their nameserver from /etc/resolv.conf
556         ServerInstance->Logs->Log("CONFIG",DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
557
558         std::ifstream resolv("/etc/resolv.conf");
559
560         while (resolv >> server)
561         {
562                 if (server == "nameserver")
563                 {
564                         resolv >> server;
565                         ServerInstance->Logs->Log("CONFIG",DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",server.c_str());
566                         return;
567                 }
568         }
569
570         ServerInstance->Logs->Log("CONFIG",DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
571         server = "127.0.0.1";
572 }
573 #endif
574
575 static void ReadXLine(ServerConfig* conf, const std::string& tag, const std::string& key, XLineFactory* make)
576 {
577         for(int i=0;; ++i)
578         {
579                 ConfigTag* ctag = conf->ConfValue(tag, i);
580                 if (!ctag)
581                         break;
582                 std::string mask;
583                 if (!ctag->readString(key, mask))
584                         throw CoreException("<"+tag+":"+key+"> missing at " + ctag->getTagLocation());
585                 std::string reason = ctag->getString("reason", "<Config>");
586                 XLine* xl = make->Generate(ServerInstance->Time(), 0, "<Config>", reason, mask);
587                 if (!ServerInstance->XLines->AddLine(xl, NULL))
588                         delete xl;
589         }
590 }
591
592 typedef std::map<std::string, ConfigTag*> LocalIndex;
593 void ServerConfig::CrossCheckOperClassType()
594 {
595         LocalIndex operclass;
596         for (int i = 0;; ++i)
597         {
598                 ConfigTag* tag = ConfValue("class", i);
599                 if (!tag)
600                         break;
601                 std::string name = tag->getString("name");
602                 if (name.empty())
603                         throw CoreException("<class:name> missing from tag at " + tag->getTagLocation());
604                 operclass[name] = tag;
605         }
606         for (int i = 0;; ++i)
607         {
608                 ConfigTag* tag = ConfValue("type", i);
609                 if (!tag)
610                         break;
611
612                 std::string name = tag->getString("name");
613                 if (name.empty())
614                         throw CoreException("<type:name> is missing from tag at " + tag->getTagLocation());
615
616                 if (!ServerInstance->IsNick(name.c_str(), Limits.NickMax))
617                         throw CoreException("<type:name> is invalid (value '" + name + "')");
618
619                 OperInfo* ifo = new OperInfo;
620                 oper_blocks[" " + name] = ifo;
621                 ifo->type_block = tag;
622
623                 std::string classname;
624                 irc::spacesepstream str(tag->getString("classes"));
625                 while (str.GetToken(classname))
626                 {
627                         LocalIndex::iterator cls = operclass.find(classname);
628                         if (cls == operclass.end())
629                                 throw CoreException("Oper type " + name + " has missing class " + classname);
630                         ifo->class_blocks.push_back(cls->second);
631                 }
632         }
633
634         for (int i = 0;; ++i)
635         {
636                 ConfigTag* tag = ConfValue("oper", i);
637                 if (!tag)
638                         break;
639
640                 std::string name = tag->getString("name");
641                 if (name.empty())
642                         throw CoreException("<oper:name> missing from tag at " + tag->getTagLocation());
643
644                 std::string type = tag->getString("type");
645                 OperIndex::iterator tblk = oper_blocks.find(" " + type);
646                 if (tblk == oper_blocks.end())
647                         throw CoreException("Oper block " + name + " has missing type " + type);
648                 if (oper_blocks.find(name) != oper_blocks.end())
649                         throw CoreException("Duplicate oper block with name " + name);
650
651                 OperInfo* ifo = new OperInfo;
652                 ifo->name = type;
653                 ifo->oper_block = tag;
654                 ifo->type_block = tblk->second->type_block;
655                 ifo->class_blocks.assign(tblk->second->class_blocks.begin(), tblk->second->class_blocks.end());
656                 oper_blocks[name] = ifo;
657         }
658 }
659
660 void ServerConfig::CrossCheckConnectBlocks(ServerConfig* current)
661 {
662         typedef std::map<std::string, ConnectClass*> ClassMap;
663         ClassMap oldBlocksByMask;
664         if (current)
665         {
666                 for(ClassVector::iterator i = current->Classes.begin(); i != current->Classes.end(); ++i)
667                 {
668                         ConnectClass* c = *i;
669                         std::string typeMask = (c->type == CC_ALLOW) ? "a" : "d";
670                         typeMask += c->host;
671                         oldBlocksByMask[typeMask] = c;
672                 }
673         }
674
675         ClassMap newBlocksByMask;
676         std::map<std::string, int> names;
677
678         bool try_again = true;
679         for(int tries=0; try_again; tries++)
680         {
681                 try_again = false;
682                 for(unsigned int i=0;; i++)
683                 {
684                         ConfigTag* tag = ConfValue("connect", i);
685                         if (!tag)
686                                 break;
687                         if (Classes.size() <= i)
688                                 Classes.resize(i+1);
689                         if (Classes[i])
690                                 continue;
691
692                         ConnectClass* parent = NULL;
693                         std::string parentName = tag->getString("parent");
694                         if (!parentName.empty())
695                         {
696                                 std::map<std::string,int>::iterator parentIter = names.find(parentName);
697                                 if (parentIter == names.end())
698                                 {
699                                         try_again = true;
700                                         // couldn't find parent this time. If it's the last time, we'll never find it.
701                                         if (tries == 50)
702                                                 throw CoreException("Could not find parent connect class \"" + parentName + "\" for connect block " + ConvToStr(i));
703                                         continue;
704                                 }
705                                 parent = Classes[parentIter->second];
706                         }
707
708                         std::string name = tag->getString("name");
709                         if (!name.empty())
710                         {
711                                 if (names.find(name) != names.end())
712                                         throw CoreException("Two connect classes with name \"" + name + "\" defined!");
713                                 names[name] = i;
714                         }
715
716                         std::string mask, typeMask;
717                         char type;
718
719                         if (tag->readString("allow", mask, false))
720                         {
721                                 type = CC_ALLOW;
722                                 typeMask = 'a' + mask;
723                         }
724                         else if (tag->readString("deny", mask, false))
725                         {
726                                 type = CC_DENY;
727                                 typeMask = 'd' + mask;
728                         }
729                         else
730                         {
731                                 throw CoreException("Connect class must have an allow or deny mask at " + tag->getTagLocation());
732                         }
733                         ClassMap::iterator dupMask = newBlocksByMask.find(typeMask);
734                         if (dupMask != newBlocksByMask.end())
735                                 throw CoreException("Two connect classes cannot have the same mask (" + mask + ")");
736
737                         ConnectClass* me = parent ? 
738                                 new ConnectClass(tag, type, mask, *parent) :
739                                 new ConnectClass(tag, type, mask);
740
741                         if (!name.empty())
742                                 me->name = name;
743
744                         tag->readString("password", me->pass);
745                         tag->readString("hash", me->hash);
746                         me->registration_timeout = tag->getInt("timeout", me->registration_timeout);
747                         me->pingtime = tag->getInt("pingfreq", me->pingtime);
748                         std::string sendq;
749                         if (tag->readString("sendq", sendq))
750                         {
751                                 // attempt to guess a good hard/soft sendq from a single value
752                                 long value = atol(sendq.c_str());
753                                 if (value > 16384)
754                                         me->softsendqmax = value / 16;
755                                 else
756                                         me->softsendqmax = value;
757                                 me->hardsendqmax = value * 8;
758                         }
759                         me->softsendqmax = tag->getInt("softsendq", me->softsendqmax);
760                         me->hardsendqmax = tag->getInt("hardsendq", me->hardsendqmax);
761                         me->recvqmax = tag->getInt("recvq", me->recvqmax);
762                         me->penaltythreshold = tag->getInt("threshold", me->penaltythreshold);
763                         me->maxlocal = tag->getInt("localmax", me->maxlocal);
764                         me->maxglobal = tag->getInt("globalmax", me->maxglobal);
765                         me->port = tag->getInt("port", me->port);
766                         me->maxchans = tag->getInt("maxchans", me->maxchans);
767                         me->limit = tag->getInt("limit", me->limit);
768
769                         ClassMap::iterator oldMask = oldBlocksByMask.find(typeMask);
770                         if (oldMask != oldBlocksByMask.end())
771                         {
772                                 ConnectClass* old = oldMask->second;
773                                 oldBlocksByMask.erase(oldMask);
774                                 old->Update(me);
775                                 delete me;
776                                 me = old;
777                         }
778                         newBlocksByMask[typeMask] = me;
779                         Classes[i] = me;
780                 }
781         }
782 }
783
784 /** Represents a deprecated configuration tag.
785  */
786 struct Deprecated
787 {
788         /** Tag name
789          */
790         const char* tag;
791         /** Tag value
792          */
793         const char* value;
794         /** Reason for deprecation
795          */
796         const char* reason;
797 };
798
799 static const Deprecated ChangedConfig[] = {
800         {"options", "hidelinks",                "has been moved to <security:hidelinks> as of 1.2a3"},
801         {"options", "hidewhois",                "has been moved to <security:hidewhois> as of 1.2a3"},
802         {"options", "userstats",                "has been moved to <security:userstats> as of 1.2a3"},
803         {"options", "customversion",    "has been moved to <security:customversion> as of 1.2a3"},
804         {"options", "hidesplits",               "has been moved to <security:hidesplits> as of 1.2a3"},
805         {"options", "hidebans",         "has been moved to <security:hidebans> as of 1.2a3"},
806         {"options", "hidekills",                "has been moved to <security:hidekills> as of 1.2a3"},
807         {"options", "operspywhois",             "has been moved to <security:operspywhois> as of 1.2a3"},
808         {"options", "announceinvites",  "has been moved to <security:announceinvites> as of 1.2a3"},
809         {"options", "hidemodes",                "has been moved to <security:hidemodes> as of 1.2a3"},
810         {"options", "maxtargets",               "has been moved to <security:maxtargets> as of 1.2a3"},
811         {"options",     "nouserdns",            "has been moved to <performance:nouserdns> as of 1.2a3"},
812         {"options",     "maxwho",               "has been moved to <performance:maxwho> as of 1.2a3"},
813         {"options",     "softlimit",            "has been moved to <performance:softlimit> as of 1.2a3"},
814         {"options", "somaxconn",                "has been moved to <performance:somaxconn> as of 1.2a3"},
815         {"options", "netbuffersize",    "has been moved to <performance:netbuffersize> as of 1.2a3"},
816         {"options", "maxwho",           "has been moved to <performance:maxwho> as of 1.2a3"},
817         {"options",     "loglevel",             "1.2 does not use the loglevel value. Please define <log> tags instead."},
818         {"die",     "value",            "has always been deprecated"},
819 };
820
821 void ServerConfig::Fill()
822 {
823         ReqRead(this, "server", "name", ServerName);
824         ReqRead(this, "power", "diepass", diepass);
825         ReqRead(this, "power", "restartpass", restartpass);
826
827         ConfigTag* options = ConfValue("options");
828         ConfigTag* security = ConfValue("security");
829         powerhash = ConfValue("power")->getString("hash");
830         DieDelay = ConfValue("power")->getInt("pause");
831         PrefixQuit = options->getString("prefixquit");
832         SuffixQuit = options->getString("suffixquit");
833         FixedQuit = options->getString("fixedquit");
834         PrefixPart = options->getString("prefixpart");
835         SuffixPart = options->getString("suffixpart");
836         FixedPart = options->getString("fixedpart");
837         SoftLimit = ConfValue("performance")->getInt("softlimit", ServerInstance->SE->GetMaxFds());
838         MaxConn = ConfValue("performance")->getInt("somaxconn", SOMAXCONN);
839         MoronBanner = options->getString("moronbanner", "You're banned!");
840         ServerDesc = ConfValue("server")->getString("description", "Configure Me");
841         Network = ConfValue("server")->getString("network", "Network");
842         sid = ConfValue("server")->getString("id", "");
843         AdminName = ConfValue("admin")->getString("name", "");
844         AdminEmail = ConfValue("admin")->getString("email", "null@example.com");
845         AdminNick = ConfValue("admin")->getString("nick", "admin");
846         ModPath = ConfValue("path")->getString("moduledir", MOD_PATH);
847         NetBufferSize = ConfValue("performance")->getInt("netbuffersize", 10240);
848         MaxWhoResults = ConfValue("performance")->getInt("maxwho", 1024);
849         dns_timeout = ConfValue("dns")->getInt("timeout", 5);
850         DisabledCommands = ConfValue("disabled")->getString("commands", "");
851         DisabledDontExist = ConfValue("disabled")->getBool("fakenonexistant");
852         SetUser = security->getString("runasuser");
853         SetGroup = security->getString("runasgroup");
854         UserStats = security->getString("userstats");
855         CustomVersion = security->getString("customversion");
856         HideSplits = security->getBool("hidesplits");
857         HideBans = security->getBool("hidebans");
858         HideWhoisServer = security->getString("hidewhois");
859         HideKillsServer = security->getString("hidekills");
860         OperSpyWhois = security->getBool("operspywhois");
861         RestrictBannedUsers = security->getBool("restrictbannedusers", true);
862         GenericOper = security->getBool("genericoper");
863         NoUserDns = ConfValue("performance")->getBool("nouserdns");
864         SyntaxHints = options->getBool("syntaxhints");
865         CycleHosts = options->getBool("cyclehosts");
866         UndernetMsgPrefix = options->getBool("ircumsgprefix");
867         FullHostInTopic = options->getBool("hostintopic");
868         MaxTargets = security->getInt("maxtargets", 20);
869         DefaultModes = options->getString("defaultmodes", "nt");
870         PID = ConfValue("pid")->getString("file");
871         WhoWasGroupSize = ConfValue("whowas")->getInt("groupsize");
872         WhoWasMaxGroups = ConfValue("whowas")->getInt("maxgroups");
873         WhoWasMaxKeep = ServerInstance->Duration(ConfValue("whowas")->getString("maxkeep"));
874         DieValue = ConfValue("die")->getString("value");
875         MaxChans = ConfValue("channels")->getInt("users");
876         OperMaxChans = ConfValue("channels")->getInt("opers");
877         c_ipv4_range = ConfValue("cidr")->getInt("ipv4clone");
878         c_ipv6_range = ConfValue("cidr")->getInt("ipv6clone");
879         Limits.NickMax = ConfValue("limits")->getInt("maxnick", 32);
880         Limits.ChanMax = ConfValue("limits")->getInt("maxchan", 64);
881         Limits.MaxModes = ConfValue("limits")->getInt("maxmodes", 20);
882         Limits.IdentMax = ConfValue("limits")->getInt("maxident", 11);
883         Limits.MaxQuit = ConfValue("limits")->getInt("maxquit", 255);
884         Limits.MaxTopic = ConfValue("limits")->getInt("maxtopic", 307);
885         Limits.MaxKick = ConfValue("limits")->getInt("maxkick", 255);
886         Limits.MaxGecos = ConfValue("limits")->getInt("maxgecos", 128);
887         Limits.MaxAway = ConfValue("limits")->getInt("maxaway", 200);
888         InvBypassModes = options->getBool("invitebypassmodes", true);
889
890         range(SoftLimit, 10, ServerInstance->SE->GetMaxFds(), ServerInstance->SE->GetMaxFds(), "<performance:softlimit>");
891         range(MaxConn, 0, SOMAXCONN, SOMAXCONN, "<performance:somaxconn>");
892         range(MaxTargets, 1, 31, 20, "<security:maxtargets>");
893         range(NetBufferSize, 1024, 65534, 10240, "<performance:netbuffersize>");
894         range(MaxWhoResults, 1, 65535, 1024, "<performace:maxwho>");
895         range(WhoWasGroupSize, 0, 10000, 10, "<whowas:groupsize>");
896         range(WhoWasMaxGroups, 0, 1000000, 10240, "<whowas:maxgroups>");
897         range(WhoWasMaxKeep, 3600, INT_MAX, 3600, "<whowas:maxkeep>");
898
899         ValidIP(DNSServer, "<dns:server>");
900         ValidHost(ServerName, "<server:name>");
901         if (!sid.empty() && !ServerInstance->IsSID(sid))
902                 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.");
903
904         for (int i = 0;; ++i)
905         {
906                 ConfigTag* tag = ConfValue("uline", i);
907                 if (!tag)
908                         break;
909                 std::string server;
910                 if (!tag->readString("server", server))
911                         throw CoreException("<uline> tag missing server at " + tag->getTagLocation());
912                 ulines[assign(server)] = tag->getBool("silent");
913         }
914
915         for(int i=0;; ++i)
916         {
917                 ConfigTag* tag = ConfValue("banlist", i);
918                 if (!tag)
919                         break;
920                 std::string chan;
921                 if (!tag->readString("chan", chan))
922                         throw CoreException("<banlist> tag missing chan at " + tag->getTagLocation());
923                 maxbans[chan] = tag->getInt("limit");
924         }
925
926         ReadXLine(this, "badip", "ipmask", ServerInstance->XLines->GetFactory("Z"));
927         ReadXLine(this, "badnick", "nick", ServerInstance->XLines->GetFactory("Q"));
928         ReadXLine(this, "badhost", "host", ServerInstance->XLines->GetFactory("K"));
929         ReadXLine(this, "exception", "host", ServerInstance->XLines->GetFactory("E"));
930
931         memset(DisabledUModes, 0, sizeof(DisabledUModes));
932         for (const unsigned char* p = (const unsigned char*)ConfValue("disabled")->getString("usermodes").c_str(); *p; ++p)
933         {
934                 if (*p < 'A' || *p > ('A' + 64)) throw CoreException(std::string("Invalid usermode ")+(char)*p+" was found.");
935                 DisabledUModes[*p - 'A'] = 1;
936         }
937
938         memset(DisabledCModes, 0, sizeof(DisabledCModes));
939         for (const unsigned char* p = (const unsigned char*)ConfValue("disabled")->getString("chanmodes").c_str(); *p; ++p)
940         {
941                 if (*p < 'A' || *p > ('A' + 64)) throw CoreException(std::string("Invalid chanmode ")+(char)*p+" was found.");
942                 DisabledCModes[*p - 'A'] = 1;
943         }
944
945         memset(HideModeLists, 0, sizeof(HideModeLists));
946         for (const unsigned char* p = (const unsigned char*)ConfValue("security")->getString("hidemodes").c_str(); *p; ++p)
947                 HideModeLists[*p] = true;
948
949         std::string v = security->getString("announceinvites");
950
951         if (v == "ops")
952                 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_OPS;
953         else if (v == "all")
954                 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_ALL;
955         else if (v == "dynamic")
956                 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_DYNAMIC;
957         else
958                 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_NONE;
959
960         Limits.Finalise();
961 }
962
963 /* These tags MUST occur and must ONLY occur once in the config file */
964 static const char* const Once[] = { "server", "admin", "files", "power", "options" };
965
966 // WARNING: it is not safe to use most of the codebase in this function, as it
967 // will run in the config reader thread
968 void ServerConfig::Read()
969 {
970         /* Load and parse the config file, if there are any errors then explode */
971
972         ParseStack stack(this);
973         try
974         {
975                 valid = stack.ParseFile(ServerInstance->ConfigFileName, 0);
976         }
977         catch (CoreException& err)
978         {
979                 valid = false;
980                 errstr << err.GetReason();
981         }
982         if (valid)
983         {
984                 ReadFile(MOTD, ConfValue("files")->getString("motd"));
985                 ReadFile(RULES, ConfValue("files")->getString("rules"));
986                 DNSServer = ConfValue("dns")->getString("server");
987                 FindDNS(DNSServer);
988         }
989 }
990
991 void ServerConfig::Apply(ServerConfig* old, const std::string &useruid)
992 {
993         valid = true;
994
995         /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
996         try
997         {
998                 /* Check we dont have more than one of singular tags, or any of them missing
999                  */
1000                 for (int Index = 0; Index * sizeof(*Once) < sizeof(Once); Index++)
1001                 {
1002                         std::string tag = Once[Index];
1003                         if (!ConfValue(tag))
1004                                 throw CoreException("You have not defined a <"+tag+"> tag, this is required.");
1005                         if (ConfValue(tag, 1))
1006                         {
1007                                 errstr << "You have more than one <" << tag << "> tag.\n"
1008                                         << "First occurrence at " << ConfValue(tag, 0)->getTagLocation()
1009                                         << "; second occurrence at " << ConfValue(tag, 1)->getTagLocation() << std::endl;
1010                         }
1011                 }
1012
1013                 for (int Index = 0; Index * sizeof(Deprecated) < sizeof(ChangedConfig); Index++)
1014                 {
1015                         std::string dummy;
1016                         if (ConfValue(ChangedConfig[Index].tag)->readString(ChangedConfig[Index].value, dummy, true))
1017                                 errstr << "Your configuration contains a deprecated value: <"
1018                                         << ChangedConfig[Index].tag << ":" << ChangedConfig[Index].value << "> - " << ChangedConfig[Index].reason
1019                                         << " (at " << ConfValue(ChangedConfig[Index].tag)->getTagLocation() << ")\n";
1020                 }
1021
1022                 Fill();
1023
1024                 // Handle special items
1025                 CrossCheckOperClassType();
1026                 CrossCheckConnectBlocks(old);
1027         }
1028         catch (CoreException &ce)
1029         {
1030                 errstr << ce.GetReason();
1031         }
1032
1033         // write once here, to try it out and make sure its ok
1034         ServerInstance->WritePID(this->PID);
1035
1036         /*
1037          * These values can only be set on boot. Keep their old values. Do it before we send messages so we actually have a servername.
1038          */
1039         if (old)
1040         {
1041                 this->ServerName = old->ServerName;
1042                 this->sid = old->sid;
1043                 this->argv = old->argv;
1044                 this->argc = old->argc;
1045
1046                 // Same for ports... they're bound later on first run.
1047                 FailedPortList pl;
1048                 ServerInstance->BindPorts(pl);
1049                 if (pl.size())
1050                 {
1051                         errstr << "Not all your client ports could be bound.\nThe following port(s) failed to bind:\n";
1052
1053                         int j = 1;
1054                         for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
1055                         {
1056                                 char buf[MAXBUF];
1057                                 snprintf(buf, MAXBUF, "%d.   Address: %s   Reason: %s\n", j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
1058                                 errstr << buf;
1059                         }
1060                 }
1061         }
1062
1063         User* user = useruid.empty() ? NULL : ServerInstance->FindNick(useruid);
1064
1065         valid = errstr.str().empty();
1066         if (!valid)
1067                 ServerInstance->Logs->Log("CONFIG",DEFAULT, "There were errors in your configuration file:");
1068
1069         while (errstr.good())
1070         {
1071                 std::string line;
1072                 getline(errstr, line, '\n');
1073                 if (!line.empty())
1074                 {
1075                         if (user)
1076                                 user->WriteServ("NOTICE %s :*** %s", user->nick.c_str(), line.c_str());
1077                         else
1078                                 ServerInstance->SNO->WriteGlobalSno('a', line);
1079                 }
1080
1081                 if (!old)
1082                 {
1083                         // Starting up, so print it out so it's seen. XXX this is a bit of a hack.
1084                         printf("%s\n", line.c_str());
1085                 }
1086         }
1087
1088         errstr.clear();
1089         errstr.str(std::string());
1090
1091         /* No old configuration -> initial boot, nothing more to do here */
1092         if (!old)
1093         {
1094                 if (!valid)
1095                 {
1096                         ServerInstance->Exit(EXIT_STATUS_CONFIG);
1097                 }
1098
1099                 if (ConfValue("options")->getBool("allowhalfop"))
1100                         ServerInstance->Modes->AddMode(new ModeChannelHalfOp);
1101
1102                 return;
1103         }
1104
1105         // If there were errors processing configuration, don't touch modules.
1106         if (!valid)
1107                 return;
1108
1109         ApplyModules(user);
1110
1111         if (user)
1112                 user->WriteServ("NOTICE %s :*** Successfully rehashed server.", user->nick.c_str());
1113         ServerInstance->SNO->WriteGlobalSno('a', "*** Successfully rehashed server.");
1114 }
1115
1116 void ServerConfig::ApplyModules(User* user)
1117 {
1118         bool AllowHalfOp = ConfValue("options")->getBool("allowhalfop");
1119         ModeHandler* mh = ServerInstance->Modes->FindMode('h', MODETYPE_CHANNEL);
1120         if (AllowHalfOp && !mh) {
1121                 ServerInstance->Logs->Log("CONFIG", DEFAULT, "Enabling halfop mode.");
1122                 mh = new ModeChannelHalfOp;
1123                 ServerInstance->Modes->AddMode(mh);
1124         } else if (!AllowHalfOp && mh) {
1125                 ServerInstance->Logs->Log("CONFIG", DEFAULT, "Disabling halfop mode.");
1126                 ServerInstance->Modes->DelMode(mh);
1127                 delete mh;
1128         }
1129
1130         Module* whowas = ServerInstance->Modules->Find("cmd_whowas.so");
1131         if (whowas)
1132                 WhowasRequest(NULL, whowas, WhowasRequest::WHOWAS_PRUNE).Send();
1133
1134         const std::vector<std::string> v = ServerInstance->Modules->GetAllModuleNames(0);
1135         std::vector<std::string> added_modules;
1136         std::set<std::string> removed_modules(v.begin(), v.end());
1137
1138         for(int i=0; ; i++)
1139         {
1140                 ConfigTag* tag = ConfValue("module", i);
1141                 if (!tag)
1142                         break;
1143                 std::string name;
1144                 if (tag->readString("name", name))
1145                 {
1146                         // if this module is already loaded, the erase will succeed, so we need do nothing
1147                         // otherwise, we need to add the module (which will be done later)
1148                         if (removed_modules.erase(name) == 0)
1149                                 added_modules.push_back(name);
1150                 }
1151         }
1152
1153         for (std::set<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
1154         {
1155                 // Don't remove cmd_*.so, just remove m_*.so
1156                 if (removing->c_str()[0] == 'c')
1157                         continue;
1158                 Module* m = ServerInstance->Modules->Find(*removing);
1159                 if (m && ServerInstance->Modules->Unload(m))
1160                 {
1161                         ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH UNLOADED MODULE: %s",removing->c_str());
1162
1163                         if (user)
1164                                 user->WriteNumeric(RPL_UNLOADEDMODULE, "%s %s :Module %s successfully unloaded.",user->nick.c_str(), removing->c_str(), removing->c_str());
1165                         else
1166                                 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully unloaded.", removing->c_str());
1167                 }
1168                 else
1169                 {
1170                         if (user)
1171                                 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());
1172                         else
1173                                  ServerInstance->SNO->WriteGlobalSno('a', "Failed to unload module %s: %s", removing->c_str(), ServerInstance->Modules->LastError().c_str());
1174                 }
1175         }
1176
1177         for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
1178         {
1179                 if (ServerInstance->Modules->Load(adding->c_str()))
1180                 {
1181                         ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH LOADED MODULE: %s",adding->c_str());
1182                         if (user)
1183                                 user->WriteNumeric(RPL_LOADEDMODULE, "%s %s :Module %s successfully loaded.",user->nick.c_str(), adding->c_str(), adding->c_str());
1184                         else
1185                                 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully loaded.", adding->c_str());
1186                 }
1187                 else
1188                 {
1189                         if (user)
1190                                 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());
1191                         else
1192                                 ServerInstance->SNO->WriteGlobalSno('a', "Failed to load module %s: %s", adding->c_str(), ServerInstance->Modules->LastError().c_str());
1193                 }
1194         }
1195 }
1196
1197 bool ServerConfig::StartsWithWindowsDriveLetter(const std::string &path)
1198 {
1199         return (path.length() > 2 && isalpha(path[0]) && path[1] == ':');
1200 }
1201
1202 ConfigTag* ServerConfig::ConfValue(const std::string &tag, int offset)
1203 {
1204         ConfigDataHash::size_type pos = offset;
1205         if (pos >= config_data.count(tag))
1206                 return NULL;
1207
1208         ConfigDataHash::iterator iter = config_data.find(tag);
1209
1210         for(int i = 0; i < offset; i++)
1211                 iter++;
1212
1213         return iter->second;
1214 }
1215
1216 bool ConfigTag::readString(const std::string& key, std::string& value, bool allow_lf)
1217 {
1218         if (!this)
1219                 return false;
1220         for(std::vector<KeyVal>::iterator j = items.begin(); j != items.end(); ++j)
1221         {
1222                 if(j->first != key)
1223                         continue;
1224                 value = j->second;
1225                 if (!allow_lf && (value.find('\n') != std::string::npos))
1226                 {
1227                         ServerInstance->Logs->Log("CONFIG",DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
1228                                 " contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
1229                         for (std::string::iterator n = value.begin(); n != value.end(); n++)
1230                                 if (*n == '\n')
1231                                         *n = ' ';
1232                 }
1233                 return true;
1234         }
1235         return false;
1236 }
1237
1238 std::string ConfigTag::getString(const std::string& key, const std::string& def)
1239 {
1240         std::string res = def;
1241         readString(key, res);
1242         return res;
1243 }
1244
1245 long ConfigTag::getInt(const std::string &key, long def)
1246 {
1247         std::string result;
1248         if(!readString(key, result))
1249                 return def;
1250
1251         const char* res_cstr = result.c_str();
1252         char* res_tail = NULL;
1253         long res = strtol(res_cstr, &res_tail, 0);
1254         if (res_tail == res_cstr)
1255                 return def;
1256         switch (toupper(*res_tail))
1257         {
1258                 case 'K':
1259                         res= res* 1024;
1260                         break;
1261                 case 'M':
1262                         res= res* 1024 * 1024;
1263                         break;
1264                 case 'G':
1265                         res= res* 1024 * 1024 * 1024;
1266                         break;
1267         }
1268         return res;
1269 }
1270
1271 double ConfigTag::getFloat(const std::string &key, double def)
1272 {
1273         std::string result;
1274         if (!readString(key, result))
1275                 return def;
1276         return strtod(result.c_str(), NULL);
1277 }
1278
1279 bool ConfigTag::getBool(const std::string &key, bool def)
1280 {
1281         std::string result;
1282         if(!readString(key, result))
1283                 return def;
1284
1285         return (result == "yes" || result == "true" || result == "1" || result == "on");
1286 }
1287
1288 std::string ConfigTag::getTagLocation()
1289 {
1290         return src_name + ":" + ConvToStr(src_line);
1291 }
1292
1293 std::string OperInfo::getConfig(const std::string& key)
1294 {
1295         std::string rv;
1296         if (type_block)
1297                 type_block->readString(key, rv);
1298         if (oper_block)
1299                 oper_block->readString(key, rv);
1300         return rv;
1301 }
1302
1303 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1304  */
1305 bool ServerConfig::ReadFile(file_cache &F, const std::string& fname)
1306 {
1307         if (fname.empty())
1308                 return false;
1309
1310         char linebuf[MAXBUF];
1311
1312         F.clear();
1313
1314         FileWrapper file(fopen(fname.c_str(), "r"));
1315
1316         if (!file)
1317                 return false;
1318         while (!feof(file))
1319         {
1320                 if (fgets(linebuf, sizeof(linebuf), file))
1321                         linebuf[strlen(linebuf)-1] = 0;
1322                 else
1323                         *linebuf = 0;
1324
1325                 F.push_back(*linebuf ? linebuf : " ");
1326         }
1327
1328         return true;
1329 }
1330
1331 bool ServerConfig::FileExists(const char* file)
1332 {
1333         struct stat sb;
1334         if (stat(file, &sb) == -1)
1335                 return false;
1336
1337         if ((sb.st_mode & S_IFDIR) > 0)
1338                 return false;
1339
1340         FILE *input = fopen(file, "r");
1341         if (input == NULL)
1342                 return false;
1343         else
1344         {
1345                 fclose(input);
1346                 return true;
1347         }
1348 }
1349
1350 const char* ServerConfig::CleanFilename(const char* name)
1351 {
1352         const char* p = name + strlen(name);
1353         while ((p != name) && (*p != '/') && (*p != '\\')) p--;
1354         return (p != name ? ++p : p);
1355 }
1356
1357 std::string ServerConfig::GetSID()
1358 {
1359         return sid;
1360 }
1361
1362 void ConfigReaderThread::Run()
1363 {
1364         Config = new ServerConfig;
1365         Config->Read();
1366         done = true;
1367 }
1368
1369 void ConfigReaderThread::Finish()
1370 {
1371         ServerConfig* old = ServerInstance->Config;
1372         ServerInstance->Logs->Log("CONFIG",DEBUG,"Switching to new configuration...");
1373         ServerInstance->Logs->CloseLogs();
1374         ServerInstance->Config = this->Config;
1375         ServerInstance->Logs->OpenFileLogs();
1376         Config->Apply(old, TheUserUID);
1377
1378         if (Config->valid)
1379         {
1380                 /*
1381                  * Apply the changed configuration from the rehash.
1382                  *
1383                  * XXX: The order of these is IMPORTANT, do not reorder them without testing
1384                  * thoroughly!!!
1385                  */
1386                 ServerInstance->XLines->CheckELines();
1387                 ServerInstance->XLines->CheckELines();
1388                 ServerInstance->XLines->ApplyLines();
1389                 ServerInstance->Res->Rehash();
1390                 ServerInstance->ResetMaxBans();
1391                 Config->ApplyDisabledCommands(Config->DisabledCommands);
1392                 User* user = TheUserUID.empty() ? ServerInstance->FindNick(TheUserUID) : NULL;
1393                 FOREACH_MOD(I_OnRehash, OnRehash(user));
1394                 ServerInstance->BuildISupport();
1395
1396                 delete old;
1397         }
1398         else
1399         {
1400                 // whoops, abort!
1401                 ServerInstance->Logs->CloseLogs();
1402                 ServerInstance->Config = old;
1403                 ServerInstance->Logs->OpenFileLogs();
1404                 delete this->Config;
1405         }
1406 }