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