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