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