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