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