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