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