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