]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/configreader.cpp
Close files opened by configreader
[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: .gdbargs $(BASE) */
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 void ServerConfig::CrossCheckOperClassType()
593 {
594         for (int i = 0;; ++i)
595         {
596                 ConfigTag* tag = ConfValue("class", i);
597                 if (!tag)
598                         break;
599                 std::string name = tag->getString("name");
600                 if (name.empty())
601                         throw CoreException("<class:name> missing from tag at " + tag->getTagLocation());
602                 operclass[name] = tag;
603         }
604         for (int i = 0;; ++i)
605         {
606                 ConfigTag* tag = ConfValue("type", i);
607                 if (!tag)
608                         break;
609
610                 std::string name = tag->getString("name");
611                 if (name.empty())
612                         throw CoreException("<type:name> is missing from tag at " + tag->getTagLocation());
613                 opertypes[name] = tag;
614
615                 std::string classname;
616                 irc::spacesepstream str(tag->getString("classes"));
617                 while (str.GetToken(classname))
618                 {
619                         if (operclass.find(classname) == operclass.end())
620                                 throw CoreException("Oper type " + name + " has missing class " + classname);
621                 }
622         }
623 }
624
625 void ServerConfig::CrossCheckConnectBlocks(ServerConfig* current)
626 {
627         typedef std::map<std::string, ConnectClass*> ClassMap;
628         ClassMap oldBlocksByMask;
629         if (current)
630         {
631                 for(ClassVector::iterator i = current->Classes.begin(); i != current->Classes.end(); ++i)
632                 {
633                         ConnectClass* c = *i;
634                         std::string typeMask = (c->type == CC_ALLOW) ? "a" : "d";
635                         typeMask += c->host;
636                         oldBlocksByMask[typeMask] = c;
637                 }
638         }
639
640         ClassMap newBlocksByMask;
641         std::map<std::string, int> names;
642
643         bool try_again = true;
644         for(int tries=0; try_again; tries++)
645         {
646                 try_again = false;
647                 for(unsigned int i=0;; i++)
648                 {
649                         ConfigTag* tag = ConfValue("connect", i);
650                         if (!tag)
651                                 break;
652                         if (Classes.size() <= i)
653                                 Classes.resize(i+1);
654                         if (Classes[i])
655                                 continue;
656
657                         ConnectClass* parent = NULL;
658                         std::string parentName = tag->getString("parent");
659                         if (!parentName.empty())
660                         {
661                                 std::map<std::string,int>::iterator parentIter = names.find(parentName);
662                                 if (parentIter == names.end())
663                                 {
664                                         try_again = true;
665                                         // couldn't find parent this time. If it's the last time, we'll never find it.
666                                         if (tries == 50)
667                                                 throw CoreException("Could not find parent connect class \"" + parentName + "\" for connect block " + ConvToStr(i));
668                                         continue;
669                                 }
670                                 parent = Classes[parentIter->second];
671                         }
672
673                         std::string name = tag->getString("name");
674                         if (!name.empty())
675                         {
676                                 if (names.find(name) != names.end())
677                                         throw CoreException("Two connect classes with name \"" + name + "\" defined!");
678                                 names[name] = i;
679                         }
680
681                         std::string mask, typeMask;
682                         char type;
683
684                         if (tag->readString("allow", mask, false))
685                         {
686                                 type = CC_ALLOW;
687                                 typeMask = 'a' + mask;
688                         }
689                         else if (tag->readString("deny", mask, false))
690                         {
691                                 type = CC_DENY;
692                                 typeMask = 'd' + mask;
693                         }
694                         else
695                         {
696                                 throw CoreException("Connect class must have an allow or deny mask at " + tag->getTagLocation());
697                         }
698                         ClassMap::iterator dupMask = newBlocksByMask.find(typeMask);
699                         if (dupMask != newBlocksByMask.end())
700                                 throw CoreException("Two connect classes cannot have the same mask (" + mask + ")");
701
702                         ConnectClass* me = parent ? 
703                                 new ConnectClass(tag, type, mask, *parent) :
704                                 new ConnectClass(tag, type, mask);
705
706                         if (!name.empty())
707                                 me->name = name;
708
709                         tag->readString("password", me->pass);
710                         tag->readString("hash", me->hash);
711                         me->registration_timeout = tag->getInt("timeout", me->registration_timeout);
712                         me->pingtime = tag->getInt("pingfreq", me->pingtime);
713                         std::string sendq;
714                         if (tag->readString("sendq", sendq))
715                         {
716                                 // attempt to guess a good hard/soft sendq from a single value
717                                 long value = atol(sendq.c_str());
718                                 if (value > 16384)
719                                         me->softsendqmax = value / 16;
720                                 else
721                                         me->softsendqmax = value;
722                                 me->hardsendqmax = value * 8;
723                         }
724                         me->softsendqmax = tag->getInt("softsendq", me->softsendqmax);
725                         me->hardsendqmax = tag->getInt("hardsendq", me->hardsendqmax);
726                         me->recvqmax = tag->getInt("recvq", me->recvqmax);
727                         me->maxlocal = tag->getInt("localmax", me->maxlocal);
728                         me->maxglobal = tag->getInt("globalmax", me->maxglobal);
729                         me->port = tag->getInt("port", me->port);
730                         me->maxchans = tag->getInt("maxchans", me->maxchans);
731                         me->limit = tag->getInt("limit", me->limit);
732
733                         ClassMap::iterator oldMask = oldBlocksByMask.find(typeMask);
734                         if (oldMask != oldBlocksByMask.end())
735                         {
736                                 ConnectClass* old = oldMask->second;
737                                 oldBlocksByMask.erase(oldMask);
738                                 old->Update(me);
739                                 delete me;
740                                 me = old;
741                         }
742                         newBlocksByMask[typeMask] = me;
743                         Classes[i] = me;
744                 }
745         }
746 }
747
748 /** Represents a deprecated configuration tag.
749  */
750 struct Deprecated
751 {
752         /** Tag name
753          */
754         const char* tag;
755         /** Tag value
756          */
757         const char* value;
758         /** Reason for deprecation
759          */
760         const char* reason;
761 };
762
763 static const Deprecated ChangedConfig[] = {
764         {"options", "hidelinks",                "has been moved to <security:hidelinks> as of 1.2a3"},
765         {"options", "hidewhois",                "has been moved to <security:hidewhois> as of 1.2a3"},
766         {"options", "userstats",                "has been moved to <security:userstats> as of 1.2a3"},
767         {"options", "customversion",    "has been moved to <security:customversion> as of 1.2a3"},
768         {"options", "hidesplits",               "has been moved to <security:hidesplits> as of 1.2a3"},
769         {"options", "hidebans",         "has been moved to <security:hidebans> as of 1.2a3"},
770         {"options", "hidekills",                "has been moved to <security:hidekills> as of 1.2a3"},
771         {"options", "operspywhois",             "has been moved to <security:operspywhois> as of 1.2a3"},
772         {"options", "announceinvites",  "has been moved to <security:announceinvites> as of 1.2a3"},
773         {"options", "hidemodes",                "has been moved to <security:hidemodes> as of 1.2a3"},
774         {"options", "maxtargets",               "has been moved to <security:maxtargets> as of 1.2a3"},
775         {"options",     "nouserdns",            "has been moved to <performance:nouserdns> as of 1.2a3"},
776         {"options",     "maxwho",               "has been moved to <performance:maxwho> as of 1.2a3"},
777         {"options",     "softlimit",            "has been moved to <performance:softlimit> as of 1.2a3"},
778         {"options", "somaxconn",                "has been moved to <performance:somaxconn> as of 1.2a3"},
779         {"options", "netbuffersize",    "has been moved to <performance:netbuffersize> as of 1.2a3"},
780         {"options", "maxwho",           "has been moved to <performance:maxwho> as of 1.2a3"},
781         {"options",     "loglevel",             "1.2 does not use the loglevel value. Please define <log> tags instead."},
782         {"die",     "value",            "has always been deprecated"},
783 };
784
785 void ServerConfig::Fill()
786 {
787         ReqRead(this, "server", "name", ServerName);
788         ReqRead(this, "power", "diepass", diepass);
789         ReqRead(this, "power", "restartpass", restartpass);
790
791         ConfigTag* options = ConfValue("options");
792         ConfigTag* security = ConfValue("security");
793         powerhash = ConfValue("power")->getString("hash");
794         DieDelay = ConfValue("power")->getInt("pause");
795         PrefixQuit = options->getString("prefixquit");
796         SuffixQuit = options->getString("suffixquit");
797         FixedQuit = options->getString("fixedquit");
798         PrefixPart = options->getString("prefixpart");
799         SuffixPart = options->getString("suffixpart");
800         FixedPart = options->getString("fixedpart");
801         SoftLimit = ConfValue("performance")->getInt("softlimit", ServerInstance->SE->GetMaxFds());
802         MaxConn = ConfValue("performance")->getInt("somaxconn", SOMAXCONN);
803         MoronBanner = options->getString("moronbanner", "You're banned!");
804         ServerDesc = ConfValue("server")->getString("description", "Configure Me");
805         Network = ConfValue("server")->getString("network", "Network");
806         sid = ConfValue("server")->getString("id", "");
807         AdminName = ConfValue("admin")->getString("name", "");
808         AdminEmail = ConfValue("admin")->getString("email", "null@example.com");
809         AdminNick = ConfValue("admin")->getString("nick", "admin");
810         ModPath = ConfValue("path")->getString("moduledir", MOD_PATH);
811         NetBufferSize = ConfValue("performance")->getInt("netbuffersize", 10240);
812         MaxWhoResults = ConfValue("performance")->getInt("maxwho", 1024);
813         dns_timeout = ConfValue("dns")->getInt("timeout", 5);
814         DisabledCommands = ConfValue("disabled")->getString("commands", "");
815         DisabledDontExist = ConfValue("disabled")->getBool("fakenonexistant");
816         SetUser = security->getString("runasuser");
817         SetGroup = security->getString("runasgroup");
818         UserStats = security->getString("userstats");
819         CustomVersion = security->getString("customversion");
820         HideSplits = security->getBool("hidesplits");
821         HideBans = security->getBool("hidebans");
822         HideWhoisServer = security->getString("hidewhois");
823         HideKillsServer = security->getString("hidekills");
824         OperSpyWhois = security->getBool("operspywhois");
825         RestrictBannedUsers = security->getBool("restrictbannedusers", true);
826         GenericOper = security->getBool("genericoper");
827         NoUserDns = ConfValue("performance")->getBool("nouserdns");
828         SyntaxHints = options->getBool("syntaxhints");
829         CycleHosts = options->getBool("cyclehosts");
830         UndernetMsgPrefix = options->getBool("ircumsgprefix");
831         FullHostInTopic = options->getBool("hostintopic");
832         MaxTargets = security->getInt("maxtargets", 20);
833         DefaultModes = options->getString("defaultmodes", "nt");
834         PID = ConfValue("pid")->getString("file");
835         WhoWasGroupSize = ConfValue("whowas")->getInt("groupsize");
836         WhoWasMaxGroups = ConfValue("whowas")->getInt("maxgroups");
837         WhoWasMaxKeep = ServerInstance->Duration(ConfValue("whowas")->getString("maxkeep"));
838         DieValue = ConfValue("die")->getString("value");
839         MaxChans = ConfValue("channels")->getInt("users");
840         OperMaxChans = ConfValue("channels")->getInt("opers");
841         c_ipv4_range = ConfValue("cidr")->getInt("ipv4clone");
842         c_ipv6_range = ConfValue("cidr")->getInt("ipv6clone");
843         Limits.NickMax = ConfValue("limits")->getInt("maxnick", 32);
844         Limits.ChanMax = ConfValue("limits")->getInt("maxchan", 64);
845         Limits.MaxModes = ConfValue("limits")->getInt("maxmodes", 20);
846         Limits.IdentMax = ConfValue("limits")->getInt("maxident", 11);
847         Limits.MaxQuit = ConfValue("limits")->getInt("maxquit", 255);
848         Limits.MaxTopic = ConfValue("limits")->getInt("maxtopic", 307);
849         Limits.MaxKick = ConfValue("limits")->getInt("maxkick", 255);
850         Limits.MaxGecos = ConfValue("limits")->getInt("maxgecos", 128);
851         Limits.MaxAway = ConfValue("limits")->getInt("maxaway", 200);
852         InvBypassModes = options->getBool("invitebypassmodes", true);
853
854         range(SoftLimit, 10, ServerInstance->SE->GetMaxFds(), ServerInstance->SE->GetMaxFds(), "<performance:softlimit>");
855         range(MaxConn, 0, SOMAXCONN, SOMAXCONN, "<performance:somaxconn>");
856         range(MaxTargets, 1, 31, 20, "<security:maxtargets>");
857         range(NetBufferSize, 1024, 65534, 10240, "<performance:netbuffersize>");
858         range(MaxWhoResults, 1, 65535, 1024, "<performace:maxwho>");
859         range(WhoWasGroupSize, 0, 10000, 10, "<whowas:groupsize>");
860         range(WhoWasMaxGroups, 0, 1000000, 10240, "<whowas:maxgroups>");
861         range(WhoWasMaxKeep, 3600, INT_MAX, 3600, "<whowas:maxkeep>");
862
863         ValidIP(DNSServer, "<dns:server>");
864         ValidHost(ServerName, "<server:name>");
865         if (!sid.empty() && !ServerInstance->IsSID(sid))
866                 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.");
867
868         for (int i = 0;; ++i)
869         {
870                 ConfigTag* tag = ConfValue("uline", i);
871                 if (!tag)
872                         break;
873                 std::string server;
874                 if (!tag->readString("server", server))
875                         throw CoreException("<uline> tag missing server at " + tag->getTagLocation());
876                 ulines[assign(server)] = tag->getBool("silent");
877         }
878
879         for(int i=0;; ++i)
880         {
881                 ConfigTag* tag = ConfValue("banlist", i);
882                 if (!tag)
883                         break;
884                 std::string chan;
885                 if (!tag->readString("chan", chan))
886                         throw CoreException("<banlist> tag missing chan at " + tag->getTagLocation());
887                 maxbans[chan] = tag->getInt("limit");
888         }
889
890         ReadXLine(this, "badip", "ipmask", ServerInstance->XLines->GetFactory("Z"));
891         ReadXLine(this, "badnick", "nick", ServerInstance->XLines->GetFactory("Q"));
892         ReadXLine(this, "badhost", "host", ServerInstance->XLines->GetFactory("K"));
893         ReadXLine(this, "exception", "host", ServerInstance->XLines->GetFactory("E"));
894
895         memset(DisabledUModes, 0, sizeof(DisabledUModes));
896         for (const unsigned char* p = (const unsigned char*)ConfValue("disabled")->getString("usermodes").c_str(); *p; ++p)
897         {
898                 if (*p < 'A' || *p > ('A' + 64)) throw CoreException(std::string("Invalid usermode ")+(char)*p+" was found.");
899                 DisabledUModes[*p - 'A'] = 1;
900         }
901
902         memset(DisabledCModes, 0, sizeof(DisabledCModes));
903         for (const unsigned char* p = (const unsigned char*)ConfValue("disabled")->getString("chanmodes").c_str(); *p; ++p)
904         {
905                 if (*p < 'A' || *p > ('A' + 64)) throw CoreException(std::string("Invalid chanmode ")+(char)*p+" was found.");
906                 DisabledCModes[*p - 'A'] = 1;
907         }
908
909         memset(HideModeLists, 0, sizeof(HideModeLists));
910         for (const unsigned char* p = (const unsigned char*)ConfValue("security")->getString("hidemodes").c_str(); *p; ++p)
911                 HideModeLists[*p] = true;
912
913         std::string v = security->getString("announceinvites");
914
915         if (v == "ops")
916                 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_OPS;
917         else if (v == "all")
918                 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_ALL;
919         else if (v == "dynamic")
920                 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_DYNAMIC;
921         else
922                 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_NONE;
923
924         Limits.Finalise();
925 }
926
927 /* These tags MUST occur and must ONLY occur once in the config file */
928 static const char* const Once[] = { "server", "admin", "files", "power", "options" };
929
930 // WARNING: it is not safe to use most of the codebase in this function, as it
931 // will run in the config reader thread
932 void ServerConfig::Read()
933 {
934         /* Load and parse the config file, if there are any errors then explode */
935
936         ParseStack stack(this);
937         try
938         {
939                 valid = stack.ParseFile(ServerInstance->ConfigFileName, 0);
940         }
941         catch (CoreException& err)
942         {
943                 valid = false;
944                 errstr << err.GetReason();
945         }
946         if (valid)
947         {
948                 ReadFile(MOTD, ConfValue("files")->getString("motd"));
949                 ReadFile(RULES, ConfValue("files")->getString("rules"));
950                 DNSServer = ConfValue("dns")->getString("server");
951                 FindDNS(DNSServer);
952         }
953 }
954
955 void ServerConfig::Apply(ServerConfig* old, const std::string &useruid)
956 {
957         valid = true;
958
959         /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
960         try
961         {
962                 /* Check we dont have more than one of singular tags, or any of them missing
963                  */
964                 for (int Index = 0; Index * sizeof(*Once) < sizeof(Once); Index++)
965                 {
966                         std::string tag = Once[Index];
967                         if (!ConfValue(tag))
968                                 throw CoreException("You have not defined a <"+tag+"> tag, this is required.");
969                         if (ConfValue(tag, 1))
970                         {
971                                 errstr << "You have more than one <" << tag << "> tag.\n"
972                                         << "First occurrence at " << ConfValue(tag, 0)->getTagLocation()
973                                         << "; second occurrence at " << ConfValue(tag, 1)->getTagLocation() << std::endl;
974                         }
975                 }
976
977                 for (int Index = 0; Index * sizeof(Deprecated) < sizeof(ChangedConfig); Index++)
978                 {
979                         std::string dummy;
980                         if (ConfValue(ChangedConfig[Index].tag)->readString(ChangedConfig[Index].value, dummy, true))
981                                 errstr << "Your configuration contains a deprecated value: <"
982                                         << ChangedConfig[Index].tag << ":" << ChangedConfig[Index].value << "> - " << ChangedConfig[Index].reason
983                                         << " (at " << ConfValue(ChangedConfig[Index].tag)->getTagLocation() << ")\n";
984                 }
985
986                 Fill();
987
988                 // Handle special items
989                 CrossCheckOperClassType();
990                 CrossCheckConnectBlocks(old);
991         }
992         catch (CoreException &ce)
993         {
994                 errstr << ce.GetReason();
995         }
996
997         // write once here, to try it out and make sure its ok
998         ServerInstance->WritePID(this->PID);
999
1000         /*
1001          * These values can only be set on boot. Keep their old values. Do it before we send messages so we actually have a servername.
1002          */
1003         if (old)
1004         {
1005                 this->ServerName = old->ServerName;
1006                 this->sid = old->sid;
1007                 this->argv = old->argv;
1008                 this->argc = old->argc;
1009
1010                 // Same for ports... they're bound later on first run.
1011                 FailedPortList pl;
1012                 ServerInstance->BindPorts(pl);
1013                 if (pl.size())
1014                 {
1015                         errstr << "Not all your client ports could be bound.\nThe following port(s) failed to bind:\n";
1016
1017                         int j = 1;
1018                         for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
1019                         {
1020                                 char buf[MAXBUF];
1021                                 snprintf(buf, MAXBUF, "%d.   Address: %s   Reason: %s\n", j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
1022                                 errstr << buf;
1023                         }
1024                 }
1025         }
1026
1027         User* user = useruid.empty() ? NULL : ServerInstance->FindNick(useruid);
1028
1029         valid = errstr.str().empty();
1030         if (!valid)
1031                 ServerInstance->Logs->Log("CONFIG",DEFAULT, "There were errors in your configuration file:");
1032
1033         while (errstr.good())
1034         {
1035                 std::string line;
1036                 getline(errstr, line, '\n');
1037                 if (!line.empty())
1038                 {
1039                         if (user)
1040                                 user->WriteServ("NOTICE %s :*** %s", user->nick.c_str(), line.c_str());
1041                         else
1042                                 ServerInstance->SNO->WriteGlobalSno('a', line);
1043                 }
1044
1045                 if (!old)
1046                 {
1047                         // Starting up, so print it out so it's seen. XXX this is a bit of a hack.
1048                         printf("%s\n", line.c_str());
1049                 }
1050         }
1051
1052         errstr.clear();
1053         errstr.str(std::string());
1054
1055         /* No old configuration -> initial boot, nothing more to do here */
1056         if (!old)
1057         {
1058                 if (!valid)
1059                 {
1060                         ServerInstance->Exit(EXIT_STATUS_CONFIG);
1061                 }
1062
1063                 if (ConfValue("options")->getBool("allowhalfop"))
1064                         ServerInstance->Modes->AddMode(new ModeChannelHalfOp);
1065
1066                 return;
1067         }
1068
1069         // If there were errors processing configuration, don't touch modules.
1070         if (!valid)
1071                 return;
1072
1073         ApplyModules(user);
1074
1075         if (user)
1076                 user->WriteServ("NOTICE %s :*** Successfully rehashed server.", user->nick.c_str());
1077         ServerInstance->SNO->WriteGlobalSno('a', "*** Successfully rehashed server.");
1078 }
1079
1080 void ServerConfig::ApplyModules(User* user)
1081 {
1082         bool AllowHalfOp = ConfValue("options")->getBool("allowhalfop");
1083         ModeHandler* mh = ServerInstance->Modes->FindMode('h', MODETYPE_CHANNEL);
1084         if (AllowHalfOp && !mh) {
1085                 ServerInstance->Logs->Log("CONFIG", DEFAULT, "Enabling halfop mode.");
1086                 mh = new ModeChannelHalfOp;
1087                 ServerInstance->Modes->AddMode(mh);
1088         } else if (!AllowHalfOp && mh) {
1089                 ServerInstance->Logs->Log("CONFIG", DEFAULT, "Disabling halfop mode.");
1090                 ServerInstance->Modes->DelMode(mh);
1091                 delete mh;
1092         }
1093
1094         Module* whowas = ServerInstance->Modules->Find("cmd_whowas.so");
1095         if (whowas)
1096                 WhowasRequest(NULL, whowas, WhowasRequest::WHOWAS_PRUNE).Send();
1097
1098         const std::vector<std::string> v = ServerInstance->Modules->GetAllModuleNames(0);
1099         std::vector<std::string> added_modules;
1100         std::set<std::string> removed_modules(v.begin(), v.end());
1101
1102         for(int i=0; ; i++)
1103         {
1104                 ConfigTag* tag = ConfValue("module", i);
1105                 if (!tag)
1106                         break;
1107                 std::string name;
1108                 if (tag->readString("name", name))
1109                 {
1110                         // if this module is already loaded, the erase will succeed, so we need do nothing
1111                         // otherwise, we need to add the module (which will be done later)
1112                         if (removed_modules.erase(name) == 0)
1113                                 added_modules.push_back(name);
1114                 }
1115         }
1116
1117         for (std::set<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
1118         {
1119                 // Don't remove cmd_*.so, just remove m_*.so
1120                 if (removing->c_str()[0] == 'c')
1121                         continue;
1122                 Module* m = ServerInstance->Modules->Find(*removing);
1123                 if (m && ServerInstance->Modules->Unload(m))
1124                 {
1125                         ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH UNLOADED MODULE: %s",removing->c_str());
1126
1127                         if (user)
1128                                 user->WriteNumeric(RPL_UNLOADEDMODULE, "%s %s :Module %s successfully unloaded.",user->nick.c_str(), removing->c_str(), removing->c_str());
1129                         else
1130                                 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully unloaded.", removing->c_str());
1131                 }
1132                 else
1133                 {
1134                         if (user)
1135                                 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());
1136                         else
1137                                  ServerInstance->SNO->WriteGlobalSno('a', "Failed to unload module %s: %s", removing->c_str(), ServerInstance->Modules->LastError().c_str());
1138                 }
1139         }
1140
1141         for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
1142         {
1143                 if (ServerInstance->Modules->Load(adding->c_str()))
1144                 {
1145                         ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH LOADED MODULE: %s",adding->c_str());
1146                         if (user)
1147                                 user->WriteNumeric(RPL_LOADEDMODULE, "%s %s :Module %s successfully loaded.",user->nick.c_str(), adding->c_str(), adding->c_str());
1148                         else
1149                                 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully loaded.", adding->c_str());
1150                 }
1151                 else
1152                 {
1153                         if (user)
1154                                 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());
1155                         else
1156                                 ServerInstance->SNO->WriteGlobalSno('a', "Failed to load module %s: %s", adding->c_str(), ServerInstance->Modules->LastError().c_str());
1157                 }
1158         }
1159 }
1160
1161 bool ServerConfig::StartsWithWindowsDriveLetter(const std::string &path)
1162 {
1163         return (path.length() > 2 && isalpha(path[0]) && path[1] == ':');
1164 }
1165
1166 ConfigTag* ServerConfig::ConfValue(const std::string &tag, int offset)
1167 {
1168         ConfigDataHash::size_type pos = offset;
1169         if (pos >= config_data.count(tag))
1170                 return NULL;
1171
1172         ConfigDataHash::iterator iter = config_data.find(tag);
1173
1174         for(int i = 0; i < offset; i++)
1175                 iter++;
1176
1177         return iter->second;
1178 }
1179
1180 bool ConfigTag::readString(const std::string& key, std::string& value, bool allow_lf)
1181 {
1182         if (!this)
1183                 return false;
1184         for(std::vector<KeyVal>::iterator j = items.begin(); j != items.end(); ++j)
1185         {
1186                 if(j->first != key)
1187                         continue;
1188                 value = j->second;
1189                 if (!allow_lf && (value.find('\n') != std::string::npos))
1190                 {
1191                         ServerInstance->Logs->Log("CONFIG",DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
1192                                 " contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
1193                         for (std::string::iterator n = value.begin(); n != value.end(); n++)
1194                                 if (*n == '\n')
1195                                         *n = ' ';
1196                 }
1197                 return true;
1198         }
1199         return false;
1200 }
1201
1202 std::string ConfigTag::getString(const std::string& key, const std::string& def)
1203 {
1204         std::string res = def;
1205         readString(key, res);
1206         return res;
1207 }
1208
1209 long ConfigTag::getInt(const std::string &key, long def)
1210 {
1211         std::string result;
1212         if(!readString(key, result))
1213                 return def;
1214
1215         const char* res_cstr = result.c_str();
1216         char* res_tail = NULL;
1217         long res = strtol(res_cstr, &res_tail, 0);
1218         if (res_tail == res_cstr)
1219                 return def;
1220         switch (toupper(*res_tail))
1221         {
1222                 case 'K':
1223                         res= res* 1024;
1224                         break;
1225                 case 'M':
1226                         res= res* 1024 * 1024;
1227                         break;
1228                 case 'G':
1229                         res= res* 1024 * 1024 * 1024;
1230                         break;
1231         }
1232         return res;
1233 }
1234
1235 double ConfigTag::getFloat(const std::string &key, double def)
1236 {
1237         std::string result;
1238         if (!readString(key, result))
1239                 return def;
1240         return strtod(result.c_str(), NULL);
1241 }
1242
1243 bool ConfigTag::getBool(const std::string &key, bool def)
1244 {
1245         std::string result;
1246         if(!readString(key, result))
1247                 return def;
1248
1249         return (result == "yes" || result == "true" || result == "1" || result == "on");
1250 }
1251
1252 std::string ConfigTag::getTagLocation()
1253 {
1254         return src_name + ":" + ConvToStr(src_line);
1255 }
1256
1257 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1258  */
1259 bool ServerConfig::ReadFile(file_cache &F, const std::string& fname)
1260 {
1261         if (fname.empty())
1262                 return false;
1263
1264         char linebuf[MAXBUF];
1265
1266         F.clear();
1267
1268         FileWrapper file(fopen(fname.c_str(), "r"));
1269
1270         if (!file)
1271                 return false;
1272         while (!feof(file))
1273         {
1274                 if (fgets(linebuf, sizeof(linebuf), file))
1275                         linebuf[strlen(linebuf)-1] = 0;
1276                 else
1277                         *linebuf = 0;
1278
1279                 F.push_back(*linebuf ? linebuf : " ");
1280         }
1281
1282         return true;
1283 }
1284
1285 bool ServerConfig::FileExists(const char* file)
1286 {
1287         struct stat sb;
1288         if (stat(file, &sb) == -1)
1289                 return false;
1290
1291         if ((sb.st_mode & S_IFDIR) > 0)
1292                 return false;
1293
1294         FILE *input = fopen(file, "r");
1295         if (input == NULL)
1296                 return false;
1297         else
1298         {
1299                 fclose(input);
1300                 return true;
1301         }
1302 }
1303
1304 const char* ServerConfig::CleanFilename(const char* name)
1305 {
1306         const char* p = name + strlen(name);
1307         while ((p != name) && (*p != '/') && (*p != '\\')) p--;
1308         return (p != name ? ++p : p);
1309 }
1310
1311 std::string ServerConfig::GetSID()
1312 {
1313         return sid;
1314 }
1315
1316 void ConfigReaderThread::Run()
1317 {
1318         Config = new ServerConfig;
1319         Config->Read();
1320         done = true;
1321 }
1322
1323 void ConfigReaderThread::Finish()
1324 {
1325         ServerConfig* old = ServerInstance->Config;
1326         ServerInstance->Logs->Log("CONFIG",DEBUG,"Switching to new configuration...");
1327         ServerInstance->Logs->CloseLogs();
1328         ServerInstance->Config = this->Config;
1329         ServerInstance->Logs->OpenFileLogs();
1330         Config->Apply(old, TheUserUID);
1331
1332         if (Config->valid)
1333         {
1334                 /*
1335                  * Apply the changed configuration from the rehash.
1336                  *
1337                  * XXX: The order of these is IMPORTANT, do not reorder them without testing
1338                  * thoroughly!!!
1339                  */
1340                 ServerInstance->XLines->CheckELines();
1341                 ServerInstance->XLines->CheckELines();
1342                 ServerInstance->XLines->ApplyLines();
1343                 ServerInstance->Res->Rehash();
1344                 ServerInstance->ResetMaxBans();
1345                 Config->ApplyDisabledCommands(Config->DisabledCommands);
1346                 User* user = TheUserUID.empty() ? ServerInstance->FindNick(TheUserUID) : NULL;
1347                 FOREACH_MOD(I_OnRehash, OnRehash(user));
1348                 ServerInstance->BuildISupport();
1349
1350                 delete old;
1351         }
1352         else
1353         {
1354                 // whoops, abort!
1355                 ServerInstance->Logs->CloseLogs();
1356                 ServerInstance->Config = old;
1357                 ServerInstance->Logs->OpenFileLogs();
1358                 delete this->Config;
1359         }
1360 }