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 std::map<std::string, std::string> vars;
57 ConfigDataHash& output;
58 std::stringstream& errstr;
60 ParseStack(ServerConfig* conf)
61 : output(conf->config_data), errstr(conf->errstr)
65 vars["newline"] = vars["nl"] = "\n";
67 bool ParseFile(const std::string& name, int flags);
68 bool ParseExec(const std::string& name, int flags);
69 void DoInclude(ConfigTag* includeTag, int flags);
79 reference<ConfigTag> tag;
82 Parser(ParseStack& me, int myflags, FILE* conf, const std::string& name)
83 : stack(me), flags(myflags), file(conf), current(name), last_tag(name), ungot(-1)
86 int next(bool eof_ok = false)
95 if (ch == EOF && !eof_ok)
97 throw CoreException("Unexpected end-of-file");
114 throw CoreException("INTERNAL ERROR: cannot unget twice");
128 void nextword(std::string& rv)
133 while (isalnum(ch) || ch == '_')
146 if (ch == '>' && key.empty())
150 else if (ch == '#' && key.empty())
157 throw CoreException("Invalid character " + std::string(1, ch) + " in key (" + key + ")");
164 throw CoreException("Invalid character in value of <" + tag->tag + ":" + key + ">");
176 varname.push_back(ch);
181 stack.errstr << "Invalid XML entity name in value of <" + tag->tag + ":" + key + ">\n"
182 << "To include an ampersand or quote, use & or "\n";
183 throw CoreException("Parse error");
186 std::map<std::string, std::string>::iterator var = stack.vars.find(varname);
187 if (var == stack.vars.end())
188 throw CoreException("Undefined XML entity reference '&" + varname + ";'");
189 value.append(var->second);
195 tag->items.push_back(KeyVal(key, value));
207 throw CoreException("Invalid character in tag name");
210 throw CoreException("Empty tag name");
212 tag = new ConfigTag(name, current.filename, current.line);
216 if (name == "include")
218 stack.DoInclude(tag, flags);
220 else if (name == "define")
222 std::string varname = tag->getString("name");
223 std::string value = tag->getString("value");
225 throw CoreException("Variable definition must include variable name");
226 stack.vars[varname] = value;
230 stack.output.insert(std::make_pair(name, tag));
232 // this is not a leak; reference<> takes care of the delete
246 // this is the one place where an EOF is not an error
261 stack.errstr << "Do not save your files as UTF-16; use ASCII!\n";
263 throw CoreException("Syntax error - start of tag expected");
267 catch (CoreException& err)
269 stack.errstr << err.GetReason() << " at " << current.str();
271 stack.errstr << " (inside tag " << tag->tag << " at line " << tag->src_line << ")\n";
273 stack.errstr << " (last tag was on line " << last_tag.line << ")\n";
279 void ParseStack::DoInclude(ConfigTag* tag, int flags)
281 if (flags & FLAG_NO_INC)
282 throw CoreException("Invalid <include> tag in file included with noinclude=\"yes\"");
284 if (tag->readString("file", name))
286 if (tag->getBool("noinclude", false))
287 flags |= FLAG_NO_INC;
288 if (tag->getBool("noexec", false))
289 flags |= FLAG_NO_EXEC;
290 if (!ParseFile(name, flags))
291 throw CoreException("Included");
293 else if (tag->readString("executable", name))
295 if (flags & FLAG_NO_EXEC)
296 throw CoreException("Invalid <include:executable> tag in file included with noexec=\"yes\"");
297 if (tag->getBool("noinclude", false))
298 flags |= FLAG_NO_INC;
299 if (tag->getBool("noexec", true))
300 flags |= FLAG_NO_EXEC;
301 if (!ParseExec(name, flags))
302 throw CoreException("Included");
306 bool ParseStack::ParseFile(const std::string& name, int flags)
308 ServerInstance->Logs->Log("CONFIG", DEBUG, "Reading file %s", name.c_str());
309 for (unsigned int t = 0; t < reading.size(); t++)
311 if (std::string(name) == reading[t])
313 throw CoreException("File " + name + " is included recursively (looped inclusion)");
317 /* It's not already included, add it to the list of files we've loaded */
319 FILE* file = fopen(name.c_str(), "r");
321 throw CoreException("Could not read \"" + name + "\" for include");
323 reading.push_back(name);
324 Parser p(*this, flags, file, name);
325 bool ok = p.outer_parse();
330 bool ParseStack::ParseExec(const std::string& name, int flags)
332 ServerInstance->Logs->Log("CONFIG", DEBUG, "Reading executable %s", name.c_str());
333 for (unsigned int t = 0; t < reading.size(); t++)
335 if (std::string(name) == reading[t])
337 throw CoreException("Executable " + name + " is included recursively (looped inclusion)");
341 /* It's not already included, add it to the list of files we've loaded */
343 FILE* file = popen(name.c_str(), "r");
345 throw CoreException("Could not open executable \"" + name + "\" for include");
347 reading.push_back(name);
348 Parser p(*this, flags, file, name);
349 bool ok = p.outer_parse();
354 /////////////////////////////////////////////////////////////////////////////
356 ServerConfig::ServerConfig()
358 WhoWasGroupSize = WhoWasMaxGroups = WhoWasMaxKeep = 0;
360 NoUserDns = forcedebug = OperSpyWhois = nofork = HideBans = HideSplits = UndernetMsgPrefix = false;
361 CycleHosts = writelog = AllowHalfop = InvBypassModes = true;
362 dns_timeout = DieDelay = 5;
364 NetBufferSize = 10240;
365 SoftLimit = ServerInstance->SE->GetMaxFds();
375 void ServerConfig::Update005()
377 std::stringstream out(data005);
380 int token_counter = 0;
384 line5 = line5 + token + " ";
386 if (token_counter >= 13)
389 snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
390 isupport.push_back(buf);
398 snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
399 isupport.push_back(buf);
403 void ServerConfig::Send005(User* user)
405 for (std::vector<std::string>::iterator line = ServerInstance->Config->isupport.begin(); line != ServerInstance->Config->isupport.end(); line++)
406 user->WriteNumeric(RPL_ISUPPORT, "%s %s", user->nick.c_str(), line->c_str());
409 static void ReqRead(ServerConfig* src, const std::string& tag, const std::string& key, std::string& dest)
411 ConfigTag* t = src->ConfValue(tag);
412 if (!t || !t->readString(key, dest))
413 throw CoreException("You must specify a value for <" + tag + ":" + key + ">");
416 template<typename T, typename V>
417 static void range(T& value, V min, V max, V def, const char* msg)
419 if (value >= (T)min && value <= (T)max)
421 ServerInstance->Logs->Log("CONFIG", DEFAULT,
422 "WARNING: %s value of %ld is not between %ld and %ld; set to %ld.",
423 msg, (long)value, (long)min, (long)max, (long)def);
428 /* 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,
429 * even in strerror(errno). They just return 'yes' or 'no' to an address without such detail as to whats WRONG with the address.
430 * Because ircd users arent as technical as they used to be (;)) we are going to give more of a useful error message.
432 static void ValidIP(const std::string& ip, const std::string& key)
434 const char* p = ip.c_str();
437 int not_numbers = false;
443 throw CoreException("The value of "+key+" is not an IP address");
445 for (const char* ptr = p; *ptr; ++ptr)
447 if (*ptr != ':' && *ptr != '.')
449 if (*ptr < '0' || *ptr > '9')
451 if ((*ptr < '0' || *ptr > '9') && (toupper(*ptr) < 'A' || toupper(*ptr) > 'F'))
457 throw CoreException("The value of "+key+" is not an IP address");
468 throw CoreException("The value of "+key+" is an IPv4 address with too many fields!");
471 throw CoreException("The value of "+key+" is an IPv6 address with too many fields!");
473 if (num_seps == 0 && num_dots < 3)
474 throw CoreException("The value of "+key+" looks to be a malformed IPv4 address");
476 if (num_seps == 0 && num_dots == 3 && not_numbers)
477 throw CoreException("The value of "+key+" contains non-numeric characters in an IPv4 address");
479 if (num_seps != 0 && not_hex)
480 throw CoreException("The value of "+key+" contains non-hexdecimal characters in an IPv6 address");
482 if (num_seps != 0 && num_dots != 3 && num_dots != 0)
483 throw CoreException("The value of "+key+" is a malformed IPv6 4in6 address");
487 static void ValidHost(const std::string& p, const std::string& msg)
490 if (p.empty() || p[0] == '.')
491 throw CoreException("The value of "+msg+" is not a valid hostname");
492 for (unsigned int i=0;i < p.length();i++)
497 throw CoreException("The value of "+msg+" is not a valid hostname");
504 throw CoreException("The value of "+msg+" is not a valid hostname");
507 // Specialized validators
509 bool ServerConfig::ApplyDisabledCommands(const std::string& data)
511 std::stringstream dcmds(data);
514 /* Enable everything first */
515 for (Commandtable::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
516 x->second->Disable(false);
518 /* Now disable all the ones which the user wants disabled */
519 while (dcmds >> thiscmd)
521 Commandtable::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
522 if (cm != ServerInstance->Parser->cmdlist.end())
524 cm->second->Disable(true);
531 // Note: the windows validator is in win32wrapper.cpp
532 void FindDNS(std::string& server);
534 static void FindDNS(std::string& server)
539 // attempt to look up their nameserver from /etc/resolv.conf
540 ServerInstance->Logs->Log("CONFIG",DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
542 std::ifstream resolv("/etc/resolv.conf");
544 while (resolv >> server)
546 if (server == "nameserver")
549 ServerInstance->Logs->Log("CONFIG",DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",server.c_str());
554 ServerInstance->Logs->Log("CONFIG",DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
555 server = "127.0.0.1";
559 static void ReadXLine(ServerConfig* conf, const std::string& tag, const std::string& key, XLineFactory* make)
563 ConfigTag* ctag = conf->ConfValue(tag, i);
567 if (!ctag->readString(key, mask))
568 throw CoreException("<"+tag+":"+key+"> missing at " + ctag->getTagLocation());
569 std::string reason = ctag->getString("reason", "<Config>");
570 XLine* xl = make->Generate(ServerInstance->Time(), 0, "<Config>", reason, mask);
571 if (!ServerInstance->XLines->AddLine(xl, NULL))
576 void ServerConfig::CrossCheckOperClassType()
578 for (int i = 0;; ++i)
580 ConfigTag* tag = ConfValue("class", i);
583 std::string name = tag->getString("name");
585 throw CoreException("<class:name> missing from tag at " + tag->getTagLocation());
586 operclass[name] = tag;
588 for (int i = 0;; ++i)
590 ConfigTag* tag = ConfValue("type", i);
594 std::string name = tag->getString("name");
596 throw CoreException("<type:name> is missing from tag at " + tag->getTagLocation());
597 opertypes[name] = tag;
599 std::string classname;
600 irc::spacesepstream str(tag->getString("classes"));
601 while (str.GetToken(classname))
603 if (operclass.find(classname) == operclass.end())
604 throw CoreException("Oper type " + name + " has missing class " + classname);
609 void ServerConfig::CrossCheckConnectBlocks(ServerConfig* current)
611 typedef std::map<std::string, ConnectClass*> ClassMap;
612 ClassMap oldBlocksByMask;
615 for(ClassVector::iterator i = current->Classes.begin(); i != current->Classes.end(); ++i)
617 ConnectClass* c = *i;
618 std::string typeMask = (c->type == CC_ALLOW) ? "a" : "d";
620 oldBlocksByMask[typeMask] = c;
624 ClassMap newBlocksByMask;
625 std::map<std::string, int> names;
627 bool try_again = true;
628 for(int tries=0; try_again; tries++)
631 for(unsigned int i=0;; i++)
633 ConfigTag* tag = ConfValue("connect", i);
636 if (Classes.size() <= i)
641 ConnectClass* parent = NULL;
642 std::string parentName = tag->getString("parent");
643 if (!parentName.empty())
645 std::map<std::string,int>::iterator parentIter = names.find(parentName);
646 if (parentIter == names.end())
649 // couldn't find parent this time. If it's the last time, we'll never find it.
651 throw CoreException("Could not find parent connect class \"" + parentName + "\" for connect block " + ConvToStr(i));
654 parent = Classes[parentIter->second];
657 std::string name = tag->getString("name");
660 if (names.find(name) != names.end())
661 throw CoreException("Two connect classes with name \"" + name + "\" defined!");
665 std::string mask, typeMask;
668 if (tag->readString("allow", mask, false))
671 typeMask = 'a' + mask;
673 else if (tag->readString("deny", mask, false))
676 typeMask = 'd' + mask;
680 throw CoreException("Connect class must have an allow or deny mask at " + tag->getTagLocation());
682 ClassMap::iterator dupMask = newBlocksByMask.find(typeMask);
683 if (dupMask != newBlocksByMask.end())
684 throw CoreException("Two connect classes cannot have the same mask (" + mask + ")");
686 ConnectClass* me = parent ?
687 new ConnectClass(tag, type, mask, *parent) :
688 new ConnectClass(tag, type, mask);
693 tag->readString("password", me->pass);
694 tag->readString("hash", me->hash);
695 me->registration_timeout = tag->getInt("timeout", me->registration_timeout);
696 me->pingtime = tag->getInt("pingfreq", me->pingtime);
698 if (tag->readString("sendq", sendq))
700 // attempt to guess a good hard/soft sendq from a single value
701 long value = atol(sendq.c_str());
703 me->softsendqmax = value / 16;
705 me->softsendqmax = value;
706 me->hardsendqmax = value * 8;
708 me->softsendqmax = tag->getInt("softsendq", me->softsendqmax);
709 me->hardsendqmax = tag->getInt("hardsendq", me->hardsendqmax);
710 me->recvqmax = tag->getInt("recvq", me->recvqmax);
711 me->maxlocal = tag->getInt("localmax", me->maxlocal);
712 me->maxglobal = tag->getInt("globalmax", me->maxglobal);
713 me->port = tag->getInt("port", me->port);
714 me->maxchans = tag->getInt("maxchans", me->maxchans);
715 me->limit = tag->getInt("limit", me->limit);
717 ClassMap::iterator oldMask = oldBlocksByMask.find(typeMask);
718 if (oldMask != oldBlocksByMask.end())
720 ConnectClass* old = oldMask->second;
721 oldBlocksByMask.erase(oldMask);
726 newBlocksByMask[typeMask] = me;
732 /** Represents a deprecated configuration tag.
742 /** Reason for deprecation
747 static const Deprecated ChangedConfig[] = {
748 {"options", "hidelinks", "has been moved to <security:hidelinks> as of 1.2a3"},
749 {"options", "hidewhois", "has been moved to <security:hidewhois> as of 1.2a3"},
750 {"options", "userstats", "has been moved to <security:userstats> as of 1.2a3"},
751 {"options", "customversion", "has been moved to <security:customversion> as of 1.2a3"},
752 {"options", "hidesplits", "has been moved to <security:hidesplits> as of 1.2a3"},
753 {"options", "hidebans", "has been moved to <security:hidebans> as of 1.2a3"},
754 {"options", "hidekills", "has been moved to <security:hidekills> as of 1.2a3"},
755 {"options", "operspywhois", "has been moved to <security:operspywhois> as of 1.2a3"},
756 {"options", "announceinvites", "has been moved to <security:announceinvites> as of 1.2a3"},
757 {"options", "hidemodes", "has been moved to <security:hidemodes> as of 1.2a3"},
758 {"options", "maxtargets", "has been moved to <security:maxtargets> as of 1.2a3"},
759 {"options", "nouserdns", "has been moved to <performance:nouserdns> as of 1.2a3"},
760 {"options", "maxwho", "has been moved to <performance:maxwho> as of 1.2a3"},
761 {"options", "softlimit", "has been moved to <performance:softlimit> as of 1.2a3"},
762 {"options", "somaxconn", "has been moved to <performance:somaxconn> as of 1.2a3"},
763 {"options", "netbuffersize", "has been moved to <performance:netbuffersize> as of 1.2a3"},
764 {"options", "maxwho", "has been moved to <performance:maxwho> as of 1.2a3"},
765 {"options", "loglevel", "1.2 does not use the loglevel value. Please define <log> tags instead."},
766 {"die", "value", "has always been deprecated"},
769 void ServerConfig::Fill()
771 ReqRead(this, "server", "name", ServerName);
772 ReqRead(this, "power", "diepass", diepass);
773 ReqRead(this, "power", "restartpass", restartpass);
775 ConfigTag* options = ConfValue("options");
776 ConfigTag* security = ConfValue("security");
777 powerhash = ConfValue("power")->getString("hash");
778 DieDelay = ConfValue("power")->getInt("pause");
779 PrefixQuit = options->getString("prefixquit");
780 SuffixQuit = options->getString("suffixquit");
781 FixedQuit = options->getString("fixedquit");
782 PrefixPart = options->getString("prefixpart");
783 SuffixPart = options->getString("suffixpart");
784 FixedPart = options->getString("fixedpart");
785 SoftLimit = ConfValue("performance")->getInt("softlimit", ServerInstance->SE->GetMaxFds());
786 MaxConn = ConfValue("performance")->getInt("somaxconn", SOMAXCONN);
787 MoronBanner = options->getString("moronbanner", "You're banned!");
788 ServerDesc = ConfValue("server")->getString("description", "Configure Me");
789 Network = ConfValue("server")->getString("network", "Network");
790 sid = ConfValue("server")->getString("id", "");
791 AdminName = ConfValue("admin")->getString("name", "");
792 AdminEmail = ConfValue("admin")->getString("email", "null@example.com");
793 AdminNick = ConfValue("admin")->getString("nick", "admin");
794 ModPath = options->getString("moduledir", MOD_PATH);
795 NetBufferSize = ConfValue("performance")->getInt("netbuffersize", 10240);
796 MaxWhoResults = ConfValue("performance")->getInt("maxwho", 1024);
797 dns_timeout = ConfValue("dns")->getInt("timeout", 5);
798 DisabledCommands = ConfValue("disabled")->getString("commands", "");
799 DisabledDontExist = ConfValue("disabled")->getBool("fakenonexistant");
800 SetUser = security->getString("runasuser");
801 SetGroup = security->getString("runasgroup");
802 UserStats = security->getString("userstats");
803 CustomVersion = security->getString("customversion");
804 HideSplits = security->getBool("hidesplits");
805 HideBans = security->getBool("hidebans");
806 HideWhoisServer = security->getString("hidewhois");
807 HideKillsServer = security->getString("hidekills");
808 OperSpyWhois = security->getBool("operspywhois");
809 RestrictBannedUsers = security->getBool("restrictbannedusers", true);
810 GenericOper = security->getBool("genericoper");
811 NoUserDns = ConfValue("performance")->getBool("nouserdns");
812 SyntaxHints = options->getBool("syntaxhints");
813 CycleHosts = options->getBool("cyclehosts");
814 UndernetMsgPrefix = options->getBool("ircumsgprefix");
815 FullHostInTopic = options->getBool("hostintopic");
816 MaxTargets = security->getInt("maxtargets", 20);
817 DefaultModes = options->getString("defaultmodes", "nt");
818 PID = ConfValue("pid")->getString("file");
819 WhoWasGroupSize = ConfValue("whowas")->getInt("groupsize");
820 WhoWasMaxGroups = ConfValue("whowas")->getInt("maxgroups");
821 WhoWasMaxKeep = ServerInstance->Duration(ConfValue("whowas")->getString("maxkeep"));
822 DieValue = ConfValue("die")->getString("value");
823 MaxChans = ConfValue("channels")->getInt("users");
824 OperMaxChans = ConfValue("channels")->getInt("opers");
825 c_ipv4_range = ConfValue("cidr")->getInt("ipv4clone");
826 c_ipv6_range = ConfValue("cidr")->getInt("ipv6clone");
827 Limits.NickMax = ConfValue("limits")->getInt("maxnick", 32);
828 Limits.ChanMax = ConfValue("limits")->getInt("maxchan", 64);
829 Limits.MaxModes = ConfValue("limits")->getInt("maxmodes", 20);
830 Limits.IdentMax = ConfValue("limits")->getInt("maxident", 11);
831 Limits.MaxQuit = ConfValue("limits")->getInt("maxquit", 255);
832 Limits.MaxTopic = ConfValue("limits")->getInt("maxtopic", 307);
833 Limits.MaxKick = ConfValue("limits")->getInt("maxkick", 255);
834 Limits.MaxGecos = ConfValue("limits")->getInt("maxgecos", 128);
835 Limits.MaxAway = ConfValue("limits")->getInt("maxaway", 200);
836 InvBypassModes = options->getBool("invitebypassmodes", true);
838 range(SoftLimit, 10, ServerInstance->SE->GetMaxFds(), ServerInstance->SE->GetMaxFds(), "<performance:softlimit>");
839 range(MaxConn, 0, SOMAXCONN, SOMAXCONN, "<performance:somaxconn>");
840 range(MaxTargets, 1, 31, 20, "<security:maxtargets>");
841 range(NetBufferSize, 1024, 65534, 10240, "<performance:netbuffersize>");
842 range(MaxWhoResults, 1, 65535, 1024, "<performace:maxwho>");
843 range(WhoWasGroupSize, 0, 10000, 10, "<whowas:groupsize>");
844 range(WhoWasMaxGroups, 0, 1000000, 10240, "<whowas:maxgroups>");
845 range(WhoWasMaxKeep, 3600, INT_MAX, 3600, "<whowas:maxkeep>");
847 ValidIP(DNSServer, "<dns:server>");
848 ValidHost(ServerName, "<server:name>");
849 if (!sid.empty() && !ServerInstance->IsSID(sid))
850 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.");
852 for (int i = 0;; ++i)
854 ConfigTag* tag = ConfValue("uline", i);
858 if (!tag->readString("server", server))
859 throw CoreException("<uline> tag missing server at " + tag->getTagLocation());
860 ulines[assign(server)] = tag->getBool("silent");
865 ConfigTag* tag = ConfValue("banlist", i);
869 if (!tag->readString("chan", chan))
870 throw CoreException("<banlist> tag missing chan at " + tag->getTagLocation());
871 maxbans[chan] = tag->getInt("limit");
874 ReadXLine(this, "badip", "ipmask", ServerInstance->XLines->GetFactory("Z"));
875 ReadXLine(this, "badnick", "nick", ServerInstance->XLines->GetFactory("Q"));
876 ReadXLine(this, "badhost", "host", ServerInstance->XLines->GetFactory("K"));
877 ReadXLine(this, "exception", "host", ServerInstance->XLines->GetFactory("E"));
879 memset(DisabledUModes, 0, sizeof(DisabledUModes));
880 for (const unsigned char* p = (const unsigned char*)ConfValue("disabled")->getString("usermodes").c_str(); *p; ++p)
882 if (*p < 'A' || *p > ('A' + 64)) throw CoreException(std::string("Invalid usermode ")+(char)*p+" was found.");
883 DisabledUModes[*p - 'A'] = 1;
886 memset(DisabledCModes, 0, sizeof(DisabledCModes));
887 for (const unsigned char* p = (const unsigned char*)ConfValue("disabled")->getString("chanmodes").c_str(); *p; ++p)
889 if (*p < 'A' || *p > ('A' + 64)) throw CoreException(std::string("Invalid chanmode ")+(char)*p+" was found.");
890 DisabledCModes[*p - 'A'] = 1;
893 memset(HideModeLists, 0, sizeof(HideModeLists));
894 for (const unsigned char* p = (const unsigned char*)ConfValue("security")->getString("hidemodes").c_str(); *p; ++p)
895 HideModeLists[*p] = true;
897 std::string v = security->getString("announceinvites");
900 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_OPS;
902 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_ALL;
903 else if (v == "dynamic")
904 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_DYNAMIC;
906 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_NONE;
911 /* These tags MUST occur and must ONLY occur once in the config file */
912 static const char* const Once[] = { "server", "admin", "files", "power", "options" };
914 // WARNING: it is not safe to use most of the codebase in this function, as it
915 // will run in the config reader thread
916 void ServerConfig::Read()
918 /* Load and parse the config file, if there are any errors then explode */
920 ParseStack stack(this);
923 valid = stack.ParseFile(ServerInstance->ConfigFileName, 0);
925 catch (CoreException& err)
928 errstr << err.GetReason();
932 ReadFile(MOTD, ConfValue("files")->getString("motd"));
933 ReadFile(RULES, ConfValue("files")->getString("rules"));
934 DNSServer = ConfValue("dns")->getString("server");
939 void ServerConfig::Apply(ServerConfig* old, const std::string &useruid)
943 /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
946 /* Check we dont have more than one of singular tags, or any of them missing
948 for (int Index = 0; Index * sizeof(*Once) < sizeof(Once); Index++)
950 std::string tag = Once[Index];
952 throw CoreException("You have not defined a <"+tag+"> tag, this is required.");
953 if (ConfValue(tag, 1))
955 errstr << "You have more than one <" << tag << "> tag.\n"
956 << "First occurrence at " << ConfValue(tag, 0)->getTagLocation()
957 << "; second occurrence at " << ConfValue(tag, 1)->getTagLocation() << std::endl;
961 for (int Index = 0; Index * sizeof(Deprecated) < sizeof(ChangedConfig); Index++)
964 if (ConfValue(ChangedConfig[Index].tag)->readString(ChangedConfig[Index].value, dummy, true))
965 errstr << "Your configuration contains a deprecated value: <"
966 << ChangedConfig[Index].tag << ":" << ChangedConfig[Index].value << "> - " << ChangedConfig[Index].reason
967 << " (at " << ConfValue(ChangedConfig[Index].tag)->getTagLocation() << ")\n";
972 // Handle special items
973 CrossCheckOperClassType();
974 CrossCheckConnectBlocks(old);
976 catch (CoreException &ce)
978 errstr << ce.GetReason();
981 // write once here, to try it out and make sure its ok
982 ServerInstance->WritePID(this->PID);
985 * These values can only be set on boot. Keep their old values. Do it before we send messages so we actually have a servername.
989 this->ServerName = old->ServerName;
990 this->sid = old->sid;
991 this->argv = old->argv;
992 this->argc = old->argc;
994 // Same for ports... they're bound later on first run.
996 ServerInstance->BindPorts(pl);
999 errstr << "Not all your client ports could be bound.\nThe following port(s) failed to bind:\n";
1002 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
1005 snprintf(buf, MAXBUF, "%d. Address: %s Reason: %s\n", j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
1011 User* user = useruid.empty() ? NULL : ServerInstance->FindNick(useruid);
1013 valid = errstr.str().empty();
1015 ServerInstance->Logs->Log("CONFIG",DEFAULT, "There were errors in your configuration file:");
1017 while (errstr.good())
1020 getline(errstr, line, '\n');
1024 user->WriteServ("NOTICE %s :*** %s", user->nick.c_str(), line.c_str());
1026 ServerInstance->SNO->WriteGlobalSno('a', line);
1031 // Starting up, so print it out so it's seen. XXX this is a bit of a hack.
1032 printf("%s\n", line.c_str());
1037 errstr.str(std::string());
1039 /* No old configuration -> initial boot, nothing more to do here */
1044 ServerInstance->Exit(EXIT_STATUS_CONFIG);
1047 if (ConfValue("options")->getBool("allowhalfop"))
1048 ServerInstance->Modes->AddMode(new ModeChannelHalfOp);
1053 // If there were errors processing configuration, don't touch modules.
1060 user->WriteServ("NOTICE %s :*** Successfully rehashed server.", user->nick.c_str());
1061 ServerInstance->SNO->WriteGlobalSno('a', "*** Successfully rehashed server.");
1064 void ServerConfig::ApplyModules(User* user)
1066 bool AllowHalfOp = ConfValue("options")->getBool("allowhalfop");
1067 ModeHandler* mh = ServerInstance->Modes->FindMode('h', MODETYPE_CHANNEL);
1068 if (AllowHalfOp && !mh) {
1069 ServerInstance->Logs->Log("CONFIG", DEFAULT, "Enabling halfop mode.");
1070 mh = new ModeChannelHalfOp;
1071 ServerInstance->Modes->AddMode(mh);
1072 } else if (!AllowHalfOp && mh) {
1073 ServerInstance->Logs->Log("CONFIG", DEFAULT, "Disabling halfop mode.");
1074 ServerInstance->Modes->DelMode(mh);
1078 Module* whowas = ServerInstance->Modules->Find("cmd_whowas.so");
1080 WhowasRequest(NULL, whowas, WhowasRequest::WHOWAS_PRUNE).Send();
1082 const std::vector<std::string> v = ServerInstance->Modules->GetAllModuleNames(0);
1083 std::vector<std::string> added_modules;
1084 std::set<std::string> removed_modules(v.begin(), v.end());
1088 ConfigTag* tag = ConfValue("module", i);
1092 if (tag->readString("name", name))
1094 // if this module is already loaded, the erase will succeed, so we need do nothing
1095 // otherwise, we need to add the module (which will be done later)
1096 if (removed_modules.erase(name) == 0)
1097 added_modules.push_back(name);
1101 for (std::set<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
1103 // Don't remove cmd_*.so, just remove m_*.so
1104 if (removing->c_str()[0] == 'c')
1106 Module* m = ServerInstance->Modules->Find(*removing);
1107 if (m && ServerInstance->Modules->Unload(m))
1109 ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH UNLOADED MODULE: %s",removing->c_str());
1112 user->WriteNumeric(RPL_UNLOADEDMODULE, "%s %s :Module %s successfully unloaded.",user->nick.c_str(), removing->c_str(), removing->c_str());
1114 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully unloaded.", removing->c_str());
1119 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());
1121 ServerInstance->SNO->WriteGlobalSno('a', "Failed to unload module %s: %s", removing->c_str(), ServerInstance->Modules->LastError().c_str());
1125 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
1127 if (ServerInstance->Modules->Load(adding->c_str()))
1129 ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH LOADED MODULE: %s",adding->c_str());
1131 user->WriteNumeric(RPL_LOADEDMODULE, "%s %s :Module %s successfully loaded.",user->nick.c_str(), adding->c_str(), adding->c_str());
1133 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully loaded.", adding->c_str());
1138 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());
1140 ServerInstance->SNO->WriteGlobalSno('a', "Failed to load module %s: %s", adding->c_str(), ServerInstance->Modules->LastError().c_str());
1145 bool ServerConfig::StartsWithWindowsDriveLetter(const std::string &path)
1147 return (path.length() > 2 && isalpha(path[0]) && path[1] == ':');
1150 ConfigTag* ServerConfig::ConfValue(const std::string &tag, int offset)
1152 ConfigDataHash::size_type pos = offset;
1153 if (pos >= config_data.count(tag))
1156 ConfigDataHash::iterator iter = config_data.find(tag);
1158 for(int i = 0; i < offset; i++)
1161 return iter->second;
1164 bool ConfigTag::readString(const std::string& key, std::string& value, bool allow_lf)
1168 for(std::vector<KeyVal>::iterator j = items.begin(); j != items.end(); ++j)
1173 if (!allow_lf && (value.find('\n') != std::string::npos))
1175 ServerInstance->Logs->Log("CONFIG",DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
1176 " contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
1177 for (std::string::iterator n = value.begin(); n != value.end(); n++)
1186 std::string ConfigTag::getString(const std::string& key, const std::string& def)
1188 std::string res = def;
1189 readString(key, res);
1193 long ConfigTag::getInt(const std::string &key, long def)
1196 if(!readString(key, result))
1199 const char* res_cstr = result.c_str();
1200 char* res_tail = NULL;
1201 long res = strtol(res_cstr, &res_tail, 0);
1202 if (res_tail == res_cstr)
1204 switch (toupper(*res_tail))
1210 res= res* 1024 * 1024;
1213 res= res* 1024 * 1024 * 1024;
1219 double ConfigTag::getFloat(const std::string &key, double def)
1222 if (!readString(key, result))
1224 return strtod(result.c_str(), NULL);
1227 bool ConfigTag::getBool(const std::string &key, bool def)
1230 if(!readString(key, result))
1233 return (result == "yes" || result == "true" || result == "1" || result == "on");
1236 std::string ConfigTag::getTagLocation()
1238 return src_name + ":" + ConvToStr(src_line);
1241 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1243 bool ServerConfig::ReadFile(file_cache &F, const std::string& fname)
1249 char linebuf[MAXBUF];
1253 if (!FileExists(fname.c_str()))
1255 file = fopen(fname.c_str(), "r");
1261 if (fgets(linebuf, sizeof(linebuf), file))
1262 linebuf[strlen(linebuf)-1] = 0;
1266 F.push_back(*linebuf ? linebuf : " ");
1277 bool ServerConfig::FileExists(const char* file)
1280 if (stat(file, &sb) == -1)
1283 if ((sb.st_mode & S_IFDIR) > 0)
1286 FILE *input = fopen(file, "r");
1296 const char* ServerConfig::CleanFilename(const char* name)
1298 const char* p = name + strlen(name);
1299 while ((p != name) && (*p != '/') && (*p != '\\')) p--;
1300 return (p != name ? ++p : p);
1303 std::string ServerConfig::GetSID()
1308 void ConfigReaderThread::Run()
1310 Config = new ServerConfig;
1315 void ConfigReaderThread::Finish()
1317 ServerConfig* old = ServerInstance->Config;
1318 ServerInstance->Logs->Log("CONFIG",DEBUG,"Switching to new configuration...");
1319 ServerInstance->Logs->CloseLogs();
1320 ServerInstance->Config = this->Config;
1321 ServerInstance->Logs->OpenFileLogs();
1322 Config->Apply(old, TheUserUID);
1327 * Apply the changed configuration from the rehash.
1329 * XXX: The order of these is IMPORTANT, do not reorder them without testing
1332 ServerInstance->XLines->CheckELines();
1333 ServerInstance->XLines->CheckELines();
1334 ServerInstance->XLines->ApplyLines();
1335 ServerInstance->Res->Rehash();
1336 ServerInstance->ResetMaxBans();
1337 Config->ApplyDisabledCommands(Config->DisabledCommands);
1338 User* user = TheUserUID.empty() ? ServerInstance->FindNick(TheUserUID) : NULL;
1339 FOREACH_MOD(I_OnRehash, OnRehash(user));
1340 ServerInstance->BuildISupport();
1347 ServerInstance->Logs->CloseLogs();
1348 ServerInstance->Config = old;
1349 ServerInstance->Logs->OpenFileLogs();
1350 delete this->Config;