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();
53 void ServerConfig::Update005()
55 std::stringstream out(data005);
56 std::vector<std::string> data;
59 data.push_back(token);
60 sort(data.begin(), data.end());
64 for(unsigned int i=0; i < data.size(); i++)
67 line5 = line5 + token + " ";
70 line5.append(":are supported by this server");
71 isupport.push_back(line5);
77 line5.append(":are supported by this server");
78 isupport.push_back(line5);
82 void ServerConfig::Send005(User* user)
84 for (std::vector<std::string>::iterator line = ServerInstance->Config->isupport.begin(); line != ServerInstance->Config->isupport.end(); line++)
85 user->WriteNumeric(RPL_ISUPPORT, "%s %s", user->nick.c_str(), line->c_str());
88 template<typename T, typename V>
89 static void range(T& value, V min, V max, V def, const char* msg)
91 if (value >= (T)min && value <= (T)max)
93 ServerInstance->Logs->Log("CONFIG", DEFAULT,
94 "WARNING: %s value of %ld is not between %ld and %ld; set to %ld.",
95 msg, (long)value, (long)min, (long)max, (long)def);
100 static void ValidIP(const std::string& ip, const std::string& key)
102 irc::sockets::sockaddrs dummy;
103 if (!irc::sockets::aptosa(ip, 0, dummy))
104 throw CoreException("The value of "+key+" is not an IP address");
107 static void ValidHost(const std::string& p, const std::string& msg)
110 if (p.empty() || p[0] == '.')
111 throw CoreException("The value of "+msg+" is not a valid hostname");
112 for (unsigned int i=0;i < p.length();i++)
117 throw CoreException("The value of "+msg+" is not a valid hostname");
124 throw CoreException("The value of "+msg+" is not a valid hostname");
127 bool ServerConfig::ApplyDisabledCommands(const std::string& data)
129 std::stringstream dcmds(data);
132 /* Enable everything first */
133 for (Commandtable::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
134 x->second->Disable(false);
136 /* Now disable all the ones which the user wants disabled */
137 while (dcmds >> thiscmd)
139 Commandtable::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
140 if (cm != ServerInstance->Parser->cmdlist.end())
142 cm->second->Disable(true);
148 static void FindDNS(std::string& server)
153 // attempt to look up their nameserver from the system
154 ServerInstance->Logs->Log("CONFIG",DEFAULT,"WARNING: <dns:server> not defined, attempting to find a working server in the system settings...");
156 PFIXED_INFO pFixedInfo;
157 DWORD dwBufferSize = sizeof(FIXED_INFO);
158 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, sizeof(FIXED_INFO));
162 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == ERROR_BUFFER_OVERFLOW) {
163 HeapFree(GetProcessHeap(), 0, pFixedInfo);
164 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, dwBufferSize);
168 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == NO_ERROR)
169 server = pFixedInfo->DnsServerList.IpAddress.String;
171 HeapFree(GetProcessHeap(), 0, pFixedInfo);
176 ServerInstance->Logs->Log("CONFIG",DEFAULT,"<dns:server> set to '%s' as first active resolver in the system settings.", server.c_str());
181 ServerInstance->Logs->Log("CONFIG",DEFAULT,"No viable nameserver found! Defaulting to nameserver '127.0.0.1'!");
183 // attempt to look up their nameserver from /etc/resolv.conf
184 ServerInstance->Logs->Log("CONFIG",DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
186 std::ifstream resolv("/etc/resolv.conf");
188 while (resolv >> server)
190 if (server == "nameserver")
193 if (server.find_first_not_of("0123456789.") == std::string::npos)
195 ServerInstance->Logs->Log("CONFIG",DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",server.c_str());
201 ServerInstance->Logs->Log("CONFIG",DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
203 server = "127.0.0.1";
206 static void ReadXLine(ServerConfig* conf, const std::string& tag, const std::string& key, XLineFactory* make)
208 ConfigTagList tags = conf->ConfTags(tag);
209 for(ConfigIter i = tags.first; i != tags.second; ++i)
211 ConfigTag* ctag = i->second;
213 if (!ctag->readString(key, mask))
214 throw CoreException("<"+tag+":"+key+"> missing at " + ctag->getTagLocation());
215 std::string reason = ctag->getString("reason", "<Config>");
216 XLine* xl = make->Generate(ServerInstance->Time(), 0, "<Config>", reason, mask);
217 if (!ServerInstance->XLines->AddLine(xl, NULL))
222 typedef std::map<std::string, ConfigTag*> LocalIndex;
223 void ServerConfig::CrossCheckOperClassType()
225 LocalIndex operclass;
226 ConfigTagList tags = ConfTags("class");
227 for(ConfigIter i = tags.first; i != tags.second; ++i)
229 ConfigTag* tag = i->second;
230 std::string name = tag->getString("name");
232 throw CoreException("<class:name> missing from tag at " + tag->getTagLocation());
233 if (operclass.find(name) != operclass.end())
234 throw CoreException("Duplicate class block with name " + name + " at " + tag->getTagLocation());
235 operclass[name] = tag;
237 tags = ConfTags("type");
238 for(ConfigIter i = tags.first; i != tags.second; ++i)
240 ConfigTag* tag = i->second;
241 std::string name = tag->getString("name");
243 throw CoreException("<type:name> is missing from tag at " + tag->getTagLocation());
244 if (!ServerInstance->IsNick(name.c_str(), Limits.NickMax))
245 throw CoreException("<type:name> is invalid (value '" + name + "')");
246 if (oper_blocks.find(" " + name) != oper_blocks.end())
247 throw CoreException("Duplicate type block with name " + name + " at " + tag->getTagLocation());
249 OperInfo* ifo = new OperInfo;
250 oper_blocks[" " + name] = ifo;
252 ifo->type_block = tag;
254 std::string classname;
255 irc::spacesepstream str(tag->getString("classes"));
256 while (str.GetToken(classname))
258 LocalIndex::iterator cls = operclass.find(classname);
259 if (cls == operclass.end())
260 throw CoreException("Oper type " + name + " has missing class " + classname);
261 ifo->class_blocks.push_back(cls->second);
265 tags = ConfTags("oper");
266 for(ConfigIter i = tags.first; i != tags.second; ++i)
268 ConfigTag* tag = i->second;
270 std::string name = tag->getString("name");
272 throw CoreException("<oper:name> missing from tag at " + tag->getTagLocation());
274 std::string type = tag->getString("type");
275 OperIndex::iterator tblk = oper_blocks.find(" " + type);
276 if (tblk == oper_blocks.end())
277 throw CoreException("Oper block " + name + " has missing type " + type);
278 if (oper_blocks.find(name) != oper_blocks.end())
279 throw CoreException("Duplicate oper block with name " + name + " at " + tag->getTagLocation());
281 OperInfo* ifo = new OperInfo;
283 ifo->oper_block = tag;
284 ifo->type_block = tblk->second->type_block;
285 ifo->class_blocks.assign(tblk->second->class_blocks.begin(), tblk->second->class_blocks.end());
286 oper_blocks[name] = ifo;
290 void ServerConfig::CrossCheckConnectBlocks(ServerConfig* current)
292 typedef std::map<std::string, ConnectClass*> ClassMap;
293 ClassMap oldBlocksByMask;
296 for(ClassVector::iterator i = current->Classes.begin(); i != current->Classes.end(); ++i)
298 ConnectClass* c = *i;
299 if (c->name.substr(0, 8) != "unnamed-")
301 oldBlocksByMask["n" + c->name] = c;
303 else if (c->type == CC_ALLOW || c->type == CC_DENY)
305 std::string typeMask = (c->type == CC_ALLOW) ? "a" : "d";
307 oldBlocksByMask[typeMask] = c;
312 int blk_count = config_data.count("connect");
315 // No connect blocks found; make a trivial default block
316 std::vector<KeyVal>* items;
317 ConfigTag* tag = ConfigTag::create("connect", "<auto>", 0, items);
318 items->push_back(std::make_pair("allow", "*"));
319 config_data.insert(std::make_pair("connect", tag));
323 Classes.resize(blk_count);
324 std::map<std::string, int> names;
326 bool try_again = true;
327 for(int tries=0; try_again; tries++)
330 ConfigTagList tags = ConfTags("connect");
332 for(ConfigIter it = tags.first; it != tags.second; ++it, ++i)
334 ConfigTag* tag = it->second;
338 ConnectClass* parent = NULL;
339 std::string parentName = tag->getString("parent");
340 if (!parentName.empty())
342 std::map<std::string,int>::iterator parentIter = names.find(parentName);
343 if (parentIter == names.end())
346 // couldn't find parent this time. If it's the last time, we'll never find it.
347 if (tries >= blk_count)
348 throw CoreException("Could not find parent connect class \"" + parentName + "\" for connect block at " + tag->getTagLocation());
351 parent = Classes[parentIter->second];
354 std::string name = tag->getString("name");
355 std::string mask, typeMask;
358 if (tag->readString("allow", mask, false))
361 typeMask = 'a' + mask;
363 else if (tag->readString("deny", mask, false))
366 typeMask = 'd' + mask;
368 else if (!name.empty())
372 typeMask = 'n' + mask;
376 throw CoreException("Connect class must have allow, deny, or name specified at " + tag->getTagLocation());
381 name = "unnamed-" + ConvToStr(i);
385 typeMask = 'n' + name;
388 if (names.find(name) != names.end())
389 throw CoreException("Two connect classes with name \"" + name + "\" defined!");
392 ConnectClass* me = parent ?
393 new ConnectClass(tag, type, mask, *parent) :
394 new ConnectClass(tag, type, mask);
398 me->registration_timeout = tag->getInt("timeout", me->registration_timeout);
399 me->pingtime = tag->getInt("pingfreq", me->pingtime);
401 if (tag->readString("sendq", sendq))
403 // attempt to guess a good hard/soft sendq from a single value
404 long value = atol(sendq.c_str());
406 me->softsendqmax = value / 16;
408 me->softsendqmax = value;
409 me->hardsendqmax = value * 8;
411 me->softsendqmax = tag->getInt("softsendq", me->softsendqmax);
412 me->hardsendqmax = tag->getInt("hardsendq", me->hardsendqmax);
413 me->recvqmax = tag->getInt("recvq", me->recvqmax);
414 me->penaltythreshold = tag->getInt("threshold", me->penaltythreshold);
415 me->commandrate = tag->getInt("commandrate", me->commandrate);
416 me->fakelag = tag->getBool("fakelag", me->fakelag);
417 me->maxlocal = tag->getInt("localmax", me->maxlocal);
418 me->maxglobal = tag->getInt("globalmax", me->maxglobal);
419 me->maxchans = tag->getInt("maxchans", me->maxchans);
420 me->maxconnwarn = tag->getBool("maxconnwarn", me->maxconnwarn);
421 me->limit = tag->getInt("limit", me->limit);
423 ClassMap::iterator oldMask = oldBlocksByMask.find(typeMask);
424 if (oldMask != oldBlocksByMask.end())
426 ConnectClass* old = oldMask->second;
427 oldBlocksByMask.erase(oldMask);
437 /** Represents a deprecated configuration tag.
447 /** Reason for deprecation
452 static const Deprecated ChangedConfig[] = {
453 {"options", "hidelinks", "has been moved to <security:hidelinks> as of 1.2a3"},
454 {"options", "hidewhois", "has been moved to <security:hidewhois> as of 1.2a3"},
455 {"options", "userstats", "has been moved to <security:userstats> as of 1.2a3"},
456 {"options", "customversion", "has been moved to <security:customversion> as of 1.2a3"},
457 {"options", "hidesplits", "has been moved to <security:hidesplits> as of 1.2a3"},
458 {"options", "hidebans", "has been moved to <security:hidebans> as of 1.2a3"},
459 {"options", "hidekills", "has been moved to <security:hidekills> as of 1.2a3"},
460 {"options", "operspywhois", "has been moved to <security:operspywhois> as of 1.2a3"},
461 {"options", "announceinvites", "has been moved to <security:announceinvites> as of 1.2a3"},
462 {"options", "hidemodes", "has been moved to <security:hidemodes> as of 1.2a3"},
463 {"options", "maxtargets", "has been moved to <security:maxtargets> as of 1.2a3"},
464 {"options", "nouserdns", "has been moved to <performance:nouserdns> as of 1.2a3"},
465 {"options", "maxwho", "has been moved to <performance:maxwho> as of 1.2a3"},
466 {"options", "softlimit", "has been moved to <performance:softlimit> as of 1.2a3"},
467 {"options", "somaxconn", "has been moved to <performance:somaxconn> as of 1.2a3"},
468 {"options", "netbuffersize", "has been moved to <performance:netbuffersize> as of 1.2a3"},
469 {"options", "maxwho", "has been moved to <performance:maxwho> as of 1.2a3"},
470 {"options", "loglevel", "1.2+ does not use the loglevel value. Please define <log> tags instead."},
471 {"die", "value", "you need to reread your config"},
472 {"bind", "transport", "has been moved to <bind:ssl> as of 2.0a1"},
473 {"link", "transport", "has been moved to <link:ssl> as of 2.0a1"},
474 {"link", "autoconnect", "2.0+ does not use the autoconnect value. Please define <autoconnect> tags instead."},
477 void ServerConfig::Fill()
479 ConfigTag* options = ConfValue("options");
480 ConfigTag* security = ConfValue("security");
483 ServerName = ConfValue("server")->getString("name");
484 sid = ConfValue("server")->getString("id");
485 ValidHost(ServerName, "<server:name>");
486 if (!sid.empty() && !ServerInstance->IsSID(sid))
487 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.");
491 if (ServerName != ConfValue("server")->getString("name"))
492 throw CoreException("You must restart to change the server name or SID");
493 std::string nsid = ConfValue("server")->getString("id");
494 if (!nsid.empty() && nsid != sid)
495 throw CoreException("You must restart to change the server name or SID");
497 diepass = ConfValue("power")->getString("diepass");
498 restartpass = ConfValue("power")->getString("restartpass");
499 powerhash = ConfValue("power")->getString("hash");
500 PrefixQuit = options->getString("prefixquit");
501 SuffixQuit = options->getString("suffixquit");
502 FixedQuit = options->getString("fixedquit");
503 PrefixPart = options->getString("prefixpart");
504 SuffixPart = options->getString("suffixpart");
505 FixedPart = options->getString("fixedpart");
506 SoftLimit = ConfValue("performance")->getInt("softlimit", ServerInstance->SE->GetMaxFds());
507 MaxConn = ConfValue("performance")->getInt("somaxconn", SOMAXCONN);
508 MoronBanner = options->getString("moronbanner", "You're banned!");
509 ServerDesc = ConfValue("server")->getString("description", "Configure Me");
510 Network = ConfValue("server")->getString("network", "Network");
511 AdminName = ConfValue("admin")->getString("name", "");
512 AdminEmail = ConfValue("admin")->getString("email", "null@example.com");
513 AdminNick = ConfValue("admin")->getString("nick", "admin");
514 ModPath = ConfValue("path")->getString("moduledir", MOD_PATH);
515 NetBufferSize = ConfValue("performance")->getInt("netbuffersize", 10240);
516 dns_timeout = ConfValue("dns")->getInt("timeout", 5);
517 DisabledCommands = ConfValue("disabled")->getString("commands", "");
518 DisabledDontExist = ConfValue("disabled")->getBool("fakenonexistant");
519 UserStats = security->getString("userstats");
520 CustomVersion = security->getString("customversion", Network + " IRCd");
521 HideSplits = security->getBool("hidesplits");
522 HideBans = security->getBool("hidebans");
523 HideWhoisServer = security->getString("hidewhois");
524 HideKillsServer = security->getString("hidekills");
525 RestrictBannedUsers = security->getBool("restrictbannedusers", true);
526 GenericOper = security->getBool("genericoper");
527 NoUserDns = ConfValue("performance")->getBool("nouserdns");
528 SyntaxHints = options->getBool("syntaxhints");
529 CycleHosts = options->getBool("cyclehosts");
530 CycleHostsFromUser = options->getBool("cyclehostsfromuser");
531 UndernetMsgPrefix = options->getBool("ircumsgprefix");
532 FullHostInTopic = options->getBool("hostintopic");
533 MaxTargets = security->getInt("maxtargets", 20);
534 DefaultModes = options->getString("defaultmodes", "nt");
535 PID = ConfValue("pid")->getString("file");
536 WhoWasGroupSize = ConfValue("whowas")->getInt("groupsize");
537 WhoWasMaxGroups = ConfValue("whowas")->getInt("maxgroups");
538 WhoWasMaxKeep = ServerInstance->Duration(ConfValue("whowas")->getString("maxkeep"));
539 MaxChans = ConfValue("channels")->getInt("users", 20);
540 OperMaxChans = ConfValue("channels")->getInt("opers", 60);
541 c_ipv4_range = ConfValue("cidr")->getInt("ipv4clone", 32);
542 c_ipv6_range = ConfValue("cidr")->getInt("ipv6clone", 128);
543 Limits.NickMax = ConfValue("limits")->getInt("maxnick", 32);
544 Limits.ChanMax = ConfValue("limits")->getInt("maxchan", 64);
545 Limits.MaxModes = ConfValue("limits")->getInt("maxmodes", 20);
546 Limits.IdentMax = ConfValue("limits")->getInt("maxident", 11);
547 Limits.MaxQuit = ConfValue("limits")->getInt("maxquit", 255);
548 Limits.MaxTopic = ConfValue("limits")->getInt("maxtopic", 307);
549 Limits.MaxKick = ConfValue("limits")->getInt("maxkick", 255);
550 Limits.MaxGecos = ConfValue("limits")->getInt("maxgecos", 128);
551 Limits.MaxAway = ConfValue("limits")->getInt("maxaway", 200);
552 InvBypassModes = options->getBool("invitebypassmodes", true);
553 NoSnoticeStack = options->getBool("nosnoticestack", false);
554 WelcomeNotice = options->getBool("welcomenotice", true);
556 range(SoftLimit, 10, ServerInstance->SE->GetMaxFds(), ServerInstance->SE->GetMaxFds(), "<performance:softlimit>");
557 range(MaxConn, 0, SOMAXCONN, SOMAXCONN, "<performance:somaxconn>");
558 range(MaxTargets, 1, 31, 20, "<security:maxtargets>");
559 range(NetBufferSize, 1024, 65534, 10240, "<performance:netbuffersize>");
560 range(WhoWasGroupSize, 0, 10000, 10, "<whowas:groupsize>");
561 range(WhoWasMaxGroups, 0, 1000000, 10240, "<whowas:maxgroups>");
562 range(WhoWasMaxKeep, 3600, INT_MAX, 3600, "<whowas:maxkeep>");
564 ValidIP(DNSServer, "<dns:server>");
566 std::string defbind = options->getString("defaultbind");
567 if (assign(defbind) == "ipv4")
569 WildcardIPv6 = false;
571 else if (assign(defbind) == "ipv6")
578 int socktest = socket(AF_INET6, SOCK_STREAM, 0);
580 WildcardIPv6 = false;
582 ServerInstance->SE->Close(socktest);
584 ConfigTagList tags = ConfTags("uline");
585 for(ConfigIter i = tags.first; i != tags.second; ++i)
587 ConfigTag* tag = i->second;
589 if (!tag->readString("server", server))
590 throw CoreException("<uline> tag missing server at " + tag->getTagLocation());
591 ulines[assign(server)] = tag->getBool("silent");
594 tags = ConfTags("banlist");
595 for(ConfigIter i = tags.first; i != tags.second; ++i)
597 ConfigTag* tag = i->second;
599 if (!tag->readString("chan", chan))
600 throw CoreException("<banlist> tag missing chan at " + tag->getTagLocation());
601 maxbans[chan] = tag->getInt("limit");
604 ReadXLine(this, "badip", "ipmask", ServerInstance->XLines->GetFactory("Z"));
605 ReadXLine(this, "badnick", "nick", ServerInstance->XLines->GetFactory("Q"));
606 ReadXLine(this, "badhost", "host", ServerInstance->XLines->GetFactory("K"));
607 ReadXLine(this, "exception", "host", ServerInstance->XLines->GetFactory("E"));
609 memset(DisabledUModes, 0, sizeof(DisabledUModes));
610 std::string modes = ConfValue("disabled")->getString("usermodes");
611 for (std::string::const_iterator p = modes.begin(); p != modes.end(); ++p)
613 // Complain when the character is not a-z or A-Z
614 if ((*p < 'A') || (*p > 'z') || ((*p < 'a') && (*p > 'Z')))
615 throw CoreException("Invalid usermode " + std::string(1, *p) + " was found.");
616 DisabledUModes[*p - 'A'] = 1;
619 memset(DisabledCModes, 0, sizeof(DisabledCModes));
620 modes = ConfValue("disabled")->getString("chanmodes");
621 for (std::string::const_iterator p = modes.begin(); p != modes.end(); ++p)
623 if ((*p < 'A') || (*p > 'z') || ((*p < 'a') && (*p > 'Z')))
624 throw CoreException("Invalid chanmode " + std::string(1, *p) + " was found.");
625 DisabledCModes[*p - 'A'] = 1;
628 memset(HideModeLists, 0, sizeof(HideModeLists));
629 modes = ConfValue("security")->getString("hidemodes");
630 for (std::string::const_iterator p = modes.begin(); p != modes.end(); ++p)
631 HideModeLists[(unsigned char) *p] = true;
633 std::string v = security->getString("announceinvites");
636 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_OPS;
638 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_ALL;
639 else if (v == "dynamic")
640 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_DYNAMIC;
642 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_NONE;
644 v = security->getString("operspywhois");
646 OperSpyWhois = SPYWHOIS_SPLITMSG;
647 else if (v == "on" || v == "yes")
648 OperSpyWhois = SPYWHOIS_SINGLEMSG;
650 OperSpyWhois = SPYWHOIS_NONE;
653 // WARNING: it is not safe to use most of the codebase in this function, as it
654 // will run in the config reader thread
655 void ServerConfig::Read()
657 /* Load and parse the config file, if there are any errors then explode */
659 ParseStack stack(this);
662 valid = stack.ParseFile(ServerInstance->ConfigFileName, 0);
664 catch (CoreException& err)
667 errstr << err.GetReason();
671 DNSServer = ConfValue("dns")->getString("server");
676 void ServerConfig::Apply(ServerConfig* old, const std::string &useruid)
682 * These values can only be set on boot. Keep their old values. Do it before we send messages so we actually have a servername.
684 this->ServerName = old->ServerName;
685 this->sid = old->sid;
686 this->cmdline = old->cmdline;
689 /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
692 for (int Index = 0; Index * sizeof(Deprecated) < sizeof(ChangedConfig); Index++)
695 ConfigTagList tags = ConfTags(ChangedConfig[Index].tag);
696 for(ConfigIter i = tags.first; i != tags.second; ++i)
698 if (i->second->readString(ChangedConfig[Index].value, dummy, true))
699 errstr << "Your configuration contains a deprecated value: <"
700 << ChangedConfig[Index].tag << ":" << ChangedConfig[Index].value << "> - " << ChangedConfig[Index].reason
701 << " (at " << i->second->getTagLocation() << ")\n";
707 // Handle special items
708 CrossCheckOperClassType();
709 CrossCheckConnectBlocks(old);
711 catch (CoreException &ce)
713 errstr << ce.GetReason();
716 // Check errors before dealing with failed binds, since continuing on failed bind is wanted in some circumstances.
717 valid = errstr.str().empty();
719 // write once here, to try it out and make sure its ok
721 ServerInstance->WritePID(this->PID);
725 // On first run, ports are bound later on
727 ServerInstance->BindPorts(pl);
730 errstr << "Not all your client ports could be bound.\nThe following port(s) failed to bind:\n";
733 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
736 snprintf(buf, MAXBUF, "%d. Address: %s Reason: %s\n", j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
742 User* user = useruid.empty() ? NULL : ServerInstance->FindNick(useruid);
745 ServerInstance->Logs->Log("CONFIG",DEFAULT, "There were errors in your configuration file:");
747 while (errstr.good())
750 getline(errstr, line, '\n');
753 // On startup, print out to console (still attached at this point)
755 std::cout << line << std::endl;
756 // If a user is rehashing, tell them directly
758 user->SendText(":%s NOTICE %s :*** %s", ServerInstance->Config->ServerName.c_str(), user->nick.c_str(), line.c_str());
760 ServerInstance->SNO->WriteGlobalSno('a', line);
764 errstr.str(std::string());
766 // Re-parse our MOTD and RULES files for colors -- Justasic
767 for (ClassVector::const_iterator it = this->Classes.begin(), it_end = this->Classes.end(); it != it_end; ++it)
769 ConfigTag *tag = (*it)->config;
770 // Make sure our connection class allows motd colors
771 if(!tag->getBool("allowmotdcolors"))
774 ConfigFileCache::iterator file = this->Files.find(tag->getString("motd", "motd"));
775 if (file != this->Files.end())
776 InspIRCd::ProcessColors(file->second);
778 file = this->Files.find(tag->getString("rules", "rules"));
779 if (file != this->Files.end())
780 InspIRCd::ProcessColors(file->second);
783 /* No old configuration -> initial boot, nothing more to do here */
788 ServerInstance->Exit(EXIT_STATUS_CONFIG);
795 // If there were errors processing configuration, don't touch modules.
802 user->SendText(":%s NOTICE %s :*** Successfully rehashed server.",
803 ServerInstance->Config->ServerName.c_str(), user->nick.c_str());
804 ServerInstance->SNO->WriteGlobalSno('a', "*** Successfully rehashed server.");
807 void ServerConfig::ApplyModules(User* user)
809 Module* whowas = ServerInstance->Modules->Find("cmd_whowas.so");
811 WhowasRequest(NULL, whowas, WhowasRequest::WHOWAS_PRUNE).Send();
813 const std::vector<std::string> v = ServerInstance->Modules->GetAllModuleNames(0);
814 std::vector<std::string> added_modules;
815 std::set<std::string> removed_modules(v.begin(), v.end());
817 ConfigTagList tags = ConfTags("module");
818 for(ConfigIter i = tags.first; i != tags.second; ++i)
820 ConfigTag* tag = i->second;
822 if (tag->readString("name", name))
824 // if this module is already loaded, the erase will succeed, so we need do nothing
825 // otherwise, we need to add the module (which will be done later)
826 if (removed_modules.erase(name) == 0)
827 added_modules.push_back(name);
831 if (ConfValue("options")->getBool("allowhalfop") && removed_modules.erase("m_halfop.so") == 0)
832 added_modules.push_back("m_halfop.so");
834 for (std::set<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
836 // Don't remove cmd_*.so, just remove m_*.so
837 if (removing->c_str()[0] == 'c')
839 Module* m = ServerInstance->Modules->Find(*removing);
840 if (m && ServerInstance->Modules->Unload(m))
842 ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH UNLOADED MODULE: %s",removing->c_str());
845 user->WriteNumeric(RPL_UNLOADEDMODULE, "%s %s :Module %s successfully unloaded.",user->nick.c_str(), removing->c_str(), removing->c_str());
847 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully unloaded.", removing->c_str());
852 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());
854 ServerInstance->SNO->WriteGlobalSno('a', "Failed to unload module %s: %s", removing->c_str(), ServerInstance->Modules->LastError().c_str());
858 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
860 if (ServerInstance->Modules->Load(adding->c_str()))
862 ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH LOADED MODULE: %s",adding->c_str());
864 user->WriteNumeric(RPL_LOADEDMODULE, "%s %s :Module %s successfully loaded.",user->nick.c_str(), adding->c_str(), adding->c_str());
866 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully loaded.", adding->c_str());
871 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());
873 ServerInstance->SNO->WriteGlobalSno('a', "Failed to load module %s: %s", adding->c_str(), ServerInstance->Modules->LastError().c_str());
878 bool ServerConfig::StartsWithWindowsDriveLetter(const std::string &path)
880 return (path.length() > 2 && isalpha(path[0]) && path[1] == ':');
883 ConfigTag* ServerConfig::ConfValue(const std::string &tag)
885 ConfigTagList found = config_data.equal_range(tag);
886 if (found.first == found.second)
888 ConfigTag* rv = found.first->second;
890 if (found.first != found.second)
891 ServerInstance->Logs->Log("CONFIG",DEFAULT, "Multiple <" + tag + "> tags found; only first will be used "
892 "(first at " + rv->getTagLocation() + "; second at " + found.first->second->getTagLocation() + ")");
896 ConfigTagList ServerConfig::ConfTags(const std::string& tag)
898 return config_data.equal_range(tag);
901 bool ServerConfig::FileExists(const char* file)
904 if (stat(file, &sb) == -1)
907 if ((sb.st_mode & S_IFDIR) > 0)
910 FILE *input = fopen(file, "r");
920 const char* ServerConfig::CleanFilename(const char* name)
922 const char* p = name + strlen(name);
923 while ((p != name) && (*p != '/') && (*p != '\\')) p--;
924 return (p != name ? ++p : p);
927 const std::string& ServerConfig::GetSID()
932 void ConfigReaderThread::Run()
938 void ConfigReaderThread::Finish()
940 ServerConfig* old = ServerInstance->Config;
941 ServerInstance->Logs->Log("CONFIG",DEBUG,"Switching to new configuration...");
942 ServerInstance->Config = this->Config;
943 Config->Apply(old, TheUserUID);
948 * Apply the changed configuration from the rehash.
950 * XXX: The order of these is IMPORTANT, do not reorder them without testing
953 ServerInstance->XLines->CheckELines();
954 ServerInstance->XLines->ApplyLines();
955 ServerInstance->Res->Rehash();
956 ServerInstance->ResetMaxBans();
957 Config->ApplyDisabledCommands(Config->DisabledCommands);
958 User* user = ServerInstance->FindNick(TheUserUID);
959 FOREACH_MOD(I_OnRehash, OnRehash(user));
960 ServerInstance->BuildISupport();
962 ServerInstance->Logs->CloseLogs();
963 ServerInstance->Logs->OpenFileLogs();
965 if (Config->RawLog && !old->RawLog)
966 ServerInstance->Users->ServerNoticeAll("*** Raw I/O logging is enabled on this server. All messages, passwords, and commands are being recorded.");
973 ServerInstance->Config = old;