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