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