2 * InspIRCd -- Internet Relay Chat Daemon
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>
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.
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
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/>.
28 #include "exitcodes.h"
29 #include "commands/cmd_whowas.h"
30 #include "configparser.h"
34 #pragma comment(lib, "Iphlpapi.lib")
37 ServerConfig::ServerConfig()
38 : NoSnoticeStack(false)
40 WhoWasGroupSize = WhoWasMaxGroups = WhoWasMaxKeep = 0;
41 RawLog = NoUserDns = HideBans = HideSplits = UndernetMsgPrefix = false;
42 WildcardIPv6 = CycleHosts = InvBypassModes = true;
45 NetBufferSize = 10240;
46 SoftLimit = ServerInstance->SE->GetMaxFds();
53 std::vector<KeyVal>* items;
54 EmptyTag = ConfigTag::create("empty", "<auto>", 0, items);
57 ServerConfig::~ServerConfig()
62 void ServerConfig::Update005()
64 std::stringstream out(data005);
65 std::vector<std::string> data;
68 data.push_back(token);
69 sort(data.begin(), data.end());
73 for(unsigned int i=0; i < data.size(); i++)
76 line5 = line5 + token + " ";
79 line5.append(":are supported by this server");
80 isupport.push_back(line5);
86 line5.append(":are supported by this server");
87 isupport.push_back(line5);
91 void ServerConfig::Send005(User* user)
93 for (std::vector<std::string>::iterator line = ServerInstance->Config->isupport.begin(); line != ServerInstance->Config->isupport.end(); line++)
94 user->WriteNumeric(RPL_ISUPPORT, "%s %s", user->nick.c_str(), line->c_str());
97 template<typename T, typename V>
98 static void range(T& value, V min, V max, V def, const char* msg)
100 if (value >= (T)min && value <= (T)max)
102 ServerInstance->Logs->Log("CONFIG", DEFAULT,
103 "WARNING: %s value of %ld is not between %ld and %ld; set to %ld.",
104 msg, (long)value, (long)min, (long)max, (long)def);
109 static void ValidIP(const std::string& ip, const std::string& key)
111 irc::sockets::sockaddrs dummy;
112 if (!irc::sockets::aptosa(ip, 0, dummy))
113 throw CoreException("The value of "+key+" is not an IP address");
116 static void ValidHost(const std::string& p, const std::string& msg)
119 if (p.empty() || p[0] == '.')
120 throw CoreException("The value of "+msg+" is not a valid hostname");
121 for (unsigned int i=0;i < p.length();i++)
126 throw CoreException("The value of "+msg+" is not a valid hostname");
133 throw CoreException("The value of "+msg+" is not a valid hostname");
136 bool ServerConfig::ApplyDisabledCommands(const std::string& data)
138 std::stringstream dcmds(data);
141 /* Enable everything first */
142 for (Commandtable::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
143 x->second->Disable(false);
145 /* Now disable all the ones which the user wants disabled */
146 while (dcmds >> thiscmd)
148 Commandtable::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
149 if (cm != ServerInstance->Parser->cmdlist.end())
151 cm->second->Disable(true);
157 static void FindDNS(std::string& server)
162 // attempt to look up their nameserver from the system
163 ServerInstance->Logs->Log("CONFIG",DEFAULT,"WARNING: <dns:server> not defined, attempting to find a working server in the system settings...");
165 PFIXED_INFO pFixedInfo;
166 DWORD dwBufferSize = sizeof(FIXED_INFO);
167 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, sizeof(FIXED_INFO));
171 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == ERROR_BUFFER_OVERFLOW) {
172 HeapFree(GetProcessHeap(), 0, pFixedInfo);
173 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, dwBufferSize);
177 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == NO_ERROR)
178 server = pFixedInfo->DnsServerList.IpAddress.String;
180 HeapFree(GetProcessHeap(), 0, pFixedInfo);
185 ServerInstance->Logs->Log("CONFIG",DEFAULT,"<dns:server> set to '%s' as first active resolver in the system settings.", server.c_str());
190 ServerInstance->Logs->Log("CONFIG",DEFAULT,"No viable nameserver found! Defaulting to nameserver '127.0.0.1'!");
192 // attempt to look up their nameserver from /etc/resolv.conf
193 ServerInstance->Logs->Log("CONFIG",DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
195 std::ifstream resolv("/etc/resolv.conf");
197 while (resolv >> server)
199 if (server == "nameserver")
202 if (server.find_first_not_of("0123456789.") == std::string::npos)
204 ServerInstance->Logs->Log("CONFIG",DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",server.c_str());
210 ServerInstance->Logs->Log("CONFIG",DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
212 server = "127.0.0.1";
215 static void ReadXLine(ServerConfig* conf, const std::string& tag, const std::string& key, XLineFactory* make)
217 ConfigTagList tags = conf->ConfTags(tag);
218 for(ConfigIter i = tags.first; i != tags.second; ++i)
220 ConfigTag* ctag = i->second;
222 if (!ctag->readString(key, mask))
223 throw CoreException("<"+tag+":"+key+"> missing at " + ctag->getTagLocation());
224 std::string reason = ctag->getString("reason", "<Config>");
225 XLine* xl = make->Generate(ServerInstance->Time(), 0, "<Config>", reason, mask);
226 if (!ServerInstance->XLines->AddLine(xl, NULL))
231 typedef std::map<std::string, ConfigTag*> LocalIndex;
232 void ServerConfig::CrossCheckOperClassType()
234 LocalIndex operclass;
235 ConfigTagList tags = ConfTags("class");
236 for(ConfigIter i = tags.first; i != tags.second; ++i)
238 ConfigTag* tag = i->second;
239 std::string name = tag->getString("name");
241 throw CoreException("<class:name> missing from tag at " + tag->getTagLocation());
242 if (operclass.find(name) != operclass.end())
243 throw CoreException("Duplicate class block with name " + name + " at " + tag->getTagLocation());
244 operclass[name] = tag;
246 tags = ConfTags("type");
247 for(ConfigIter i = tags.first; i != tags.second; ++i)
249 ConfigTag* tag = i->second;
250 std::string name = tag->getString("name");
252 throw CoreException("<type:name> is missing from tag at " + tag->getTagLocation());
253 if (!ServerInstance->IsNick(name.c_str(), Limits.NickMax))
254 throw CoreException("<type:name> is invalid (value '" + name + "')");
255 if (oper_blocks.find(" " + name) != oper_blocks.end())
256 throw CoreException("Duplicate type block with name " + name + " at " + tag->getTagLocation());
258 OperInfo* ifo = new OperInfo;
259 oper_blocks[" " + name] = ifo;
261 ifo->type_block = tag;
263 std::string classname;
264 irc::spacesepstream str(tag->getString("classes"));
265 while (str.GetToken(classname))
267 LocalIndex::iterator cls = operclass.find(classname);
268 if (cls == operclass.end())
269 throw CoreException("Oper type " + name + " has missing class " + classname);
270 ifo->class_blocks.push_back(cls->second);
274 tags = ConfTags("oper");
275 for(ConfigIter i = tags.first; i != tags.second; ++i)
277 ConfigTag* tag = i->second;
279 std::string name = tag->getString("name");
281 throw CoreException("<oper:name> missing from tag at " + tag->getTagLocation());
283 std::string type = tag->getString("type");
284 OperIndex::iterator tblk = oper_blocks.find(" " + type);
285 if (tblk == oper_blocks.end())
286 throw CoreException("Oper block " + name + " has missing type " + type);
287 if (oper_blocks.find(name) != oper_blocks.end())
288 throw CoreException("Duplicate oper block with name " + name + " at " + tag->getTagLocation());
290 OperInfo* ifo = new OperInfo;
292 ifo->oper_block = tag;
293 ifo->type_block = tblk->second->type_block;
294 ifo->class_blocks.assign(tblk->second->class_blocks.begin(), tblk->second->class_blocks.end());
295 oper_blocks[name] = ifo;
299 void ServerConfig::CrossCheckConnectBlocks(ServerConfig* current)
301 typedef std::map<std::string, ConnectClass*> ClassMap;
302 ClassMap oldBlocksByMask;
305 for(ClassVector::iterator i = current->Classes.begin(); i != current->Classes.end(); ++i)
307 ConnectClass* c = *i;
308 if (c->name.substr(0, 8) != "unnamed-")
310 oldBlocksByMask["n" + c->name] = c;
312 else if (c->type == CC_ALLOW || c->type == CC_DENY)
314 std::string typeMask = (c->type == CC_ALLOW) ? "a" : "d";
316 oldBlocksByMask[typeMask] = c;
321 int blk_count = config_data.count("connect");
324 // No connect blocks found; make a trivial default block
325 std::vector<KeyVal>* items;
326 ConfigTag* tag = ConfigTag::create("connect", "<auto>", 0, items);
327 items->push_back(std::make_pair("allow", "*"));
328 config_data.insert(std::make_pair("connect", tag));
332 Classes.resize(blk_count);
333 std::map<std::string, int> names;
335 bool try_again = true;
336 for(int tries=0; try_again; tries++)
339 ConfigTagList tags = ConfTags("connect");
341 for(ConfigIter it = tags.first; it != tags.second; ++it, ++i)
343 ConfigTag* tag = it->second;
347 ConnectClass* parent = NULL;
348 std::string parentName = tag->getString("parent");
349 if (!parentName.empty())
351 std::map<std::string,int>::iterator parentIter = names.find(parentName);
352 if (parentIter == names.end())
355 // couldn't find parent this time. If it's the last time, we'll never find it.
356 if (tries >= blk_count)
357 throw CoreException("Could not find parent connect class \"" + parentName + "\" for connect block at " + tag->getTagLocation());
360 parent = Classes[parentIter->second];
363 std::string name = tag->getString("name");
364 std::string mask, typeMask;
367 if (tag->readString("allow", mask, false))
370 typeMask = 'a' + mask;
372 else if (tag->readString("deny", mask, false))
375 typeMask = 'd' + mask;
377 else if (!name.empty())
381 typeMask = 'n' + mask;
385 throw CoreException("Connect class must have allow, deny, or name specified at " + tag->getTagLocation());
390 name = "unnamed-" + ConvToStr(i);
394 typeMask = 'n' + name;
397 if (names.find(name) != names.end())
398 throw CoreException("Two connect classes with name \"" + name + "\" defined!");
401 ConnectClass* me = parent ?
402 new ConnectClass(tag, type, mask, *parent) :
403 new ConnectClass(tag, type, mask);
407 me->registration_timeout = tag->getInt("timeout", me->registration_timeout);
408 me->pingtime = tag->getInt("pingfreq", me->pingtime);
410 if (tag->readString("sendq", sendq))
412 // attempt to guess a good hard/soft sendq from a single value
413 long value = atol(sendq.c_str());
415 me->softsendqmax = value / 16;
417 me->softsendqmax = value;
418 me->hardsendqmax = value * 8;
420 me->softsendqmax = tag->getInt("softsendq", me->softsendqmax);
421 me->hardsendqmax = tag->getInt("hardsendq", me->hardsendqmax);
422 me->recvqmax = tag->getInt("recvq", me->recvqmax);
423 me->penaltythreshold = tag->getInt("threshold", me->penaltythreshold);
424 me->commandrate = tag->getInt("commandrate", me->commandrate);
425 me->fakelag = tag->getBool("fakelag", me->fakelag);
426 me->maxlocal = tag->getInt("localmax", me->maxlocal);
427 me->maxglobal = tag->getInt("globalmax", me->maxglobal);
428 me->maxchans = tag->getInt("maxchans", me->maxchans);
429 me->maxconnwarn = tag->getBool("maxconnwarn", me->maxconnwarn);
430 me->limit = tag->getInt("limit", me->limit);
432 ClassMap::iterator oldMask = oldBlocksByMask.find(typeMask);
433 if (oldMask != oldBlocksByMask.end())
435 ConnectClass* old = oldMask->second;
436 oldBlocksByMask.erase(oldMask);
446 /** Represents a deprecated configuration tag.
456 /** Reason for deprecation
461 static const Deprecated ChangedConfig[] = {
462 {"options", "hidelinks", "has been moved to <security:hidelinks> as of 1.2a3"},
463 {"options", "hidewhois", "has been moved to <security:hidewhois> as of 1.2a3"},
464 {"options", "userstats", "has been moved to <security:userstats> as of 1.2a3"},
465 {"options", "customversion", "has been moved to <security:customversion> as of 1.2a3"},
466 {"options", "hidesplits", "has been moved to <security:hidesplits> as of 1.2a3"},
467 {"options", "hidebans", "has been moved to <security:hidebans> as of 1.2a3"},
468 {"options", "hidekills", "has been moved to <security:hidekills> as of 1.2a3"},
469 {"options", "operspywhois", "has been moved to <security:operspywhois> as of 1.2a3"},
470 {"options", "announceinvites", "has been moved to <security:announceinvites> as of 1.2a3"},
471 {"options", "hidemodes", "has been moved to <security:hidemodes> as of 1.2a3"},
472 {"options", "maxtargets", "has been moved to <security:maxtargets> as of 1.2a3"},
473 {"options", "nouserdns", "has been moved to <performance:nouserdns> as of 1.2a3"},
474 {"options", "maxwho", "has been moved to <performance:maxwho> as of 1.2a3"},
475 {"options", "softlimit", "has been moved to <performance:softlimit> as of 1.2a3"},
476 {"options", "somaxconn", "has been moved to <performance:somaxconn> as of 1.2a3"},
477 {"options", "netbuffersize", "has been moved to <performance:netbuffersize> as of 1.2a3"},
478 {"options", "maxwho", "has been moved to <performance:maxwho> as of 1.2a3"},
479 {"options", "loglevel", "1.2+ does not use the loglevel value. Please define <log> tags instead."},
480 {"die", "value", "you need to reread your config"},
481 {"bind", "transport", "has been moved to <bind:ssl> as of 2.0a1"},
482 {"link", "transport", "has been moved to <link:ssl> as of 2.0a1"},
483 {"link", "autoconnect", "2.0+ does not use the autoconnect value. Please define <autoconnect> tags instead."},
486 void ServerConfig::Fill()
488 ConfigTag* options = ConfValue("options");
489 ConfigTag* security = ConfValue("security");
492 ServerName = ConfValue("server")->getString("name");
493 sid = ConfValue("server")->getString("id");
494 ValidHost(ServerName, "<server:name>");
495 if (!sid.empty() && !ServerInstance->IsSID(sid))
496 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.");
500 if (ServerName != ConfValue("server")->getString("name"))
501 throw CoreException("You must restart to change the server name or SID");
502 std::string nsid = ConfValue("server")->getString("id");
503 if (!nsid.empty() && nsid != sid)
504 throw CoreException("You must restart to change the server name or SID");
506 diepass = ConfValue("power")->getString("diepass");
507 restartpass = ConfValue("power")->getString("restartpass");
508 powerhash = ConfValue("power")->getString("hash");
509 PrefixQuit = options->getString("prefixquit");
510 SuffixQuit = options->getString("suffixquit");
511 FixedQuit = options->getString("fixedquit");
512 PrefixPart = options->getString("prefixpart");
513 SuffixPart = options->getString("suffixpart");
514 FixedPart = options->getString("fixedpart");
515 SoftLimit = ConfValue("performance")->getInt("softlimit", ServerInstance->SE->GetMaxFds());
516 MaxConn = ConfValue("performance")->getInt("somaxconn", SOMAXCONN);
517 MoronBanner = options->getString("moronbanner", "You're banned!");
518 ServerDesc = ConfValue("server")->getString("description", "Configure Me");
519 Network = ConfValue("server")->getString("network", "Network");
520 AdminName = ConfValue("admin")->getString("name", "");
521 AdminEmail = ConfValue("admin")->getString("email", "null@example.com");
522 AdminNick = ConfValue("admin")->getString("nick", "admin");
523 ModPath = ConfValue("path")->getString("moduledir", MOD_PATH);
524 NetBufferSize = ConfValue("performance")->getInt("netbuffersize", 10240);
525 dns_timeout = ConfValue("dns")->getInt("timeout", 5);
526 DisabledCommands = ConfValue("disabled")->getString("commands", "");
527 DisabledDontExist = ConfValue("disabled")->getBool("fakenonexistant");
528 UserStats = security->getString("userstats");
529 CustomVersion = security->getString("customversion", Network + " IRCd");
530 HideSplits = security->getBool("hidesplits");
531 HideBans = security->getBool("hidebans");
532 HideWhoisServer = security->getString("hidewhois");
533 HideKillsServer = security->getString("hidekills");
534 HideULineKills = security->getBool("hideulinekills");
535 RestrictBannedUsers = security->getBool("restrictbannedusers", true);
536 GenericOper = security->getBool("genericoper");
537 NoUserDns = ConfValue("performance")->getBool("nouserdns");
538 SyntaxHints = options->getBool("syntaxhints");
539 CycleHosts = options->getBool("cyclehosts");
540 CycleHostsFromUser = options->getBool("cyclehostsfromuser");
541 UndernetMsgPrefix = options->getBool("ircumsgprefix");
542 FullHostInTopic = options->getBool("hostintopic");
543 MaxTargets = security->getInt("maxtargets", 20);
544 DefaultModes = options->getString("defaultmodes", "nt");
545 PID = ConfValue("pid")->getString("file");
546 WhoWasGroupSize = ConfValue("whowas")->getInt("groupsize");
547 WhoWasMaxGroups = ConfValue("whowas")->getInt("maxgroups");
548 WhoWasMaxKeep = ServerInstance->Duration(ConfValue("whowas")->getString("maxkeep"));
549 MaxChans = ConfValue("channels")->getInt("users", 20);
550 OperMaxChans = ConfValue("channels")->getInt("opers", 60);
551 c_ipv4_range = ConfValue("cidr")->getInt("ipv4clone", 32);
552 c_ipv6_range = ConfValue("cidr")->getInt("ipv6clone", 128);
553 Limits.NickMax = ConfValue("limits")->getInt("maxnick", 32);
554 Limits.ChanMax = ConfValue("limits")->getInt("maxchan", 64);
555 Limits.MaxModes = ConfValue("limits")->getInt("maxmodes", 20);
556 Limits.IdentMax = ConfValue("limits")->getInt("maxident", 11);
557 Limits.MaxQuit = ConfValue("limits")->getInt("maxquit", 255);
558 Limits.MaxTopic = ConfValue("limits")->getInt("maxtopic", 307);
559 Limits.MaxKick = ConfValue("limits")->getInt("maxkick", 255);
560 Limits.MaxGecos = ConfValue("limits")->getInt("maxgecos", 128);
561 Limits.MaxAway = ConfValue("limits")->getInt("maxaway", 200);
562 InvBypassModes = options->getBool("invitebypassmodes", true);
563 NoSnoticeStack = options->getBool("nosnoticestack", false);
564 WelcomeNotice = options->getBool("welcomenotice", true);
566 range(SoftLimit, 10, ServerInstance->SE->GetMaxFds(), ServerInstance->SE->GetMaxFds(), "<performance:softlimit>");
567 if (ConfValue("performance")->getBool("limitsomaxconn", true))
568 range(MaxConn, 0, SOMAXCONN, SOMAXCONN, "<performance:somaxconn>");
569 range(MaxTargets, 1, 31, 20, "<security:maxtargets>");
570 range(NetBufferSize, 1024, 65534, 10240, "<performance:netbuffersize>");
571 range(WhoWasGroupSize, 0, 10000, 10, "<whowas:groupsize>");
572 range(WhoWasMaxGroups, 0, 1000000, 10240, "<whowas:maxgroups>");
573 range(WhoWasMaxKeep, 3600, INT_MAX, 3600, "<whowas:maxkeep>");
575 ValidIP(DNSServer, "<dns:server>");
577 std::string defbind = options->getString("defaultbind");
578 if (assign(defbind) == "ipv4")
580 WildcardIPv6 = false;
582 else if (assign(defbind) == "ipv6")
589 int socktest = socket(AF_INET6, SOCK_STREAM, 0);
591 WildcardIPv6 = false;
593 ServerInstance->SE->Close(socktest);
595 ConfigTagList tags = ConfTags("uline");
596 for(ConfigIter i = tags.first; i != tags.second; ++i)
598 ConfigTag* tag = i->second;
600 if (!tag->readString("server", server))
601 throw CoreException("<uline> tag missing server at " + tag->getTagLocation());
602 ulines[assign(server)] = tag->getBool("silent");
605 tags = ConfTags("banlist");
606 for(ConfigIter i = tags.first; i != tags.second; ++i)
608 ConfigTag* tag = i->second;
610 if (!tag->readString("chan", chan))
611 throw CoreException("<banlist> tag missing chan at " + tag->getTagLocation());
612 maxbans[chan] = tag->getInt("limit");
615 ReadXLine(this, "badip", "ipmask", ServerInstance->XLines->GetFactory("Z"));
616 ReadXLine(this, "badnick", "nick", ServerInstance->XLines->GetFactory("Q"));
617 ReadXLine(this, "badhost", "host", ServerInstance->XLines->GetFactory("K"));
618 ReadXLine(this, "exception", "host", ServerInstance->XLines->GetFactory("E"));
620 memset(DisabledUModes, 0, sizeof(DisabledUModes));
621 std::string modes = ConfValue("disabled")->getString("usermodes");
622 for (std::string::const_iterator p = modes.begin(); p != modes.end(); ++p)
624 // Complain when the character is not a-z or A-Z
625 if ((*p < 'A') || (*p > 'z') || ((*p < 'a') && (*p > 'Z')))
626 throw CoreException("Invalid usermode " + std::string(1, *p) + " was found.");
627 DisabledUModes[*p - 'A'] = 1;
630 memset(DisabledCModes, 0, sizeof(DisabledCModes));
631 modes = ConfValue("disabled")->getString("chanmodes");
632 for (std::string::const_iterator p = modes.begin(); p != modes.end(); ++p)
634 if ((*p < 'A') || (*p > 'z') || ((*p < 'a') && (*p > 'Z')))
635 throw CoreException("Invalid chanmode " + std::string(1, *p) + " was found.");
636 DisabledCModes[*p - 'A'] = 1;
639 memset(HideModeLists, 0, sizeof(HideModeLists));
640 modes = ConfValue("security")->getString("hidemodes");
641 for (std::string::const_iterator p = modes.begin(); p != modes.end(); ++p)
642 HideModeLists[(unsigned char) *p] = true;
644 std::string v = security->getString("announceinvites");
647 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_OPS;
649 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_ALL;
650 else if (v == "dynamic")
651 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_DYNAMIC;
653 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_NONE;
655 v = security->getString("operspywhois");
657 OperSpyWhois = SPYWHOIS_SPLITMSG;
658 else if (v == "on" || v == "yes")
659 OperSpyWhois = SPYWHOIS_SINGLEMSG;
661 OperSpyWhois = SPYWHOIS_NONE;
664 // WARNING: it is not safe to use most of the codebase in this function, as it
665 // will run in the config reader thread
666 void ServerConfig::Read()
668 /* Load and parse the config file, if there are any errors then explode */
670 ParseStack stack(this);
673 valid = stack.ParseFile(ServerInstance->ConfigFileName, 0);
675 catch (CoreException& err)
678 errstr << err.GetReason();
682 DNSServer = ConfValue("dns")->getString("server");
687 void ServerConfig::Apply(ServerConfig* old, const std::string &useruid)
693 * These values can only be set on boot. Keep their old values. Do it before we send messages so we actually have a servername.
695 this->ServerName = old->ServerName;
696 this->sid = old->sid;
697 this->cmdline = old->cmdline;
700 /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
703 for (int Index = 0; Index * sizeof(Deprecated) < sizeof(ChangedConfig); Index++)
706 ConfigTagList tags = ConfTags(ChangedConfig[Index].tag);
707 for(ConfigIter i = tags.first; i != tags.second; ++i)
709 if (i->second->readString(ChangedConfig[Index].value, dummy, true))
710 errstr << "Your configuration contains a deprecated value: <"
711 << ChangedConfig[Index].tag << ":" << ChangedConfig[Index].value << "> - " << ChangedConfig[Index].reason
712 << " (at " << i->second->getTagLocation() << ")\n";
718 // Handle special items
719 CrossCheckOperClassType();
720 CrossCheckConnectBlocks(old);
722 catch (CoreException &ce)
724 errstr << ce.GetReason();
727 // Check errors before dealing with failed binds, since continuing on failed bind is wanted in some circumstances.
728 valid = errstr.str().empty();
730 // write once here, to try it out and make sure its ok
732 ServerInstance->WritePID(this->PID, !old);
736 // On first run, ports are bound later on
738 ServerInstance->BindPorts(pl);
741 errstr << "Not all your client ports could be bound.\nThe following port(s) failed to bind:\n";
744 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
747 snprintf(buf, MAXBUF, "%d. Address: %s Reason: %s\n", j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
753 User* user = useruid.empty() ? NULL : ServerInstance->FindNick(useruid);
757 ServerInstance->Logs->Log("CONFIG",DEFAULT, "There were errors in your configuration file:");
761 while (errstr.good())
764 getline(errstr, line, '\n');
767 // On startup, print out to console (still attached at this point)
769 std::cout << line << std::endl;
770 // If a user is rehashing, tell them directly
772 user->SendText(":%s NOTICE %s :*** %s", ServerInstance->Config->ServerName.c_str(), user->nick.c_str(), line.c_str());
774 ServerInstance->SNO->WriteGlobalSno('a', line);
778 errstr.str(std::string());
780 // Re-parse our MOTD and RULES files for colors -- Justasic
781 for (ClassVector::const_iterator it = this->Classes.begin(), it_end = this->Classes.end(); it != it_end; ++it)
783 ConfigTag *tag = (*it)->config;
784 // Make sure our connection class allows motd colors
785 if(!tag->getBool("allowmotdcolors"))
788 ConfigFileCache::iterator file = this->Files.find(tag->getString("motd", "motd"));
789 if (file != this->Files.end())
790 InspIRCd::ProcessColors(file->second);
792 file = this->Files.find(tag->getString("rules", "rules"));
793 if (file != this->Files.end())
794 InspIRCd::ProcessColors(file->second);
797 /* No old configuration -> initial boot, nothing more to do here */
802 ServerInstance->Exit(EXIT_STATUS_CONFIG);
809 // If there were errors processing configuration, don't touch modules.
816 user->SendText(":%s NOTICE %s :*** Successfully rehashed server.",
817 ServerInstance->Config->ServerName.c_str(), user->nick.c_str());
818 ServerInstance->SNO->WriteGlobalSno('a', "*** Successfully rehashed server.");
821 void ServerConfig::ApplyModules(User* user)
823 Module* whowas = ServerInstance->Modules->Find("cmd_whowas.so");
825 WhowasRequest(NULL, whowas, WhowasRequest::WHOWAS_PRUNE).Send();
827 const std::vector<std::string> v = ServerInstance->Modules->GetAllModuleNames(0);
828 std::vector<std::string> added_modules;
829 std::set<std::string> removed_modules(v.begin(), v.end());
831 ConfigTagList tags = ConfTags("module");
832 for(ConfigIter i = tags.first; i != tags.second; ++i)
834 ConfigTag* tag = i->second;
836 if (tag->readString("name", name))
838 // if this module is already loaded, the erase will succeed, so we need do nothing
839 // otherwise, we need to add the module (which will be done later)
840 if (removed_modules.erase(name) == 0)
841 added_modules.push_back(name);
845 if (ConfValue("options")->getBool("allowhalfop") && removed_modules.erase("m_halfop.so") == 0)
846 added_modules.push_back("m_halfop.so");
848 for (std::set<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
850 // Don't remove cmd_*.so, just remove m_*.so
851 if (removing->c_str()[0] == 'c')
853 Module* m = ServerInstance->Modules->Find(*removing);
854 if (m && ServerInstance->Modules->Unload(m))
856 ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH UNLOADED MODULE: %s",removing->c_str());
859 user->WriteNumeric(RPL_UNLOADEDMODULE, "%s %s :Module %s successfully unloaded.",user->nick.c_str(), removing->c_str(), removing->c_str());
861 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully unloaded.", removing->c_str());
866 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());
868 ServerInstance->SNO->WriteGlobalSno('a', "Failed to unload module %s: %s", removing->c_str(), ServerInstance->Modules->LastError().c_str());
872 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
874 if (ServerInstance->Modules->Load(adding->c_str()))
876 ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH LOADED MODULE: %s",adding->c_str());
878 user->WriteNumeric(RPL_LOADEDMODULE, "%s %s :Module %s successfully loaded.",user->nick.c_str(), adding->c_str(), adding->c_str());
880 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully loaded.", adding->c_str());
885 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());
887 ServerInstance->SNO->WriteGlobalSno('a', "Failed to load module %s: %s", adding->c_str(), ServerInstance->Modules->LastError().c_str());
892 bool ServerConfig::StartsWithWindowsDriveLetter(const std::string &path)
894 return (path.length() > 2 && isalpha(path[0]) && path[1] == ':');
897 ConfigTag* ServerConfig::ConfValue(const std::string &tag)
899 ConfigTagList found = config_data.equal_range(tag);
900 if (found.first == found.second)
902 ConfigTag* rv = found.first->second;
904 if (found.first != found.second)
905 ServerInstance->Logs->Log("CONFIG",DEFAULT, "Multiple <" + tag + "> tags found; only first will be used "
906 "(first at " + rv->getTagLocation() + "; second at " + found.first->second->getTagLocation() + ")");
910 ConfigTagList ServerConfig::ConfTags(const std::string& tag)
912 return config_data.equal_range(tag);
915 bool ServerConfig::FileExists(const char* file)
918 if (stat(file, &sb) == -1)
921 if ((sb.st_mode & S_IFDIR) > 0)
924 FILE *input = fopen(file, "r");
934 const char* ServerConfig::CleanFilename(const char* name)
936 const char* p = name + strlen(name);
937 while ((p != name) && (*p != '/') && (*p != '\\')) p--;
938 return (p != name ? ++p : p);
941 const std::string& ServerConfig::GetSID()
946 void ConfigReaderThread::Run()
952 void ConfigReaderThread::Finish()
954 ServerConfig* old = ServerInstance->Config;
955 ServerInstance->Logs->Log("CONFIG",DEBUG,"Switching to new configuration...");
956 ServerInstance->Config = this->Config;
957 Config->Apply(old, TheUserUID);
962 * Apply the changed configuration from the rehash.
964 * XXX: The order of these is IMPORTANT, do not reorder them without testing
967 ServerInstance->Users->RehashCloneCounts();
968 ServerInstance->XLines->CheckELines();
969 ServerInstance->XLines->ApplyLines();
970 ServerInstance->Res->Rehash();
971 ServerInstance->ResetMaxBans();
972 Config->ApplyDisabledCommands(Config->DisabledCommands);
973 User* user = ServerInstance->FindNick(TheUserUID);
974 FOREACH_MOD(I_OnRehash, OnRehash(user));
975 ServerInstance->BuildISupport();
977 ServerInstance->Logs->CloseLogs();
978 ServerInstance->Logs->OpenFileLogs();
980 if (Config->RawLog && !old->RawLog)
981 ServerInstance->Users->ServerNoticeAll("*** Raw I/O logging is enabled on this server. All messages, passwords, and commands are being recorded.");
988 ServerInstance->Config = old;