1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2009 InspIRCd Development Team
6 * See: http://wiki.inspircd.org/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
15 /* $CopyInstall: conf/inspircd.quotes.example $(CONPATH) */
16 /* $CopyInstall: conf/inspircd.rules.example $(CONPATH) */
17 /* $CopyInstall: conf/inspircd.motd.example $(CONPATH) */
18 /* $CopyInstall: conf/inspircd.helpop-full.example $(CONPATH) */
19 /* $CopyInstall: conf/inspircd.helpop.example $(CONPATH) */
20 /* $CopyInstall: conf/inspircd.censor.example $(CONPATH) */
21 /* $CopyInstall: conf/inspircd.filter.example $(CONPATH) */
22 /* $CopyInstall: conf/inspircd.conf.example $(CONPATH) */
23 /* $CopyInstall: conf/modules.conf.example $(CONPATH) */
24 /* $CopyInstall: conf/opers.conf.example $(CONPATH) */
25 /* $CopyInstall: conf/links.conf.example $(CONPATH) */
26 /* $CopyInstall: .gdbargs $(BASE) */
31 #include "exitcodes.h"
32 #include "commands/cmd_whowas.h"
33 #include "modes/cmode_h.h"
40 fpos(const std::string& name, int l = 1, int c = 1) : filename(name), line(l), col(c) {}
43 return filename + ":" + ConvToStr(line) + ":" + ConvToStr(col);
55 std::vector<std::string> reading;
56 ConfigDataHash& output;
57 std::stringstream& errstr;
59 ParseStack(ServerConfig* conf)
60 : output(conf->config_data), errstr(conf->errstr)
62 bool ParseFile(const std::string& name, int flags);
63 bool ParseExec(const std::string& name, int flags);
64 void DoInclude(ConfigTag* includeTag, int flags);
74 reference<ConfigTag> tag;
77 Parser(ParseStack& me, int myflags, FILE* conf, const std::string& name)
78 : stack(me), flags(myflags), file(conf), current(name), last_tag(name), ungot(-1)
81 int next(bool eof_ok = false)
90 if (ch == EOF && !eof_ok)
92 throw CoreException("Unexpected end-of-file");
109 throw CoreException("INTERNAL ERROR: cannot unget twice");
123 void nextword(std::string& rv)
128 while (isalnum(ch) || ch == '_')
141 if (ch == '>' && key.empty())
145 else if (ch == '#' && key.empty())
152 throw CoreException("Invalid character " + std::string(1, ch) + " in key (" + key + ")");
159 throw CoreException("Invalid character in value of <" + tag->tag + ":" + key + ">");
176 tag->items.push_back(KeyVal(key, value));
188 throw CoreException("Invalid character in tag name");
191 throw CoreException("Empty tag name");
193 tag = new ConfigTag(name, current.filename, current.line);
197 if (tag->tag == "include")
199 stack.DoInclude(tag, flags);
203 stack.output.insert(std::make_pair(tag->tag, tag));
205 // this is not a leak; reference<> takes care of the delete
219 // this is the one place where an EOF is not an error
234 stack.errstr << "Do not save your files as UTF-16; use ASCII!\n";
236 throw CoreException("Syntax error - start of tag expected");
240 catch (CoreException& err)
242 stack.errstr << err.GetReason() << " at " << current.str();
244 stack.errstr << " (inside tag " << tag->tag << " at line " << tag->src_line << ")\n";
246 stack.errstr << " (last tag was on line " << last_tag.line << ")\n";
252 void ParseStack::DoInclude(ConfigTag* tag, int flags)
254 if (flags & FLAG_NO_INC)
255 throw CoreException("Invalid <include> tag in file included with noinclude=\"yes\"");
257 if (tag->readString("file", name))
259 if (tag->getBool("noinclude", false))
260 flags |= FLAG_NO_INC;
261 if (tag->getBool("noexec", false))
262 flags |= FLAG_NO_EXEC;
263 if (!ParseFile(name, flags))
264 throw CoreException("Included");
266 else if (tag->readString("executable", name))
268 if (flags & FLAG_NO_EXEC)
269 throw CoreException("Invalid <include:executable> tag in file included with noexec=\"yes\"");
270 if (tag->getBool("noinclude", false))
271 flags |= FLAG_NO_INC;
272 if (tag->getBool("noexec", true))
273 flags |= FLAG_NO_EXEC;
274 if (!ParseExec(name, flags))
275 throw CoreException("Included");
279 bool ParseStack::ParseFile(const std::string& name, int flags)
281 ServerInstance->Logs->Log("CONFIG", DEBUG, "Reading file %s", name.c_str());
282 for (unsigned int t = 0; t < reading.size(); t++)
284 if (std::string(name) == reading[t])
286 throw CoreException("File " + name + " is included recursively (looped inclusion)");
290 /* It's not already included, add it to the list of files we've loaded */
292 FILE* file = fopen(name.c_str(), "r");
294 throw CoreException("Could not read \"" + name + "\" for include");
296 reading.push_back(name);
297 Parser p(*this, flags, file, name);
298 bool ok = p.outer_parse();
303 bool ParseStack::ParseExec(const std::string& name, int flags)
305 ServerInstance->Logs->Log("CONFIG", DEBUG, "Reading executable %s", name.c_str());
306 for (unsigned int t = 0; t < reading.size(); t++)
308 if (std::string(name) == reading[t])
310 throw CoreException("Executable " + name + " is included recursively (looped inclusion)");
314 /* It's not already included, add it to the list of files we've loaded */
316 FILE* file = popen(name.c_str(), "r");
318 throw CoreException("Could not open executable \"" + name + "\" for include");
320 reading.push_back(name);
321 Parser p(*this, flags, file, name);
322 bool ok = p.outer_parse();
327 /////////////////////////////////////////////////////////////////////////////
329 ServerConfig::ServerConfig()
331 WhoWasGroupSize = WhoWasMaxGroups = WhoWasMaxKeep = 0;
333 NoUserDns = forcedebug = OperSpyWhois = nofork = HideBans = HideSplits = UndernetMsgPrefix = false;
334 CycleHosts = writelog = AllowHalfop = InvBypassModes = true;
335 dns_timeout = DieDelay = 5;
337 NetBufferSize = 10240;
338 SoftLimit = ServerInstance->SE->GetMaxFds();
348 void ServerConfig::Update005()
350 std::stringstream out(data005);
353 int token_counter = 0;
357 line5 = line5 + token + " ";
359 if (token_counter >= 13)
362 snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
363 isupport.push_back(buf);
371 snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
372 isupport.push_back(buf);
376 void ServerConfig::Send005(User* user)
378 for (std::vector<std::string>::iterator line = ServerInstance->Config->isupport.begin(); line != ServerInstance->Config->isupport.end(); line++)
379 user->WriteNumeric(RPL_ISUPPORT, "%s %s", user->nick.c_str(), line->c_str());
382 static void ReqRead(ServerConfig* src, const std::string& tag, const std::string& key, std::string& dest)
384 ConfigTag* t = src->ConfValue(tag);
385 if (!t || !t->readString(key, dest))
386 throw CoreException("You must specify a value for <" + tag + ":" + key + ">");
389 template<typename T, typename V>
390 static void range(T& value, V min, V max, V def, const char* msg)
392 if (value >= (T)min && value <= (T)max)
394 ServerInstance->Logs->Log("CONFIG", DEFAULT,
395 "WARNING: %s value of %ld is not between %ld and %ld; set to %ld.",
396 msg, (long)value, (long)min, (long)max, (long)def);
401 /* NOTE: Before anyone asks why we're not using inet_pton for this, it is because inet_pton and friends do not return so much detail,
402 * even in strerror(errno). They just return 'yes' or 'no' to an address without such detail as to whats WRONG with the address.
403 * Because ircd users arent as technical as they used to be (;)) we are going to give more of a useful error message.
405 static void ValidIP(const std::string& ip, const std::string& key)
407 const char* p = ip.c_str();
410 int not_numbers = false;
416 throw CoreException("The value of "+key+" is not an IP address");
418 for (const char* ptr = p; *ptr; ++ptr)
420 if (*ptr != ':' && *ptr != '.')
422 if (*ptr < '0' || *ptr > '9')
424 if ((*ptr < '0' || *ptr > '9') && (toupper(*ptr) < 'A' || toupper(*ptr) > 'F'))
430 throw CoreException("The value of "+key+" is not an IP address");
441 throw CoreException("The value of "+key+" is an IPv4 address with too many fields!");
444 throw CoreException("The value of "+key+" is an IPv6 address with too many fields!");
446 if (num_seps == 0 && num_dots < 3)
447 throw CoreException("The value of "+key+" looks to be a malformed IPv4 address");
449 if (num_seps == 0 && num_dots == 3 && not_numbers)
450 throw CoreException("The value of "+key+" contains non-numeric characters in an IPv4 address");
452 if (num_seps != 0 && not_hex)
453 throw CoreException("The value of "+key+" contains non-hexdecimal characters in an IPv6 address");
455 if (num_seps != 0 && num_dots != 3 && num_dots != 0)
456 throw CoreException("The value of "+key+" is a malformed IPv6 4in6 address");
460 static void ValidHost(const std::string& p, const std::string& msg)
463 if (p.empty() || p[0] == '.')
464 throw CoreException("The value of "+msg+" is not a valid hostname");
465 for (unsigned int i=0;i < p.length();i++)
470 throw CoreException("The value of "+msg+" is not a valid hostname");
477 throw CoreException("The value of "+msg+" is not a valid hostname");
480 // Specialized validators
482 bool ServerConfig::ApplyDisabledCommands(const std::string& data)
484 std::stringstream dcmds(data);
487 /* Enable everything first */
488 for (Commandtable::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
489 x->second->Disable(false);
491 /* Now disable all the ones which the user wants disabled */
492 while (dcmds >> thiscmd)
494 Commandtable::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
495 if (cm != ServerInstance->Parser->cmdlist.end())
497 cm->second->Disable(true);
504 // Note: the windows validator is in win32wrapper.cpp
505 void FindDNS(std::string& server);
507 static void FindDNS(std::string& server)
512 // attempt to look up their nameserver from /etc/resolv.conf
513 ServerInstance->Logs->Log("CONFIG",DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
515 std::ifstream resolv("/etc/resolv.conf");
517 while (resolv >> server)
519 if (server == "nameserver")
522 ServerInstance->Logs->Log("CONFIG",DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",server.c_str());
527 ServerInstance->Logs->Log("CONFIG",DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
528 server = "127.0.0.1";
532 static void ReadXLine(ServerConfig* conf, const std::string& tag, const std::string& key, XLineFactory* make)
536 ConfigTag* ctag = conf->ConfValue(tag, i);
540 if (!ctag->readString(key, mask))
541 throw CoreException("<"+tag+":"+key+"> missing at " + ctag->getTagLocation());
542 std::string reason = ctag->getString("reason", "<Config>");
543 XLine* xl = make->Generate(ServerInstance->Time(), 0, "<Config>", reason, mask);
544 if (!ServerInstance->XLines->AddLine(xl, NULL))
549 void ServerConfig::CrossCheckOperClassType()
551 for (int i = 0;; ++i)
553 ConfigTag* tag = ConfValue("class", i);
556 std::string name = tag->getString("name");
558 throw CoreException("<class:name> missing from tag at " + tag->getTagLocation());
559 operclass[name] = tag;
561 for (int i = 0;; ++i)
563 ConfigTag* tag = ConfValue("type", i);
567 std::string name = tag->getString("name");
569 throw CoreException("<type:name> is missing from tag at " + tag->getTagLocation());
570 opertypes[name] = tag;
572 std::string classname;
573 irc::spacesepstream str(tag->getString("classes"));
574 while (str.GetToken(classname))
576 if (operclass.find(classname) == operclass.end())
577 throw CoreException("Oper type " + name + " has missing class " + classname);
582 void ServerConfig::CrossCheckConnectBlocks(ServerConfig* current)
584 typedef std::map<std::string, ConnectClass*> ClassMap;
585 ClassMap oldBlocksByMask;
588 for(ClassVector::iterator i = current->Classes.begin(); i != current->Classes.end(); ++i)
590 ConnectClass* c = *i;
591 std::string typeMask = (c->type == CC_ALLOW) ? "a" : "d";
593 oldBlocksByMask[typeMask] = c;
597 ClassMap newBlocksByMask;
598 std::map<std::string, int> names;
600 bool try_again = true;
601 for(int tries=0; try_again; tries++)
604 for(unsigned int i=0;; i++)
606 ConfigTag* tag = ConfValue("connect", i);
609 if (Classes.size() <= i)
614 ConnectClass* parent = NULL;
615 std::string parentName = tag->getString("parent");
616 if (!parentName.empty())
618 std::map<std::string,int>::iterator parentIter = names.find(parentName);
619 if (parentIter == names.end())
622 // couldn't find parent this time. If it's the last time, we'll never find it.
624 throw CoreException("Could not find parent connect class \"" + parentName + "\" for connect block " + ConvToStr(i));
627 parent = Classes[parentIter->second];
630 std::string name = tag->getString("name");
633 if (names.find(name) != names.end())
634 throw CoreException("Two connect classes with name \"" + name + "\" defined!");
638 std::string mask, typeMask;
641 if (tag->readString("allow", mask, false))
644 typeMask = 'a' + mask;
646 else if (tag->readString("deny", mask, false))
649 typeMask = 'd' + mask;
653 throw CoreException("Connect class must have an allow or deny mask at " + tag->getTagLocation());
655 ClassMap::iterator dupMask = newBlocksByMask.find(typeMask);
656 if (dupMask != newBlocksByMask.end())
657 throw CoreException("Two connect classes cannot have the same mask (" + mask + ")");
659 ConnectClass* me = parent ?
660 new ConnectClass(tag, type, mask, *parent) :
661 new ConnectClass(tag, type, mask);
666 tag->readString("password", me->pass);
667 tag->readString("hash", me->hash);
668 me->registration_timeout = tag->getInt("timeout", me->registration_timeout);
669 me->pingtime = tag->getInt("pingfreq", me->pingtime);
671 if (tag->readString("sendq", sendq))
673 // attempt to guess a good hard/soft sendq from a single value
674 long value = atol(sendq.c_str());
676 me->softsendqmax = value / 16;
678 me->softsendqmax = value;
679 me->hardsendqmax = value * 8;
681 me->softsendqmax = tag->getInt("softsendq", me->softsendqmax);
682 me->hardsendqmax = tag->getInt("hardsendq", me->hardsendqmax);
683 me->recvqmax = tag->getInt("recvq", me->recvqmax);
684 me->maxlocal = tag->getInt("localmax", me->maxlocal);
685 me->maxglobal = tag->getInt("globalmax", me->maxglobal);
686 me->port = tag->getInt("port", me->port);
687 me->maxchans = tag->getInt("maxchans", me->maxchans);
688 me->limit = tag->getInt("limit", me->limit);
690 ClassMap::iterator oldMask = oldBlocksByMask.find(typeMask);
691 if (oldMask != oldBlocksByMask.end())
693 ConnectClass* old = oldMask->second;
694 oldBlocksByMask.erase(oldMask);
699 newBlocksByMask[typeMask] = me;
705 /** Represents a deprecated configuration tag.
715 /** Reason for deprecation
720 static const Deprecated ChangedConfig[] = {
721 {"options", "hidelinks", "has been moved to <security:hidelinks> as of 1.2a3"},
722 {"options", "hidewhois", "has been moved to <security:hidewhois> as of 1.2a3"},
723 {"options", "userstats", "has been moved to <security:userstats> as of 1.2a3"},
724 {"options", "customversion", "has been moved to <security:customversion> as of 1.2a3"},
725 {"options", "hidesplits", "has been moved to <security:hidesplits> as of 1.2a3"},
726 {"options", "hidebans", "has been moved to <security:hidebans> as of 1.2a3"},
727 {"options", "hidekills", "has been moved to <security:hidekills> as of 1.2a3"},
728 {"options", "operspywhois", "has been moved to <security:operspywhois> as of 1.2a3"},
729 {"options", "announceinvites", "has been moved to <security:announceinvites> as of 1.2a3"},
730 {"options", "hidemodes", "has been moved to <security:hidemodes> as of 1.2a3"},
731 {"options", "maxtargets", "has been moved to <security:maxtargets> as of 1.2a3"},
732 {"options", "nouserdns", "has been moved to <performance:nouserdns> as of 1.2a3"},
733 {"options", "maxwho", "has been moved to <performance:maxwho> as of 1.2a3"},
734 {"options", "softlimit", "has been moved to <performance:softlimit> as of 1.2a3"},
735 {"options", "somaxconn", "has been moved to <performance:somaxconn> as of 1.2a3"},
736 {"options", "netbuffersize", "has been moved to <performance:netbuffersize> as of 1.2a3"},
737 {"options", "maxwho", "has been moved to <performance:maxwho> as of 1.2a3"},
738 {"options", "loglevel", "1.2 does not use the loglevel value. Please define <log> tags instead."},
739 {"die", "value", "has always been deprecated"},
742 void ServerConfig::Fill()
744 ReqRead(this, "server", "name", ServerName);
745 ReqRead(this, "power", "diepass", diepass);
746 ReqRead(this, "power", "restartpass", restartpass);
748 ConfigTag* options = ConfValue("options");
749 ConfigTag* security = ConfValue("security");
750 powerhash = ConfValue("power")->getString("hash");
751 DieDelay = ConfValue("power")->getInt("pause");
752 PrefixQuit = options->getString("prefixquit");
753 SuffixQuit = options->getString("suffixquit");
754 FixedQuit = options->getString("fixedquit");
755 PrefixPart = options->getString("prefixpart");
756 SuffixPart = options->getString("suffixpart");
757 FixedPart = options->getString("fixedpart");
758 SoftLimit = ConfValue("performance")->getInt("softlimit", ServerInstance->SE->GetMaxFds());
759 MaxConn = ConfValue("performance")->getInt("somaxconn", SOMAXCONN);
760 MoronBanner = options->getString("moronbanner", "You're banned!");
761 ServerDesc = ConfValue("server")->getString("description", "Configure Me");
762 Network = ConfValue("server")->getString("network", "Network");
763 sid = ConfValue("server")->getString("id", "");
764 AdminName = ConfValue("admin")->getString("name", "");
765 AdminEmail = ConfValue("admin")->getString("email", "null@example.com");
766 AdminNick = ConfValue("admin")->getString("nick", "admin");
767 ModPath = options->getString("moduledir", MOD_PATH);
768 NetBufferSize = ConfValue("performance")->getInt("netbuffersize", 10240);
769 MaxWhoResults = ConfValue("performance")->getInt("maxwho", 1024);
770 dns_timeout = ConfValue("dns")->getInt("timeout", 5);
771 DisabledCommands = ConfValue("disabled")->getString("commands", "");
772 DisabledDontExist = ConfValue("disabled")->getBool("fakenonexistant");
773 SetUser = security->getString("runasuser");
774 SetGroup = security->getString("runasgroup");
775 UserStats = security->getString("userstats");
776 CustomVersion = security->getString("customversion");
777 HideSplits = security->getBool("hidesplits");
778 HideBans = security->getBool("hidebans");
779 HideWhoisServer = security->getString("hidewhois");
780 HideKillsServer = security->getString("hidekills");
781 OperSpyWhois = security->getBool("operspywhois");
782 RestrictBannedUsers = security->getBool("restrictbannedusers", true);
783 GenericOper = security->getBool("genericoper");
784 NoUserDns = ConfValue("performance")->getBool("nouserdns");
785 SyntaxHints = options->getBool("syntaxhints");
786 CycleHosts = options->getBool("cyclehosts");
787 UndernetMsgPrefix = options->getBool("ircumsgprefix");
788 FullHostInTopic = options->getBool("hostintopic");
789 MaxTargets = security->getInt("maxtargets", 20);
790 DefaultModes = options->getString("defaultmodes", "nt");
791 PID = ConfValue("pid")->getString("file");
792 WhoWasGroupSize = ConfValue("whowas")->getInt("groupsize");
793 WhoWasMaxGroups = ConfValue("whowas")->getInt("maxgroups");
794 WhoWasMaxKeep = ServerInstance->Duration(ConfValue("whowas")->getString("maxkeep"));
795 DieValue = ConfValue("die")->getString("value");
796 MaxChans = ConfValue("channels")->getInt("users");
797 OperMaxChans = ConfValue("channels")->getInt("opers");
798 c_ipv4_range = ConfValue("cidr")->getInt("ipv4clone");
799 c_ipv6_range = ConfValue("cidr")->getInt("ipv6clone");
800 Limits.NickMax = ConfValue("limits")->getInt("maxnick", 32);
801 Limits.ChanMax = ConfValue("limits")->getInt("maxchan", 64);
802 Limits.MaxModes = ConfValue("limits")->getInt("maxmodes", 20);
803 Limits.IdentMax = ConfValue("limits")->getInt("maxident", 11);
804 Limits.MaxQuit = ConfValue("limits")->getInt("maxquit", 255);
805 Limits.MaxTopic = ConfValue("limits")->getInt("maxtopic", 307);
806 Limits.MaxKick = ConfValue("limits")->getInt("maxkick", 255);
807 Limits.MaxGecos = ConfValue("limits")->getInt("maxgecos", 128);
808 Limits.MaxAway = ConfValue("limits")->getInt("maxaway", 200);
809 InvBypassModes = options->getBool("invitebypassmodes", true);
811 range(SoftLimit, 10, ServerInstance->SE->GetMaxFds(), ServerInstance->SE->GetMaxFds(), "<performance:softlimit>");
812 range(MaxConn, 0, SOMAXCONN, SOMAXCONN, "<performance:somaxconn>");
813 range(MaxTargets, 1, 31, 20, "<security:maxtargets>");
814 range(NetBufferSize, 1024, 65534, 10240, "<performance:netbuffersize>");
815 range(MaxWhoResults, 1, 65535, 1024, "<performace:maxwho>");
816 range(WhoWasGroupSize, 0, 10000, 10, "<whowas:groupsize>");
817 range(WhoWasMaxGroups, 0, 1000000, 10240, "<whowas:maxgroups>");
818 range(WhoWasMaxKeep, 3600, INT_MAX, 3600, "<whowas:maxkeep>");
820 ValidIP(DNSServer, "<dns:server>");
821 ValidHost(ServerName, "<server:name>");
822 if (!sid.empty() && !ServerInstance->IsSID(sid))
823 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.");
825 for (int i = 0;; ++i)
827 ConfigTag* tag = ConfValue("uline", i);
831 if (!tag->readString("server", server))
832 throw CoreException("<uline> tag missing server at " + tag->getTagLocation());
833 ulines[assign(server)] = tag->getBool("silent");
838 ConfigTag* tag = ConfValue("banlist", i);
842 if (!tag->readString("chan", chan))
843 throw CoreException("<banlist> tag missing chan at " + tag->getTagLocation());
844 maxbans[chan] = tag->getInt("limit");
847 ReadXLine(this, "badip", "ipmask", ServerInstance->XLines->GetFactory("Z"));
848 ReadXLine(this, "badnick", "nick", ServerInstance->XLines->GetFactory("Q"));
849 ReadXLine(this, "badhost", "host", ServerInstance->XLines->GetFactory("K"));
850 ReadXLine(this, "exception", "host", ServerInstance->XLines->GetFactory("E"));
852 memset(DisabledUModes, 0, sizeof(DisabledUModes));
853 for (const unsigned char* p = (const unsigned char*)ConfValue("disabled")->getString("usermodes").c_str(); *p; ++p)
855 if (*p < 'A' || *p > ('A' + 64)) throw CoreException(std::string("Invalid usermode ")+(char)*p+" was found.");
856 DisabledUModes[*p - 'A'] = 1;
859 memset(DisabledCModes, 0, sizeof(DisabledCModes));
860 for (const unsigned char* p = (const unsigned char*)ConfValue("disabled")->getString("chanmodes").c_str(); *p; ++p)
862 if (*p < 'A' || *p > ('A' + 64)) throw CoreException(std::string("Invalid chanmode ")+(char)*p+" was found.");
863 DisabledCModes[*p - 'A'] = 1;
866 memset(HideModeLists, 0, sizeof(HideModeLists));
867 for (const unsigned char* p = (const unsigned char*)ConfValue("security")->getString("hidemodes").c_str(); *p; ++p)
868 HideModeLists[*p] = true;
870 std::string v = security->getString("announceinvites");
873 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_OPS;
875 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_ALL;
876 else if (v == "dynamic")
877 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_DYNAMIC;
879 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_NONE;
884 /* These tags MUST occur and must ONLY occur once in the config file */
885 static const char* const Once[] = { "server", "admin", "files", "power", "options" };
887 // WARNING: it is not safe to use most of the codebase in this function, as it
888 // will run in the config reader thread
889 void ServerConfig::Read()
891 /* Load and parse the config file, if there are any errors then explode */
893 ParseStack stack(this);
896 valid = stack.ParseFile(ServerInstance->ConfigFileName, 0);
898 catch (CoreException& err)
901 errstr << err.GetReason();
905 ReadFile(MOTD, ConfValue("files")->getString("motd"));
906 ReadFile(RULES, ConfValue("files")->getString("rules"));
907 DNSServer = ConfValue("dns")->getString("server");
912 void ServerConfig::Apply(ServerConfig* old, const std::string &useruid)
916 /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
919 /* Check we dont have more than one of singular tags, or any of them missing
921 for (int Index = 0; Index * sizeof(*Once) < sizeof(Once); Index++)
923 std::string tag = Once[Index];
925 throw CoreException("You have not defined a <"+tag+"> tag, this is required.");
926 if (ConfValue(tag, 1))
928 errstr << "You have more than one <" << tag << "> tag.\n"
929 << "First occurrence at " << ConfValue(tag, 0)->getTagLocation()
930 << "; second occurrence at " << ConfValue(tag, 1)->getTagLocation() << std::endl;
934 for (int Index = 0; Index * sizeof(Deprecated) < sizeof(ChangedConfig); Index++)
937 if (ConfValue(ChangedConfig[Index].tag)->readString(ChangedConfig[Index].value, dummy, true))
938 errstr << "Your configuration contains a deprecated value: <"
939 << ChangedConfig[Index].tag << ":" << ChangedConfig[Index].value << "> - " << ChangedConfig[Index].reason
940 << " (at " << ConfValue(ChangedConfig[Index].tag)->getTagLocation() << ")\n";
945 // Handle special items
946 CrossCheckOperClassType();
947 CrossCheckConnectBlocks(old);
949 catch (CoreException &ce)
951 errstr << ce.GetReason();
954 // write once here, to try it out and make sure its ok
955 ServerInstance->WritePID(this->PID);
958 * These values can only be set on boot. Keep their old values. Do it before we send messages so we actually have a servername.
962 this->ServerName = old->ServerName;
963 this->sid = old->sid;
964 this->argv = old->argv;
965 this->argc = old->argc;
967 // Same for ports... they're bound later on first run.
969 ServerInstance->BindPorts(pl);
972 errstr << "Not all your client ports could be bound.\nThe following port(s) failed to bind:\n";
975 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
978 snprintf(buf, MAXBUF, "%d. Address: %s Reason: %s\n", j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
984 User* user = useruid.empty() ? NULL : ServerInstance->FindNick(useruid);
986 valid = errstr.str().empty();
988 ServerInstance->Logs->Log("CONFIG",DEFAULT, "There were errors in your configuration file:");
990 while (errstr.good())
993 getline(errstr, line, '\n');
997 user->WriteServ("NOTICE %s :*** %s", user->nick.c_str(), line.c_str());
999 ServerInstance->SNO->WriteGlobalSno('a', line);
1004 // Starting up, so print it out so it's seen. XXX this is a bit of a hack.
1005 printf("%s\n", line.c_str());
1010 errstr.str(std::string());
1012 /* No old configuration -> initial boot, nothing more to do here */
1017 ServerInstance->Exit(EXIT_STATUS_CONFIG);
1020 if (ConfValue("options")->getBool("allowhalfop"))
1021 ServerInstance->Modes->AddMode(new ModeChannelHalfOp);
1026 // If there were errors processing configuration, don't touch modules.
1033 user->WriteServ("NOTICE %s :*** Successfully rehashed server.", user->nick.c_str());
1034 ServerInstance->SNO->WriteGlobalSno('a', "*** Successfully rehashed server.");
1037 void ServerConfig::ApplyModules(User* user)
1039 bool AllowHalfOp = ConfValue("options")->getBool("allowhalfop");
1040 ModeHandler* mh = ServerInstance->Modes->FindMode('h', MODETYPE_CHANNEL);
1041 if (AllowHalfOp && !mh) {
1042 ServerInstance->Logs->Log("CONFIG", DEFAULT, "Enabling halfop mode.");
1043 mh = new ModeChannelHalfOp;
1044 ServerInstance->Modes->AddMode(mh);
1045 } else if (!AllowHalfOp && mh) {
1046 ServerInstance->Logs->Log("CONFIG", DEFAULT, "Disabling halfop mode.");
1047 ServerInstance->Modes->DelMode(mh);
1051 Module* whowas = ServerInstance->Modules->Find("cmd_whowas.so");
1053 WhowasRequest(NULL, whowas, WhowasRequest::WHOWAS_PRUNE).Send();
1055 const std::vector<std::string> v = ServerInstance->Modules->GetAllModuleNames(0);
1056 std::vector<std::string> added_modules;
1057 std::set<std::string> removed_modules(v.begin(), v.end());
1061 ConfigTag* tag = ConfValue("module", i);
1065 if (tag->readString("name", name))
1067 // if this module is already loaded, the erase will succeed, so we need do nothing
1068 // otherwise, we need to add the module (which will be done later)
1069 if (removed_modules.erase(name) == 0)
1070 added_modules.push_back(name);
1074 for (std::set<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
1076 // Don't remove cmd_*.so, just remove m_*.so
1077 if (removing->c_str()[0] == 'c')
1079 Module* m = ServerInstance->Modules->Find(*removing);
1080 if (m && ServerInstance->Modules->Unload(m))
1082 ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH UNLOADED MODULE: %s",removing->c_str());
1085 user->WriteNumeric(RPL_UNLOADEDMODULE, "%s %s :Module %s successfully unloaded.",user->nick.c_str(), removing->c_str(), removing->c_str());
1087 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully unloaded.", removing->c_str());
1092 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());
1094 ServerInstance->SNO->WriteGlobalSno('a', "Failed to unload module %s: %s", removing->c_str(), ServerInstance->Modules->LastError().c_str());
1098 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
1100 if (ServerInstance->Modules->Load(adding->c_str()))
1102 ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH LOADED MODULE: %s",adding->c_str());
1104 user->WriteNumeric(RPL_LOADEDMODULE, "%s %s :Module %s successfully loaded.",user->nick.c_str(), adding->c_str(), adding->c_str());
1106 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully loaded.", adding->c_str());
1111 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());
1113 ServerInstance->SNO->WriteGlobalSno('a', "Failed to load module %s: %s", adding->c_str(), ServerInstance->Modules->LastError().c_str());
1118 bool ServerConfig::StartsWithWindowsDriveLetter(const std::string &path)
1120 return (path.length() > 2 && isalpha(path[0]) && path[1] == ':');
1123 ConfigTag* ServerConfig::ConfValue(const std::string &tag, int offset)
1125 ConfigDataHash::size_type pos = offset;
1126 if (pos >= config_data.count(tag))
1129 ConfigDataHash::iterator iter = config_data.find(tag);
1131 for(int i = 0; i < offset; i++)
1134 return iter->second;
1137 bool ConfigTag::readString(const std::string& key, std::string& value, bool allow_lf)
1141 for(std::vector<KeyVal>::iterator j = items.begin(); j != items.end(); ++j)
1146 if (!allow_lf && (value.find('\n') != std::string::npos))
1148 ServerInstance->Logs->Log("CONFIG",DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
1149 " contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
1150 for (std::string::iterator n = value.begin(); n != value.end(); n++)
1159 std::string ConfigTag::getString(const std::string& key, const std::string& def)
1161 std::string res = def;
1162 readString(key, res);
1166 long ConfigTag::getInt(const std::string &key, long def)
1169 if(!readString(key, result))
1172 const char* res_cstr = result.c_str();
1173 char* res_tail = NULL;
1174 long res = strtol(res_cstr, &res_tail, 0);
1175 if (res_tail == res_cstr)
1177 switch (toupper(*res_tail))
1183 res= res* 1024 * 1024;
1186 res= res* 1024 * 1024 * 1024;
1192 double ConfigTag::getFloat(const std::string &key, double def)
1195 if (!readString(key, result))
1197 return strtod(result.c_str(), NULL);
1200 bool ConfigTag::getBool(const std::string &key, bool def)
1203 if(!readString(key, result))
1206 return (result == "yes" || result == "true" || result == "1" || result == "on");
1209 std::string ConfigTag::getTagLocation()
1211 return src_name + ":" + ConvToStr(src_line);
1214 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1216 bool ServerConfig::ReadFile(file_cache &F, const std::string& fname)
1222 char linebuf[MAXBUF];
1226 if (!FileExists(fname.c_str()))
1228 file = fopen(fname.c_str(), "r");
1234 if (fgets(linebuf, sizeof(linebuf), file))
1235 linebuf[strlen(linebuf)-1] = 0;
1239 F.push_back(*linebuf ? linebuf : " ");
1250 bool ServerConfig::FileExists(const char* file)
1253 if (stat(file, &sb) == -1)
1256 if ((sb.st_mode & S_IFDIR) > 0)
1259 FILE *input = fopen(file, "r");
1269 const char* ServerConfig::CleanFilename(const char* name)
1271 const char* p = name + strlen(name);
1272 while ((p != name) && (*p != '/') && (*p != '\\')) p--;
1273 return (p != name ? ++p : p);
1276 std::string ServerConfig::GetSID()
1281 void ConfigReaderThread::Run()
1283 Config = new ServerConfig;
1288 void ConfigReaderThread::Finish()
1290 ServerConfig* old = ServerInstance->Config;
1291 ServerInstance->Logs->Log("CONFIG",DEBUG,"Switching to new configuration...");
1292 ServerInstance->Logs->CloseLogs();
1293 ServerInstance->Config = this->Config;
1294 ServerInstance->Logs->OpenFileLogs();
1295 Config->Apply(old, TheUserUID);
1300 * Apply the changed configuration from the rehash.
1302 * XXX: The order of these is IMPORTANT, do not reorder them without testing
1305 ServerInstance->XLines->CheckELines();
1306 ServerInstance->XLines->CheckELines();
1307 ServerInstance->XLines->ApplyLines();
1308 ServerInstance->Res->Rehash();
1309 ServerInstance->ResetMaxBans();
1310 Config->ApplyDisabledCommands(Config->DisabledCommands);
1311 User* user = TheUserUID.empty() ? ServerInstance->FindNick(TheUserUID) : NULL;
1312 FOREACH_MOD(I_OnRehash, OnRehash(user));
1313 ServerInstance->BuildISupport();
1320 ServerInstance->Logs->CloseLogs();
1321 ServerInstance->Config = old;
1322 ServerInstance->Logs->OpenFileLogs();
1323 delete this->Config;