]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/configreader.cpp
Move the definition of the BanCacheHit constructor into the source file from the...
[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 "xline.h"
27 #include "listmode.h"
28 #include "exitcodes.h"
29 #include "configparser.h"
30 #include <iostream>
31
32 ServerConfig::ServerConfig()
33 {
34         RawLog = HideBans = HideSplits = UndernetMsgPrefix = false;
35         WildcardIPv6 = InvBypassModes = true;
36         dns_timeout = 5;
37         MaxTargets = 20;
38         NetBufferSize = 10240;
39         MaxConn = SOMAXCONN;
40         MaxChans = 20;
41         OperMaxChans = 30;
42         c_ipv4_range = 32;
43         c_ipv6_range = 128;
44 }
45
46 static void ValidHost(const std::string& p, const std::string& msg)
47 {
48         int num_dots = 0;
49         if (p.empty() || p[0] == '.')
50                 throw CoreException("The value of "+msg+" is not a valid hostname");
51         for (unsigned int i=0;i < p.length();i++)
52         {
53                 switch (p[i])
54                 {
55                         case ' ':
56                                 throw CoreException("The value of "+msg+" is not a valid hostname");
57                         case '.':
58                                 num_dots++;
59                         break;
60                 }
61         }
62         if (num_dots == 0)
63                 throw CoreException("The value of "+msg+" is not a valid hostname");
64 }
65
66 bool ServerConfig::ApplyDisabledCommands(const std::string& data)
67 {
68         std::stringstream dcmds(data);
69         std::string thiscmd;
70
71         /* Enable everything first */
72         for (Commandtable::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
73                 x->second->Disable(false);
74
75         /* Now disable all the ones which the user wants disabled */
76         while (dcmds >> thiscmd)
77         {
78                 Commandtable::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
79                 if (cm != ServerInstance->Parser->cmdlist.end())
80                 {
81                         cm->second->Disable(true);
82                 }
83         }
84         return true;
85 }
86
87 static void ReadXLine(ServerConfig* conf, const std::string& tag, const std::string& key, XLineFactory* make)
88 {
89         ConfigTagList tags = conf->ConfTags(tag);
90         for(ConfigIter i = tags.first; i != tags.second; ++i)
91         {
92                 ConfigTag* ctag = i->second;
93                 std::string mask;
94                 if (!ctag->readString(key, mask))
95                         throw CoreException("<"+tag+":"+key+"> missing at " + ctag->getTagLocation());
96                 std::string reason = ctag->getString("reason", "<Config>");
97                 XLine* xl = make->Generate(ServerInstance->Time(), 0, "<Config>", reason, mask);
98                 if (!ServerInstance->XLines->AddLine(xl, NULL))
99                         delete xl;
100         }
101 }
102
103 typedef std::map<std::string, ConfigTag*> LocalIndex;
104 void ServerConfig::CrossCheckOperClassType()
105 {
106         LocalIndex operclass;
107         ConfigTagList tags = ConfTags("class");
108         for(ConfigIter i = tags.first; i != tags.second; ++i)
109         {
110                 ConfigTag* tag = i->second;
111                 std::string name = tag->getString("name");
112                 if (name.empty())
113                         throw CoreException("<class:name> missing from tag at " + tag->getTagLocation());
114                 if (operclass.find(name) != operclass.end())
115                         throw CoreException("Duplicate class block with name " + name + " at " + tag->getTagLocation());
116                 operclass[name] = tag;
117         }
118         tags = ConfTags("type");
119         for(ConfigIter i = tags.first; i != tags.second; ++i)
120         {
121                 ConfigTag* tag = i->second;
122                 std::string name = tag->getString("name");
123                 if (name.empty())
124                         throw CoreException("<type:name> is missing from tag at " + tag->getTagLocation());
125                 if (OperTypes.find(name) != OperTypes.end())
126                         throw CoreException("Duplicate type block with name " + name + " at " + tag->getTagLocation());
127
128                 OperInfo* ifo = new OperInfo;
129                 OperTypes[name] = ifo;
130                 ifo->name = name;
131                 ifo->type_block = tag;
132
133                 std::string classname;
134                 irc::spacesepstream str(tag->getString("classes"));
135                 while (str.GetToken(classname))
136                 {
137                         LocalIndex::iterator cls = operclass.find(classname);
138                         if (cls == operclass.end())
139                                 throw CoreException("Oper type " + name + " has missing class " + classname);
140                         ifo->class_blocks.push_back(cls->second);
141                 }
142         }
143
144         tags = ConfTags("oper");
145         for(ConfigIter i = tags.first; i != tags.second; ++i)
146         {
147                 ConfigTag* tag = i->second;
148
149                 std::string name = tag->getString("name");
150                 if (name.empty())
151                         throw CoreException("<oper:name> missing from tag at " + tag->getTagLocation());
152
153                 std::string type = tag->getString("type");
154                 OperIndex::iterator tblk = OperTypes.find(type);
155                 if (tblk == OperTypes.end())
156                         throw CoreException("Oper block " + name + " has missing type " + type);
157                 if (oper_blocks.find(name) != oper_blocks.end())
158                         throw CoreException("Duplicate oper block with name " + name + " at " + tag->getTagLocation());
159
160                 OperInfo* ifo = new OperInfo;
161                 ifo->name = type;
162                 ifo->oper_block = tag;
163                 ifo->type_block = tblk->second->type_block;
164                 ifo->class_blocks.assign(tblk->second->class_blocks.begin(), tblk->second->class_blocks.end());
165                 oper_blocks[name] = ifo;
166         }
167 }
168
169 void ServerConfig::CrossCheckConnectBlocks(ServerConfig* current)
170 {
171         typedef std::map<std::string, ConnectClass*> ClassMap;
172         ClassMap oldBlocksByMask;
173         if (current)
174         {
175                 for(ClassVector::iterator i = current->Classes.begin(); i != current->Classes.end(); ++i)
176                 {
177                         ConnectClass* c = *i;
178                         if (c->name.compare(0, 8, "unnamed-", 8))
179                         {
180                                 oldBlocksByMask["n" + c->name] = c;
181                         }
182                         else if (c->type == CC_ALLOW || c->type == CC_DENY)
183                         {
184                                 std::string typeMask = (c->type == CC_ALLOW) ? "a" : "d";
185                                 typeMask += c->host;
186                                 oldBlocksByMask[typeMask] = c;
187                         }
188                 }
189         }
190
191         int blk_count = config_data.count("connect");
192         if (blk_count == 0)
193         {
194                 // No connect blocks found; make a trivial default block
195                 std::vector<KeyVal>* items;
196                 ConfigTag* tag = ConfigTag::create("connect", "<auto>", 0, items);
197                 items->push_back(std::make_pair("allow", "*"));
198                 config_data.insert(std::make_pair("connect", tag));
199                 blk_count = 1;
200         }
201
202         Classes.resize(blk_count);
203         std::map<std::string, int> names;
204
205         bool try_again = true;
206         for(int tries=0; try_again; tries++)
207         {
208                 try_again = false;
209                 ConfigTagList tags = ConfTags("connect");
210                 int i=0;
211                 for(ConfigIter it = tags.first; it != tags.second; ++it, ++i)
212                 {
213                         ConfigTag* tag = it->second;
214                         if (Classes[i])
215                                 continue;
216
217                         ConnectClass* parent = NULL;
218                         std::string parentName = tag->getString("parent");
219                         if (!parentName.empty())
220                         {
221                                 std::map<std::string,int>::iterator parentIter = names.find(parentName);
222                                 if (parentIter == names.end())
223                                 {
224                                         try_again = true;
225                                         // couldn't find parent this time. If it's the last time, we'll never find it.
226                                         if (tries >= blk_count)
227                                                 throw CoreException("Could not find parent connect class \"" + parentName + "\" for connect block at " + tag->getTagLocation());
228                                         continue;
229                                 }
230                                 parent = Classes[parentIter->second];
231                         }
232
233                         std::string name = tag->getString("name");
234                         std::string mask, typeMask;
235                         char type;
236
237                         if (tag->readString("allow", mask, false))
238                         {
239                                 type = CC_ALLOW;
240                                 typeMask = 'a' + mask;
241                         }
242                         else if (tag->readString("deny", mask, false))
243                         {
244                                 type = CC_DENY;
245                                 typeMask = 'd' + mask;
246                         }
247                         else if (!name.empty())
248                         {
249                                 type = CC_NAMED;
250                                 mask = name;
251                                 typeMask = 'n' + mask;
252                         }
253                         else
254                         {
255                                 throw CoreException("Connect class must have allow, deny, or name specified at " + tag->getTagLocation());
256                         }
257
258                         if (name.empty())
259                         {
260                                 name = "unnamed-" + ConvToStr(i);
261                         }
262                         else
263                         {
264                                 typeMask = 'n' + name;
265                         }
266
267                         if (names.find(name) != names.end())
268                                 throw CoreException("Two connect classes with name \"" + name + "\" defined!");
269                         names[name] = i;
270
271                         ConnectClass* me = parent ?
272                                 new ConnectClass(tag, type, mask, *parent) :
273                                 new ConnectClass(tag, type, mask);
274
275                         me->name = name;
276
277                         me->registration_timeout = tag->getInt("timeout", me->registration_timeout);
278                         me->pingtime = tag->getInt("pingfreq", me->pingtime);
279                         std::string sendq;
280                         if (tag->readString("sendq", sendq))
281                         {
282                                 // attempt to guess a good hard/soft sendq from a single value
283                                 long value = atol(sendq.c_str());
284                                 if (value > 16384)
285                                         me->softsendqmax = value / 16;
286                                 else
287                                         me->softsendqmax = value;
288                                 me->hardsendqmax = value * 8;
289                         }
290                         me->softsendqmax = tag->getInt("softsendq", me->softsendqmax);
291                         me->hardsendqmax = tag->getInt("hardsendq", me->hardsendqmax);
292                         me->recvqmax = tag->getInt("recvq", me->recvqmax);
293                         me->penaltythreshold = tag->getInt("threshold", me->penaltythreshold);
294                         me->commandrate = tag->getInt("commandrate", me->commandrate);
295                         me->fakelag = tag->getBool("fakelag", me->fakelag);
296                         me->maxlocal = tag->getInt("localmax", me->maxlocal);
297                         me->maxglobal = tag->getInt("globalmax", me->maxglobal);
298                         me->maxchans = tag->getInt("maxchans", me->maxchans);
299                         me->maxconnwarn = tag->getBool("maxconnwarn", me->maxconnwarn);
300                         me->limit = tag->getInt("limit", me->limit);
301                         me->resolvehostnames = tag->getBool("resolvehostnames", me->resolvehostnames);
302
303                         ClassMap::iterator oldMask = oldBlocksByMask.find(typeMask);
304                         if (oldMask != oldBlocksByMask.end())
305                         {
306                                 ConnectClass* old = oldMask->second;
307                                 oldBlocksByMask.erase(oldMask);
308                                 old->Update(me);
309                                 delete me;
310                                 me = old;
311                         }
312                         Classes[i] = me;
313                 }
314         }
315 }
316
317 /** Represents a deprecated configuration tag.
318  */
319 struct DeprecatedConfig
320 {
321         /** Tag name. */
322         std::string tag;
323
324         /** Attribute key. */
325         std::string key;
326
327         /** Attribute value. */
328         std::string value;
329
330         /** Reason for deprecation. */
331         std::string reason;
332 };
333
334 static const DeprecatedConfig ChangedConfig[] = {
335         { "bind",        "transport",   "",                 "has been moved to <bind:ssl> as of 2.0" },
336         { "die",         "value",       "",                 "you need to reread your config" },
337         { "gnutls",      "starttls",    "",                 "has been replaced with m_starttls as of 2.2" },
338         { "link",        "autoconnect", "",                 "2.0+ does not use this attribute - define <autoconnect> tags instead" },
339         { "link",        "transport",   "",                 "has been moved to <link:ssl> as of 2.0" },
340         { "module",      "name",        "m_chanprotect.so", "has been replaced with m_customprefix as of 2.2" },
341         { "module",      "name",        "m_halfop.so",      "has been replaced with m_customprefix as of 2.2" },
342         { "options",     "cyclehosts",  "",                 "has been replaced with m_hostcycle as of 2.2" },
343         { "performance", "nouserdns",   "",                 "has been moved to <connect:resolvehostnames> as of 2.2" }
344 };
345
346 void ServerConfig::Fill()
347 {
348         ConfigTag* options = ConfValue("options");
349         ConfigTag* security = ConfValue("security");
350         if (sid.empty())
351         {
352                 ServerName = ConfValue("server")->getString("name", "irc.example.com");
353                 ValidHost(ServerName, "<server:name>");
354
355                 sid = ConfValue("server")->getString("id");
356                 if (!sid.empty() && !InspIRCd::IsSID(sid))
357                         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.");
358         }
359         else
360         {
361                 if (ServerName != ConfValue("server")->getString("name"))
362                         throw CoreException("You must restart to change the server name");
363
364                 std::string nsid = ConfValue("server")->getString("id");
365                 if (!nsid.empty() && nsid != sid)
366                         throw CoreException("You must restart to change the server id");
367         }
368         SoftLimit = ConfValue("performance")->getInt("softlimit", (SocketEngine::GetMaxFds() > 0 ? SocketEngine::GetMaxFds() : LONG_MAX), 10);
369         CCOnConnect = ConfValue("performance")->getBool("clonesonconnect", true);
370         MaxConn = ConfValue("performance")->getInt("somaxconn", SOMAXCONN);
371         XLineMessage = options->getString("xlinemessage", options->getString("moronbanner", "You're banned!"));
372         ServerDesc = ConfValue("server")->getString("description", "Configure Me");
373         Network = ConfValue("server")->getString("network", "Network");
374         NetBufferSize = ConfValue("performance")->getInt("netbuffersize", 10240, 1024, 65534);
375         dns_timeout = ConfValue("dns")->getInt("timeout", 5);
376         DisabledCommands = ConfValue("disabled")->getString("commands", "");
377         DisabledDontExist = ConfValue("disabled")->getBool("fakenonexistant");
378         UserStats = security->getString("userstats");
379         CustomVersion = security->getString("customversion");
380         HideSplits = security->getBool("hidesplits");
381         HideBans = security->getBool("hidebans");
382         HideWhoisServer = security->getString("hidewhois");
383         HideKillsServer = security->getString("hidekills");
384         RestrictBannedUsers = security->getBool("restrictbannedusers", true);
385         GenericOper = security->getBool("genericoper");
386         SyntaxHints = options->getBool("syntaxhints");
387         CycleHostsFromUser = options->getBool("cyclehostsfromuser");
388         UndernetMsgPrefix = options->getBool("ircumsgprefix");
389         FullHostInTopic = options->getBool("hostintopic");
390         MaxTargets = security->getInt("maxtargets", 20, 1, 31);
391         DefaultModes = options->getString("defaultmodes", "not");
392         PID = ConfValue("pid")->getString("file");
393         MaxChans = ConfValue("channels")->getInt("users", 20);
394         OperMaxChans = ConfValue("channels")->getInt("opers");
395         c_ipv4_range = ConfValue("cidr")->getInt("ipv4clone", 32);
396         c_ipv6_range = ConfValue("cidr")->getInt("ipv6clone", 128);
397         Limits.NickMax = ConfValue("limits")->getInt("maxnick", 32);
398         Limits.ChanMax = ConfValue("limits")->getInt("maxchan", 64);
399         Limits.MaxModes = ConfValue("limits")->getInt("maxmodes", 20);
400         Limits.IdentMax = ConfValue("limits")->getInt("maxident", 11);
401         Limits.MaxHost = ConfValue("limits")->getInt("maxhost", 64);
402         Limits.MaxQuit = ConfValue("limits")->getInt("maxquit", 255);
403         Limits.MaxTopic = ConfValue("limits")->getInt("maxtopic", 307);
404         Limits.MaxKick = ConfValue("limits")->getInt("maxkick", 255);
405         Limits.MaxGecos = ConfValue("limits")->getInt("maxgecos", 128);
406         Limits.MaxAway = ConfValue("limits")->getInt("maxaway", 200);
407         Limits.MaxLine = ConfValue("limits")->getInt("maxline", 512);
408         Paths.Config = ConfValue("path")->getString("configdir", INSPIRCD_CONFIG_PATH);
409         Paths.Data = ConfValue("path")->getString("datadir", INSPIRCD_DATA_PATH);
410         Paths.Log = ConfValue("path")->getString("logdir", INSPIRCD_LOG_PATH);
411         Paths.Module = ConfValue("path")->getString("moduledir", INSPIRCD_MODULE_PATH);
412         InvBypassModes = options->getBool("invitebypassmodes", true);
413         NoSnoticeStack = options->getBool("nosnoticestack", false);
414
415         if (Network.find(' ') != std::string::npos)
416                 throw CoreException(Network + " is not a valid network name. A network name must not contain spaces.");
417
418         std::string defbind = options->getString("defaultbind");
419         if (assign(defbind) == "ipv4")
420         {
421                 WildcardIPv6 = false;
422         }
423         else if (assign(defbind) == "ipv6")
424         {
425                 WildcardIPv6 = true;
426         }
427         else
428         {
429                 WildcardIPv6 = true;
430                 int socktest = socket(AF_INET6, SOCK_STREAM, 0);
431                 if (socktest < 0)
432                         WildcardIPv6 = false;
433                 else
434                         SocketEngine::Close(socktest);
435         }
436
437         ReadXLine(this, "badip", "ipmask", ServerInstance->XLines->GetFactory("Z"));
438         ReadXLine(this, "badnick", "nick", ServerInstance->XLines->GetFactory("Q"));
439         ReadXLine(this, "badhost", "host", ServerInstance->XLines->GetFactory("K"));
440         ReadXLine(this, "exception", "host", ServerInstance->XLines->GetFactory("E"));
441
442         memset(DisabledUModes, 0, sizeof(DisabledUModes));
443         std::string modes = ConfValue("disabled")->getString("usermodes");
444         for (std::string::const_iterator p = modes.begin(); p != modes.end(); ++p)
445         {
446                 // Complain when the character is not a-z or A-Z
447                 if ((*p < 'A') || (*p > 'z') || ((*p < 'a') && (*p > 'Z')))
448                         throw CoreException("Invalid usermode " + std::string(1, *p) + " was found.");
449                 DisabledUModes[*p - 'A'] = 1;
450         }
451
452         memset(DisabledCModes, 0, sizeof(DisabledCModes));
453         modes = ConfValue("disabled")->getString("chanmodes");
454         for (std::string::const_iterator p = modes.begin(); p != modes.end(); ++p)
455         {
456                 if ((*p < 'A') || (*p > 'z') || ((*p < 'a') && (*p > 'Z')))
457                         throw CoreException("Invalid chanmode " + std::string(1, *p) + " was found.");
458                 DisabledCModes[*p - 'A'] = 1;
459         }
460
461         memset(HideModeLists, 0, sizeof(HideModeLists));
462         modes = ConfValue("security")->getString("hidemodes");
463         for (std::string::const_iterator p = modes.begin(); p != modes.end(); ++p)
464                 HideModeLists[(unsigned char) *p] = true;
465
466         std::string v = security->getString("announceinvites");
467
468         if (v == "ops")
469                 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_OPS;
470         else if (v == "all")
471                 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_ALL;
472         else if (v == "dynamic")
473                 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_DYNAMIC;
474         else
475                 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_NONE;
476
477         v = security->getString("operspywhois");
478         if (v == "splitmsg")
479                 OperSpyWhois = SPYWHOIS_SPLITMSG;
480         else if (v == "on" || v == "yes")
481                 OperSpyWhois = SPYWHOIS_SINGLEMSG;
482         else
483                 OperSpyWhois = SPYWHOIS_NONE;
484 }
485
486 // WARNING: it is not safe to use most of the codebase in this function, as it
487 // will run in the config reader thread
488 void ServerConfig::Read()
489 {
490         /* Load and parse the config file, if there are any errors then explode */
491
492         ParseStack stack(this);
493         try
494         {
495                 valid = stack.ParseFile(ServerInstance->ConfigFileName, 0);
496         }
497         catch (CoreException& err)
498         {
499                 valid = false;
500                 errstr << err.GetReason() << std::endl;
501         }
502 }
503
504 void ServerConfig::Apply(ServerConfig* old, const std::string &useruid)
505 {
506         valid = true;
507         if (old)
508         {
509                 /*
510                  * These values can only be set on boot. Keep their old values. Do it before we send messages so we actually have a servername.
511                  */
512                 this->ServerName = old->ServerName;
513                 this->sid = old->sid;
514                 this->cmdline = old->cmdline;
515         }
516
517         /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
518         try
519         {
520                 for (int index = 0; index * sizeof(DeprecatedConfig) < sizeof(ChangedConfig); index++)
521                 {
522                         std::string value;
523                         ConfigTagList tags = ConfTags(ChangedConfig[index].tag);
524                         for(ConfigIter i = tags.first; i != tags.second; ++i)
525                         {
526                                 if (i->second->readString(ChangedConfig[index].key, value, true)
527                                         && (ChangedConfig[index].value.empty() || value == ChangedConfig[index].value))
528                                 {
529                                         errstr << "Your configuration contains a deprecated value: <"  << ChangedConfig[index].tag;
530                                         if (ChangedConfig[index].value.empty())
531                                         {
532                                                 errstr << ':' << ChangedConfig[index].key;
533                                         }
534                                         else
535                                         {
536                                                 errstr << ' ' << ChangedConfig[index].key << "=\"" << ChangedConfig[index].value << "\"";
537                                         }
538                                         errstr << "> - " << ChangedConfig[index].reason << " (at " << i->second->getTagLocation() << ")" << std::endl;
539                                 }
540                         }
541                 }
542
543                 Fill();
544
545                 // Handle special items
546                 CrossCheckOperClassType();
547                 CrossCheckConnectBlocks(old);
548         }
549         catch (CoreException &ce)
550         {
551                 errstr << ce.GetReason();
552         }
553
554         // Check errors before dealing with failed binds, since continuing on failed bind is wanted in some circumstances.
555         valid = errstr.str().empty();
556
557         // write once here, to try it out and make sure its ok
558         if (valid)
559                 ServerInstance->WritePID(this->PID);
560
561         ConfigTagList binds = ConfTags("bind");
562         if (binds.first == binds.second)
563                  errstr << "Possible configuration error: you have not defined any <bind> blocks." << std::endl
564                          << "You will need to do this if you want clients to be able to connect!" << std::endl;
565
566         if (old)
567         {
568                 // On first run, ports are bound later on
569                 FailedPortList pl;
570                 ServerInstance->BindPorts(pl);
571                 if (pl.size())
572                 {
573                         errstr << "Not all your client ports could be bound." << std::endl
574                                 << "The following port(s) failed to bind:" << std::endl;
575
576                         int j = 1;
577                         for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
578                         {
579                                 errstr << j << ".\tAddress: " << (i->first.empty() ? "<all>" : i->first.c_str()) << "\tReason: "
580                                         << i->second << std::endl;
581                         }
582                 }
583         }
584
585         User* user = useruid.empty() ? NULL : ServerInstance->FindNick(useruid);
586
587         if (!valid)
588         {
589                 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "There were errors in your configuration file:");
590                 Classes.clear();
591         }
592
593         while (errstr.good())
594         {
595                 std::string line;
596                 getline(errstr, line, '\n');
597                 if (line.empty())
598                         continue;
599                 // On startup, print out to console (still attached at this point)
600                 if (!old)
601                         std::cout << line << std::endl;
602                 // If a user is rehashing, tell them directly
603                 if (user)
604                         user->SendText(":%s NOTICE %s :*** %s", ServerInstance->Config->ServerName.c_str(), user->nick.c_str(), line.c_str());
605                 // Also tell opers
606                 ServerInstance->SNO->WriteGlobalSno('a', line);
607         }
608
609         errstr.clear();
610         errstr.str(std::string());
611
612         // Re-parse our MOTD and RULES files for colors -- Justasic
613         for (ClassVector::const_iterator it = this->Classes.begin(), it_end = this->Classes.end(); it != it_end; ++it)
614         {
615                 ConfigTag *tag = (*it)->config;
616                 // Make sure our connection class allows motd colors
617                 if(!tag->getBool("allowmotdcolors"))
618                       continue;
619
620                 ConfigFileCache::iterator file = this->Files.find(tag->getString("motd", "motd"));
621                 if (file != this->Files.end())
622                       InspIRCd::ProcessColors(file->second);
623         }
624
625         /* No old configuration -> initial boot, nothing more to do here */
626         if (!old)
627         {
628                 if (!valid)
629                 {
630                         ServerInstance->Exit(EXIT_STATUS_CONFIG);
631                 }
632
633                 return;
634         }
635
636
637         // If there were errors processing configuration, don't touch modules.
638         if (!valid)
639                 return;
640
641         ApplyModules(user);
642
643         if (user)
644                 user->SendText(":%s NOTICE %s :*** Successfully rehashed server.",
645                         ServerInstance->Config->ServerName.c_str(), user->nick.c_str());
646         ServerInstance->SNO->WriteGlobalSno('a', "*** Successfully rehashed server.");
647 }
648
649 void ServerConfig::ApplyModules(User* user)
650 {
651         std::vector<std::string> added_modules;
652         ModuleManager::ModuleMap removed_modules = ServerInstance->Modules->GetModules();
653
654         ConfigTagList tags = ConfTags("module");
655         for(ConfigIter i = tags.first; i != tags.second; ++i)
656         {
657                 ConfigTag* tag = i->second;
658                 std::string name;
659                 if (tag->readString("name", name))
660                 {
661                         // if this module is already loaded, the erase will succeed, so we need do nothing
662                         // otherwise, we need to add the module (which will be done later)
663                         if (removed_modules.erase(name) == 0)
664                                 added_modules.push_back(name);
665                 }
666         }
667
668         for (ModuleManager::ModuleMap::iterator i = removed_modules.begin(); i != removed_modules.end(); ++i)
669         {
670                 const std::string& modname = i->first;
671                 // Don't remove core_*.so, just remove m_*.so
672                 if (modname.c_str()[0] == 'c')
673                         continue;
674                 if (ServerInstance->Modules->Unload(i->second))
675                 {
676                         ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH UNLOADED MODULE: %s", modname.c_str());
677
678                         if (user)
679                                 user->WriteNumeric(RPL_UNLOADEDMODULE, "%s :Module %s successfully unloaded.", modname.c_str(), modname.c_str());
680                         else
681                                 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully unloaded.", modname.c_str());
682                 }
683                 else
684                 {
685                         if (user)
686                                 user->WriteNumeric(ERR_CANTUNLOADMODULE, "%s :Failed to unload module %s: %s", modname.c_str(), modname.c_str(), ServerInstance->Modules->LastError().c_str());
687                         else
688                                  ServerInstance->SNO->WriteGlobalSno('a', "Failed to unload module %s: %s", modname.c_str(), ServerInstance->Modules->LastError().c_str());
689                 }
690         }
691
692         for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
693         {
694                 if (ServerInstance->Modules->Load(adding->c_str()))
695                 {
696                         ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH LOADED MODULE: %s",adding->c_str());
697                         if (user)
698                                 user->WriteNumeric(RPL_LOADEDMODULE, "%s :Module %s successfully loaded.", adding->c_str(), adding->c_str());
699                         else
700                                 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully loaded.", adding->c_str());
701                 }
702                 else
703                 {
704                         if (user)
705                                 user->WriteNumeric(ERR_CANTLOADMODULE, "%s :Failed to load module %s: %s", adding->c_str(), adding->c_str(), ServerInstance->Modules->LastError().c_str());
706                         else
707                                 ServerInstance->SNO->WriteGlobalSno('a', "Failed to load module %s: %s", adding->c_str(), ServerInstance->Modules->LastError().c_str());
708                 }
709         }
710 }
711
712 ConfigTag* ServerConfig::ConfValue(const std::string &tag)
713 {
714         ConfigTagList found = config_data.equal_range(tag);
715         if (found.first == found.second)
716                 return NULL;
717         ConfigTag* rv = found.first->second;
718         found.first++;
719         if (found.first != found.second)
720                 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Multiple <" + tag + "> tags found; only first will be used "
721                         "(first at " + rv->getTagLocation() + "; second at " + found.first->second->getTagLocation() + ")");
722         return rv;
723 }
724
725 ConfigTagList ServerConfig::ConfTags(const std::string& tag)
726 {
727         return config_data.equal_range(tag);
728 }
729
730 std::string ServerConfig::Escape(const std::string& str, bool xml)
731 {
732         std::string escaped;
733         for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
734         {
735                 switch (*it)
736                 {
737                         case '"':
738                                 escaped += xml ? "&quot;" : "\"";
739                                 break;
740                         case '&':
741                                 escaped += xml ? "&amp;" : "&";
742                                 break;
743                         case '\\':
744                                 escaped += xml ? "\\" : "\\\\";
745                                 break;
746                         default:
747                                 escaped += *it;
748                                 break;
749                 }
750         }
751         return escaped;
752 }
753
754 void ConfigReaderThread::Run()
755 {
756         Config->Read();
757         done = true;
758 }
759
760 void ConfigReaderThread::Finish()
761 {
762         ServerConfig* old = ServerInstance->Config;
763         ServerInstance->Logs->Log("CONFIG", LOG_DEBUG, "Switching to new configuration...");
764         ServerInstance->Config = this->Config;
765         Config->Apply(old, TheUserUID);
766
767         if (Config->valid)
768         {
769                 /*
770                  * Apply the changed configuration from the rehash.
771                  *
772                  * XXX: The order of these is IMPORTANT, do not reorder them without testing
773                  * thoroughly!!!
774                  */
775                 ServerInstance->XLines->CheckELines();
776                 ServerInstance->XLines->ApplyLines();
777                 ChanModeReference ban(NULL, "ban");
778                 static_cast<ListModeBase*>(*ban)->DoRehash();
779                 Config->ApplyDisabledCommands(Config->DisabledCommands);
780                 User* user = ServerInstance->FindNick(TheUserUID);
781
782                 ConfigStatus status(user);
783                 const ModuleManager::ModuleMap& mods = ServerInstance->Modules->GetModules();
784                 for (ModuleManager::ModuleMap::const_iterator i = mods.begin(); i != mods.end(); ++i)
785                         i->second->ReadConfig(status);
786
787                 ServerInstance->ISupport.Build();
788
789                 ServerInstance->Logs->CloseLogs();
790                 ServerInstance->Logs->OpenFileLogs();
791
792                 if (Config->RawLog && !old->RawLog)
793                         ServerInstance->Users->ServerNoticeAll("*** Raw I/O logging is enabled on this server. All messages, passwords, and commands are being recorded.");
794
795                 Config = old;
796         }
797         else
798         {
799                 // whoops, abort!
800                 ServerInstance->Config = old;
801         }
802 }