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