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