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()
39 WhoWasGroupSize = WhoWasMaxGroups = WhoWasMaxKeep = 0;
40 RawLog = NoUserDns = HideBans = HideSplits = UndernetMsgPrefix = false;
41 WildcardIPv6 = CycleHosts = InvBypassModes = true;
44 NetBufferSize = 10240;
45 SoftLimit = ServerInstance->SE->GetMaxFds();
52 std::vector<KeyVal>* items;
53 EmptyTag = ConfigTag::create("empty", "<auto>", 0, items);
56 ServerConfig::~ServerConfig()
61 void ServerConfig::Update005()
63 std::stringstream out(data005);
64 std::vector<std::string> data;
67 data.push_back(token);
68 sort(data.begin(), data.end());
72 for(unsigned int i=0; i < data.size(); i++)
75 line5 = line5 + token + " ";
78 line5.append(":are supported by this server");
79 isupport.push_back(line5);
85 line5.append(":are supported by this server");
86 isupport.push_back(line5);
90 void ServerConfig::Send005(User* user)
92 for (std::vector<std::string>::iterator line = ServerInstance->Config->isupport.begin(); line != ServerInstance->Config->isupport.end(); line++)
93 user->WriteNumeric(RPL_ISUPPORT, "%s %s", user->nick.c_str(), line->c_str());
96 template<typename T, typename V>
97 static void range(T& value, V min, V max, V def, const char* msg)
99 if (value >= (T)min && value <= (T)max)
101 ServerInstance->Logs->Log("CONFIG", DEFAULT,
102 "WARNING: %s value of %ld is not between %ld and %ld; set to %ld.",
103 msg, (long)value, (long)min, (long)max, (long)def);
108 static void ValidIP(const std::string& ip, const std::string& key)
110 irc::sockets::sockaddrs dummy;
111 if (!irc::sockets::aptosa(ip, 0, dummy))
112 throw CoreException("The value of "+key+" is not an IP address");
115 static void ValidHost(const std::string& p, const std::string& msg)
118 if (p.empty() || p[0] == '.')
119 throw CoreException("The value of "+msg+" is not a valid hostname");
120 for (unsigned int i=0;i < p.length();i++)
125 throw CoreException("The value of "+msg+" is not a valid hostname");
132 throw CoreException("The value of "+msg+" is not a valid hostname");
135 bool ServerConfig::ApplyDisabledCommands(const std::string& data)
137 std::stringstream dcmds(data);
140 /* Enable everything first */
141 for (Commandtable::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
142 x->second->Disable(false);
144 /* Now disable all the ones which the user wants disabled */
145 while (dcmds >> thiscmd)
147 Commandtable::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
148 if (cm != ServerInstance->Parser->cmdlist.end())
150 cm->second->Disable(true);
156 static void FindDNS(std::string& server)
161 // attempt to look up their nameserver from the system
162 ServerInstance->Logs->Log("CONFIG",DEFAULT,"WARNING: <dns:server> not defined, attempting to find a working server in the system settings...");
164 PFIXED_INFO pFixedInfo;
165 DWORD dwBufferSize = sizeof(FIXED_INFO);
166 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, sizeof(FIXED_INFO));
170 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == ERROR_BUFFER_OVERFLOW) {
171 HeapFree(GetProcessHeap(), 0, pFixedInfo);
172 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, dwBufferSize);
176 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == NO_ERROR)
177 server = pFixedInfo->DnsServerList.IpAddress.String;
179 HeapFree(GetProcessHeap(), 0, pFixedInfo);
184 ServerInstance->Logs->Log("CONFIG",DEFAULT,"<dns:server> set to '%s' as first active resolver in the system settings.", server.c_str());
189 ServerInstance->Logs->Log("CONFIG",DEFAULT,"No viable nameserver found! Defaulting to nameserver '127.0.0.1'!");
191 // attempt to look up their nameserver from /etc/resolv.conf
192 ServerInstance->Logs->Log("CONFIG",DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
194 std::ifstream resolv("/etc/resolv.conf");
196 while (resolv >> server)
198 if (server == "nameserver")
201 if (server.find_first_not_of("0123456789.") == std::string::npos)
203 ServerInstance->Logs->Log("CONFIG",DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",server.c_str());
209 ServerInstance->Logs->Log("CONFIG",DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
211 server = "127.0.0.1";
214 static void ReadXLine(ServerConfig* conf, const std::string& tag, const std::string& key, XLineFactory* make)
216 ConfigTagList tags = conf->ConfTags(tag);
217 for(ConfigIter i = tags.first; i != tags.second; ++i)
219 ConfigTag* ctag = i->second;
221 if (!ctag->readString(key, mask))
222 throw CoreException("<"+tag+":"+key+"> missing at " + ctag->getTagLocation());
223 std::string reason = ctag->getString("reason", "<Config>");
224 XLine* xl = make->Generate(ServerInstance->Time(), 0, "<Config>", reason, mask);
225 if (!ServerInstance->XLines->AddLine(xl, NULL))
230 typedef std::map<std::string, ConfigTag*> LocalIndex;
231 void ServerConfig::CrossCheckOperClassType()
233 LocalIndex operclass;
234 ConfigTagList tags = ConfTags("class");
235 for(ConfigIter i = tags.first; i != tags.second; ++i)
237 ConfigTag* tag = i->second;
238 std::string name = tag->getString("name");
240 throw CoreException("<class:name> missing from tag at " + tag->getTagLocation());
241 if (operclass.find(name) != operclass.end())
242 throw CoreException("Duplicate class block with name " + name + " at " + tag->getTagLocation());
243 operclass[name] = tag;
245 tags = ConfTags("type");
246 for(ConfigIter i = tags.first; i != tags.second; ++i)
248 ConfigTag* tag = i->second;
249 std::string name = tag->getString("name");
251 throw CoreException("<type:name> is missing from tag at " + tag->getTagLocation());
252 if (!ServerInstance->IsNick(name.c_str(), Limits.NickMax))
253 throw CoreException("<type:name> is invalid (value '" + name + "')");
254 if (oper_blocks.find(" " + name) != oper_blocks.end())
255 throw CoreException("Duplicate type block with name " + name + " at " + tag->getTagLocation());
257 OperInfo* ifo = new OperInfo;
258 oper_blocks[" " + name] = ifo;
260 ifo->type_block = tag;
262 std::string classname;
263 irc::spacesepstream str(tag->getString("classes"));
264 while (str.GetToken(classname))
266 LocalIndex::iterator cls = operclass.find(classname);
267 if (cls == operclass.end())
268 throw CoreException("Oper type " + name + " has missing class " + classname);
269 ifo->class_blocks.push_back(cls->second);
273 tags = ConfTags("oper");
274 for(ConfigIter i = tags.first; i != tags.second; ++i)
276 ConfigTag* tag = i->second;
278 std::string name = tag->getString("name");
280 throw CoreException("<oper:name> missing from tag at " + tag->getTagLocation());
282 std::string type = tag->getString("type");
283 OperIndex::iterator tblk = oper_blocks.find(" " + type);
284 if (tblk == oper_blocks.end())
285 throw CoreException("Oper block " + name + " has missing type " + type);
286 if (oper_blocks.find(name) != oper_blocks.end())
287 throw CoreException("Duplicate oper block with name " + name + " at " + tag->getTagLocation());
289 OperInfo* ifo = new OperInfo;
291 ifo->oper_block = tag;
292 ifo->type_block = tblk->second->type_block;
293 ifo->class_blocks.assign(tblk->second->class_blocks.begin(), tblk->second->class_blocks.end());
294 oper_blocks[name] = ifo;
298 void ServerConfig::CrossCheckConnectBlocks(ServerConfig* current)
300 typedef std::map<std::string, ConnectClass*> ClassMap;
301 ClassMap oldBlocksByMask;
304 for(ClassVector::iterator i = current->Classes.begin(); i != current->Classes.end(); ++i)
306 ConnectClass* c = *i;
307 if (c->name.substr(0, 8) != "unnamed-")
309 oldBlocksByMask["n" + c->name] = c;
311 else if (c->type == CC_ALLOW || c->type == CC_DENY)
313 std::string typeMask = (c->type == CC_ALLOW) ? "a" : "d";
315 oldBlocksByMask[typeMask] = c;
320 int blk_count = config_data.count("connect");
323 // No connect blocks found; make a trivial default block
324 std::vector<KeyVal>* items;
325 ConfigTag* tag = ConfigTag::create("connect", "<auto>", 0, items);
326 items->push_back(std::make_pair("allow", "*"));
327 config_data.insert(std::make_pair("connect", tag));
331 Classes.resize(blk_count);
332 std::map<std::string, int> names;
334 bool try_again = true;
335 for(int tries=0; try_again; tries++)
338 ConfigTagList tags = ConfTags("connect");
340 for(ConfigIter it = tags.first; it != tags.second; ++it, ++i)
342 ConfigTag* tag = it->second;
346 ConnectClass* parent = NULL;
347 std::string parentName = tag->getString("parent");
348 if (!parentName.empty())
350 std::map<std::string,int>::iterator parentIter = names.find(parentName);
351 if (parentIter == names.end())
354 // couldn't find parent this time. If it's the last time, we'll never find it.
355 if (tries >= blk_count)
356 throw CoreException("Could not find parent connect class \"" + parentName + "\" for connect block at " + tag->getTagLocation());
359 parent = Classes[parentIter->second];
362 std::string name = tag->getString("name");
363 std::string mask, typeMask;
366 if (tag->readString("allow", mask, false))
369 typeMask = 'a' + mask;
371 else if (tag->readString("deny", mask, false))
374 typeMask = 'd' + mask;
376 else if (!name.empty())
380 typeMask = 'n' + mask;
384 throw CoreException("Connect class must have allow, deny, or name specified at " + tag->getTagLocation());
389 name = "unnamed-" + ConvToStr(i);
393 typeMask = 'n' + name;
396 if (names.find(name) != names.end())
397 throw CoreException("Two connect classes with name \"" + name + "\" defined!");
400 ConnectClass* me = parent ?
401 new ConnectClass(tag, type, mask, *parent) :
402 new ConnectClass(tag, type, mask);
406 me->registration_timeout = tag->getInt("timeout", me->registration_timeout);
407 me->pingtime = tag->getInt("pingfreq", me->pingtime);
409 if (tag->readString("sendq", sendq))
411 // attempt to guess a good hard/soft sendq from a single value
412 long value = atol(sendq.c_str());
414 me->softsendqmax = value / 16;
416 me->softsendqmax = value;
417 me->hardsendqmax = value * 8;
419 me->softsendqmax = tag->getInt("softsendq", me->softsendqmax);
420 me->hardsendqmax = tag->getInt("hardsendq", me->hardsendqmax);
421 me->recvqmax = tag->getInt("recvq", me->recvqmax);
422 me->penaltythreshold = tag->getInt("threshold", me->penaltythreshold);
423 me->commandrate = tag->getInt("commandrate", me->commandrate);
424 me->fakelag = tag->getBool("fakelag", me->fakelag);
425 me->maxlocal = tag->getInt("localmax", me->maxlocal);
426 me->maxglobal = tag->getInt("globalmax", me->maxglobal);
427 me->maxchans = tag->getInt("maxchans", me->maxchans);
428 me->maxconnwarn = tag->getBool("maxconnwarn", me->maxconnwarn);
429 me->limit = tag->getInt("limit", me->limit);
431 ClassMap::iterator oldMask = oldBlocksByMask.find(typeMask);
432 if (oldMask != oldBlocksByMask.end())
434 ConnectClass* old = oldMask->second;
435 oldBlocksByMask.erase(oldMask);
445 /** Represents a deprecated configuration tag.
455 /** Reason for deprecation
460 static const Deprecated ChangedConfig[] = {
461 {"options", "hidelinks", "has been moved to <security:hidelinks> as of 1.2a3"},
462 {"options", "hidewhois", "has been moved to <security:hidewhois> as of 1.2a3"},
463 {"options", "userstats", "has been moved to <security:userstats> as of 1.2a3"},
464 {"options", "customversion", "has been moved to <security:customversion> as of 1.2a3"},
465 {"options", "hidesplits", "has been moved to <security:hidesplits> as of 1.2a3"},
466 {"options", "hidebans", "has been moved to <security:hidebans> as of 1.2a3"},
467 {"options", "hidekills", "has been moved to <security:hidekills> as of 1.2a3"},
468 {"options", "operspywhois", "has been moved to <security:operspywhois> as of 1.2a3"},
469 {"options", "announceinvites", "has been moved to <security:announceinvites> as of 1.2a3"},
470 {"options", "hidemodes", "has been moved to <security:hidemodes> as of 1.2a3"},
471 {"options", "maxtargets", "has been moved to <security:maxtargets> as of 1.2a3"},
472 {"options", "nouserdns", "has been moved to <performance:nouserdns> as of 1.2a3"},
473 {"options", "maxwho", "has been moved to <performance:maxwho> as of 1.2a3"},
474 {"options", "softlimit", "has been moved to <performance:softlimit> as of 1.2a3"},
475 {"options", "somaxconn", "has been moved to <performance:somaxconn> as of 1.2a3"},
476 {"options", "netbuffersize", "has been moved to <performance:netbuffersize> as of 1.2a3"},
477 {"options", "maxwho", "has been moved to <performance:maxwho> as of 1.2a3"},
478 {"options", "loglevel", "1.2+ does not use the loglevel value. Please define <log> tags instead."},
479 {"die", "value", "you need to reread your config"},
480 {"bind", "transport", "has been moved to <bind:ssl> as of 2.0a1"},
481 {"link", "transport", "has been moved to <link:ssl> as of 2.0a1"},
482 {"link", "autoconnect", "2.0+ does not use the autoconnect value. Please define <autoconnect> tags instead."},
485 void ServerConfig::Fill()
487 ConfigTag* options = ConfValue("options");
488 ConfigTag* security = ConfValue("security");
491 ServerName = ConfValue("server")->getString("name");
492 sid = ConfValue("server")->getString("id");
493 ValidHost(ServerName, "<server:name>");
494 if (!sid.empty() && !ServerInstance->IsSID(sid))
495 throw CoreException(sid + " is not a valid server ID. A server ID must be 3 characters long, with the first character a digit and the next two characters a digit or letter.");
499 if (ServerName != ConfValue("server")->getString("name"))
500 throw CoreException("You must restart to change the server name or SID");
501 std::string nsid = ConfValue("server")->getString("id");
502 if (!nsid.empty() && nsid != sid)
503 throw CoreException("You must restart to change the server name or SID");
505 diepass = ConfValue("power")->getString("diepass");
506 restartpass = ConfValue("power")->getString("restartpass");
507 powerhash = ConfValue("power")->getString("hash");
508 PrefixQuit = options->getString("prefixquit");
509 SuffixQuit = options->getString("suffixquit");
510 FixedQuit = options->getString("fixedquit");
511 PrefixPart = options->getString("prefixpart");
512 SuffixPart = options->getString("suffixpart");
513 FixedPart = options->getString("fixedpart");
514 SoftLimit = ConfValue("performance")->getInt("softlimit", ServerInstance->SE->GetMaxFds());
515 MaxConn = ConfValue("performance")->getInt("somaxconn", SOMAXCONN);
516 MoronBanner = options->getString("moronbanner", "You're banned!");
517 ServerDesc = ConfValue("server")->getString("description", "Configure Me");
518 Network = ConfValue("server")->getString("network", "Network");
519 AdminName = ConfValue("admin")->getString("name", "");
520 AdminEmail = ConfValue("admin")->getString("email", "null@example.com");
521 AdminNick = ConfValue("admin")->getString("nick", "admin");
522 ModPath = ConfValue("path")->getString("moduledir", MOD_PATH);
523 NetBufferSize = ConfValue("performance")->getInt("netbuffersize", 10240);
524 dns_timeout = ConfValue("dns")->getInt("timeout", 5);
525 DisabledCommands = ConfValue("disabled")->getString("commands", "");
526 DisabledDontExist = ConfValue("disabled")->getBool("fakenonexistant");
527 UserStats = security->getString("userstats");
528 CustomVersion = security->getString("customversion", Network + " IRCd");
529 HideSplits = security->getBool("hidesplits");
530 HideBans = security->getBool("hidebans");
531 HideWhoisServer = security->getString("hidewhois");
532 HideKillsServer = security->getString("hidekills");
533 RestrictBannedUsers = security->getBool("restrictbannedusers", true);
534 GenericOper = security->getBool("genericoper");
535 NoUserDns = ConfValue("performance")->getBool("nouserdns");
536 SyntaxHints = options->getBool("syntaxhints");
537 CycleHosts = options->getBool("cyclehosts");
538 CycleHostsFromUser = options->getBool("cyclehostsfromuser");
539 UndernetMsgPrefix = options->getBool("ircumsgprefix");
540 FullHostInTopic = options->getBool("hostintopic");
541 MaxTargets = security->getInt("maxtargets", 20);
542 DefaultModes = options->getString("defaultmodes", "nt");
543 PID = ConfValue("pid")->getString("file");
544 WhoWasGroupSize = ConfValue("whowas")->getInt("groupsize");
545 WhoWasMaxGroups = ConfValue("whowas")->getInt("maxgroups");
546 WhoWasMaxKeep = ServerInstance->Duration(ConfValue("whowas")->getString("maxkeep"));
547 MaxChans = ConfValue("channels")->getInt("users", 20);
548 OperMaxChans = ConfValue("channels")->getInt("opers", 60);
549 c_ipv4_range = ConfValue("cidr")->getInt("ipv4clone", 32);
550 c_ipv6_range = ConfValue("cidr")->getInt("ipv6clone", 128);
551 Limits.NickMax = ConfValue("limits")->getInt("maxnick", 32);
552 Limits.ChanMax = ConfValue("limits")->getInt("maxchan", 64);
553 Limits.MaxModes = ConfValue("limits")->getInt("maxmodes", 20);
554 Limits.IdentMax = ConfValue("limits")->getInt("maxident", 11);
555 Limits.MaxQuit = ConfValue("limits")->getInt("maxquit", 255);
556 Limits.MaxTopic = ConfValue("limits")->getInt("maxtopic", 307);
557 Limits.MaxKick = ConfValue("limits")->getInt("maxkick", 255);
558 Limits.MaxGecos = ConfValue("limits")->getInt("maxgecos", 128);
559 Limits.MaxAway = ConfValue("limits")->getInt("maxaway", 200);
560 InvBypassModes = options->getBool("invitebypassmodes", true);
561 NoSnoticeStack = options->getBool("nosnoticestack", false);
562 WelcomeNotice = options->getBool("welcomenotice", true);
564 range(SoftLimit, 10, ServerInstance->SE->GetMaxFds(), ServerInstance->SE->GetMaxFds(), "<performance:softlimit>");
565 if (ConfValue("performance")->getBool("limitsomaxconn", true))
566 range(MaxConn, 0, SOMAXCONN, SOMAXCONN, "<performance:somaxconn>");
567 range(MaxTargets, 1, 31, 20, "<security:maxtargets>");
568 range(NetBufferSize, 1024, 65534, 10240, "<performance:netbuffersize>");
569 range(WhoWasGroupSize, 0, 10000, 10, "<whowas:groupsize>");
570 range(WhoWasMaxGroups, 0, 1000000, 10240, "<whowas:maxgroups>");
571 range(WhoWasMaxKeep, 3600, INT_MAX, 3600, "<whowas:maxkeep>");
573 ValidIP(DNSServer, "<dns:server>");
575 std::string defbind = options->getString("defaultbind");
576 if (assign(defbind) == "ipv4")
578 WildcardIPv6 = false;
580 else if (assign(defbind) == "ipv6")
587 int socktest = socket(AF_INET6, SOCK_STREAM, 0);
589 WildcardIPv6 = false;
591 ServerInstance->SE->Close(socktest);
593 ConfigTagList tags = ConfTags("uline");
594 for(ConfigIter i = tags.first; i != tags.second; ++i)
596 ConfigTag* tag = i->second;
598 if (!tag->readString("server", server))
599 throw CoreException("<uline> tag missing server at " + tag->getTagLocation());
600 ulines[assign(server)] = tag->getBool("silent");
603 tags = ConfTags("banlist");
604 for(ConfigIter i = tags.first; i != tags.second; ++i)
606 ConfigTag* tag = i->second;
608 if (!tag->readString("chan", chan))
609 throw CoreException("<banlist> tag missing chan at " + tag->getTagLocation());
610 maxbans[chan] = tag->getInt("limit");
613 ReadXLine(this, "badip", "ipmask", ServerInstance->XLines->GetFactory("Z"));
614 ReadXLine(this, "badnick", "nick", ServerInstance->XLines->GetFactory("Q"));
615 ReadXLine(this, "badhost", "host", ServerInstance->XLines->GetFactory("K"));
616 ReadXLine(this, "exception", "host", ServerInstance->XLines->GetFactory("E"));
618 memset(DisabledUModes, 0, sizeof(DisabledUModes));
619 std::string modes = ConfValue("disabled")->getString("usermodes");
620 for (std::string::const_iterator p = modes.begin(); p != modes.end(); ++p)
622 // Complain when the character is not a-z or A-Z
623 if ((*p < 'A') || (*p > 'z') || ((*p < 'a') && (*p > 'Z')))
624 throw CoreException("Invalid usermode " + std::string(1, *p) + " was found.");
625 DisabledUModes[*p - 'A'] = 1;
628 memset(DisabledCModes, 0, sizeof(DisabledCModes));
629 modes = ConfValue("disabled")->getString("chanmodes");
630 for (std::string::const_iterator p = modes.begin(); p != modes.end(); ++p)
632 if ((*p < 'A') || (*p > 'z') || ((*p < 'a') && (*p > 'Z')))
633 throw CoreException("Invalid chanmode " + std::string(1, *p) + " was found.");
634 DisabledCModes[*p - 'A'] = 1;
637 memset(HideModeLists, 0, sizeof(HideModeLists));
638 modes = ConfValue("security")->getString("hidemodes");
639 for (std::string::const_iterator p = modes.begin(); p != modes.end(); ++p)
640 HideModeLists[(unsigned char) *p] = true;
642 std::string v = security->getString("announceinvites");
645 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_OPS;
647 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_ALL;
648 else if (v == "dynamic")
649 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_DYNAMIC;
651 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_NONE;
653 v = security->getString("operspywhois");
655 OperSpyWhois = SPYWHOIS_SPLITMSG;
656 else if (v == "on" || v == "yes")
657 OperSpyWhois = SPYWHOIS_SINGLEMSG;
659 OperSpyWhois = SPYWHOIS_NONE;
662 // WARNING: it is not safe to use most of the codebase in this function, as it
663 // will run in the config reader thread
664 void ServerConfig::Read()
666 /* Load and parse the config file, if there are any errors then explode */
668 ParseStack stack(this);
671 valid = stack.ParseFile(ServerInstance->ConfigFileName, 0);
673 catch (CoreException& err)
676 errstr << err.GetReason();
680 DNSServer = ConfValue("dns")->getString("server");
685 void ServerConfig::Apply(ServerConfig* old, const std::string &useruid)
691 * These values can only be set on boot. Keep their old values. Do it before we send messages so we actually have a servername.
693 this->ServerName = old->ServerName;
694 this->sid = old->sid;
695 this->cmdline = old->cmdline;
698 /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
701 for (int Index = 0; Index * sizeof(Deprecated) < sizeof(ChangedConfig); Index++)
704 ConfigTagList tags = ConfTags(ChangedConfig[Index].tag);
705 for(ConfigIter i = tags.first; i != tags.second; ++i)
707 if (i->second->readString(ChangedConfig[Index].value, dummy, true))
708 errstr << "Your configuration contains a deprecated value: <"
709 << ChangedConfig[Index].tag << ":" << ChangedConfig[Index].value << "> - " << ChangedConfig[Index].reason
710 << " (at " << i->second->getTagLocation() << ")\n";
716 // Handle special items
717 CrossCheckOperClassType();
718 CrossCheckConnectBlocks(old);
720 catch (CoreException &ce)
722 errstr << ce.GetReason();
725 // Check errors before dealing with failed binds, since continuing on failed bind is wanted in some circumstances.
726 valid = errstr.str().empty();
728 // write once here, to try it out and make sure its ok
730 ServerInstance->WritePID(this->PID);
734 // On first run, ports are bound later on
736 ServerInstance->BindPorts(pl);
739 errstr << "Not all your client ports could be bound.\nThe following port(s) failed to bind:\n";
742 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
745 snprintf(buf, MAXBUF, "%d. Address: %s Reason: %s\n", j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
751 User* user = useruid.empty() ? NULL : ServerInstance->FindNick(useruid);
755 ServerInstance->Logs->Log("CONFIG",DEFAULT, "There were errors in your configuration file:");
759 while (errstr.good())
762 getline(errstr, line, '\n');
765 // On startup, print out to console (still attached at this point)
767 std::cout << line << std::endl;
768 // If a user is rehashing, tell them directly
770 user->SendText(":%s NOTICE %s :*** %s", ServerInstance->Config->ServerName.c_str(), user->nick.c_str(), line.c_str());
772 ServerInstance->SNO->WriteGlobalSno('a', line);
776 errstr.str(std::string());
778 // Re-parse our MOTD and RULES files for colors -- Justasic
779 for (ClassVector::const_iterator it = this->Classes.begin(), it_end = this->Classes.end(); it != it_end; ++it)
781 ConfigTag *tag = (*it)->config;
782 // Make sure our connection class allows motd colors
783 if(!tag->getBool("allowmotdcolors"))
786 ConfigFileCache::iterator file = this->Files.find(tag->getString("motd", "motd"));
787 if (file != this->Files.end())
788 InspIRCd::ProcessColors(file->second);
790 file = this->Files.find(tag->getString("rules", "rules"));
791 if (file != this->Files.end())
792 InspIRCd::ProcessColors(file->second);
795 /* No old configuration -> initial boot, nothing more to do here */
800 ServerInstance->Exit(EXIT_STATUS_CONFIG);
807 // If there were errors processing configuration, don't touch modules.
814 user->SendText(":%s NOTICE %s :*** Successfully rehashed server.",
815 ServerInstance->Config->ServerName.c_str(), user->nick.c_str());
816 ServerInstance->SNO->WriteGlobalSno('a', "*** Successfully rehashed server.");
819 void ServerConfig::ApplyModules(User* user)
821 Module* whowas = ServerInstance->Modules->Find("cmd_whowas.so");
823 WhowasRequest(NULL, whowas, WhowasRequest::WHOWAS_PRUNE).Send();
825 const std::vector<std::string> v = ServerInstance->Modules->GetAllModuleNames(0);
826 std::vector<std::string> added_modules;
827 std::set<std::string> removed_modules(v.begin(), v.end());
829 ConfigTagList tags = ConfTags("module");
830 for(ConfigIter i = tags.first; i != tags.second; ++i)
832 ConfigTag* tag = i->second;
834 if (tag->readString("name", name))
836 // if this module is already loaded, the erase will succeed, so we need do nothing
837 // otherwise, we need to add the module (which will be done later)
838 if (removed_modules.erase(name) == 0)
839 added_modules.push_back(name);
843 if (ConfValue("options")->getBool("allowhalfop") && removed_modules.erase("m_halfop.so") == 0)
844 added_modules.push_back("m_halfop.so");
846 for (std::set<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
848 // Don't remove cmd_*.so, just remove m_*.so
849 if (removing->c_str()[0] == 'c')
851 Module* m = ServerInstance->Modules->Find(*removing);
852 if (m && ServerInstance->Modules->Unload(m))
854 ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH UNLOADED MODULE: %s",removing->c_str());
857 user->WriteNumeric(RPL_UNLOADEDMODULE, "%s %s :Module %s successfully unloaded.",user->nick.c_str(), removing->c_str(), removing->c_str());
859 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully unloaded.", removing->c_str());
864 user->WriteNumeric(ERR_CANTUNLOADMODULE, "%s %s :Failed to unload module %s: %s",user->nick.c_str(), removing->c_str(), removing->c_str(), ServerInstance->Modules->LastError().c_str());
866 ServerInstance->SNO->WriteGlobalSno('a', "Failed to unload module %s: %s", removing->c_str(), ServerInstance->Modules->LastError().c_str());
870 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
872 if (ServerInstance->Modules->Load(adding->c_str()))
874 ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH LOADED MODULE: %s",adding->c_str());
876 user->WriteNumeric(RPL_LOADEDMODULE, "%s %s :Module %s successfully loaded.",user->nick.c_str(), adding->c_str(), adding->c_str());
878 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully loaded.", adding->c_str());
883 user->WriteNumeric(ERR_CANTLOADMODULE, "%s %s :Failed to load module %s: %s",user->nick.c_str(), adding->c_str(), adding->c_str(), ServerInstance->Modules->LastError().c_str());
885 ServerInstance->SNO->WriteGlobalSno('a', "Failed to load module %s: %s", adding->c_str(), ServerInstance->Modules->LastError().c_str());
890 bool ServerConfig::StartsWithWindowsDriveLetter(const std::string &path)
892 return (path.length() > 2 && isalpha(path[0]) && path[1] == ':');
895 ConfigTag* ServerConfig::ConfValue(const std::string &tag)
897 ConfigTagList found = config_data.equal_range(tag);
898 if (found.first == found.second)
900 ConfigTag* rv = found.first->second;
902 if (found.first != found.second)
903 ServerInstance->Logs->Log("CONFIG",DEFAULT, "Multiple <" + tag + "> tags found; only first will be used "
904 "(first at " + rv->getTagLocation() + "; second at " + found.first->second->getTagLocation() + ")");
908 ConfigTagList ServerConfig::ConfTags(const std::string& tag)
910 return config_data.equal_range(tag);
913 bool ServerConfig::FileExists(const char* file)
916 if (stat(file, &sb) == -1)
919 if ((sb.st_mode & S_IFDIR) > 0)
922 FILE *input = fopen(file, "r");
932 const char* ServerConfig::CleanFilename(const char* name)
934 const char* p = name + strlen(name);
935 while ((p != name) && (*p != '/') && (*p != '\\')) p--;
936 return (p != name ? ++p : p);
939 const std::string& ServerConfig::GetSID()
944 void ConfigReaderThread::Run()
950 void ConfigReaderThread::Finish()
952 ServerConfig* old = ServerInstance->Config;
953 ServerInstance->Logs->Log("CONFIG",DEBUG,"Switching to new configuration...");
954 ServerInstance->Config = this->Config;
955 Config->Apply(old, TheUserUID);
960 * Apply the changed configuration from the rehash.
962 * XXX: The order of these is IMPORTANT, do not reorder them without testing
965 ServerInstance->XLines->CheckELines();
966 ServerInstance->XLines->ApplyLines();
967 ServerInstance->Res->Rehash();
968 ServerInstance->ResetMaxBans();
969 Config->ApplyDisabledCommands(Config->DisabledCommands);
970 User* user = ServerInstance->FindNick(TheUserUID);
971 FOREACH_MOD(I_OnRehash, OnRehash(user));
972 ServerInstance->BuildISupport();
974 ServerInstance->Logs->CloseLogs();
975 ServerInstance->Logs->OpenFileLogs();
977 if (Config->RawLog && !old->RawLog)
978 ServerInstance->Users->ServerNoticeAll("*** Raw I/O logging is enabled on this server. All messages, passwords, and commands are being recorded.");
985 ServerInstance->Config = old;