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