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