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