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