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: tools/gdbargs $(BASE)/.gdbargs */
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));
208 else if (!isspace(spc))
209 throw CoreException("Invalid character in tag name");
212 throw CoreException("Empty tag name");
214 tag = new ConfigTag(name, current.filename, current.line);
218 if (name == "include")
220 stack.DoInclude(tag, flags);
222 else if (name == "define")
224 std::string varname = tag->getString("name");
225 std::string value = tag->getString("value");
227 throw CoreException("Variable definition must include variable name");
228 stack.vars[varname] = value;
232 stack.output.insert(std::make_pair(name, tag));
234 // this is not a leak; reference<> takes care of the delete
248 // this is the one place where an EOF is not an error
263 stack.errstr << "Do not save your files as UTF-16; use ASCII!\n";
265 throw CoreException("Syntax error - start of tag expected");
269 catch (CoreException& err)
271 stack.errstr << err.GetReason() << " at " << current.str();
273 stack.errstr << " (inside tag " << tag->tag << " at line " << tag->src_line << ")\n";
275 stack.errstr << " (last tag was on line " << last_tag.line << ")\n";
281 void ParseStack::DoInclude(ConfigTag* tag, int flags)
283 if (flags & FLAG_NO_INC)
284 throw CoreException("Invalid <include> tag in file included with noinclude=\"yes\"");
286 if (tag->readString("file", name))
288 if (tag->getBool("noinclude", false))
289 flags |= FLAG_NO_INC;
290 if (tag->getBool("noexec", false))
291 flags |= FLAG_NO_EXEC;
292 if (!ParseFile(name, flags))
293 throw CoreException("Included");
295 else if (tag->readString("executable", name))
297 if (flags & FLAG_NO_EXEC)
298 throw CoreException("Invalid <include:executable> tag in file included with noexec=\"yes\"");
299 if (tag->getBool("noinclude", false))
300 flags |= FLAG_NO_INC;
301 if (tag->getBool("noexec", true))
302 flags |= FLAG_NO_EXEC;
303 if (!ParseExec(name, flags))
304 throw CoreException("Included");
308 /** RAII wrapper on FILE* to close files on exceptions */
312 FileWrapper(FILE* file) : f(file) {}
313 operator bool() { return f; }
314 operator FILE*() { return f; }
322 bool ParseStack::ParseFile(const std::string& name, int flags)
324 ServerInstance->Logs->Log("CONFIG", DEBUG, "Reading file %s", name.c_str());
325 for (unsigned int t = 0; t < reading.size(); t++)
327 if (std::string(name) == reading[t])
329 throw CoreException("File " + name + " is included recursively (looped inclusion)");
333 /* It's not already included, add it to the list of files we've loaded */
335 FileWrapper file(fopen(name.c_str(), "r"));
337 throw CoreException("Could not read \"" + name + "\" for include");
339 reading.push_back(name);
340 Parser p(*this, flags, file, name);
341 bool ok = p.outer_parse();
346 bool ParseStack::ParseExec(const std::string& name, int flags)
348 ServerInstance->Logs->Log("CONFIG", DEBUG, "Reading executable %s", name.c_str());
349 for (unsigned int t = 0; t < reading.size(); t++)
351 if (std::string(name) == reading[t])
353 throw CoreException("Executable " + name + " is included recursively (looped inclusion)");
357 /* It's not already included, add it to the list of files we've loaded */
359 FileWrapper file(popen(name.c_str(), "r"));
361 throw CoreException("Could not open executable \"" + name + "\" for include");
363 reading.push_back(name);
364 Parser p(*this, flags, file, name);
365 bool ok = p.outer_parse();
370 /////////////////////////////////////////////////////////////////////////////
372 ServerConfig::ServerConfig()
374 WhoWasGroupSize = WhoWasMaxGroups = WhoWasMaxKeep = 0;
376 NoUserDns = forcedebug = OperSpyWhois = nofork = HideBans = HideSplits = UndernetMsgPrefix = false;
377 CycleHosts = writelog = AllowHalfop = InvBypassModes = true;
378 dns_timeout = DieDelay = 5;
380 NetBufferSize = 10240;
381 SoftLimit = ServerInstance->SE->GetMaxFds();
391 void ServerConfig::Update005()
393 std::stringstream out(data005);
396 int token_counter = 0;
400 line5 = line5 + token + " ";
402 if (token_counter >= 13)
405 snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
406 isupport.push_back(buf);
414 snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
415 isupport.push_back(buf);
419 void ServerConfig::Send005(User* user)
421 for (std::vector<std::string>::iterator line = ServerInstance->Config->isupport.begin(); line != ServerInstance->Config->isupport.end(); line++)
422 user->WriteNumeric(RPL_ISUPPORT, "%s %s", user->nick.c_str(), line->c_str());
425 static void ReqRead(ServerConfig* src, const std::string& tag, const std::string& key, std::string& dest)
427 ConfigTag* t = src->ConfValue(tag);
428 if (!t || !t->readString(key, dest))
429 throw CoreException("You must specify a value for <" + tag + ":" + key + ">");
432 template<typename T, typename V>
433 static void range(T& value, V min, V max, V def, const char* msg)
435 if (value >= (T)min && value <= (T)max)
437 ServerInstance->Logs->Log("CONFIG", DEFAULT,
438 "WARNING: %s value of %ld is not between %ld and %ld; set to %ld.",
439 msg, (long)value, (long)min, (long)max, (long)def);
444 /* 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,
445 * even in strerror(errno). They just return 'yes' or 'no' to an address without such detail as to whats WRONG with the address.
446 * Because ircd users arent as technical as they used to be (;)) we are going to give more of a useful error message.
448 static void ValidIP(const std::string& ip, const std::string& key)
450 const char* p = ip.c_str();
453 int not_numbers = false;
459 throw CoreException("The value of "+key+" is not an IP address");
461 for (const char* ptr = p; *ptr; ++ptr)
463 if (*ptr != ':' && *ptr != '.')
465 if (*ptr < '0' || *ptr > '9')
467 if ((*ptr < '0' || *ptr > '9') && (toupper(*ptr) < 'A' || toupper(*ptr) > 'F'))
473 throw CoreException("The value of "+key+" is not an IP address");
484 throw CoreException("The value of "+key+" is an IPv4 address with too many fields!");
487 throw CoreException("The value of "+key+" is an IPv6 address with too many fields!");
489 if (num_seps == 0 && num_dots < 3)
490 throw CoreException("The value of "+key+" looks to be a malformed IPv4 address");
492 if (num_seps == 0 && num_dots == 3 && not_numbers)
493 throw CoreException("The value of "+key+" contains non-numeric characters in an IPv4 address");
495 if (num_seps != 0 && not_hex)
496 throw CoreException("The value of "+key+" contains non-hexdecimal characters in an IPv6 address");
498 if (num_seps != 0 && num_dots != 3 && num_dots != 0)
499 throw CoreException("The value of "+key+" is a malformed IPv6 4in6 address");
503 static void ValidHost(const std::string& p, const std::string& msg)
506 if (p.empty() || p[0] == '.')
507 throw CoreException("The value of "+msg+" is not a valid hostname");
508 for (unsigned int i=0;i < p.length();i++)
513 throw CoreException("The value of "+msg+" is not a valid hostname");
520 throw CoreException("The value of "+msg+" is not a valid hostname");
523 // Specialized validators
525 bool ServerConfig::ApplyDisabledCommands(const std::string& data)
527 std::stringstream dcmds(data);
530 /* Enable everything first */
531 for (Commandtable::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
532 x->second->Disable(false);
534 /* Now disable all the ones which the user wants disabled */
535 while (dcmds >> thiscmd)
537 Commandtable::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
538 if (cm != ServerInstance->Parser->cmdlist.end())
540 cm->second->Disable(true);
547 // Note: the windows validator is in win32wrapper.cpp
548 void FindDNS(std::string& server);
550 static void FindDNS(std::string& server)
555 // attempt to look up their nameserver from /etc/resolv.conf
556 ServerInstance->Logs->Log("CONFIG",DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
558 std::ifstream resolv("/etc/resolv.conf");
560 while (resolv >> server)
562 if (server == "nameserver")
565 ServerInstance->Logs->Log("CONFIG",DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",server.c_str());
570 ServerInstance->Logs->Log("CONFIG",DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
571 server = "127.0.0.1";
575 static void ReadXLine(ServerConfig* conf, const std::string& tag, const std::string& key, XLineFactory* make)
579 ConfigTag* ctag = conf->ConfValue(tag, i);
583 if (!ctag->readString(key, mask))
584 throw CoreException("<"+tag+":"+key+"> missing at " + ctag->getTagLocation());
585 std::string reason = ctag->getString("reason", "<Config>");
586 XLine* xl = make->Generate(ServerInstance->Time(), 0, "<Config>", reason, mask);
587 if (!ServerInstance->XLines->AddLine(xl, NULL))
592 void ServerConfig::CrossCheckOperClassType()
594 for (int i = 0;; ++i)
596 ConfigTag* tag = ConfValue("class", i);
599 std::string name = tag->getString("name");
601 throw CoreException("<class:name> missing from tag at " + tag->getTagLocation());
602 operclass[name] = tag;
604 for (int i = 0;; ++i)
606 ConfigTag* tag = ConfValue("type", i);
610 std::string name = tag->getString("name");
612 throw CoreException("<type:name> is missing from tag at " + tag->getTagLocation());
613 opertypes[name] = tag;
615 std::string classname;
616 irc::spacesepstream str(tag->getString("classes"));
617 while (str.GetToken(classname))
619 if (operclass.find(classname) == operclass.end())
620 throw CoreException("Oper type " + name + " has missing class " + classname);
625 void ServerConfig::CrossCheckConnectBlocks(ServerConfig* current)
627 typedef std::map<std::string, ConnectClass*> ClassMap;
628 ClassMap oldBlocksByMask;
631 for(ClassVector::iterator i = current->Classes.begin(); i != current->Classes.end(); ++i)
633 ConnectClass* c = *i;
634 std::string typeMask = (c->type == CC_ALLOW) ? "a" : "d";
636 oldBlocksByMask[typeMask] = c;
640 ClassMap newBlocksByMask;
641 std::map<std::string, int> names;
643 bool try_again = true;
644 for(int tries=0; try_again; tries++)
647 for(unsigned int i=0;; i++)
649 ConfigTag* tag = ConfValue("connect", i);
652 if (Classes.size() <= i)
657 ConnectClass* parent = NULL;
658 std::string parentName = tag->getString("parent");
659 if (!parentName.empty())
661 std::map<std::string,int>::iterator parentIter = names.find(parentName);
662 if (parentIter == names.end())
665 // couldn't find parent this time. If it's the last time, we'll never find it.
667 throw CoreException("Could not find parent connect class \"" + parentName + "\" for connect block " + ConvToStr(i));
670 parent = Classes[parentIter->second];
673 std::string name = tag->getString("name");
676 if (names.find(name) != names.end())
677 throw CoreException("Two connect classes with name \"" + name + "\" defined!");
681 std::string mask, typeMask;
684 if (tag->readString("allow", mask, false))
687 typeMask = 'a' + mask;
689 else if (tag->readString("deny", mask, false))
692 typeMask = 'd' + mask;
696 throw CoreException("Connect class must have an allow or deny mask at " + tag->getTagLocation());
698 ClassMap::iterator dupMask = newBlocksByMask.find(typeMask);
699 if (dupMask != newBlocksByMask.end())
700 throw CoreException("Two connect classes cannot have the same mask (" + mask + ")");
702 ConnectClass* me = parent ?
703 new ConnectClass(tag, type, mask, *parent) :
704 new ConnectClass(tag, type, mask);
709 tag->readString("password", me->pass);
710 tag->readString("hash", me->hash);
711 me->registration_timeout = tag->getInt("timeout", me->registration_timeout);
712 me->pingtime = tag->getInt("pingfreq", me->pingtime);
714 if (tag->readString("sendq", sendq))
716 // attempt to guess a good hard/soft sendq from a single value
717 long value = atol(sendq.c_str());
719 me->softsendqmax = value / 16;
721 me->softsendqmax = value;
722 me->hardsendqmax = value * 8;
724 me->softsendqmax = tag->getInt("softsendq", me->softsendqmax);
725 me->hardsendqmax = tag->getInt("hardsendq", me->hardsendqmax);
726 me->recvqmax = tag->getInt("recvq", me->recvqmax);
727 me->penaltythreshold = tag->getInt("threshold", me->penaltythreshold);
728 me->maxlocal = tag->getInt("localmax", me->maxlocal);
729 me->maxglobal = tag->getInt("globalmax", me->maxglobal);
730 me->port = tag->getInt("port", me->port);
731 me->maxchans = tag->getInt("maxchans", me->maxchans);
732 me->limit = tag->getInt("limit", me->limit);
734 ClassMap::iterator oldMask = oldBlocksByMask.find(typeMask);
735 if (oldMask != oldBlocksByMask.end())
737 ConnectClass* old = oldMask->second;
738 oldBlocksByMask.erase(oldMask);
743 newBlocksByMask[typeMask] = me;
749 /** Represents a deprecated configuration tag.
759 /** Reason for deprecation
764 static const Deprecated ChangedConfig[] = {
765 {"options", "hidelinks", "has been moved to <security:hidelinks> as of 1.2a3"},
766 {"options", "hidewhois", "has been moved to <security:hidewhois> as of 1.2a3"},
767 {"options", "userstats", "has been moved to <security:userstats> as of 1.2a3"},
768 {"options", "customversion", "has been moved to <security:customversion> as of 1.2a3"},
769 {"options", "hidesplits", "has been moved to <security:hidesplits> as of 1.2a3"},
770 {"options", "hidebans", "has been moved to <security:hidebans> as of 1.2a3"},
771 {"options", "hidekills", "has been moved to <security:hidekills> as of 1.2a3"},
772 {"options", "operspywhois", "has been moved to <security:operspywhois> as of 1.2a3"},
773 {"options", "announceinvites", "has been moved to <security:announceinvites> as of 1.2a3"},
774 {"options", "hidemodes", "has been moved to <security:hidemodes> as of 1.2a3"},
775 {"options", "maxtargets", "has been moved to <security:maxtargets> as of 1.2a3"},
776 {"options", "nouserdns", "has been moved to <performance:nouserdns> as of 1.2a3"},
777 {"options", "maxwho", "has been moved to <performance:maxwho> as of 1.2a3"},
778 {"options", "softlimit", "has been moved to <performance:softlimit> as of 1.2a3"},
779 {"options", "somaxconn", "has been moved to <performance:somaxconn> as of 1.2a3"},
780 {"options", "netbuffersize", "has been moved to <performance:netbuffersize> as of 1.2a3"},
781 {"options", "maxwho", "has been moved to <performance:maxwho> as of 1.2a3"},
782 {"options", "loglevel", "1.2 does not use the loglevel value. Please define <log> tags instead."},
783 {"die", "value", "has always been deprecated"},
786 void ServerConfig::Fill()
788 ReqRead(this, "server", "name", ServerName);
789 ReqRead(this, "power", "diepass", diepass);
790 ReqRead(this, "power", "restartpass", restartpass);
792 ConfigTag* options = ConfValue("options");
793 ConfigTag* security = ConfValue("security");
794 powerhash = ConfValue("power")->getString("hash");
795 DieDelay = ConfValue("power")->getInt("pause");
796 PrefixQuit = options->getString("prefixquit");
797 SuffixQuit = options->getString("suffixquit");
798 FixedQuit = options->getString("fixedquit");
799 PrefixPart = options->getString("prefixpart");
800 SuffixPart = options->getString("suffixpart");
801 FixedPart = options->getString("fixedpart");
802 SoftLimit = ConfValue("performance")->getInt("softlimit", ServerInstance->SE->GetMaxFds());
803 MaxConn = ConfValue("performance")->getInt("somaxconn", SOMAXCONN);
804 MoronBanner = options->getString("moronbanner", "You're banned!");
805 ServerDesc = ConfValue("server")->getString("description", "Configure Me");
806 Network = ConfValue("server")->getString("network", "Network");
807 sid = ConfValue("server")->getString("id", "");
808 AdminName = ConfValue("admin")->getString("name", "");
809 AdminEmail = ConfValue("admin")->getString("email", "null@example.com");
810 AdminNick = ConfValue("admin")->getString("nick", "admin");
811 ModPath = ConfValue("path")->getString("moduledir", MOD_PATH);
812 NetBufferSize = ConfValue("performance")->getInt("netbuffersize", 10240);
813 MaxWhoResults = ConfValue("performance")->getInt("maxwho", 1024);
814 dns_timeout = ConfValue("dns")->getInt("timeout", 5);
815 DisabledCommands = ConfValue("disabled")->getString("commands", "");
816 DisabledDontExist = ConfValue("disabled")->getBool("fakenonexistant");
817 SetUser = security->getString("runasuser");
818 SetGroup = security->getString("runasgroup");
819 UserStats = security->getString("userstats");
820 CustomVersion = security->getString("customversion");
821 HideSplits = security->getBool("hidesplits");
822 HideBans = security->getBool("hidebans");
823 HideWhoisServer = security->getString("hidewhois");
824 HideKillsServer = security->getString("hidekills");
825 OperSpyWhois = security->getBool("operspywhois");
826 RestrictBannedUsers = security->getBool("restrictbannedusers", true);
827 GenericOper = security->getBool("genericoper");
828 NoUserDns = ConfValue("performance")->getBool("nouserdns");
829 SyntaxHints = options->getBool("syntaxhints");
830 CycleHosts = options->getBool("cyclehosts");
831 UndernetMsgPrefix = options->getBool("ircumsgprefix");
832 FullHostInTopic = options->getBool("hostintopic");
833 MaxTargets = security->getInt("maxtargets", 20);
834 DefaultModes = options->getString("defaultmodes", "nt");
835 PID = ConfValue("pid")->getString("file");
836 WhoWasGroupSize = ConfValue("whowas")->getInt("groupsize");
837 WhoWasMaxGroups = ConfValue("whowas")->getInt("maxgroups");
838 WhoWasMaxKeep = ServerInstance->Duration(ConfValue("whowas")->getString("maxkeep"));
839 DieValue = ConfValue("die")->getString("value");
840 MaxChans = ConfValue("channels")->getInt("users");
841 OperMaxChans = ConfValue("channels")->getInt("opers");
842 c_ipv4_range = ConfValue("cidr")->getInt("ipv4clone");
843 c_ipv6_range = ConfValue("cidr")->getInt("ipv6clone");
844 Limits.NickMax = ConfValue("limits")->getInt("maxnick", 32);
845 Limits.ChanMax = ConfValue("limits")->getInt("maxchan", 64);
846 Limits.MaxModes = ConfValue("limits")->getInt("maxmodes", 20);
847 Limits.IdentMax = ConfValue("limits")->getInt("maxident", 11);
848 Limits.MaxQuit = ConfValue("limits")->getInt("maxquit", 255);
849 Limits.MaxTopic = ConfValue("limits")->getInt("maxtopic", 307);
850 Limits.MaxKick = ConfValue("limits")->getInt("maxkick", 255);
851 Limits.MaxGecos = ConfValue("limits")->getInt("maxgecos", 128);
852 Limits.MaxAway = ConfValue("limits")->getInt("maxaway", 200);
853 InvBypassModes = options->getBool("invitebypassmodes", true);
855 range(SoftLimit, 10, ServerInstance->SE->GetMaxFds(), ServerInstance->SE->GetMaxFds(), "<performance:softlimit>");
856 range(MaxConn, 0, SOMAXCONN, SOMAXCONN, "<performance:somaxconn>");
857 range(MaxTargets, 1, 31, 20, "<security:maxtargets>");
858 range(NetBufferSize, 1024, 65534, 10240, "<performance:netbuffersize>");
859 range(MaxWhoResults, 1, 65535, 1024, "<performace:maxwho>");
860 range(WhoWasGroupSize, 0, 10000, 10, "<whowas:groupsize>");
861 range(WhoWasMaxGroups, 0, 1000000, 10240, "<whowas:maxgroups>");
862 range(WhoWasMaxKeep, 3600, INT_MAX, 3600, "<whowas:maxkeep>");
864 ValidIP(DNSServer, "<dns:server>");
865 ValidHost(ServerName, "<server:name>");
866 if (!sid.empty() && !ServerInstance->IsSID(sid))
867 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.");
869 for (int i = 0;; ++i)
871 ConfigTag* tag = ConfValue("uline", i);
875 if (!tag->readString("server", server))
876 throw CoreException("<uline> tag missing server at " + tag->getTagLocation());
877 ulines[assign(server)] = tag->getBool("silent");
882 ConfigTag* tag = ConfValue("banlist", i);
886 if (!tag->readString("chan", chan))
887 throw CoreException("<banlist> tag missing chan at " + tag->getTagLocation());
888 maxbans[chan] = tag->getInt("limit");
891 ReadXLine(this, "badip", "ipmask", ServerInstance->XLines->GetFactory("Z"));
892 ReadXLine(this, "badnick", "nick", ServerInstance->XLines->GetFactory("Q"));
893 ReadXLine(this, "badhost", "host", ServerInstance->XLines->GetFactory("K"));
894 ReadXLine(this, "exception", "host", ServerInstance->XLines->GetFactory("E"));
896 memset(DisabledUModes, 0, sizeof(DisabledUModes));
897 for (const unsigned char* p = (const unsigned char*)ConfValue("disabled")->getString("usermodes").c_str(); *p; ++p)
899 if (*p < 'A' || *p > ('A' + 64)) throw CoreException(std::string("Invalid usermode ")+(char)*p+" was found.");
900 DisabledUModes[*p - 'A'] = 1;
903 memset(DisabledCModes, 0, sizeof(DisabledCModes));
904 for (const unsigned char* p = (const unsigned char*)ConfValue("disabled")->getString("chanmodes").c_str(); *p; ++p)
906 if (*p < 'A' || *p > ('A' + 64)) throw CoreException(std::string("Invalid chanmode ")+(char)*p+" was found.");
907 DisabledCModes[*p - 'A'] = 1;
910 memset(HideModeLists, 0, sizeof(HideModeLists));
911 for (const unsigned char* p = (const unsigned char*)ConfValue("security")->getString("hidemodes").c_str(); *p; ++p)
912 HideModeLists[*p] = true;
914 std::string v = security->getString("announceinvites");
917 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_OPS;
919 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_ALL;
920 else if (v == "dynamic")
921 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_DYNAMIC;
923 AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_NONE;
928 /* These tags MUST occur and must ONLY occur once in the config file */
929 static const char* const Once[] = { "server", "admin", "files", "power", "options" };
931 // WARNING: it is not safe to use most of the codebase in this function, as it
932 // will run in the config reader thread
933 void ServerConfig::Read()
935 /* Load and parse the config file, if there are any errors then explode */
937 ParseStack stack(this);
940 valid = stack.ParseFile(ServerInstance->ConfigFileName, 0);
942 catch (CoreException& err)
945 errstr << err.GetReason();
949 ReadFile(MOTD, ConfValue("files")->getString("motd"));
950 ReadFile(RULES, ConfValue("files")->getString("rules"));
951 DNSServer = ConfValue("dns")->getString("server");
956 void ServerConfig::Apply(ServerConfig* old, const std::string &useruid)
960 /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
963 /* Check we dont have more than one of singular tags, or any of them missing
965 for (int Index = 0; Index * sizeof(*Once) < sizeof(Once); Index++)
967 std::string tag = Once[Index];
969 throw CoreException("You have not defined a <"+tag+"> tag, this is required.");
970 if (ConfValue(tag, 1))
972 errstr << "You have more than one <" << tag << "> tag.\n"
973 << "First occurrence at " << ConfValue(tag, 0)->getTagLocation()
974 << "; second occurrence at " << ConfValue(tag, 1)->getTagLocation() << std::endl;
978 for (int Index = 0; Index * sizeof(Deprecated) < sizeof(ChangedConfig); Index++)
981 if (ConfValue(ChangedConfig[Index].tag)->readString(ChangedConfig[Index].value, dummy, true))
982 errstr << "Your configuration contains a deprecated value: <"
983 << ChangedConfig[Index].tag << ":" << ChangedConfig[Index].value << "> - " << ChangedConfig[Index].reason
984 << " (at " << ConfValue(ChangedConfig[Index].tag)->getTagLocation() << ")\n";
989 // Handle special items
990 CrossCheckOperClassType();
991 CrossCheckConnectBlocks(old);
993 catch (CoreException &ce)
995 errstr << ce.GetReason();
998 // write once here, to try it out and make sure its ok
999 ServerInstance->WritePID(this->PID);
1002 * These values can only be set on boot. Keep their old values. Do it before we send messages so we actually have a servername.
1006 this->ServerName = old->ServerName;
1007 this->sid = old->sid;
1008 this->argv = old->argv;
1009 this->argc = old->argc;
1011 // Same for ports... they're bound later on first run.
1013 ServerInstance->BindPorts(pl);
1016 errstr << "Not all your client ports could be bound.\nThe following port(s) failed to bind:\n";
1019 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
1022 snprintf(buf, MAXBUF, "%d. Address: %s Reason: %s\n", j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
1028 User* user = useruid.empty() ? NULL : ServerInstance->FindNick(useruid);
1030 valid = errstr.str().empty();
1032 ServerInstance->Logs->Log("CONFIG",DEFAULT, "There were errors in your configuration file:");
1034 while (errstr.good())
1037 getline(errstr, line, '\n');
1041 user->WriteServ("NOTICE %s :*** %s", user->nick.c_str(), line.c_str());
1043 ServerInstance->SNO->WriteGlobalSno('a', line);
1048 // Starting up, so print it out so it's seen. XXX this is a bit of a hack.
1049 printf("%s\n", line.c_str());
1054 errstr.str(std::string());
1056 /* No old configuration -> initial boot, nothing more to do here */
1061 ServerInstance->Exit(EXIT_STATUS_CONFIG);
1064 if (ConfValue("options")->getBool("allowhalfop"))
1065 ServerInstance->Modes->AddMode(new ModeChannelHalfOp);
1070 // If there were errors processing configuration, don't touch modules.
1077 user->WriteServ("NOTICE %s :*** Successfully rehashed server.", user->nick.c_str());
1078 ServerInstance->SNO->WriteGlobalSno('a', "*** Successfully rehashed server.");
1081 void ServerConfig::ApplyModules(User* user)
1083 bool AllowHalfOp = ConfValue("options")->getBool("allowhalfop");
1084 ModeHandler* mh = ServerInstance->Modes->FindMode('h', MODETYPE_CHANNEL);
1085 if (AllowHalfOp && !mh) {
1086 ServerInstance->Logs->Log("CONFIG", DEFAULT, "Enabling halfop mode.");
1087 mh = new ModeChannelHalfOp;
1088 ServerInstance->Modes->AddMode(mh);
1089 } else if (!AllowHalfOp && mh) {
1090 ServerInstance->Logs->Log("CONFIG", DEFAULT, "Disabling halfop mode.");
1091 ServerInstance->Modes->DelMode(mh);
1095 Module* whowas = ServerInstance->Modules->Find("cmd_whowas.so");
1097 WhowasRequest(NULL, whowas, WhowasRequest::WHOWAS_PRUNE).Send();
1099 const std::vector<std::string> v = ServerInstance->Modules->GetAllModuleNames(0);
1100 std::vector<std::string> added_modules;
1101 std::set<std::string> removed_modules(v.begin(), v.end());
1105 ConfigTag* tag = ConfValue("module", i);
1109 if (tag->readString("name", name))
1111 // if this module is already loaded, the erase will succeed, so we need do nothing
1112 // otherwise, we need to add the module (which will be done later)
1113 if (removed_modules.erase(name) == 0)
1114 added_modules.push_back(name);
1118 for (std::set<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
1120 // Don't remove cmd_*.so, just remove m_*.so
1121 if (removing->c_str()[0] == 'c')
1123 Module* m = ServerInstance->Modules->Find(*removing);
1124 if (m && ServerInstance->Modules->Unload(m))
1126 ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH UNLOADED MODULE: %s",removing->c_str());
1129 user->WriteNumeric(RPL_UNLOADEDMODULE, "%s %s :Module %s successfully unloaded.",user->nick.c_str(), removing->c_str(), removing->c_str());
1131 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully unloaded.", removing->c_str());
1136 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());
1138 ServerInstance->SNO->WriteGlobalSno('a', "Failed to unload module %s: %s", removing->c_str(), ServerInstance->Modules->LastError().c_str());
1142 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
1144 if (ServerInstance->Modules->Load(adding->c_str()))
1146 ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH LOADED MODULE: %s",adding->c_str());
1148 user->WriteNumeric(RPL_LOADEDMODULE, "%s %s :Module %s successfully loaded.",user->nick.c_str(), adding->c_str(), adding->c_str());
1150 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully loaded.", adding->c_str());
1155 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());
1157 ServerInstance->SNO->WriteGlobalSno('a', "Failed to load module %s: %s", adding->c_str(), ServerInstance->Modules->LastError().c_str());
1162 bool ServerConfig::StartsWithWindowsDriveLetter(const std::string &path)
1164 return (path.length() > 2 && isalpha(path[0]) && path[1] == ':');
1167 ConfigTag* ServerConfig::ConfValue(const std::string &tag, int offset)
1169 ConfigDataHash::size_type pos = offset;
1170 if (pos >= config_data.count(tag))
1173 ConfigDataHash::iterator iter = config_data.find(tag);
1175 for(int i = 0; i < offset; i++)
1178 return iter->second;
1181 bool ConfigTag::readString(const std::string& key, std::string& value, bool allow_lf)
1185 for(std::vector<KeyVal>::iterator j = items.begin(); j != items.end(); ++j)
1190 if (!allow_lf && (value.find('\n') != std::string::npos))
1192 ServerInstance->Logs->Log("CONFIG",DEFAULT, "Value of <" + tag + ":" + key + "> at " + getTagLocation() +
1193 " contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
1194 for (std::string::iterator n = value.begin(); n != value.end(); n++)
1203 std::string ConfigTag::getString(const std::string& key, const std::string& def)
1205 std::string res = def;
1206 readString(key, res);
1210 long ConfigTag::getInt(const std::string &key, long def)
1213 if(!readString(key, result))
1216 const char* res_cstr = result.c_str();
1217 char* res_tail = NULL;
1218 long res = strtol(res_cstr, &res_tail, 0);
1219 if (res_tail == res_cstr)
1221 switch (toupper(*res_tail))
1227 res= res* 1024 * 1024;
1230 res= res* 1024 * 1024 * 1024;
1236 double ConfigTag::getFloat(const std::string &key, double def)
1239 if (!readString(key, result))
1241 return strtod(result.c_str(), NULL);
1244 bool ConfigTag::getBool(const std::string &key, bool def)
1247 if(!readString(key, result))
1250 return (result == "yes" || result == "true" || result == "1" || result == "on");
1253 std::string ConfigTag::getTagLocation()
1255 return src_name + ":" + ConvToStr(src_line);
1258 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1260 bool ServerConfig::ReadFile(file_cache &F, const std::string& fname)
1265 char linebuf[MAXBUF];
1269 FileWrapper file(fopen(fname.c_str(), "r"));
1275 if (fgets(linebuf, sizeof(linebuf), file))
1276 linebuf[strlen(linebuf)-1] = 0;
1280 F.push_back(*linebuf ? linebuf : " ");
1286 bool ServerConfig::FileExists(const char* file)
1289 if (stat(file, &sb) == -1)
1292 if ((sb.st_mode & S_IFDIR) > 0)
1295 FILE *input = fopen(file, "r");
1305 const char* ServerConfig::CleanFilename(const char* name)
1307 const char* p = name + strlen(name);
1308 while ((p != name) && (*p != '/') && (*p != '\\')) p--;
1309 return (p != name ? ++p : p);
1312 std::string ServerConfig::GetSID()
1317 void ConfigReaderThread::Run()
1319 Config = new ServerConfig;
1324 void ConfigReaderThread::Finish()
1326 ServerConfig* old = ServerInstance->Config;
1327 ServerInstance->Logs->Log("CONFIG",DEBUG,"Switching to new configuration...");
1328 ServerInstance->Logs->CloseLogs();
1329 ServerInstance->Config = this->Config;
1330 ServerInstance->Logs->OpenFileLogs();
1331 Config->Apply(old, TheUserUID);
1336 * Apply the changed configuration from the rehash.
1338 * XXX: The order of these is IMPORTANT, do not reorder them without testing
1341 ServerInstance->XLines->CheckELines();
1342 ServerInstance->XLines->CheckELines();
1343 ServerInstance->XLines->ApplyLines();
1344 ServerInstance->Res->Rehash();
1345 ServerInstance->ResetMaxBans();
1346 Config->ApplyDisabledCommands(Config->DisabledCommands);
1347 User* user = TheUserUID.empty() ? ServerInstance->FindNick(TheUserUID) : NULL;
1348 FOREACH_MOD(I_OnRehash, OnRehash(user));
1349 ServerInstance->BuildISupport();
1356 ServerInstance->Logs->CloseLogs();
1357 ServerInstance->Config = old;
1358 ServerInstance->Logs->OpenFileLogs();
1359 delete this->Config;