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