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