]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/configreader.cpp
Release v2.0.22
[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         HideULineKills = security->getBool("hideulinekills");
535         RestrictBannedUsers = security->getBool("restrictbannedusers", true);
536         GenericOper = security->getBool("genericoper");
537         NoUserDns = ConfValue("performance")->getBool("nouserdns");
538         SyntaxHints = options->getBool("syntaxhints");
539         CycleHosts = options->getBool("cyclehosts");
540         CycleHostsFromUser = options->getBool("cyclehostsfromuser");
541         UndernetMsgPrefix = options->getBool("ircumsgprefix");
542         FullHostInTopic = options->getBool("hostintopic");
543         MaxTargets = security->getInt("maxtargets", 20);
544         DefaultModes = options->getString("defaultmodes", "nt");
545         PID = ConfValue("pid")->getString("file");
546         WhoWasGroupSize = ConfValue("whowas")->getInt("groupsize");
547         WhoWasMaxGroups = ConfValue("whowas")->getInt("maxgroups");
548         WhoWasMaxKeep = ServerInstance->Duration(ConfValue("whowas")->getString("maxkeep"));
549         MaxChans = ConfValue("channels")->getInt("users", 20);
550         OperMaxChans = ConfValue("channels")->getInt("opers", 60);
551         c_ipv4_range = ConfValue("cidr")->getInt("ipv4clone", 32);
552         c_ipv6_range = ConfValue("cidr")->getInt("ipv6clone", 128);
553         Limits.NickMax = ConfValue("limits")->getInt("maxnick", 32);
554         Limits.ChanMax = ConfValue("limits")->getInt("maxchan", 64);
555         Limits.MaxModes = ConfValue("limits")->getInt("maxmodes", 20);
556         Limits.IdentMax = ConfValue("limits")->getInt("maxident", 11);
557         Limits.MaxQuit = ConfValue("limits")->getInt("maxquit", 255);
558         Limits.MaxTopic = ConfValue("limits")->getInt("maxtopic", 307);
559         Limits.MaxKick = ConfValue("limits")->getInt("maxkick", 255);
560         Limits.MaxGecos = ConfValue("limits")->getInt("maxgecos", 128);
561         Limits.MaxAway = ConfValue("limits")->getInt("maxaway", 200);
562         InvBypassModes = options->getBool("invitebypassmodes", true);
563         NoSnoticeStack = options->getBool("nosnoticestack", false);
564         WelcomeNotice = options->getBool("welcomenotice", true);
565
566         range(SoftLimit, 10, ServerInstance->SE->GetMaxFds(), ServerInstance->SE->GetMaxFds(), "<performance:softlimit>");
567         if (ConfValue("performance")->getBool("limitsomaxconn", true))
568                 range(MaxConn, 0, SOMAXCONN, SOMAXCONN, "<performance:somaxconn>");
569         range(MaxTargets, 1, 31, 20, "<security:maxtargets>");
570         range(NetBufferSize, 1024, 65534, 10240, "<performance:netbuffersize>");
571         range(WhoWasGroupSize, 0, 10000, 10, "<whowas:groupsize>");
572         range(WhoWasMaxGroups, 0, 1000000, 10240, "<whowas:maxgroups>");
573         range(WhoWasMaxKeep, 3600, INT_MAX, 3600, "<whowas:maxkeep>");
574
575         ValidIP(DNSServer, "<dns:server>");
576
577         std::string defbind = options->getString("defaultbind");
578         if (assign(defbind) == "ipv4")
579         {
580                 WildcardIPv6 = false;
581         }
582         else if (assign(defbind) == "ipv6")
583         {
584                 WildcardIPv6 = true;
585         }
586         else
587         {
588                 WildcardIPv6 = true;
589                 int socktest = socket(AF_INET6, SOCK_STREAM, 0);
590                 if (socktest < 0)
591                         WildcardIPv6 = false;
592                 else
593                         ServerInstance->SE->Close(socktest);
594         }
595         ConfigTagList tags = ConfTags("uline");
596         for(ConfigIter i = tags.first; i != tags.second; ++i)
597         {
598                 ConfigTag* tag = i->second;
599                 std::string server;
600                 if (!tag->readString("server", server))
601                         throw CoreException("<uline> tag missing server at " + tag->getTagLocation());
602                 ulines[assign(server)] = tag->getBool("silent");
603         }
604
605         tags = ConfTags("banlist");
606         for(ConfigIter i = tags.first; i != tags.second; ++i)
607         {
608                 ConfigTag* tag = i->second;
609                 std::string chan;
610                 if (!tag->readString("chan", chan))
611                         throw CoreException("<banlist> tag missing chan at " + tag->getTagLocation());
612                 maxbans[chan] = tag->getInt("limit");
613         }
614
615         ReadXLine(this, "badip", "ipmask", ServerInstance->XLines->GetFactory("Z"));
616         ReadXLine(this, "badnick", "nick", ServerInstance->XLines->GetFactory("Q"));
617         ReadXLine(this, "badhost", "host", ServerInstance->XLines->GetFactory("K"));
618         ReadXLine(this, "exception", "host", ServerInstance->XLines->GetFactory("E"));
619
620         memset(DisabledUModes, 0, sizeof(DisabledUModes));
621         std::string modes = ConfValue("disabled")->getString("usermodes");
622         for (std::string::const_iterator p = modes.begin(); p != modes.end(); ++p)
623         {
624                 // Complain when the character is not a-z or A-Z
625                 if ((*p < 'A') || (*p > 'z') || ((*p < 'a') && (*p > 'Z')))
626                         throw CoreException("Invalid usermode " + std::string(1, *p) + " was found.");
627                 DisabledUModes[*p - 'A'] = 1;
628         }
629
630         memset(DisabledCModes, 0, sizeof(DisabledCModes));
631         modes = ConfValue("disabled")->getString("chanmodes");
632         for (std::string::const_iterator p = modes.begin(); p != modes.end(); ++p)
633         {
634                 if ((*p < 'A') || (*p > 'z') || ((*p < 'a') && (*p > 'Z')))
635                         throw CoreException("Invalid chanmode " + std::string(1, *p) + " was found.");
636                 DisabledCModes[*p - 'A'] = 1;
637         }
638
639         memset(HideModeLists, 0, sizeof(HideModeLists));
640         modes = ConfValue("security")->getString("hidemodes");
641         for (std::string::const_iterator p = modes.begin(); p != modes.end(); ++p)
642                 HideModeLists[(unsigned char) *p] = true;
643
644         std::string v = security->getString("announceinvites");
645
646         if (v == "ops")
647                 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_OPS;
648         else if (v == "all")
649                 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_ALL;
650         else if (v == "dynamic")
651                 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_DYNAMIC;
652         else
653                 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_NONE;
654
655         v = security->getString("operspywhois");
656         if (v == "splitmsg")
657                 OperSpyWhois = SPYWHOIS_SPLITMSG;
658         else if (v == "on" || v == "yes")
659                 OperSpyWhois = SPYWHOIS_SINGLEMSG;
660         else
661                 OperSpyWhois = SPYWHOIS_NONE;
662 }
663
664 // WARNING: it is not safe to use most of the codebase in this function, as it
665 // will run in the config reader thread
666 void ServerConfig::Read()
667 {
668         /* Load and parse the config file, if there are any errors then explode */
669
670         ParseStack stack(this);
671         try
672         {
673                 valid = stack.ParseFile(ServerInstance->ConfigFileName, 0);
674         }
675         catch (CoreException& err)
676         {
677                 valid = false;
678                 errstr << err.GetReason();
679         }
680         if (valid)
681         {
682                 DNSServer = ConfValue("dns")->getString("server");
683                 FindDNS(DNSServer);
684         }
685 }
686
687 void ServerConfig::Apply(ServerConfig* old, const std::string &useruid)
688 {
689         valid = true;
690         if (old)
691         {
692                 /*
693                  * These values can only be set on boot. Keep their old values. Do it before we send messages so we actually have a servername.
694                  */
695                 this->ServerName = old->ServerName;
696                 this->sid = old->sid;
697                 this->cmdline = old->cmdline;
698         }
699
700         /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
701         try
702         {
703                 for (int Index = 0; Index * sizeof(Deprecated) < sizeof(ChangedConfig); Index++)
704                 {
705                         std::string dummy;
706                         ConfigTagList tags = ConfTags(ChangedConfig[Index].tag);
707                         for(ConfigIter i = tags.first; i != tags.second; ++i)
708                         {
709                                 if (i->second->readString(ChangedConfig[Index].value, dummy, true))
710                                         errstr << "Your configuration contains a deprecated value: <"
711                                                 << ChangedConfig[Index].tag << ":" << ChangedConfig[Index].value << "> - " << ChangedConfig[Index].reason
712                                                 << " (at " << i->second->getTagLocation() << ")\n";
713                         }
714                 }
715
716                 Fill();
717
718                 // Handle special items
719                 CrossCheckOperClassType();
720                 CrossCheckConnectBlocks(old);
721         }
722         catch (CoreException &ce)
723         {
724                 errstr << ce.GetReason();
725         }
726
727         // Check errors before dealing with failed binds, since continuing on failed bind is wanted in some circumstances.
728         valid = errstr.str().empty();
729
730         // write once here, to try it out and make sure its ok
731         if (valid)
732                 ServerInstance->WritePID(this->PID, !old);
733
734         if (old && valid)
735         {
736                 // On first run, ports are bound later on
737                 FailedPortList pl;
738                 ServerInstance->BindPorts(pl);
739                 if (pl.size())
740                 {
741                         errstr << "Not all your client ports could be bound.\nThe following port(s) failed to bind:\n";
742
743                         int j = 1;
744                         for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
745                         {
746                                 char buf[MAXBUF];
747                                 snprintf(buf, MAXBUF, "%d.   Address: %s   Reason: %s\n", j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
748                                 errstr << buf;
749                         }
750                 }
751         }
752
753         User* user = useruid.empty() ? NULL : ServerInstance->FindNick(useruid);
754
755         if (!valid)
756         {
757                 ServerInstance->Logs->Log("CONFIG",DEFAULT, "There were errors in your configuration file:");
758                 Classes.clear();
759         }
760
761         while (errstr.good())
762         {
763                 std::string line;
764                 getline(errstr, line, '\n');
765                 if (line.empty())
766                         continue;
767                 // On startup, print out to console (still attached at this point)
768                 if (!old)
769                         std::cout << line << std::endl;
770                 // If a user is rehashing, tell them directly
771                 if (user)
772                         user->SendText(":%s NOTICE %s :*** %s", ServerInstance->Config->ServerName.c_str(), user->nick.c_str(), line.c_str());
773                 // Also tell opers
774                 ServerInstance->SNO->WriteGlobalSno('a', line);
775         }
776
777         errstr.clear();
778         errstr.str(std::string());
779
780         // Re-parse our MOTD and RULES files for colors -- Justasic
781         for (ClassVector::const_iterator it = this->Classes.begin(), it_end = this->Classes.end(); it != it_end; ++it)
782         {
783                 ConfigTag *tag = (*it)->config;
784                 // Make sure our connection class allows motd colors
785                 if(!tag->getBool("allowmotdcolors"))
786                       continue;
787
788                 ConfigFileCache::iterator file = this->Files.find(tag->getString("motd", "motd"));
789                 if (file != this->Files.end())
790                       InspIRCd::ProcessColors(file->second);
791
792                 file = this->Files.find(tag->getString("rules", "rules"));
793                 if (file != this->Files.end())
794                       InspIRCd::ProcessColors(file->second);
795         }
796
797         /* No old configuration -> initial boot, nothing more to do here */
798         if (!old)
799         {
800                 if (!valid)
801                 {
802                         ServerInstance->Exit(EXIT_STATUS_CONFIG);
803                 }
804
805                 return;
806         }
807
808
809         // If there were errors processing configuration, don't touch modules.
810         if (!valid)
811                 return;
812
813         ApplyModules(user);
814
815         if (user)
816                 user->SendText(":%s NOTICE %s :*** Successfully rehashed server.",
817                         ServerInstance->Config->ServerName.c_str(), user->nick.c_str());
818         ServerInstance->SNO->WriteGlobalSno('a', "*** Successfully rehashed server.");
819 }
820
821 void ServerConfig::ApplyModules(User* user)
822 {
823         Module* whowas = ServerInstance->Modules->Find("cmd_whowas.so");
824         if (whowas)
825                 WhowasRequest(NULL, whowas, WhowasRequest::WHOWAS_PRUNE).Send();
826
827         const std::vector<std::string> v = ServerInstance->Modules->GetAllModuleNames(0);
828         std::vector<std::string> added_modules;
829         std::set<std::string> removed_modules(v.begin(), v.end());
830
831         ConfigTagList tags = ConfTags("module");
832         for(ConfigIter i = tags.first; i != tags.second; ++i)
833         {
834                 ConfigTag* tag = i->second;
835                 std::string name;
836                 if (tag->readString("name", name))
837                 {
838                         // if this module is already loaded, the erase will succeed, so we need do nothing
839                         // otherwise, we need to add the module (which will be done later)
840                         if (removed_modules.erase(name) == 0)
841                                 added_modules.push_back(name);
842                 }
843         }
844
845         if (ConfValue("options")->getBool("allowhalfop") && removed_modules.erase("m_halfop.so") == 0)
846                 added_modules.push_back("m_halfop.so");
847
848         for (std::set<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
849         {
850                 // Don't remove cmd_*.so, just remove m_*.so
851                 if (removing->c_str()[0] == 'c')
852                         continue;
853                 Module* m = ServerInstance->Modules->Find(*removing);
854                 if (m && ServerInstance->Modules->Unload(m))
855                 {
856                         ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH UNLOADED MODULE: %s",removing->c_str());
857
858                         if (user)
859                                 user->WriteNumeric(RPL_UNLOADEDMODULE, "%s %s :Module %s successfully unloaded.",user->nick.c_str(), removing->c_str(), removing->c_str());
860                         else
861                                 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully unloaded.", removing->c_str());
862                 }
863                 else
864                 {
865                         if (user)
866                                 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());
867                         else
868                                  ServerInstance->SNO->WriteGlobalSno('a', "Failed to unload module %s: %s", removing->c_str(), ServerInstance->Modules->LastError().c_str());
869                 }
870         }
871
872         for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
873         {
874                 if (ServerInstance->Modules->Load(adding->c_str()))
875                 {
876                         ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH LOADED MODULE: %s",adding->c_str());
877                         if (user)
878                                 user->WriteNumeric(RPL_LOADEDMODULE, "%s %s :Module %s successfully loaded.",user->nick.c_str(), adding->c_str(), adding->c_str());
879                         else
880                                 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully loaded.", adding->c_str());
881                 }
882                 else
883                 {
884                         if (user)
885                                 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());
886                         else
887                                 ServerInstance->SNO->WriteGlobalSno('a', "Failed to load module %s: %s", adding->c_str(), ServerInstance->Modules->LastError().c_str());
888                 }
889         }
890 }
891
892 bool ServerConfig::StartsWithWindowsDriveLetter(const std::string &path)
893 {
894         return (path.length() > 2 && isalpha(path[0]) && path[1] == ':');
895 }
896
897 ConfigTag* ServerConfig::ConfValue(const std::string &tag)
898 {
899         ConfigTagList found = config_data.equal_range(tag);
900         if (found.first == found.second)
901                 return EmptyTag;
902         ConfigTag* rv = found.first->second;
903         found.first++;
904         if (found.first != found.second)
905                 ServerInstance->Logs->Log("CONFIG",DEFAULT, "Multiple <" + tag + "> tags found; only first will be used "
906                         "(first at " + rv->getTagLocation() + "; second at " + found.first->second->getTagLocation() + ")");
907         return rv;
908 }
909
910 ConfigTagList ServerConfig::ConfTags(const std::string& tag)
911 {
912         return config_data.equal_range(tag);
913 }
914
915 bool ServerConfig::FileExists(const char* file)
916 {
917         struct stat sb;
918         if (stat(file, &sb) == -1)
919                 return false;
920
921         if ((sb.st_mode & S_IFDIR) > 0)
922                 return false;
923
924         FILE *input = fopen(file, "r");
925         if (input == NULL)
926                 return false;
927         else
928         {
929                 fclose(input);
930                 return true;
931         }
932 }
933
934 const char* ServerConfig::CleanFilename(const char* name)
935 {
936         const char* p = name + strlen(name);
937         while ((p != name) && (*p != '/') && (*p != '\\')) p--;
938         return (p != name ? ++p : p);
939 }
940
941 const std::string& ServerConfig::GetSID()
942 {
943         return sid;
944 }
945
946 void ConfigReaderThread::Run()
947 {
948         Config->Read();
949         done = true;
950 }
951
952 void ConfigReaderThread::Finish()
953 {
954         ServerConfig* old = ServerInstance->Config;
955         ServerInstance->Logs->Log("CONFIG",DEBUG,"Switching to new configuration...");
956         ServerInstance->Config = this->Config;
957         Config->Apply(old, TheUserUID);
958
959         if (Config->valid)
960         {
961                 /*
962                  * Apply the changed configuration from the rehash.
963                  *
964                  * XXX: The order of these is IMPORTANT, do not reorder them without testing
965                  * thoroughly!!!
966                  */
967                 ServerInstance->Users->RehashCloneCounts();
968                 ServerInstance->XLines->CheckELines();
969                 ServerInstance->XLines->ApplyLines();
970                 ServerInstance->Res->Rehash();
971                 ServerInstance->ResetMaxBans();
972                 Config->ApplyDisabledCommands(Config->DisabledCommands);
973                 User* user = ServerInstance->FindNick(TheUserUID);
974                 FOREACH_MOD(I_OnRehash, OnRehash(user));
975                 ServerInstance->BuildISupport();
976
977                 ServerInstance->Logs->CloseLogs();
978                 ServerInstance->Logs->OpenFileLogs();
979
980                 if (Config->RawLog && !old->RawLog)
981                         ServerInstance->Users->ServerNoticeAll("*** Raw I/O logging is enabled on this server. All messages, passwords, and commands are being recorded.");
982
983                 Config = old;
984         }
985         else
986         {
987                 // whoops, abort!
988                 ServerInstance->Config = old;
989         }
990 }