]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/configreader.cpp
Update copyright headers.
[user/henk/code/inspircd.git] / src / configreader.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2019 Matt Schatz <genius3000@g3k.solutions>
5  *   Copyright (C) 2013-2016 Attila Molnar <attilamolnar@hush.com>
6  *   Copyright (C) 2013-2014, 2016-2021 Sadie Powell <sadie@witchery.services>
7  *   Copyright (C) 2013 Daniel Vassdal <shutter@canternet.org>
8  *   Copyright (C) 2012 Robby <robby@chatbelgie.be>
9  *   Copyright (C) 2012 Justin Crawford <Justasic@Gmail.com>
10  *   Copyright (C) 2012 DjSlash <djslash@djslash.org>
11  *   Copyright (C) 2012 ChrisTX <xpipe@hotmail.de>
12  *   Copyright (C) 2009-2011 Daniel De Graaf <danieldg@inspircd.org>
13  *   Copyright (C) 2009 Uli Schlachter <psychon@inspircd.org>
14  *   Copyright (C) 2008 Thomas Stagner <aquanight@inspircd.org>
15  *   Copyright (C) 2007-2010 Robin Burchell <robin+git@viroteck.net>
16  *   Copyright (C) 2007 Dennis Friis <peavey@inspircd.org>
17  *   Copyright (C) 2006-2008 Craig Edwards <brain@inspircd.org>
18  *   Copyright (C) 2006 Oliver Lupton <om@inspircd.org>
19  *
20  * This file is part of InspIRCd.  InspIRCd is free software: you can
21  * redistribute it and/or modify it under the terms of the GNU General Public
22  * License as published by the Free Software Foundation, version 2.
23  *
24  * This program is distributed in the hope that it will be useful, but WITHOUT
25  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
26  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
27  * details.
28  *
29  * You should have received a copy of the GNU General Public License
30  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
31  */
32
33
34 #include "inspircd.h"
35 #include "xline.h"
36 #include "listmode.h"
37 #include "exitcodes.h"
38 #include "configparser.h"
39 #include <iostream>
40
41 ServerLimits::ServerLimits(ConfigTag* tag)
42         : MaxLine(tag->getUInt("maxline", 512, 512))
43         , NickMax(tag->getUInt("maxnick", 30, 1, MaxLine))
44         , ChanMax(tag->getUInt("maxchan", 64, 1, MaxLine))
45         , MaxModes(tag->getUInt("maxmodes", 20, 1))
46         , IdentMax(tag->getUInt("maxident", 10, 1))
47         , MaxQuit(tag->getUInt("maxquit", 255, 0, MaxLine))
48         , MaxTopic(tag->getUInt("maxtopic", 307, 1, MaxLine))
49         , MaxKick(tag->getUInt("maxkick", 255, 1, MaxLine))
50         , MaxReal(tag->getUInt("maxreal", tag->getUInt("maxgecos", 128), 1, MaxLine))
51         , MaxAway(tag->getUInt("maxaway", 200, 1, MaxLine))
52         , MaxHost(tag->getUInt("maxhost", 64, 1, MaxLine))
53 {
54 }
55
56 ServerConfig::ServerPaths::ServerPaths(ConfigTag* tag)
57         : Config(tag->getString("configdir", INSPIRCD_CONFIG_PATH, 1))
58         , Data(tag->getString("datadir", INSPIRCD_DATA_PATH, 1))
59         , Log(tag->getString("logdir", INSPIRCD_LOG_PATH, 1))
60         , Module(tag->getString("moduledir", INSPIRCD_MODULE_PATH, 1))
61         , Runtime(tag->getString("runtimedir", INSPIRCD_RUNTIME_PATH, 1))
62 {
63 }
64
65 static ConfigTag* CreateEmptyTag()
66 {
67         ConfigItems* items;
68         return ConfigTag::create("empty", "<auto>", 0, items);
69 }
70
71 ServerConfig::ServerConfig()
72         : EmptyTag(CreateEmptyTag())
73         , Limits(EmptyTag)
74         , Paths(EmptyTag)
75         , RawLog(false)
76         , NoSnoticeStack(false)
77 {
78 }
79
80 ServerConfig::~ServerConfig()
81 {
82         delete EmptyTag;
83 }
84
85 static void ReadXLine(ServerConfig* conf, const std::string& tag, const std::string& key, XLineFactory* make)
86 {
87         insp::flat_set<std::string> configlines;
88
89         ConfigTagList tags = conf->ConfTags(tag);
90         for(ConfigIter i = tags.first; i != tags.second; ++i)
91         {
92                 ConfigTag* ctag = i->second;
93
94                 const std::string mask = ctag->getString(key);
95                 if (mask.empty())
96                         throw CoreException("<" + tag + ":" + key + "> missing at " + ctag->getTagLocation());
97
98                 const std::string reason = ctag->getString("reason");
99                 if (reason.empty())
100                         throw CoreException("<" + tag + ":reason> missing at " + ctag->getTagLocation());
101
102                 XLine* xl = make->Generate(ServerInstance->Time(), 0, ServerInstance->Config->ServerName, reason, mask);
103                 xl->from_config = true;
104                 configlines.insert(xl->Displayable());
105                 if (!ServerInstance->XLines->AddLine(xl, NULL))
106                         delete xl;
107         }
108
109         ServerInstance->XLines->ExpireRemovedConfigLines(make->GetType(), configlines);
110 }
111
112 typedef std::map<std::string, ConfigTag*> LocalIndex;
113 void ServerConfig::CrossCheckOperClassType()
114 {
115         LocalIndex operclass;
116         ConfigTagList tags = ConfTags("class");
117         for(ConfigIter i = tags.first; i != tags.second; ++i)
118         {
119                 ConfigTag* tag = i->second;
120                 std::string name = tag->getString("name");
121                 if (name.empty())
122                         throw CoreException("<class:name> missing from tag at " + tag->getTagLocation());
123                 if (operclass.find(name) != operclass.end())
124                         throw CoreException("Duplicate class block with name " + name + " at " + tag->getTagLocation());
125                 operclass[name] = tag;
126         }
127         tags = ConfTags("type");
128         for(ConfigIter i = tags.first; i != tags.second; ++i)
129         {
130                 ConfigTag* tag = i->second;
131                 std::string name = tag->getString("name");
132                 if (name.empty())
133                         throw CoreException("<type:name> is missing from tag at " + tag->getTagLocation());
134                 if (OperTypes.find(name) != OperTypes.end())
135                         throw CoreException("Duplicate type block with name " + name + " at " + tag->getTagLocation());
136
137                 OperInfo* ifo = new OperInfo(name);
138                 OperTypes[name] = ifo;
139                 ifo->type_block = tag;
140
141                 std::string classname;
142                 irc::spacesepstream str(tag->getString("classes"));
143                 while (str.GetToken(classname))
144                 {
145                         LocalIndex::iterator cls = operclass.find(classname);
146                         if (cls == operclass.end())
147                                 throw CoreException("Oper type " + name + " has missing class " + classname);
148                         ifo->class_blocks.push_back(cls->second);
149                 }
150         }
151
152         tags = ConfTags("oper");
153         for(ConfigIter i = tags.first; i != tags.second; ++i)
154         {
155                 ConfigTag* tag = i->second;
156
157                 std::string name = tag->getString("name");
158                 if (name.empty())
159                         throw CoreException("<oper:name> missing from tag at " + tag->getTagLocation());
160
161                 std::string type = tag->getString("type");
162                 OperIndex::iterator tblk = OperTypes.find(type);
163                 if (tblk == OperTypes.end())
164                         throw CoreException("Oper block " + name + " has missing type " + type);
165                 if (oper_blocks.find(name) != oper_blocks.end())
166                         throw CoreException("Duplicate oper block with name " + name + " at " + tag->getTagLocation());
167
168                 OperInfo* ifo = new OperInfo(type);
169                 ifo->oper_block = tag;
170                 ifo->type_block = tblk->second->type_block;
171                 ifo->class_blocks.assign(tblk->second->class_blocks.begin(), tblk->second->class_blocks.end());
172                 oper_blocks[name] = ifo;
173         }
174 }
175
176 void ServerConfig::CrossCheckConnectBlocks(ServerConfig* current)
177 {
178         typedef std::map<std::string, ConnectClass*> ClassMap;
179         ClassMap oldBlocksByMask;
180         if (current)
181         {
182                 for(ClassVector::iterator i = current->Classes.begin(); i != current->Classes.end(); ++i)
183                 {
184                         ConnectClass* c = *i;
185                         if (c->name.compare(0, 8, "unnamed-", 8))
186                         {
187                                 oldBlocksByMask["n" + c->name] = c;
188                         }
189                         else if (c->type == CC_ALLOW || c->type == CC_DENY)
190                         {
191                                 std::string typeMask = (c->type == CC_ALLOW) ? "a" : "d";
192                                 typeMask += c->host;
193                                 oldBlocksByMask[typeMask] = c;
194                         }
195                 }
196         }
197
198         size_t blk_count = config_data.count("connect");
199         if (blk_count == 0)
200         {
201                 // No connect blocks found; make a trivial default block
202                 ConfigItems* items;
203                 ConfigTag* tag = ConfigTag::create("connect", "<auto>", 0, items);
204                 (*items)["allow"] = "*";
205                 config_data.insert(std::make_pair("connect", tag));
206                 blk_count = 1;
207         }
208
209         Classes.resize(blk_count);
210         std::map<std::string, size_t> names;
211
212         bool try_again = true;
213         for(size_t tries = 0; try_again; tries++)
214         {
215                 try_again = false;
216                 ConfigTagList tags = ConfTags("connect");
217                 size_t i = 0;
218                 for(ConfigIter it = tags.first; it != tags.second; ++it, ++i)
219                 {
220                         ConfigTag* tag = it->second;
221                         if (Classes[i])
222                                 continue;
223
224                         ConnectClass* parent = NULL;
225                         std::string parentName = tag->getString("parent");
226                         if (!parentName.empty())
227                         {
228                                 std::map<std::string, size_t>::const_iterator parentIter = names.find(parentName);
229                                 if (parentIter == names.end())
230                                 {
231                                         try_again = true;
232                                         // couldn't find parent this time. If it's the last time, we'll never find it.
233                                         if (tries >= blk_count)
234                                                 throw CoreException("Could not find parent connect class \"" + parentName + "\" for connect block at " + tag->getTagLocation());
235                                         continue;
236                                 }
237                                 parent = Classes[parentIter->second];
238                         }
239
240                         std::string name = tag->getString("name");
241                         std::string mask, typeMask;
242                         char type;
243
244                         if (tag->readString("allow", mask, false))
245                         {
246                                 type = CC_ALLOW;
247                                 typeMask = 'a' + mask;
248                         }
249                         else if (tag->readString("deny", mask, false))
250                         {
251                                 type = CC_DENY;
252                                 typeMask = 'd' + mask;
253                         }
254                         else if (!name.empty())
255                         {
256                                 type = CC_NAMED;
257                                 mask = name;
258                                 typeMask = 'n' + mask;
259                         }
260                         else
261                         {
262                                 throw CoreException("Connect class must have allow, deny, or name specified at " + tag->getTagLocation());
263                         }
264
265                         if (name.empty())
266                         {
267                                 name = "unnamed-" + ConvToStr(i);
268                         }
269                         else
270                         {
271                                 typeMask = 'n' + name;
272                         }
273
274                         if (names.find(name) != names.end())
275                                 throw CoreException("Two connect classes with name \"" + name + "\" defined!");
276                         names[name] = i;
277
278                         ConnectClass* me = parent ?
279                                 new ConnectClass(tag, type, mask, *parent) :
280                                 new ConnectClass(tag, type, mask);
281
282                         me->name = name;
283
284                         me->registration_timeout = tag->getDuration("timeout", me->registration_timeout);
285                         me->pingtime = tag->getDuration("pingfreq", me->pingtime);
286                         std::string sendq;
287                         if (tag->readString("sendq", sendq))
288                         {
289                                 // attempt to guess a good hard/soft sendq from a single value
290                                 unsigned long value = strtoul(sendq.c_str(), NULL, 10);
291                                 if (value > 16384)
292                                         me->softsendqmax = value / 16;
293                                 else
294                                         me->softsendqmax = value;
295                                 me->hardsendqmax = value * 8;
296                         }
297                         me->softsendqmax = tag->getUInt("softsendq", me->softsendqmax);
298                         me->hardsendqmax = tag->getUInt("hardsendq", me->hardsendqmax);
299                         me->recvqmax = tag->getUInt("recvq", me->recvqmax);
300                         me->penaltythreshold = tag->getUInt("threshold", me->penaltythreshold);
301                         me->commandrate = tag->getUInt("commandrate", me->commandrate);
302                         me->fakelag = tag->getBool("fakelag", me->fakelag);
303                         me->maxlocal = tag->getUInt("localmax", me->maxlocal);
304                         me->maxglobal = tag->getUInt("globalmax", me->maxglobal);
305                         me->maxchans = tag->getUInt("maxchans", me->maxchans);
306                         me->maxconnwarn = tag->getBool("maxconnwarn", me->maxconnwarn);
307                         me->limit = tag->getUInt("limit", me->limit);
308                         me->resolvehostnames = tag->getBool("resolvehostnames", me->resolvehostnames);
309                         me->password = tag->getString("password", me->password);
310
311                         me->passwordhash = tag->getString("hash", me->passwordhash);
312                         if (!me->password.empty() && (me->passwordhash.empty() || stdalgo::string::equalsci(me->passwordhash, "plaintext")))
313                         {
314                                 ServerInstance->Logs->Log("CONNECTCLASS", LOG_DEFAULT, "<connect> tag '%s' at %s contains an plain text password, this is insecure!",
315                                         name.c_str(), tag->getTagLocation().c_str());
316                         }
317
318                         std::string ports = tag->getString("port");
319                         if (!ports.empty())
320                         {
321                                 irc::portparser portrange(ports, false);
322                                 while (int port = portrange.GetToken())
323                                         me->ports.insert(port);
324                         }
325
326                         ClassMap::iterator oldMask = oldBlocksByMask.find(typeMask);
327                         if (oldMask != oldBlocksByMask.end())
328                         {
329                                 ConnectClass* old = oldMask->second;
330                                 oldBlocksByMask.erase(oldMask);
331                                 old->Update(me);
332                                 delete me;
333                                 me = old;
334                         }
335                         Classes[i] = me;
336                 }
337         }
338 }
339
340 static std::string GetServerHost()
341 {
342 #ifndef _WIN32
343         char hostname[256];
344         if (gethostname(hostname, sizeof(hostname)) == 0)
345         {
346                 std::string name(hostname);
347                 if (name.find('.') == std::string::npos)
348                         name.push_back('.');
349
350                 if (name.length() <= ServerInstance->Config->Limits.MaxHost && InspIRCd::IsHost(name))
351                         return name;
352         }
353 #endif
354         return "irc.example.com";
355 }
356
357 void ServerConfig::Fill()
358 {
359         ConfigTag* options = ConfValue("options");
360         ConfigTag* security = ConfValue("security");
361         ConfigTag* server = ConfValue("server");
362         if (sid.empty())
363         {
364                 ServerName = server->getString("name", GetServerHost(), InspIRCd::IsHost);
365
366                 sid = server->getString("id");
367                 if (!sid.empty() && !InspIRCd::IsSID(sid))
368                         throw CoreException(sid + " is not a valid server ID. A server ID must be 3 characters long, with the first character a digit and the next two characters a digit or letter.");
369
370                 CaseMapping = options->getString("casemapping", "rfc1459", 1);
371                 if (CaseMapping == "ascii")
372                         national_case_insensitive_map = ascii_case_insensitive_map;
373                 else if (CaseMapping == "rfc1459")
374                         national_case_insensitive_map = rfc_case_insensitive_map;
375                 else
376                         throw CoreException("<options:casemapping> must be set to 'ascii', or 'rfc1459'");
377         }
378         else
379         {
380                 std::string name = server->getString("name");
381                 if (!name.empty() && name != ServerName)
382                         throw CoreException("You must restart to change the server name");
383
384                 std::string nsid = server->getString("id");
385                 if (!nsid.empty() && nsid != sid)
386                         throw CoreException("You must restart to change the server id");
387
388                 std::string casemapping = options->getString("casemapping");
389                 // Ignore this value if CaseMapping is set to something the core doesn't provide (i.e., m_nationalchars).
390                 if (!casemapping.empty() && casemapping != CaseMapping && (CaseMapping == "ascii" || CaseMapping == "rfc1459"))
391                         throw CoreException("You must restart to change the server casemapping");
392
393         }
394         SoftLimit = ConfValue("performance")->getUInt("softlimit", (SocketEngine::GetMaxFds() > 0 ? SocketEngine::GetMaxFds() : LONG_MAX), 10);
395         CCOnConnect = ConfValue("performance")->getBool("clonesonconnect", true);
396         MaxConn = ConfValue("performance")->getUInt("somaxconn", SOMAXCONN);
397         TimeSkipWarn = ConfValue("performance")->getDuration("timeskipwarn", 2, 0, 30);
398         XLineMessage = options->getString("xlinemessage", options->getString("moronbanner", "You're banned!"));
399         ServerDesc = server->getString("description", "Configure Me", 1);
400         Network = server->getString("network", "Network", 1);
401         NetBufferSize = ConfValue("performance")->getInt("netbuffersize", 10240, 1024, 65534);
402         CustomVersion = security->getString("customversion");
403         HideBans = security->getBool("hidebans");
404         HideServer = security->getString("hideserver", security->getString("hidewhois"));
405         SyntaxHints = options->getBool("syntaxhints");
406         FullHostInTopic = options->getBool("hostintopic");
407         MaxTargets = security->getUInt("maxtargets", 20, 1, 31);
408         DefaultModes = options->getString("defaultmodes", "not");
409         PID = ConfValue("pid")->getString("file");
410         MaxChans = ConfValue("channels")->getUInt("users", 20);
411         OperMaxChans = ConfValue("channels")->getUInt("opers", 0);
412         c_ipv4_range = ConfValue("cidr")->getUInt("ipv4clone", 32, 1, 32);
413         c_ipv6_range = ConfValue("cidr")->getUInt("ipv6clone", 128, 1, 128);
414         Limits = ServerLimits(ConfValue("limits"));
415         Paths = ServerPaths(ConfValue("path"));
416         NoSnoticeStack = options->getBool("nosnoticestack", false);
417
418         std::string defbind = options->getString("defaultbind");
419         if (stdalgo::string::equalsci(defbind, "ipv4"))
420         {
421                 WildcardIPv6 = false;
422         }
423         else if (stdalgo::string::equalsci(defbind, "ipv6"))
424         {
425                 WildcardIPv6 = true;
426         }
427         else
428         {
429                 WildcardIPv6 = true;
430                 int socktest = socket(AF_INET6, SOCK_STREAM, 0);
431                 if (socktest < 0)
432                         WildcardIPv6 = false;
433                 else
434                         SocketEngine::Close(socktest);
435         }
436
437         ReadXLine(this, "badip", "ipmask", ServerInstance->XLines->GetFactory("Z"));
438         ReadXLine(this, "badnick", "nick", ServerInstance->XLines->GetFactory("Q"));
439         ReadXLine(this, "badhost", "host", ServerInstance->XLines->GetFactory("K"));
440         ReadXLine(this, "exception", "host", ServerInstance->XLines->GetFactory("E"));
441
442         const std::string restrictbannedusers = options->getString("restrictbannedusers", "yes", 1);
443         if (stdalgo::string::equalsci(restrictbannedusers, "no"))
444                 RestrictBannedUsers = ServerConfig::BUT_NORMAL;
445         else if (stdalgo::string::equalsci(restrictbannedusers, "silent"))
446                 RestrictBannedUsers = ServerConfig::BUT_RESTRICT_SILENT;
447         else if (stdalgo::string::equalsci(restrictbannedusers, "yes"))
448                 RestrictBannedUsers =  ServerConfig::BUT_RESTRICT_NOTIFY;
449         else
450                 throw CoreException(restrictbannedusers + " is an invalid <options:restrictbannedusers> value, at " + options->getTagLocation());
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.empty())
530                 {
531                         errstr << "Warning! Some of your listener" << (pl.size() == 1 ? "s" : "") << " failed to bind:" << std::endl;
532                         for (FailedPortList::const_iterator iter = pl.begin(); iter != pl.end(); ++iter)
533                         {
534                                 const FailedPort& fp = *iter;
535                                 errstr << "  " << fp.sa.str() << ": " << strerror(fp.error) << std::endl
536                                         << "  " << "Created from <bind> tag at " << fp.tag->getTagLocation() << std::endl;
537                         }
538                 }
539         }
540
541         User* user = useruid.empty() ? NULL : ServerInstance->FindUUID(useruid);
542
543         if (!valid)
544         {
545                 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "There were errors in your configuration file:");
546                 Classes.clear();
547         }
548
549         while (errstr.good())
550         {
551                 std::string line;
552                 getline(errstr, line, '\n');
553                 if (line.empty())
554                         continue;
555                 // On startup, print out to console (still attached at this point)
556                 if (!old)
557                         std::cout << line << std::endl;
558                 // If a user is rehashing, tell them directly
559                 if (user)
560                         user->WriteRemoteNotice(InspIRCd::Format("*** %s", line.c_str()));
561                 // Also tell opers
562                 ServerInstance->SNO->WriteGlobalSno('a', line);
563         }
564
565         errstr.clear();
566         errstr.str(std::string());
567
568         /* No old configuration -> initial boot, nothing more to do here */
569         if (!old)
570         {
571                 if (!valid)
572                 {
573                         ServerInstance->Exit(EXIT_STATUS_CONFIG);
574                 }
575
576                 return;
577         }
578
579
580         // If there were errors processing configuration, don't touch modules.
581         if (!valid)
582                 return;
583
584         ApplyModules(user);
585
586         if (user)
587                 user->WriteRemoteNotice("*** Successfully rehashed server.");
588         ServerInstance->SNO->WriteGlobalSno('a', "*** Successfully rehashed server.");
589 }
590
591 void ServerConfig::ApplyModules(User* user)
592 {
593         std::vector<std::string> added_modules;
594         ModuleManager::ModuleMap removed_modules = ServerInstance->Modules->GetModules();
595
596         ConfigTagList tags = ConfTags("module");
597         for(ConfigIter i = tags.first; i != tags.second; ++i)
598         {
599                 ConfigTag* tag = i->second;
600                 std::string name;
601                 if (tag->readString("name", name))
602                 {
603                         name = ModuleManager::ExpandModName(name);
604                         // if this module is already loaded, the erase will succeed, so we need do nothing
605                         // otherwise, we need to add the module (which will be done later)
606                         if (removed_modules.erase(name) == 0)
607                                 added_modules.push_back(name);
608                 }
609         }
610
611         for (ModuleManager::ModuleMap::iterator i = removed_modules.begin(); i != removed_modules.end(); ++i)
612         {
613                 const std::string& modname = i->first;
614                 // Don't remove core_*.so, just remove m_*.so
615                 if (InspIRCd::Match(modname, "core_*.so", ascii_case_insensitive_map))
616                         continue;
617                 if (ServerInstance->Modules->Unload(i->second))
618                 {
619                         ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH UNLOADED MODULE: %s", modname.c_str());
620
621                         if (user)
622                                 user->WriteNumeric(RPL_UNLOADEDMODULE, modname, InspIRCd::Format("Module %s successfully unloaded.", modname.c_str()));
623                         else
624                                 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully unloaded.", modname.c_str());
625                 }
626                 else
627                 {
628                         if (user)
629                                 user->WriteNumeric(ERR_CANTUNLOADMODULE, modname, InspIRCd::Format("Failed to unload module %s: %s", modname.c_str(), ServerInstance->Modules->LastError().c_str()));
630                         else
631                                 ServerInstance->SNO->WriteGlobalSno('a', "Failed to unload module %s: %s", modname.c_str(), ServerInstance->Modules->LastError().c_str());
632                 }
633         }
634
635         for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
636         {
637                 // Skip modules which are already loaded.
638                 if (ServerInstance->Modules->Find(*adding))
639                         continue;
640
641                 if (ServerInstance->Modules->Load(*adding))
642                 {
643                         ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH LOADED MODULE: %s",adding->c_str());
644                         if (user)
645                                 user->WriteNumeric(RPL_LOADEDMODULE, *adding, InspIRCd::Format("Module %s successfully loaded.", adding->c_str()));
646                         else
647                                 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully loaded.", adding->c_str());
648                 }
649                 else
650                 {
651                         if (user)
652                                 user->WriteNumeric(ERR_CANTLOADMODULE, *adding, InspIRCd::Format("Failed to load module %s: %s", adding->c_str(), ServerInstance->Modules->LastError().c_str()));
653                         else
654                                 ServerInstance->SNO->WriteGlobalSno('a', "Failed to load module %s: %s", adding->c_str(), ServerInstance->Modules->LastError().c_str());
655                 }
656         }
657 }
658
659 ConfigTag* ServerConfig::ConfValue(const std::string &tag)
660 {
661         ConfigTagList found = config_data.equal_range(tag);
662         if (found.first == found.second)
663                 return EmptyTag;
664         ConfigTag* rv = found.first->second;
665         found.first++;
666         if (found.first != found.second)
667                 ServerInstance->Logs->Log("CONFIG", LOG_DEFAULT, "Multiple <" + tag + "> tags found; only first will be used "
668                         "(first at " + rv->getTagLocation() + "; second at " + found.first->second->getTagLocation() + ")");
669         return rv;
670 }
671
672 ConfigTagList ServerConfig::ConfTags(const std::string& tag)
673 {
674         return config_data.equal_range(tag);
675 }
676
677 std::string ServerConfig::Escape(const std::string& str, bool xml)
678 {
679         std::string escaped;
680         for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
681         {
682                 switch (*it)
683                 {
684                         case '"':
685                                 escaped += xml ? "&quot;" : "\"";
686                                 break;
687                         case '&':
688                                 escaped += xml ? "&amp;" : "&";
689                                 break;
690                         case '\\':
691                                 escaped += xml ? "\\" : "\\\\";
692                                 break;
693                         default:
694                                 escaped += *it;
695                                 break;
696                 }
697         }
698         return escaped;
699 }
700
701 void ConfigReaderThread::Run()
702 {
703         Config->Read();
704         done = true;
705 }
706
707 void ConfigReaderThread::Finish()
708 {
709         ServerConfig* old = ServerInstance->Config;
710         ServerInstance->Logs->Log("CONFIG", LOG_DEBUG, "Switching to new configuration...");
711         ServerInstance->Config = this->Config;
712         Config->Apply(old, TheUserUID);
713
714         if (Config->valid)
715         {
716                 /*
717                  * Apply the changed configuration from the rehash.
718                  *
719                  * XXX: The order of these is IMPORTANT, do not reorder them without testing
720                  * thoroughly!!!
721                  */
722                 ServerInstance->Users.RehashCloneCounts();
723                 ServerInstance->XLines->CheckELines();
724                 ServerInstance->XLines->ApplyLines();
725                 User* user = ServerInstance->FindUUID(TheUserUID);
726
727                 ConfigStatus status(user);
728                 const ModuleManager::ModuleMap& mods = ServerInstance->Modules->GetModules();
729                 for (ModuleManager::ModuleMap::const_iterator i = mods.begin(); i != mods.end(); ++i)
730                 {
731                         try
732                         {
733                                 ServerInstance->Logs->Log("MODULE", LOG_DEBUG, "Rehashing " + i->first);
734                                 i->second->ReadConfig(status);
735                         }
736                         catch (CoreException& modex)
737                         {
738                                 ServerInstance->Logs->Log("MODULE", LOG_DEFAULT, "Exception caught: " + modex.GetReason());
739                                 if (user)
740                                         user->WriteNotice(i->first + ": " + modex.GetReason());
741                         }
742                 }
743
744                 // The description of this server may have changed - update it for WHOIS etc.
745                 ServerInstance->FakeClient->server->description = Config->ServerDesc;
746
747                 ServerInstance->ISupport.Build();
748
749                 ServerInstance->Logs->CloseLogs();
750                 ServerInstance->Logs->OpenFileLogs();
751
752                 if (Config->RawLog && !old->RawLog)
753                         ServerInstance->Users->ServerNoticeAll("*** Raw I/O logging is enabled on this server. All messages, passwords, and commands are being recorded.");
754
755                 Config = old;
756         }
757         else
758         {
759                 // whoops, abort!
760                 ServerInstance->Config = old;
761         }
762 }