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