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