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