]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/configreader.cpp
Fix undefined behavior caused by referencing the returned buffer by std::string:...
[user/henk/code/inspircd.git] / src / configreader.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2007-2009 Robin Burchell <robin+git@viroteck.net>
6  *   Copyright (C) 2006-2009 Dennis Friis <peavey@inspircd.org>
7  *   Copyright (C) 2006-2008 Craig Edwards <craigedwards@brainbox.cc>
8  *   Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
9  *   Copyright (C) 2006 Oliver Lupton <oliverlupton@gmail.com>
10  *
11  * This file is part of InspIRCd.  InspIRCd is free software: you can
12  * redistribute it and/or modify it under the terms of the GNU General Public
13  * License as published by the Free Software Foundation, version 2.
14  *
15  * This program is distributed in the hope that it will be useful, but WITHOUT
16  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  */
23
24
25 #include "inspircd.h"
26 #include <fstream>
27 #include "xline.h"
28 #include "exitcodes.h"
29 #include "commands/cmd_whowas.h"
30 #include "configparser.h"
31
32 ServerConfig::ServerConfig()
33 {
34         WhoWasGroupSize = WhoWasMaxGroups = WhoWasMaxKeep = 0;
35         RawLog = NoUserDns = HideBans = HideSplits = UndernetMsgPrefix = false;
36         WildcardIPv6 = CycleHosts = InvBypassModes = true;
37         dns_timeout = 5;
38         MaxTargets = 20;
39         NetBufferSize = 10240;
40         SoftLimit = ServerInstance->SE->GetMaxFds();
41         MaxConn = SOMAXCONN;
42         MaxChans = 20;
43         OperMaxChans = 30;
44         c_ipv4_range = 32;
45         c_ipv6_range = 128;
46 }
47
48 void ServerConfig::Update005()
49 {
50         std::stringstream out(data005);
51         std::vector<std::string> data;
52         std::string token;
53         while (out >> token)
54                 data.push_back(token);
55         sort(data.begin(), data.end());
56
57         std::string line5;
58         isupport.clear();
59         for(unsigned int i=0; i < data.size(); i++)
60         {
61                 token = data[i];
62                 line5 = line5 + token + " ";
63                 if (i % 13 == 12)
64                 {
65                         line5.append(":are supported by this server");
66                         isupport.push_back(line5);
67                         line5.clear();
68                 }
69         }
70         if (!line5.empty())
71         {
72                 line5.append(":are supported by this server");
73                 isupport.push_back(line5);
74         }
75 }
76
77 void ServerConfig::Send005(User* user)
78 {
79         for (std::vector<std::string>::iterator line = ServerInstance->Config->isupport.begin(); line != ServerInstance->Config->isupport.end(); line++)
80                 user->WriteNumeric(RPL_ISUPPORT, "%s %s", user->nick.c_str(), line->c_str());
81 }
82
83 template<typename T, typename V>
84 static void range(T& value, V min, V max, V def, const char* msg)
85 {
86         if (value >= (T)min && value <= (T)max)
87                 return;
88         ServerInstance->Logs->Log("CONFIG", DEFAULT,
89                 "WARNING: %s value of %ld is not between %ld and %ld; set to %ld.",
90                 msg, (long)value, (long)min, (long)max, (long)def);
91         value = def;
92 }
93
94
95 static void ValidIP(const std::string& ip, const std::string& key)
96 {
97         irc::sockets::sockaddrs dummy;
98         if (!irc::sockets::aptosa(ip, 0, dummy))
99                 throw CoreException("The value of "+key+" is not an IP address");
100 }
101
102 static void ValidHost(const std::string& p, const std::string& msg)
103 {
104         int num_dots = 0;
105         if (p.empty() || p[0] == '.')
106                 throw CoreException("The value of "+msg+" is not a valid hostname");
107         for (unsigned int i=0;i < p.length();i++)
108         {
109                 switch (p[i])
110                 {
111                         case ' ':
112                                 throw CoreException("The value of "+msg+" is not a valid hostname");
113                         case '.':
114                                 num_dots++;
115                         break;
116                 }
117         }
118         if (num_dots == 0)
119                 throw CoreException("The value of "+msg+" is not a valid hostname");
120 }
121
122 bool ServerConfig::ApplyDisabledCommands(const std::string& data)
123 {
124         std::stringstream dcmds(data);
125         std::string thiscmd;
126
127         /* Enable everything first */
128         for (Commandtable::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
129                 x->second->Disable(false);
130
131         /* Now disable all the ones which the user wants disabled */
132         while (dcmds >> thiscmd)
133         {
134                 Commandtable::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
135                 if (cm != ServerInstance->Parser->cmdlist.end())
136                 {
137                         cm->second->Disable(true);
138                 }
139         }
140         return true;
141 }
142
143 #ifdef WINDOWS
144 // Note: the windows validator is in win32wrapper.cpp
145 void FindDNS(std::string& server);
146 #else
147 static void FindDNS(std::string& server)
148 {
149         if (!server.empty())
150                 return;
151
152         // attempt to look up their nameserver from /etc/resolv.conf
153         ServerInstance->Logs->Log("CONFIG",DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
154
155         std::ifstream resolv("/etc/resolv.conf");
156
157         while (resolv >> server)
158         {
159                 if (server == "nameserver")
160                 {
161                         resolv >> server;
162                         if (server.find_first_not_of("0123456789.") == std::string::npos)
163                         {
164                                 ServerInstance->Logs->Log("CONFIG",DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",server.c_str());
165                                 return;
166                         }
167                 }
168         }
169
170         ServerInstance->Logs->Log("CONFIG",DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
171         server = "127.0.0.1";
172 }
173 #endif
174
175 static void ReadXLine(ServerConfig* conf, const std::string& tag, const std::string& key, XLineFactory* make)
176 {
177         ConfigTagList tags = conf->ConfTags(tag);
178         for(ConfigIter i = tags.first; i != tags.second; ++i)
179         {
180                 ConfigTag* ctag = i->second;
181                 std::string mask;
182                 if (!ctag->readString(key, mask))
183                         throw CoreException("<"+tag+":"+key+"> missing at " + ctag->getTagLocation());
184                 std::string reason = ctag->getString("reason", "<Config>");
185                 XLine* xl = make->Generate(ServerInstance->Time(), 0, "<Config>", reason, mask);
186                 if (!ServerInstance->XLines->AddLine(xl, NULL))
187                         delete xl;
188         }
189 }
190
191 typedef std::map<std::string, ConfigTag*> LocalIndex;
192 void ServerConfig::CrossCheckOperClassType()
193 {
194         LocalIndex operclass;
195         ConfigTagList tags = ConfTags("class");
196         for(ConfigIter i = tags.first; i != tags.second; ++i)
197         {
198                 ConfigTag* tag = i->second;
199                 std::string name = tag->getString("name");
200                 if (name.empty())
201                         throw CoreException("<class:name> missing from tag at " + tag->getTagLocation());
202                 if (operclass.find(name) != operclass.end())
203                         throw CoreException("Duplicate class block with name " + name + " at " + tag->getTagLocation());
204                 operclass[name] = tag;
205         }
206         tags = ConfTags("type");
207         for(ConfigIter i = tags.first; i != tags.second; ++i)
208         {
209                 ConfigTag* tag = i->second;
210                 std::string name = tag->getString("name");
211                 if (name.empty())
212                         throw CoreException("<type:name> is missing from tag at " + tag->getTagLocation());
213                 if (!ServerInstance->IsNick(name.c_str(), Limits.NickMax))
214                         throw CoreException("<type:name> is invalid (value '" + name + "')");
215                 if (oper_blocks.find(" " + name) != oper_blocks.end())
216                         throw CoreException("Duplicate type block with name " + name + " at " + tag->getTagLocation());
217
218                 OperInfo* ifo = new OperInfo;
219                 oper_blocks[" " + name] = ifo;
220                 ifo->name = name;
221                 ifo->type_block = tag;
222
223                 std::string classname;
224                 irc::spacesepstream str(tag->getString("classes"));
225                 while (str.GetToken(classname))
226                 {
227                         LocalIndex::iterator cls = operclass.find(classname);
228                         if (cls == operclass.end())
229                                 throw CoreException("Oper type " + name + " has missing class " + classname);
230                         ifo->class_blocks.push_back(cls->second);
231                 }
232         }
233
234         tags = ConfTags("oper");
235         for(ConfigIter i = tags.first; i != tags.second; ++i)
236         {
237                 ConfigTag* tag = i->second;
238
239                 std::string name = tag->getString("name");
240                 if (name.empty())
241                         throw CoreException("<oper:name> missing from tag at " + tag->getTagLocation());
242
243                 std::string type = tag->getString("type");
244                 OperIndex::iterator tblk = oper_blocks.find(" " + type);
245                 if (tblk == oper_blocks.end())
246                         throw CoreException("Oper block " + name + " has missing type " + type);
247                 if (oper_blocks.find(name) != oper_blocks.end())
248                         throw CoreException("Duplicate oper block with name " + name + " at " + tag->getTagLocation());
249
250                 OperInfo* ifo = new OperInfo;
251                 ifo->name = type;
252                 ifo->oper_block = tag;
253                 ifo->type_block = tblk->second->type_block;
254                 ifo->class_blocks.assign(tblk->second->class_blocks.begin(), tblk->second->class_blocks.end());
255                 oper_blocks[name] = ifo;
256         }
257 }
258
259 void ServerConfig::CrossCheckConnectBlocks(ServerConfig* current)
260 {
261         typedef std::map<std::string, ConnectClass*> ClassMap;
262         ClassMap oldBlocksByMask;
263         if (current)
264         {
265                 for(ClassVector::iterator i = current->Classes.begin(); i != current->Classes.end(); ++i)
266                 {
267                         ConnectClass* c = *i;
268                         if (c->name.substr(0, 8) != "unnamed-")
269                         {
270                                 oldBlocksByMask["n" + c->name] = c;
271                         }
272                         else if (c->type == CC_ALLOW || c->type == CC_DENY)
273                         {
274                                 std::string typeMask = (c->type == CC_ALLOW) ? "a" : "d";
275                                 typeMask += c->host;
276                                 oldBlocksByMask[typeMask] = c;
277                         }
278                 }
279         }
280
281         int blk_count = config_data.count("connect");
282         if (blk_count == 0)
283         {
284                 // No connect blocks found; make a trivial default block
285                 std::vector<KeyVal>* items;
286                 ConfigTag* tag = ConfigTag::create("connect", "<auto>", 0, items);
287                 items->push_back(std::make_pair("allow", "*"));
288                 config_data.insert(std::make_pair("connect", tag));
289                 blk_count = 1;
290         }
291
292         Classes.resize(blk_count);
293         std::map<std::string, int> names;
294
295         bool try_again = true;
296         for(int tries=0; try_again; tries++)
297         {
298                 try_again = false;
299                 ConfigTagList tags = ConfTags("connect");
300                 int i=0;
301                 for(ConfigIter it = tags.first; it != tags.second; ++it, ++i)
302                 {
303                         ConfigTag* tag = it->second;
304                         if (Classes[i])
305                                 continue;
306
307                         ConnectClass* parent = NULL;
308                         std::string parentName = tag->getString("parent");
309                         if (!parentName.empty())
310                         {
311                                 std::map<std::string,int>::iterator parentIter = names.find(parentName);
312                                 if (parentIter == names.end())
313                                 {
314                                         try_again = true;
315                                         // couldn't find parent this time. If it's the last time, we'll never find it.
316                                         if (tries >= blk_count)
317                                                 throw CoreException("Could not find parent connect class \"" + parentName + "\" for connect block at " + tag->getTagLocation());
318                                         continue;
319                                 }
320                                 parent = Classes[parentIter->second];
321                         }
322
323                         std::string name = tag->getString("name");
324                         std::string mask, typeMask;
325                         char type;
326
327                         if (tag->readString("allow", mask, false))
328                         {
329                                 type = CC_ALLOW;
330                                 typeMask = 'a' + mask;
331                         }
332                         else if (tag->readString("deny", mask, false))
333                         {
334                                 type = CC_DENY;
335                                 typeMask = 'd' + mask;
336                         }
337                         else if (!name.empty())
338                         {
339                                 type = CC_NAMED;
340                                 mask = name;
341                                 typeMask = 'n' + mask;
342                         }
343                         else
344                         {
345                                 throw CoreException("Connect class must have allow, deny, or name specified at " + tag->getTagLocation());
346                         }
347
348                         if (name.empty())
349                         {
350                                 name = "unnamed-" + ConvToStr(i);
351                         }
352                         else
353                         {
354                                 typeMask = 'n' + name;
355                         }
356
357                         if (names.find(name) != names.end())
358                                 throw CoreException("Two connect classes with name \"" + name + "\" defined!");
359                         names[name] = i;
360
361                         ConnectClass* me = parent ? 
362                                 new ConnectClass(tag, type, mask, *parent) :
363                                 new ConnectClass(tag, type, mask);
364
365                         me->name = name;
366
367                         me->registration_timeout = tag->getInt("timeout", me->registration_timeout);
368                         me->pingtime = tag->getInt("pingfreq", me->pingtime);
369                         std::string sendq;
370                         if (tag->readString("sendq", sendq))
371                         {
372                                 // attempt to guess a good hard/soft sendq from a single value
373                                 long value = atol(sendq.c_str());
374                                 if (value > 16384)
375                                         me->softsendqmax = value / 16;
376                                 else
377                                         me->softsendqmax = value;
378                                 me->hardsendqmax = value * 8;
379                         }
380                         me->softsendqmax = tag->getInt("softsendq", me->softsendqmax);
381                         me->hardsendqmax = tag->getInt("hardsendq", me->hardsendqmax);
382                         me->recvqmax = tag->getInt("recvq", me->recvqmax);
383                         me->penaltythreshold = tag->getInt("threshold", me->penaltythreshold);
384                         me->commandrate = tag->getInt("commandrate", me->commandrate);
385                         me->fakelag = tag->getBool("fakelag", me->fakelag);
386                         me->maxlocal = tag->getInt("localmax", me->maxlocal);
387                         me->maxglobal = tag->getInt("globalmax", me->maxglobal);
388                         me->maxchans = tag->getInt("maxchans", me->maxchans);
389                         me->maxconnwarn = tag->getBool("maxconnwarn", me->maxconnwarn);
390                         me->limit = tag->getInt("limit", me->limit);
391
392                         ClassMap::iterator oldMask = oldBlocksByMask.find(typeMask);
393                         if (oldMask != oldBlocksByMask.end())
394                         {
395                                 ConnectClass* old = oldMask->second;
396                                 oldBlocksByMask.erase(oldMask);
397                                 old->Update(me);
398                                 delete me;
399                                 me = old;
400                         }
401                         Classes[i] = me;
402                 }
403         }
404 }
405
406 /** Represents a deprecated configuration tag.
407  */
408 struct Deprecated
409 {
410         /** Tag name
411          */
412         const char* tag;
413         /** Tag value
414          */
415         const char* value;
416         /** Reason for deprecation
417          */
418         const char* reason;
419 };
420
421 static const Deprecated ChangedConfig[] = {
422         {"options", "hidelinks",                "has been moved to <security:hidelinks> as of 1.2a3"},
423         {"options", "hidewhois",                "has been moved to <security:hidewhois> as of 1.2a3"},
424         {"options", "userstats",                "has been moved to <security:userstats> as of 1.2a3"},
425         {"options", "customversion",    "has been moved to <security:customversion> as of 1.2a3"},
426         {"options", "hidesplits",               "has been moved to <security:hidesplits> as of 1.2a3"},
427         {"options", "hidebans",         "has been moved to <security:hidebans> as of 1.2a3"},
428         {"options", "hidekills",                "has been moved to <security:hidekills> as of 1.2a3"},
429         {"options", "operspywhois",             "has been moved to <security:operspywhois> as of 1.2a3"},
430         {"options", "announceinvites",  "has been moved to <security:announceinvites> as of 1.2a3"},
431         {"options", "hidemodes",                "has been moved to <security:hidemodes> as of 1.2a3"},
432         {"options", "maxtargets",               "has been moved to <security:maxtargets> as of 1.2a3"},
433         {"options",     "nouserdns",            "has been moved to <performance:nouserdns> as of 1.2a3"},
434         {"options",     "maxwho",               "has been moved to <performance:maxwho> as of 1.2a3"},
435         {"options",     "softlimit",            "has been moved to <performance:softlimit> as of 1.2a3"},
436         {"options", "somaxconn",                "has been moved to <performance:somaxconn> as of 1.2a3"},
437         {"options", "netbuffersize",    "has been moved to <performance:netbuffersize> as of 1.2a3"},
438         {"options", "maxwho",           "has been moved to <performance:maxwho> as of 1.2a3"},
439         {"options",     "loglevel",             "1.2+ does not use the loglevel value. Please define <log> tags instead."},
440         {"die",     "value",            "you need to reread your config"},
441         {"bind",    "transport",                "has been moved to <bind:ssl> as of 2.0a1"},
442         {"link",    "transport",                "has been moved to <link:ssl> as of 2.0a1"},
443         
444 };
445
446 void ServerConfig::Fill()
447 {
448         ConfigTag* options = ConfValue("options");
449         ConfigTag* security = ConfValue("security");
450         if (sid.empty())
451         {
452                 ServerName = ConfValue("server")->getString("name");
453                 sid = ConfValue("server")->getString("id");
454                 ValidHost(ServerName, "<server:name>");
455                 if (!sid.empty() && !ServerInstance->IsSID(sid))
456                         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.");
457         }
458         else
459         {
460                 if (ServerName != ConfValue("server")->getString("name"))
461                         throw CoreException("You must restart to change the server name or SID");
462                 std::string nsid = ConfValue("server")->getString("id");
463                 if (!nsid.empty() && nsid != sid)
464                         throw CoreException("You must restart to change the server name or SID");
465         }
466         diepass = ConfValue("power")->getString("diepass");
467         restartpass = ConfValue("power")->getString("restartpass");
468         powerhash = ConfValue("power")->getString("hash");
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         AdminName = ConfValue("admin")->getString("name", "");
481         AdminEmail = ConfValue("admin")->getString("email", "null@example.com");
482         AdminNick = ConfValue("admin")->getString("nick", "admin");
483         ModPath = ConfValue("path")->getString("moduledir", MOD_PATH);
484         NetBufferSize = ConfValue("performance")->getInt("netbuffersize", 10240);
485         dns_timeout = ConfValue("dns")->getInt("timeout", 5);
486         DisabledCommands = ConfValue("disabled")->getString("commands", "");
487         DisabledDontExist = ConfValue("disabled")->getBool("fakenonexistant");
488         UserStats = security->getString("userstats");
489         CustomVersion = security->getString("customversion", Network + " IRCd");
490         HideSplits = security->getBool("hidesplits");
491         HideBans = security->getBool("hidebans");
492         HideWhoisServer = security->getString("hidewhois");
493         HideKillsServer = security->getString("hidekills");
494         RestrictBannedUsers = security->getBool("restrictbannedusers", true);
495         GenericOper = security->getBool("genericoper");
496         NoUserDns = ConfValue("performance")->getBool("nouserdns");
497         SyntaxHints = options->getBool("syntaxhints");
498         CycleHosts = options->getBool("cyclehosts");
499         CycleHostsFromUser = options->getBool("cyclehostsfromuser");
500         UndernetMsgPrefix = options->getBool("ircumsgprefix");
501         FullHostInTopic = options->getBool("hostintopic");
502         MaxTargets = security->getInt("maxtargets", 20);
503         DefaultModes = options->getString("defaultmodes", "nt");
504         PID = ConfValue("pid")->getString("file");
505         WhoWasGroupSize = ConfValue("whowas")->getInt("groupsize");
506         WhoWasMaxGroups = ConfValue("whowas")->getInt("maxgroups");
507         WhoWasMaxKeep = ServerInstance->Duration(ConfValue("whowas")->getString("maxkeep"));
508         MaxChans = ConfValue("channels")->getInt("users", 20);
509         OperMaxChans = ConfValue("channels")->getInt("opers", 60);
510         c_ipv4_range = ConfValue("cidr")->getInt("ipv4clone", 32);
511         c_ipv6_range = ConfValue("cidr")->getInt("ipv6clone", 128);
512         Limits.NickMax = ConfValue("limits")->getInt("maxnick", 32);
513         Limits.ChanMax = ConfValue("limits")->getInt("maxchan", 64);
514         Limits.MaxModes = ConfValue("limits")->getInt("maxmodes", 20);
515         Limits.IdentMax = ConfValue("limits")->getInt("maxident", 11);
516         Limits.MaxQuit = ConfValue("limits")->getInt("maxquit", 255);
517         Limits.MaxTopic = ConfValue("limits")->getInt("maxtopic", 307);
518         Limits.MaxKick = ConfValue("limits")->getInt("maxkick", 255);
519         Limits.MaxGecos = ConfValue("limits")->getInt("maxgecos", 128);
520         Limits.MaxAway = ConfValue("limits")->getInt("maxaway", 200);
521         InvBypassModes = options->getBool("invitebypassmodes", true);
522         NoSnoticeStack = options->getBool("nosnoticestack", false);
523         WelcomeNotice = options->getBool("welcomenotice", true);
524
525         range(SoftLimit, 10, ServerInstance->SE->GetMaxFds(), ServerInstance->SE->GetMaxFds(), "<performance:softlimit>");
526         range(MaxConn, 0, SOMAXCONN, SOMAXCONN, "<performance:somaxconn>");
527         range(MaxTargets, 1, 31, 20, "<security:maxtargets>");
528         range(NetBufferSize, 1024, 65534, 10240, "<performance:netbuffersize>");
529         range(WhoWasGroupSize, 0, 10000, 10, "<whowas:groupsize>");
530         range(WhoWasMaxGroups, 0, 1000000, 10240, "<whowas:maxgroups>");
531         range(WhoWasMaxKeep, 3600, INT_MAX, 3600, "<whowas:maxkeep>");
532
533         ValidIP(DNSServer, "<dns:server>");
534
535         std::string defbind = options->getString("defaultbind");
536         if (assign(defbind) == "ipv4")
537         {
538                 WildcardIPv6 = false;
539         }
540         else if (assign(defbind) == "ipv6")
541         {
542                 WildcardIPv6 = true;
543         }
544         else
545         {
546                 WildcardIPv6 = true;
547                 int socktest = socket(AF_INET6, SOCK_STREAM, 0);
548                 if (socktest < 0)
549                         WildcardIPv6 = false;
550                 else
551                         ServerInstance->SE->Close(socktest);
552         }
553         ConfigTagList tags = ConfTags("uline");
554         for(ConfigIter i = tags.first; i != tags.second; ++i)
555         {
556                 ConfigTag* tag = i->second;
557                 std::string server;
558                 if (!tag->readString("server", server))
559                         throw CoreException("<uline> tag missing server at " + tag->getTagLocation());
560                 ulines[assign(server)] = tag->getBool("silent");
561         }
562
563         tags = ConfTags("banlist");
564         for(ConfigIter i = tags.first; i != tags.second; ++i)
565         {
566                 ConfigTag* tag = i->second;
567                 std::string chan;
568                 if (!tag->readString("chan", chan))
569                         throw CoreException("<banlist> tag missing chan at " + tag->getTagLocation());
570                 maxbans[chan] = tag->getInt("limit");
571         }
572
573         ReadXLine(this, "badip", "ipmask", ServerInstance->XLines->GetFactory("Z"));
574         ReadXLine(this, "badnick", "nick", ServerInstance->XLines->GetFactory("Q"));
575         ReadXLine(this, "badhost", "host", ServerInstance->XLines->GetFactory("K"));
576         ReadXLine(this, "exception", "host", ServerInstance->XLines->GetFactory("E"));
577
578         memset(DisabledUModes, 0, sizeof(DisabledUModes));
579         std::string modes = ConfValue("disabled")->getString("usermodes");
580         for (std::string::const_iterator p = modes.begin(); p != modes.end(); ++p)
581         {
582                 if (*p < 'A' || *p > ('A' + 64)) throw CoreException(std::string("Invalid usermode ")+(char)*p+" was found.");
583                 DisabledUModes[*p - 'A'] = 1;
584         }
585
586         memset(DisabledCModes, 0, sizeof(DisabledCModes));
587         modes = ConfValue("disabled")->getString("chanmodes");
588         for (std::string::const_iterator p = modes.begin(); p != modes.end(); ++p)
589         {
590                 if (*p < 'A' || *p > ('A' + 64)) throw CoreException(std::string("Invalid chanmode ")+(char)*p+" was found.");
591                 DisabledCModes[*p - 'A'] = 1;
592         }
593
594         memset(HideModeLists, 0, sizeof(HideModeLists));
595         modes = ConfValue("security")->getString("hidemodes");
596         for (std::string::const_iterator p = modes.begin(); p != modes.end(); ++p)
597                 HideModeLists[(unsigned char) *p] = true;
598
599         std::string v = security->getString("announceinvites");
600
601         if (v == "ops")
602                 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_OPS;
603         else if (v == "all")
604                 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_ALL;
605         else if (v == "dynamic")
606                 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_DYNAMIC;
607         else
608                 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_NONE;
609
610         v = security->getString("operspywhois");
611         if (v == "splitmsg")
612                 OperSpyWhois = SPYWHOIS_SPLITMSG;
613         else if (v == "on" || v == "yes")
614                 OperSpyWhois = SPYWHOIS_SINGLEMSG;
615         else
616                 OperSpyWhois = SPYWHOIS_NONE;
617
618         Limits.Finalise();
619 }
620
621 // WARNING: it is not safe to use most of the codebase in this function, as it
622 // will run in the config reader thread
623 void ServerConfig::Read()
624 {
625         /* Load and parse the config file, if there are any errors then explode */
626
627         ParseStack stack(this);
628         try
629         {
630                 valid = stack.ParseFile(ServerInstance->ConfigFileName, 0);
631         }
632         catch (CoreException& err)
633         {
634                 valid = false;
635                 errstr << err.GetReason();
636         }
637         if (valid)
638         {
639                 DNSServer = ConfValue("dns")->getString("server");
640                 FindDNS(DNSServer);
641         }
642 }
643
644 void ServerConfig::Apply(ServerConfig* old, const std::string &useruid)
645 {
646         valid = true;
647         if (old)
648         {
649                 /*
650                  * These values can only be set on boot. Keep their old values. Do it before we send messages so we actually have a servername.
651                  */
652                 this->ServerName = old->ServerName;
653                 this->sid = old->sid;
654                 this->cmdline = old->cmdline;
655         }
656
657         /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
658         try
659         {
660                 for (int Index = 0; Index * sizeof(Deprecated) < sizeof(ChangedConfig); Index++)
661                 {
662                         std::string dummy;
663                         ConfigTagList tags = ConfTags(ChangedConfig[Index].tag);
664                         for(ConfigIter i = tags.first; i != tags.second; ++i)
665                         {
666                                 if (i->second->readString(ChangedConfig[Index].value, dummy, true))
667                                         errstr << "Your configuration contains a deprecated value: <"
668                                                 << ChangedConfig[Index].tag << ":" << ChangedConfig[Index].value << "> - " << ChangedConfig[Index].reason
669                                                 << " (at " << i->second->getTagLocation() << ")\n";
670                         }
671                 }
672
673                 Fill();
674
675                 // Handle special items
676                 CrossCheckOperClassType();
677                 CrossCheckConnectBlocks(old);
678         }
679         catch (CoreException &ce)
680         {
681                 errstr << ce.GetReason();
682         }
683
684         // Check errors before dealing with failed binds, since continuing on failed bind is wanted in some circumstances.
685         valid = errstr.str().empty();
686
687         // write once here, to try it out and make sure its ok
688         if (valid)
689                 ServerInstance->WritePID(this->PID);
690
691         if (old)
692         {
693                 // On first run, ports are bound later on
694                 FailedPortList pl;
695                 ServerInstance->BindPorts(pl);
696                 if (pl.size())
697                 {
698                         errstr << "Not all your client ports could be bound.\nThe following port(s) failed to bind:\n";
699
700                         int j = 1;
701                         for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
702                         {
703                                 char buf[MAXBUF];
704                                 snprintf(buf, MAXBUF, "%d.   Address: %s   Reason: %s\n", j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
705                                 errstr << buf;
706                         }
707                 }
708         }
709
710         User* user = useruid.empty() ? NULL : ServerInstance->FindNick(useruid);
711
712         if (!valid)
713                 ServerInstance->Logs->Log("CONFIG",DEFAULT, "There were errors in your configuration file:");
714
715         while (errstr.good())
716         {
717                 std::string line;
718                 getline(errstr, line, '\n');
719                 if (line.empty())
720                         continue;
721                 // On startup, print out to console (still attached at this point)
722                 if (!old)
723                         printf("%s\n", line.c_str());
724                 // If a user is rehashing, tell them directly
725                 if (user)
726                         user->SendText(":%s NOTICE %s :*** %s", ServerInstance->Config->ServerName.c_str(), user->nick.c_str(), line.c_str());
727                 // Also tell opers
728                 ServerInstance->SNO->WriteGlobalSno('a', line);
729         }
730
731         errstr.clear();
732         errstr.str(std::string());
733
734         // Re-parse our MOTD and RULES files for colors -- Justasic
735         for (ClassVector::const_iterator it = this->Classes.begin(), it_end = this->Classes.end(); it != it_end; ++it)
736         {
737                 ConfigTag *tag = (*it)->config;
738                 // Make sure our connection class allows motd colors
739                 if(!tag->getBool("allowmotdcolors"))
740                       continue;
741
742                 ConfigFileCache::iterator motdfile = this->Files.find(tag->getString("motd", "motd"));
743                 ConfigFileCache::iterator rulesfile = this->Files.find(tag->getString("rules", "rules"));
744
745                 if(motdfile != this->Files.end())
746                       this->ProcessColors(motdfile);
747
748                 if(rulesfile != this->Files.end())
749                       this->ProcessColors(rulesfile);
750         }
751
752         /* No old configuration -> initial boot, nothing more to do here */
753         if (!old)
754         {
755                 if (!valid)
756                 {
757                         ServerInstance->Exit(EXIT_STATUS_CONFIG);
758                 }
759
760                 return;
761         }
762
763
764         // If there were errors processing configuration, don't touch modules.
765         if (!valid)
766                 return;
767
768         ApplyModules(user);
769
770         if (user)
771                 user->SendText(":%s NOTICE %s :*** Successfully rehashed server.",
772                         ServerInstance->Config->ServerName.c_str(), user->nick.c_str());
773         ServerInstance->SNO->WriteGlobalSno('a', "*** Successfully rehashed server.");
774 }
775
776 void ServerConfig::ApplyModules(User* user)
777 {
778         Module* whowas = ServerInstance->Modules->Find("cmd_whowas.so");
779         if (whowas)
780                 WhowasRequest(NULL, whowas, WhowasRequest::WHOWAS_PRUNE).Send();
781
782         const std::vector<std::string> v = ServerInstance->Modules->GetAllModuleNames(0);
783         std::vector<std::string> added_modules;
784         std::set<std::string> removed_modules(v.begin(), v.end());
785
786         ConfigTagList tags = ConfTags("module");
787         for(ConfigIter i = tags.first; i != tags.second; ++i)
788         {
789                 ConfigTag* tag = i->second;
790                 std::string name;
791                 if (tag->readString("name", name))
792                 {
793                         // if this module is already loaded, the erase will succeed, so we need do nothing
794                         // otherwise, we need to add the module (which will be done later)
795                         if (removed_modules.erase(name) == 0)
796                                 added_modules.push_back(name);
797                 }
798         }
799
800         if (ConfValue("options")->getBool("allowhalfop") && removed_modules.erase("m_halfop.so") == 0)
801                 added_modules.push_back("m_halfop.so");
802
803         for (std::set<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
804         {
805                 // Don't remove cmd_*.so, just remove m_*.so
806                 if (removing->c_str()[0] == 'c')
807                         continue;
808                 Module* m = ServerInstance->Modules->Find(*removing);
809                 if (m && ServerInstance->Modules->Unload(m))
810                 {
811                         ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH UNLOADED MODULE: %s",removing->c_str());
812
813                         if (user)
814                                 user->WriteNumeric(RPL_UNLOADEDMODULE, "%s %s :Module %s successfully unloaded.",user->nick.c_str(), removing->c_str(), removing->c_str());
815                         else
816                                 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully unloaded.", removing->c_str());
817                 }
818                 else
819                 {
820                         if (user)
821                                 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());
822                         else
823                                  ServerInstance->SNO->WriteGlobalSno('a', "Failed to unload module %s: %s", removing->c_str(), ServerInstance->Modules->LastError().c_str());
824                 }
825         }
826
827         for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
828         {
829                 if (ServerInstance->Modules->Load(adding->c_str()))
830                 {
831                         ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH LOADED MODULE: %s",adding->c_str());
832                         if (user)
833                                 user->WriteNumeric(RPL_LOADEDMODULE, "%s %s :Module %s successfully loaded.",user->nick.c_str(), adding->c_str(), adding->c_str());
834                         else
835                                 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully loaded.", adding->c_str());
836                 }
837                 else
838                 {
839                         if (user)
840                                 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());
841                         else
842                                 ServerInstance->SNO->WriteGlobalSno('a', "Failed to load module %s: %s", adding->c_str(), ServerInstance->Modules->LastError().c_str());
843                 }
844         }
845 }
846
847 bool ServerConfig::StartsWithWindowsDriveLetter(const std::string &path)
848 {
849         return (path.length() > 2 && isalpha(path[0]) && path[1] == ':');
850 }
851
852 ConfigTag* ServerConfig::ConfValue(const std::string &tag)
853 {
854         ConfigTagList found = config_data.equal_range(tag);
855         if (found.first == found.second)
856                 return NULL;
857         ConfigTag* rv = found.first->second;
858         found.first++;
859         if (found.first != found.second)
860                 ServerInstance->Logs->Log("CONFIG",DEFAULT, "Multiple <" + tag + "> tags found; only first will be used "
861                         "(first at " + rv->getTagLocation() + "; second at " + found.first->second->getTagLocation() + ")");
862         return rv;
863 }
864
865 ConfigTagList ServerConfig::ConfTags(const std::string& tag)
866 {
867         return config_data.equal_range(tag);
868 }
869
870 /*
871  * Replace all color codes from the special[] array to actual
872  * color code chars using C++ style escape sequences. You
873  * can append other chars to replace if you like -- Justasic
874  */
875 void ServerConfig::ProcessColors(ConfigFileCache::iterator &file)
876 {
877         static struct special_chars
878         {
879                 std::string character;
880                 std::string replace;
881                 special_chars(const std::string &c, const std::string &r) : character(c), replace(r) { }
882         }
883
884         special[] = {
885                 special_chars("\\002", "\002"),  // Bold
886                 special_chars("\\037", "\037"),  // underline
887                 special_chars("\\003", "\003"),  // Color
888                 special_chars("\\017", "\017"), // Stop colors
889                 special_chars("\\u", "\037"),    // Alias for underline
890                 special_chars("\\b", "\002"),    // Alias for Bold
891                 special_chars("\\x", "\017"),    // Alias for stop
892                 special_chars("\\c", "\003"),    // Alias for color
893                 special_chars("", "")
894         };
895
896         for(file_cache::iterator it = file->second.begin(), it_end = file->second.end(); it != it_end; it++)
897         {
898                 std::string ret = *it;
899                 for(int i = 0; special[i].character.empty() == false; ++i)
900                 {
901                         std::string::size_type pos = ret.find(special[i].character);
902                         if(pos == std::string::npos) // Couldn't find the character, skip this line
903                                 continue;
904                         
905                         if((pos > 0) && (ret[pos-1] == '\\') && (ret[pos] == '\\'))
906                                 continue; // Skip double slashes.
907
908                         // Replace all our characters in the array
909                         while(pos != std::string::npos)
910                         {
911                                 ret = ret.substr(0, pos) + special[i].replace + ret.substr(pos + special[i].character.size());
912                                 pos = ret.find(special[i].character, pos + special[i].replace.size());
913                         }
914                 }
915
916                 // Replace double slashes with a single slash before we return
917                 std::string::size_type pos = ret.find("\\\\");
918                 while(pos != std::string::npos)
919                 {
920                         ret = ret.substr(0, pos) + "\\" + ret.substr(pos + 2);
921                         pos = ret.find("\\\\", pos + 1);
922                 }
923                 *it = ret;
924         }
925 }
926
927 bool ServerConfig::FileExists(const char* file)
928 {
929         struct stat sb;
930         if (stat(file, &sb) == -1)
931                 return false;
932
933         if ((sb.st_mode & S_IFDIR) > 0)
934                 return false;
935
936         FILE *input = fopen(file, "r");
937         if (input == NULL)
938                 return false;
939         else
940         {
941                 fclose(input);
942                 return true;
943         }
944 }
945
946 const char* ServerConfig::CleanFilename(const char* name)
947 {
948         const char* p = name + strlen(name);
949         while ((p != name) && (*p != '/') && (*p != '\\')) p--;
950         return (p != name ? ++p : p);
951 }
952
953 std::string ServerConfig::GetSID()
954 {
955         return sid;
956 }
957
958 void ConfigReaderThread::Run()
959 {
960         Config->Read();
961         done = true;
962 }
963
964 void ConfigReaderThread::Finish()
965 {
966         ServerConfig* old = ServerInstance->Config;
967         ServerInstance->Logs->Log("CONFIG",DEBUG,"Switching to new configuration...");
968         ServerInstance->Config = this->Config;
969         Config->Apply(old, TheUserUID);
970
971         if (Config->valid)
972         {
973                 /*
974                  * Apply the changed configuration from the rehash.
975                  *
976                  * XXX: The order of these is IMPORTANT, do not reorder them without testing
977                  * thoroughly!!!
978                  */
979                 ServerInstance->XLines->CheckELines();
980                 ServerInstance->XLines->ApplyLines();
981                 ServerInstance->Res->Rehash();
982                 ServerInstance->ResetMaxBans();
983                 Config->ApplyDisabledCommands(Config->DisabledCommands);
984                 User* user = ServerInstance->FindNick(TheUserUID);
985                 FOREACH_MOD(I_OnRehash, OnRehash(user));
986                 ServerInstance->BuildISupport();
987
988                 ServerInstance->Logs->CloseLogs();
989                 ServerInstance->Logs->OpenFileLogs();
990
991                 if (Config->RawLog && !old->RawLog)
992                         ServerInstance->Users->ServerNoticeAll("*** Raw I/O logging is enabled on this server. All messages, passwords, and commands are being recorded.");
993
994                 Config = old;
995         }
996         else
997         {
998                 // whoops, abort!
999                 ServerInstance->Config = old;
1000         }
1001 }