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