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