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