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 "configparser.h"
33 #pragma comment(lib, "Iphlpapi.lib")
36 ServerConfig::ServerConfig()
38 RawLog = NoUserDns = HideBans = HideSplits = UndernetMsgPrefix = false;
39 WildcardIPv6 = CycleHosts = InvBypassModes = true;
42 NetBufferSize = 10240;
43 SoftLimit = ServerInstance->SE->GetMaxFds();
51 void ServerConfig::Update005()
53 std::stringstream out(data005);
54 std::vector<std::string> data;
57 data.push_back(token);
58 sort(data.begin(), data.end());
62 for(unsigned int i=0; i < data.size(); i++)
65 line5 = line5 + token + " ";
68 line5.append(":are supported by this server");
69 isupport.push_back(line5);
75 line5.append(":are supported by this server");
76 isupport.push_back(line5);
80 void ServerConfig::Send005(User* user)
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());
86 template<typename T, typename V>
87 static void range(T& value, V min, V max, V def, const char* msg)
89 if (value >= (T)min && value <= (T)max)
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);
98 static void ValidIP(const std::string& ip, const std::string& key)
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");
105 static void ValidHost(const std::string& p, const std::string& msg)
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++)
115 throw CoreException("The value of "+msg+" is not a valid hostname");
122 throw CoreException("The value of "+msg+" is not a valid hostname");
125 bool ServerConfig::ApplyDisabledCommands(const std::string& data)
127 std::stringstream dcmds(data);
130 /* Enable everything first */
131 for (Commandtable::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
132 x->second->Disable(false);
134 /* Now disable all the ones which the user wants disabled */
135 while (dcmds >> thiscmd)
137 Commandtable::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
138 if (cm != ServerInstance->Parser->cmdlist.end())
140 cm->second->Disable(true);
146 static void FindDNS(std::string& server)
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...");
154 PFIXED_INFO pFixedInfo;
155 DWORD dwBufferSize = sizeof(FIXED_INFO);
156 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, sizeof(FIXED_INFO));
160 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == ERROR_BUFFER_OVERFLOW) {
161 HeapFree(GetProcessHeap(), 0, pFixedInfo);
162 pFixedInfo = (PFIXED_INFO) HeapAlloc(GetProcessHeap(), 0, dwBufferSize);
166 if (GetNetworkParams(pFixedInfo, &dwBufferSize) == NO_ERROR)
167 server = pFixedInfo->DnsServerList.IpAddress.String;
169 HeapFree(GetProcessHeap(), 0, pFixedInfo);
174 ServerInstance->Logs->Log("CONFIG",DEFAULT,"<dns:server> set to '%s' as first active resolver in the system settings.", server.c_str());
179 ServerInstance->Logs->Log("CONFIG",DEFAULT,"No viable nameserver found! Defaulting to nameserver '127.0.0.1'!");
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...");
184 std::ifstream resolv("/etc/resolv.conf");
186 while (resolv >> server)
188 if (server == "nameserver")
191 if (server.find_first_not_of("0123456789.") == std::string::npos)
193 ServerInstance->Logs->Log("CONFIG",DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",server.c_str());
199 ServerInstance->Logs->Log("CONFIG",DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
201 server = "127.0.0.1";
204 static void ReadXLine(ServerConfig* conf, const std::string& tag, const std::string& key, XLineFactory* make)
206 ConfigTagList tags = conf->ConfTags(tag);
207 for(ConfigIter i = tags.first; i != tags.second; ++i)
209 ConfigTag* ctag = i->second;
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))
220 typedef std::map<std::string, ConfigTag*> LocalIndex;
221 void ServerConfig::CrossCheckOperClassType()
223 LocalIndex operclass;
224 ConfigTagList tags = ConfTags("class");
225 for(ConfigIter i = tags.first; i != tags.second; ++i)
227 ConfigTag* tag = i->second;
228 std::string name = tag->getString("name");
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;
235 tags = ConfTags("type");
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("<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());
247 OperInfo* ifo = new OperInfo;
248 oper_blocks[" " + name] = ifo;
250 ifo->type_block = tag;
252 std::string classname;
253 irc::spacesepstream str(tag->getString("classes"));
254 while (str.GetToken(classname))
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);
263 tags = ConfTags("oper");
264 for(ConfigIter i = tags.first; i != tags.second; ++i)
266 ConfigTag* tag = i->second;
268 std::string name = tag->getString("name");
270 throw CoreException("<oper:name> missing from tag at " + tag->getTagLocation());
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());
279 OperInfo* ifo = new OperInfo;
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;
288 void ServerConfig::CrossCheckConnectBlocks(ServerConfig* current)
290 typedef std::map<std::string, ConnectClass*> ClassMap;
291 ClassMap oldBlocksByMask;
294 for(ClassVector::iterator i = current->Classes.begin(); i != current->Classes.end(); ++i)
296 ConnectClass* c = *i;
297 if (c->name.substr(0, 8) != "unnamed-")
299 oldBlocksByMask["n" + c->name] = c;
301 else if (c->type == CC_ALLOW || c->type == CC_DENY)
303 std::string typeMask = (c->type == CC_ALLOW) ? "a" : "d";
305 oldBlocksByMask[typeMask] = c;
310 int blk_count = config_data.count("connect");
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));
321 Classes.resize(blk_count);
322 std::map<std::string, int> names;
324 bool try_again = true;
325 for(int tries=0; try_again; tries++)
328 ConfigTagList tags = ConfTags("connect");
330 for(ConfigIter it = tags.first; it != tags.second; ++it, ++i)
332 ConfigTag* tag = it->second;
336 ConnectClass* parent = NULL;
337 std::string parentName = tag->getString("parent");
338 if (!parentName.empty())
340 std::map<std::string,int>::iterator parentIter = names.find(parentName);
341 if (parentIter == names.end())
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());
349 parent = Classes[parentIter->second];
352 std::string name = tag->getString("name");
353 std::string mask, typeMask;
356 if (tag->readString("allow", mask, false))
359 typeMask = 'a' + mask;
361 else if (tag->readString("deny", mask, false))
364 typeMask = 'd' + mask;
366 else if (!name.empty())
370 typeMask = 'n' + mask;
374 throw CoreException("Connect class must have allow, deny, or name specified at " + tag->getTagLocation());
379 name = "unnamed-" + ConvToStr(i);
383 typeMask = 'n' + name;
386 if (names.find(name) != names.end())
387 throw CoreException("Two connect classes with name \"" + name + "\" defined!");
390 ConnectClass* me = parent ?
391 new ConnectClass(tag, type, mask, *parent) :
392 new ConnectClass(tag, type, mask);
396 me->registration_timeout = tag->getInt("timeout", me->registration_timeout);
397 me->pingtime = tag->getInt("pingfreq", me->pingtime);
399 if (tag->readString("sendq", sendq))
401 // attempt to guess a good hard/soft sendq from a single value
402 long value = atol(sendq.c_str());
404 me->softsendqmax = value / 16;
406 me->softsendqmax = value;
407 me->hardsendqmax = value * 8;
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);
421 ClassMap::iterator oldMask = oldBlocksByMask.find(typeMask);
422 if (oldMask != oldBlocksByMask.end())
424 ConnectClass* old = oldMask->second;
425 oldBlocksByMask.erase(oldMask);
435 /** Represents a deprecated configuration tag.
437 struct DeprecatedConfig
442 /** Attribute key. */
445 /** Attribute value. */
448 /** Reason for deprecation. */
452 static const DeprecatedConfig ChangedConfig[] = {
453 { "bind", "transport", "", "has been moved to <bind:ssl> as of 2.0" },
454 { "die", "value", "", "you need to reread your config" },
455 { "link", "autoconnect", "", "2.0+ does not use this attribute - define <autoconnect> tags instead" },
456 { "link", "transport", "", "has been moved to <link:ssl> as of 2.0" },
457 { "module", "name", "m_chanprotect.so", "has been replaced with m_customprefix as of 2.2" },
458 { "module", "name", "m_halfop.so", "has been replaced with m_customprefix as of 2.2" },
461 void ServerConfig::Fill()
463 ConfigTag* options = ConfValue("options");
464 ConfigTag* security = ConfValue("security");
467 ServerName = ConfValue("server")->getString("name");
468 sid = ConfValue("server")->getString("id");
469 ValidHost(ServerName, "<server:name>");
470 if (!sid.empty() && !InspIRCd::IsSID(sid))
471 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.");
475 if (ServerName != ConfValue("server")->getString("name"))
476 throw CoreException("You must restart to change the server name or SID");
477 std::string nsid = ConfValue("server")->getString("id");
478 if (!nsid.empty() && nsid != sid)
479 throw CoreException("You must restart to change the server name or SID");
481 diepass = ConfValue("power")->getString("diepass");
482 restartpass = ConfValue("power")->getString("restartpass");
483 powerhash = ConfValue("power")->getString("hash");
484 PrefixQuit = options->getString("prefixquit");
485 SuffixQuit = options->getString("suffixquit");
486 FixedQuit = options->getString("fixedquit");
487 PrefixPart = options->getString("prefixpart");
488 SuffixPart = options->getString("suffixpart");
489 FixedPart = options->getString("fixedpart");
490 SoftLimit = ConfValue("performance")->getInt("softlimit", ServerInstance->SE->GetMaxFds());
491 MaxConn = ConfValue("performance")->getInt("somaxconn", SOMAXCONN);
492 MoronBanner = options->getString("moronbanner", "You're banned!");
493 ServerDesc = ConfValue("server")->getString("description", "Configure Me");
494 Network = ConfValue("server")->getString("network", "Network");
495 AdminName = ConfValue("admin")->getString("name", "");
496 AdminEmail = ConfValue("admin")->getString("email", "null@example.com");
497 AdminNick = ConfValue("admin")->getString("nick", "admin");
498 ModPath = ConfValue("path")->getString("moduledir", MOD_PATH);
499 NetBufferSize = ConfValue("performance")->getInt("netbuffersize", 10240);
500 dns_timeout = ConfValue("dns")->getInt("timeout", 5);
501 DisabledCommands = ConfValue("disabled")->getString("commands", "");
502 DisabledDontExist = ConfValue("disabled")->getBool("fakenonexistant");
503 UserStats = security->getString("userstats");
504 CustomVersion = security->getString("customversion", Network + " IRCd");
505 HideSplits = security->getBool("hidesplits");
506 HideBans = security->getBool("hidebans");
507 HideWhoisServer = security->getString("hidewhois");
508 HideKillsServer = security->getString("hidekills");
509 RestrictBannedUsers = security->getBool("restrictbannedusers", true);
510 GenericOper = security->getBool("genericoper");
511 NoUserDns = ConfValue("performance")->getBool("nouserdns");
512 SyntaxHints = options->getBool("syntaxhints");
513 CycleHosts = options->getBool("cyclehosts");
514 CycleHostsFromUser = options->getBool("cyclehostsfromuser");
515 UndernetMsgPrefix = options->getBool("ircumsgprefix");
516 FullHostInTopic = options->getBool("hostintopic");
517 MaxTargets = security->getInt("maxtargets", 20);
518 DefaultModes = options->getString("defaultmodes", "nt");
519 PID = ConfValue("pid")->getString("file");
520 MaxChans = ConfValue("channels")->getInt("users", 20);
521 OperMaxChans = ConfValue("channels")->getInt("opers", 60);
522 c_ipv4_range = ConfValue("cidr")->getInt("ipv4clone", 32);
523 c_ipv6_range = ConfValue("cidr")->getInt("ipv6clone", 128);
524 Limits.NickMax = ConfValue("limits")->getInt("maxnick", 32);
525 Limits.ChanMax = ConfValue("limits")->getInt("maxchan", 64);
526 Limits.MaxModes = ConfValue("limits")->getInt("maxmodes", 20);
527 Limits.IdentMax = ConfValue("limits")->getInt("maxident", 11);
528 Limits.MaxQuit = ConfValue("limits")->getInt("maxquit", 255);
529 Limits.MaxTopic = ConfValue("limits")->getInt("maxtopic", 307);
530 Limits.MaxKick = ConfValue("limits")->getInt("maxkick", 255);
531 Limits.MaxGecos = ConfValue("limits")->getInt("maxgecos", 128);
532 Limits.MaxAway = ConfValue("limits")->getInt("maxaway", 200);
533 InvBypassModes = options->getBool("invitebypassmodes", true);
534 NoSnoticeStack = options->getBool("nosnoticestack", false);
536 range(SoftLimit, 10, ServerInstance->SE->GetMaxFds(), ServerInstance->SE->GetMaxFds(), "<performance:softlimit>");
537 range(MaxConn, 0, SOMAXCONN, SOMAXCONN, "<performance:somaxconn>");
538 range(MaxTargets, 1, 31, 20, "<security:maxtargets>");
539 range(NetBufferSize, 1024, 65534, 10240, "<performance:netbuffersize>");
541 ValidIP(DNSServer, "<dns:server>");
543 std::string defbind = options->getString("defaultbind");
544 if (assign(defbind) == "ipv4")
546 WildcardIPv6 = false;
548 else if (assign(defbind) == "ipv6")
555 int socktest = socket(AF_INET6, SOCK_STREAM, 0);
557 WildcardIPv6 = false;
559 ServerInstance->SE->Close(socktest);
561 ConfigTagList tags = ConfTags("uline");
562 for(ConfigIter i = tags.first; i != tags.second; ++i)
564 ConfigTag* tag = i->second;
566 if (!tag->readString("server", server))
567 throw CoreException("<uline> tag missing server at " + tag->getTagLocation());
568 ulines[assign(server)] = tag->getBool("silent");
571 tags = ConfTags("banlist");
572 for(ConfigIter i = tags.first; i != tags.second; ++i)
574 ConfigTag* tag = i->second;
576 if (!tag->readString("chan", chan))
577 throw CoreException("<banlist> tag missing chan at " + tag->getTagLocation());
578 maxbans[chan] = tag->getInt("limit");
581 ReadXLine(this, "badip", "ipmask", ServerInstance->XLines->GetFactory("Z"));
582 ReadXLine(this, "badnick", "nick", ServerInstance->XLines->GetFactory("Q"));
583 ReadXLine(this, "badhost", "host", ServerInstance->XLines->GetFactory("K"));
584 ReadXLine(this, "exception", "host", ServerInstance->XLines->GetFactory("E"));
586 memset(DisabledUModes, 0, sizeof(DisabledUModes));
587 std::string modes = ConfValue("disabled")->getString("usermodes");
588 for (std::string::const_iterator p = modes.begin(); p != modes.end(); ++p)
590 // Complain when the character is not a-z or A-Z
591 if ((*p < 'A') || (*p > 'z') || ((*p < 'a') && (*p > 'Z')))
592 throw CoreException("Invalid usermode " + std::string(1, *p) + " was found.");
593 DisabledUModes[*p - 'A'] = 1;
596 memset(DisabledCModes, 0, sizeof(DisabledCModes));
597 modes = ConfValue("disabled")->getString("chanmodes");
598 for (std::string::const_iterator p = modes.begin(); p != modes.end(); ++p)
600 if ((*p < 'A') || (*p > 'z') || ((*p < 'a') && (*p > 'Z')))
601 throw CoreException("Invalid chanmode " + std::string(1, *p) + " was found.");
602 DisabledCModes[*p - 'A'] = 1;
605 memset(HideModeLists, 0, sizeof(HideModeLists));
606 modes = ConfValue("security")->getString("hidemodes");
607 for (std::string::const_iterator p = modes.begin(); p != modes.end(); ++p)
608 HideModeLists[(unsigned char) *p] = true;
610 std::string v = security->getString("announceinvites");
613 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_OPS;
615 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_ALL;
616 else if (v == "dynamic")
617 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_DYNAMIC;
619 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_NONE;
621 v = security->getString("operspywhois");
623 OperSpyWhois = SPYWHOIS_SPLITMSG;
624 else if (v == "on" || v == "yes")
625 OperSpyWhois = SPYWHOIS_SINGLEMSG;
627 OperSpyWhois = SPYWHOIS_NONE;
630 // WARNING: it is not safe to use most of the codebase in this function, as it
631 // will run in the config reader thread
632 void ServerConfig::Read()
634 /* Load and parse the config file, if there are any errors then explode */
636 ParseStack stack(this);
639 valid = stack.ParseFile(ServerInstance->ConfigFileName, 0);
641 catch (CoreException& err)
644 errstr << err.GetReason();
648 DNSServer = ConfValue("dns")->getString("server");
653 void ServerConfig::Apply(ServerConfig* old, const std::string &useruid)
659 * These values can only be set on boot. Keep their old values. Do it before we send messages so we actually have a servername.
661 this->ServerName = old->ServerName;
662 this->sid = old->sid;
663 this->cmdline = old->cmdline;
666 /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
669 for (int index = 0; index * sizeof(DeprecatedConfig) < sizeof(ChangedConfig); index++)
672 ConfigTagList tags = ConfTags(ChangedConfig[index].tag);
673 for(ConfigIter i = tags.first; i != tags.second; ++i)
675 if (i->second->readString(ChangedConfig[index].key, value, true)
676 && (ChangedConfig[index].value.empty() || value == ChangedConfig[index].value))
678 errstr << "Your configuration contains a deprecated value: <" << ChangedConfig[index].tag;
679 if (ChangedConfig[index].value.empty())
681 errstr << ':' << ChangedConfig[index].key;
685 errstr << ' ' << ChangedConfig[index].key << "=\"" << ChangedConfig[index].value << "\"";
687 errstr << "> - " << ChangedConfig[index].reason << " (at " << i->second->getTagLocation() << ")\n";
694 // Handle special items
695 CrossCheckOperClassType();
696 CrossCheckConnectBlocks(old);
698 catch (CoreException &ce)
700 errstr << ce.GetReason();
703 // Check errors before dealing with failed binds, since continuing on failed bind is wanted in some circumstances.
704 valid = errstr.str().empty();
706 // write once here, to try it out and make sure its ok
708 ServerInstance->WritePID(this->PID);
712 // On first run, ports are bound later on
714 ServerInstance->BindPorts(pl);
717 errstr << "Not all your client ports could be bound.\nThe following port(s) failed to bind:\n";
720 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
723 snprintf(buf, MAXBUF, "%d. Address: %s Reason: %s\n", j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
729 User* user = useruid.empty() ? NULL : ServerInstance->FindNick(useruid);
732 ServerInstance->Logs->Log("CONFIG",DEFAULT, "There were errors in your configuration file:");
734 while (errstr.good())
737 getline(errstr, line, '\n');
740 // On startup, print out to console (still attached at this point)
742 std::cout << line << std::endl;
743 // If a user is rehashing, tell them directly
745 user->SendText(":%s NOTICE %s :*** %s", ServerInstance->Config->ServerName.c_str(), user->nick.c_str(), line.c_str());
747 ServerInstance->SNO->WriteGlobalSno('a', line);
751 errstr.str(std::string());
753 // Re-parse our MOTD and RULES files for colors -- Justasic
754 for (ClassVector::const_iterator it = this->Classes.begin(), it_end = this->Classes.end(); it != it_end; ++it)
756 ConfigTag *tag = (*it)->config;
757 // Make sure our connection class allows motd colors
758 if(!tag->getBool("allowmotdcolors"))
761 ConfigFileCache::iterator file = this->Files.find(tag->getString("motd", "motd"));
762 if (file != this->Files.end())
763 InspIRCd::ProcessColors(file->second);
765 file = this->Files.find(tag->getString("rules", "rules"));
766 if (file != this->Files.end())
767 InspIRCd::ProcessColors(file->second);
770 /* No old configuration -> initial boot, nothing more to do here */
775 ServerInstance->Exit(EXIT_STATUS_CONFIG);
782 // If there were errors processing configuration, don't touch modules.
789 user->SendText(":%s NOTICE %s :*** Successfully rehashed server.",
790 ServerInstance->Config->ServerName.c_str(), user->nick.c_str());
791 ServerInstance->SNO->WriteGlobalSno('a', "*** Successfully rehashed server.");
794 void ServerConfig::ApplyModules(User* user)
796 const std::vector<std::string> v = ServerInstance->Modules->GetAllModuleNames(0);
797 std::vector<std::string> added_modules;
798 std::set<std::string> removed_modules(v.begin(), v.end());
800 ConfigTagList tags = ConfTags("module");
801 for(ConfigIter i = tags.first; i != tags.second; ++i)
803 ConfigTag* tag = i->second;
805 if (tag->readString("name", name))
807 // if this module is already loaded, the erase will succeed, so we need do nothing
808 // otherwise, we need to add the module (which will be done later)
809 if (removed_modules.erase(name) == 0)
810 added_modules.push_back(name);
814 if (ConfValue("options")->getBool("allowhalfop") && removed_modules.erase("m_halfop.so") == 0)
815 added_modules.push_back("m_halfop.so");
817 for (std::set<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
819 // Don't remove cmd_*.so, just remove m_*.so
820 if (removing->c_str()[0] == 'c')
822 Module* m = ServerInstance->Modules->Find(*removing);
823 if (m && ServerInstance->Modules->Unload(m))
825 ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH UNLOADED MODULE: %s",removing->c_str());
828 user->WriteNumeric(RPL_UNLOADEDMODULE, "%s %s :Module %s successfully unloaded.",user->nick.c_str(), removing->c_str(), removing->c_str());
830 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully unloaded.", removing->c_str());
835 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());
837 ServerInstance->SNO->WriteGlobalSno('a', "Failed to unload module %s: %s", removing->c_str(), ServerInstance->Modules->LastError().c_str());
841 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
843 if (ServerInstance->Modules->Load(adding->c_str()))
845 ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH LOADED MODULE: %s",adding->c_str());
847 user->WriteNumeric(RPL_LOADEDMODULE, "%s %s :Module %s successfully loaded.",user->nick.c_str(), adding->c_str(), adding->c_str());
849 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully loaded.", adding->c_str());
854 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());
856 ServerInstance->SNO->WriteGlobalSno('a', "Failed to load module %s: %s", adding->c_str(), ServerInstance->Modules->LastError().c_str());
861 bool ServerConfig::StartsWithWindowsDriveLetter(const std::string &path)
863 return (path.length() > 2 && isalpha(path[0]) && path[1] == ':');
866 ConfigTag* ServerConfig::ConfValue(const std::string &tag)
868 ConfigTagList found = config_data.equal_range(tag);
869 if (found.first == found.second)
871 ConfigTag* rv = found.first->second;
873 if (found.first != found.second)
874 ServerInstance->Logs->Log("CONFIG",DEFAULT, "Multiple <" + tag + "> tags found; only first will be used "
875 "(first at " + rv->getTagLocation() + "; second at " + found.first->second->getTagLocation() + ")");
879 ConfigTagList ServerConfig::ConfTags(const std::string& tag)
881 return config_data.equal_range(tag);
884 bool ServerConfig::FileExists(const char* file)
887 if (stat(file, &sb) == -1)
890 if ((sb.st_mode & S_IFDIR) > 0)
893 FILE *input = fopen(file, "r");
903 const char* ServerConfig::CleanFilename(const char* name)
905 const char* p = name + strlen(name);
906 while ((p != name) && (*p != '/') && (*p != '\\')) p--;
907 return (p != name ? ++p : p);
910 const std::string& ServerConfig::GetSID()
915 void ConfigReaderThread::Run()
921 void ConfigReaderThread::Finish()
923 ServerConfig* old = ServerInstance->Config;
924 ServerInstance->Logs->Log("CONFIG",DEBUG,"Switching to new configuration...");
925 ServerInstance->Config = this->Config;
926 Config->Apply(old, TheUserUID);
931 * Apply the changed configuration from the rehash.
933 * XXX: The order of these is IMPORTANT, do not reorder them without testing
936 ServerInstance->XLines->CheckELines();
937 ServerInstance->XLines->ApplyLines();
938 ServerInstance->Res->Rehash();
939 ServerInstance->ResetMaxBans();
940 Config->ApplyDisabledCommands(Config->DisabledCommands);
941 User* user = ServerInstance->FindNick(TheUserUID);
942 FOREACH_MOD(I_OnRehash, OnRehash(user));
943 ServerInstance->BuildISupport();
945 ServerInstance->Logs->CloseLogs();
946 ServerInstance->Logs->OpenFileLogs();
948 if (Config->RawLog && !old->RawLog)
949 ServerInstance->Users->ServerNoticeAll("*** Raw I/O logging is enabled on this server. All messages, passwords, and commands are being recorded.");
956 ServerInstance->Config = old;