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"
35 ServerConfig::ServerConfig()
37 WhoWasGroupSize = WhoWasMaxGroups = WhoWasMaxKeep = 0;
39 NoUserDns = forcedebug = OperSpyWhois = nofork = HideBans = HideSplits = UndernetMsgPrefix = false;
40 CycleHosts = writelog = AllowHalfop = InvBypassModes = true;
41 dns_timeout = DieDelay = 5;
43 NetBufferSize = 10240;
44 SoftLimit = ServerInstance->SE->GetMaxFds();
54 void ServerConfig::Update005()
56 std::stringstream out(data005);
59 int token_counter = 0;
63 line5 = line5 + token + " ";
65 if (token_counter >= 13)
68 snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
69 isupport.push_back(buf);
77 snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
78 isupport.push_back(buf);
82 void ServerConfig::Send005(User* user)
84 for (std::vector<std::string>::iterator line = ServerInstance->Config->isupport.begin(); line != ServerInstance->Config->isupport.end(); line++)
85 user->WriteNumeric(RPL_ISUPPORT, "%s %s", user->nick.c_str(), line->c_str());
88 bool ServerConfig::CheckOnce(const char* tag)
90 int count = ConfValueEnum(tag);
93 throw CoreException("You have more than one <"+std::string(tag)+"> tag, this is not permitted.");
95 throw CoreException("You have not defined a <"+std::string(tag)+"> tag, this is required.");
99 static void ValidateNoSpaces(const char* p, const std::string &tag, const std::string &val)
101 for (const char* ptr = p; *ptr; ++ptr)
104 throw CoreException("The value of <"+tag+":"+val+"> cannot contain spaces");
108 /* 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,
109 * even in strerror(errno). They just return 'yes' or 'no' to an address without such detail as to whats WRONG with the address.
110 * Because ircd users arent as technical as they used to be (;)) we are going to give more of a useful error message.
112 static void ValidateIP(const char* p, const std::string &tag, const std::string &val, bool wild)
116 int not_numbers = false;
122 throw CoreException("The value of <"+tag+":"+val+"> is not an IP address");
124 for (const char* ptr = p; *ptr; ++ptr)
126 if (wild && (*ptr == '*' || *ptr == '?' || *ptr == '/'))
129 if (*ptr != ':' && *ptr != '.')
131 if (*ptr < '0' || *ptr > '9')
133 if ((*ptr < '0' || *ptr > '9') && (toupper(*ptr) < 'A' || toupper(*ptr) > 'F'))
139 throw CoreException("The value of <"+tag+":"+val+"> is not an IP address");
150 throw CoreException("The value of <"+tag+":"+val+"> is an IPv4 address with too many fields!");
153 throw CoreException("The value of <"+tag+":"+val+"> is an IPv6 address with too many fields!");
155 if (num_seps == 0 && num_dots < 3 && !wild)
156 throw CoreException("The value of <"+tag+":"+val+"> looks to be a malformed IPv4 address");
158 if (num_seps == 0 && num_dots == 3 && not_numbers)
159 throw CoreException("The value of <"+tag+":"+val+"> contains non-numeric characters in an IPv4 address");
161 if (num_seps != 0 && not_hex)
162 throw CoreException("The value of <"+tag+":"+val+"> contains non-hexdecimal characters in an IPv6 address");
164 if (num_seps != 0 && num_dots != 3 && num_dots != 0 && !wild)
165 throw CoreException("The value of <"+tag+":"+val+"> is a malformed IPv6 4in6 address");
169 static void ValidateHostname(const char* p, const std::string &tag, const std::string &val)
175 throw CoreException("The value of <"+tag+":"+val+"> is not a valid hostname");
176 for (const char* ptr = p; *ptr; ++ptr)
181 throw CoreException("The value of <"+tag+":"+val+"> is not a valid hostname");
188 throw CoreException("The value of <"+tag+":"+val+"> is not a valid hostname");
192 // Specialized validators
194 static bool ValidateMaxTargets(ServerConfig* conf, const char*, const char*, ValueItem &data)
196 if ((data.GetInteger() < 1) || (data.GetInteger() > 31))
198 ServerInstance->Logs->Log("CONFIG",DEFAULT,"WARNING: <security:maxtargets> value is greater than 31 or less than 1, set to 20.");
204 static bool ValidateSoftLimit(ServerConfig* conf, const char*, const char*, ValueItem &data)
206 if ((data.GetInteger() < 1) || (data.GetInteger() > ServerInstance->SE->GetMaxFds()))
208 ServerInstance->Logs->Log("CONFIG",DEFAULT,"WARNING: <performance:softlimit> value is greater than %d or less than 0, set to %d.",ServerInstance->SE->GetMaxFds(),ServerInstance->SE->GetMaxFds());
209 data.Set(ServerInstance->SE->GetMaxFds());
214 static bool ValidateMaxConn(ServerConfig* conf, const char*, const char*, ValueItem &data)
216 if (data.GetInteger() > SOMAXCONN)
217 ServerInstance->Logs->Log("CONFIG",DEFAULT,"WARNING: <performance:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
221 bool ServerConfig::ApplyDisabledCommands(const std::string& data)
223 std::stringstream dcmds(data);
226 /* Enable everything first */
227 for (Commandtable::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
228 x->second->Disable(false);
230 /* Now disable all the ones which the user wants disabled */
231 while (dcmds >> thiscmd)
233 Commandtable::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
234 if (cm != ServerInstance->Parser->cmdlist.end())
236 cm->second->Disable(true);
242 static bool ValidateDisabledUModes(ServerConfig* conf, const char*, const char*, ValueItem &data)
244 memset(conf->DisabledUModes, 0, sizeof(conf->DisabledUModes));
245 for (const unsigned char* p = (const unsigned char*)data.GetString(); *p; ++p)
247 if (*p < 'A' || *p > ('A' + 64)) throw CoreException(std::string("Invalid usermode ")+(char)*p+" was found.");
248 conf->DisabledUModes[*p - 'A'] = 1;
253 static bool ValidateDisabledCModes(ServerConfig* conf, const char*, const char*, ValueItem &data)
255 memset(conf->DisabledCModes, 0, sizeof(conf->DisabledCModes));
256 for (const unsigned char* p = (const unsigned char*)data.GetString(); *p; ++p)
258 if (*p < 'A' || *p > ('A' + 64)) throw CoreException(std::string("Invalid chanmode ")+(char)*p+" was found.");
259 conf->DisabledCModes[*p - 'A'] = 1;
265 // Note: the windows validator is in win32wrapper.cpp
266 bool ValidateDnsServer(ServerConfig* conf, const char*, const char*, ValueItem &data);
268 static bool ValidateDnsServer(ServerConfig* conf, const char*, const char*, ValueItem &data)
270 if (!*(data.GetString()))
272 std::string nameserver;
273 // attempt to look up their nameserver from /etc/resolv.conf
274 ServerInstance->Logs->Log("CONFIG",DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
275 std::ifstream resolv("/etc/resolv.conf");
276 bool found_server = false;
278 if (resolv.is_open())
280 while (resolv >> nameserver)
282 if ((nameserver == "nameserver") && (!found_server))
284 resolv >> nameserver;
285 data.Set(nameserver.c_str());
287 ServerInstance->Logs->Log("CONFIG",DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
293 ServerInstance->Logs->Log("CONFIG",DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
294 data.Set("127.0.0.1");
299 ServerInstance->Logs->Log("CONFIG",DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
300 data.Set("127.0.0.1");
307 static bool ValidateServerName(ServerConfig* conf, const char*, const char*, ValueItem &data)
309 ServerInstance->Logs->Log("CONFIG",DEFAULT,"Validating server name");
310 /* If we already have a servername, and they changed it, we should throw an exception. */
311 if (!strchr(data.GetString(), '.'))
313 ServerInstance->Logs->Log("CONFIG",DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s.'",
314 data.GetString(),data.GetString());
315 std::string moo = data.GetValue();
316 data.Set(moo.append("."));
318 ValidateHostname(data.GetString(), "server", "name");
322 static bool ValidateNetBufferSize(ServerConfig* conf, const char*, const char*, ValueItem &data)
324 // 65534 not 65535 because of null terminator
325 if ((!data.GetInteger()) || (data.GetInteger() > 65534) || (data.GetInteger() < 1024))
327 ServerInstance->Logs->Log("CONFIG",DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
333 static bool ValidateMaxWho(ServerConfig* conf, const char*, const char*, ValueItem &data)
335 if ((data.GetInteger() > 65535) || (data.GetInteger() < 1))
337 ServerInstance->Logs->Log("CONFIG",DEFAULT,"<performance:maxwho> size out of range, setting to default of 1024.");
343 static bool ValidateHalfOp(ServerConfig* conf, const char*, const char*, ValueItem &data)
345 ModeHandler* mh = ServerInstance->Modes->FindMode('h', MODETYPE_CHANNEL);
346 if (data.GetBool() && !mh) {
347 ServerInstance->Logs->Log("CONFIG", DEFAULT, "Enabling halfop mode.");
348 mh = new ModeChannelHalfOp;
349 ServerInstance->Modes->AddMode(mh);
350 } else if (!data.GetBool() && mh) {
351 ServerInstance->Logs->Log("CONFIG", DEFAULT, "Disabling halfop mode.");
352 ServerInstance->Modes->DelMode(mh);
358 static bool ValidateMotd(ServerConfig* conf, const char*, const char*, ValueItem &data)
360 conf->ReadFile(conf->MOTD, data.GetString());
364 static bool ValidateNotEmpty(ServerConfig*, const char* tag, const char* val, ValueItem &data)
366 if (data.GetValue().empty())
367 throw CoreException(std::string("The value for <")+tag+":"+val+"> cannot be empty!");
371 static bool ValidateRules(ServerConfig* conf, const char*, const char*, ValueItem &data)
373 conf->ReadFile(conf->RULES, data.GetString());
377 static bool ValidateModeLists(ServerConfig* conf, const char*, const char*, ValueItem &data)
379 memset(conf->HideModeLists, 0, sizeof(conf->HideModeLists));
380 for (const unsigned char* x = (const unsigned char*)data.GetString(); *x; ++x)
381 conf->HideModeLists[*x] = true;
385 static bool ValidateInvite(ServerConfig* conf, const char*, const char*, ValueItem &data)
387 const std::string& v = data.GetValue();
390 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_OPS;
392 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_ALL;
393 else if (v == "dynamic")
394 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_DYNAMIC;
396 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_NONE;
401 static bool ValidateSID(ServerConfig* conf, const char*, const char*, ValueItem &data)
403 ServerInstance->Logs->Log("CONFIG",DEFAULT,"Validating server id");
405 const std::string& sid = data.GetValue();
407 if (!sid.empty() && !ServerInstance->IsSID(sid))
409 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.");
417 static bool ValidateWhoWas(ServerConfig* conf, const char*, const char*, ValueItem &data)
419 conf->WhoWasMaxKeep = ServerInstance->Duration(data.GetString());
421 if (conf->WhoWasGroupSize < 0)
422 conf->WhoWasGroupSize = 0;
424 if (conf->WhoWasMaxGroups < 0)
425 conf->WhoWasMaxGroups = 0;
427 if (conf->WhoWasMaxKeep < 3600)
429 conf->WhoWasMaxKeep = 3600;
430 ServerInstance->Logs->Log("CONFIG",DEFAULT,"WARNING: <whowas:maxkeep> value less than 3600, setting to default 3600");
433 Module* whowas = ServerInstance->Modules->Find("cmd_whowas.so");
436 WhowasRequest(NULL, whowas, WhowasRequest::WHOWAS_PRUNE).Send();
442 /* Callback called to process a single <uline> tag
444 static bool DoULine(ServerConfig* conf, const char*, const char**, ValueList &values, int*)
446 const char* server = values[0].GetString();
447 const bool silent = values[1].GetBool();
448 conf->ulines[server] = silent;
452 /* Callback called to process a single <banlist> tag
454 static bool DoMaxBans(ServerConfig* conf, const char*, const char**, ValueList &values, int*)
456 const char* channel = values[0].GetString();
457 int limit = values[1].GetInteger();
458 conf->maxbans[channel] = limit;
462 static bool DoZLine(ServerConfig* conf, const char* tag, const char** entries, ValueList &values, int* types)
464 const char* reason = values[0].GetString();
465 const char* ipmask = values[1].GetString();
467 ZLine* zl = new ZLine(ServerInstance->Time(), 0, "<Config>", reason, ipmask);
468 if (!ServerInstance->XLines->AddLine(zl, NULL))
474 static bool DoQLine(ServerConfig* conf, const char* tag, const char** entries, ValueList &values, int* types)
476 const char* reason = values[0].GetString();
477 const char* nick = values[1].GetString();
479 QLine* ql = new QLine(ServerInstance->Time(), 0, "<Config>", reason, nick);
480 if (!ServerInstance->XLines->AddLine(ql, NULL))
486 static bool DoKLine(ServerConfig* conf, const char* tag, const char** entries, ValueList &values, int* types)
488 const char* reason = values[0].GetString();
489 const char* host = values[1].GetString();
491 XLineManager* xlm = ServerInstance->XLines;
493 IdentHostPair ih = xlm->IdentSplit(host);
495 KLine* kl = new KLine(ServerInstance->Time(), 0, "<Config>", reason, ih.first.c_str(), ih.second.c_str());
496 if (!xlm->AddLine(kl, NULL))
501 static bool DoELine(ServerConfig* conf, const char* tag, const char** entries, ValueList &values, int* types)
503 const char* reason = values[0].GetString();
504 const char* host = values[1].GetString();
506 XLineManager* xlm = ServerInstance->XLines;
508 IdentHostPair ih = xlm->IdentSplit(host);
510 ELine* el = new ELine(ServerInstance->Time(), 0, "<Config>", reason, ih.first.c_str(), ih.second.c_str());
511 if (!xlm->AddLine(el, NULL))
516 static bool DoType(ServerConfig* conf, const char*, const char**, ValueList &values, int*)
518 const char* TypeName = values[0].GetString();
519 const char* Classes = values[1].GetString();
521 conf->opertypes[TypeName] = std::string(Classes);
525 static bool DoClass(ServerConfig* conf, const char* tag, const char**, ValueList &values, int*)
527 const char* ClassName = values[0].GetString();
528 const char* CommandList = values[1].GetString();
529 const char* UModeList = values[2].GetString();
530 const char* CModeList = values[3].GetString();
531 const char *PrivsList = values[4].GetString();
533 for (const char* c = UModeList; *c; ++c)
535 if ((*c < 'A' || *c > 'z') && *c != '*')
537 throw CoreException("Character " + std::string(1, *c) + " is not a valid mode in <class:usermodes>");
540 for (const char* c = CModeList; *c; ++c)
542 if ((*c < 'A' || *c > 'z') && *c != '*')
544 throw CoreException("Character " + std::string(1, *c) + " is not a valid mode in <class:chanmodes>");
548 conf->operclass[ClassName].commandlist = CommandList;
549 conf->operclass[ClassName].umodelist = UModeList;
550 conf->operclass[ClassName].cmodelist = CModeList;
551 conf->operclass[ClassName].privs = PrivsList;
555 void ServerConfig::CrossCheckOperClassType()
557 for (int i = 0; i < ConfValueEnum("type"); ++i)
559 char item[MAXBUF], classn[MAXBUF], classes[MAXBUF];
560 std::string classname;
561 ConfValue("type", "classes", "", i, classes, MAXBUF, false);
562 irc::spacesepstream str(classes);
563 ConfValue("type", "name", "", i, item, MAXBUF, false);
564 while (str.GetToken(classname))
567 bool foundclass = false;
568 for (int j = 0; j < ConfValueEnum("class"); ++j)
570 ConfValue("class", "name", "", j, classn, MAXBUF, false);
571 if (!strcmp(classn, classname.c_str()))
580 snprintf(msg, MAXBUF, " Warning: Oper type '%s' has a missing class named '%s', this does nothing!\n",
581 item, classname.c_str());
582 throw CoreException(msg);
588 void ServerConfig::CrossCheckConnectBlocks(ServerConfig* current)
590 typedef std::map<std::string, ConnectClass*> ClassMap;
591 ClassMap oldBlocksByMask;
594 for(ClassVector::iterator i = current->Classes.begin(); i != current->Classes.end(); ++i)
596 ConnectClass* c = *i;
597 std::string typeMask = (c->type == CC_ALLOW) ? "a" : "d";
599 oldBlocksByMask[typeMask] = c;
603 int block_count = ConfValueEnum("connect");
604 ClassMap newBlocksByMask;
605 Classes.resize(block_count, NULL);
606 std::map<std::string, int> names;
608 bool try_again = true;
609 for(int tries=0; try_again && tries < block_count + 1; tries++)
612 for(int i=0; i < block_count; i++)
617 ConnectClass* parent = NULL;
618 std::string parentName;
619 if (ConfValue("connect", "parent", i, parentName, false))
621 std::map<std::string,int>::iterator parentIter = names.find(parentName);
622 if (parentIter == names.end())
625 // couldn't find parent this time. If it's the last time, we'll never find it.
626 if (tries == block_count)
627 throw CoreException("Could not find parent connect class \"" + parentName + "\" for connect block " + ConvToStr(i));
630 parent = Classes[parentIter->second];
634 if (ConfValue("connect", "name", i, name, false))
636 if (names.find(name) != names.end())
637 throw CoreException("Two connect classes with name \"" + name + "\" defined!");
641 std::string mask, typeMask;
644 if (ConfValue("connect", "allow", i, mask, false))
647 typeMask = 'a' + mask;
649 else if (ConfValue("connect", "deny", i, mask, false))
652 typeMask = 'd' + mask;
656 throw CoreException("Connect class must have an allow or deny mask (#" + ConvToStr(i) + ")");
658 ClassMap::iterator dupMask = newBlocksByMask.find(typeMask);
659 if (dupMask != newBlocksByMask.end())
660 throw CoreException("Two connect classes cannot have the same mask (" + mask + ")");
662 ConnectClass* me = parent ?
663 new ConnectClass(type, mask, *parent) :
664 new ConnectClass(type, mask);
670 if (ConfValue("connect", "password", i, tmpv, false))
672 if (ConfValue("connect", "hash", i, tmpv, false))
674 if (ConfValue("connect", "timeout", i, tmpv, false))
675 me->registration_timeout = atol(tmpv.c_str());
676 if (ConfValue("connect", "pingfreq", i, tmpv, false))
677 me->pingtime = atol(tmpv.c_str());
678 if (ConfValue("connect", "sendq", i, tmpv, false))
680 // attempt to guess a good hard/soft sendq from a single value
681 long value = atol(tmpv.c_str());
683 me->softsendqmax = value / 16;
685 me->softsendqmax = value;
686 me->hardsendqmax = value * 8;
688 if (ConfValue("connect", "softsendq", i, tmpv, false))
689 me->softsendqmax = atol(tmpv.c_str());
690 if (ConfValue("connect", "hardsendq", i, tmpv, false))
691 me->hardsendqmax = atol(tmpv.c_str());
692 if (ConfValue("connect", "recvq", i, tmpv, false))
693 me->recvqmax = atol(tmpv.c_str());
694 if (ConfValue("connect", "localmax", i, tmpv, false))
695 me->maxlocal = atol(tmpv.c_str());
696 if (ConfValue("connect", "globalmax", i, tmpv, false))
697 me->maxglobal = atol(tmpv.c_str());
698 if (ConfValue("connect", "port", i, tmpv, false))
699 me->port = atol(tmpv.c_str());
700 if (ConfValue("connect", "maxchans", i, tmpv, false))
701 me->maxchans = atol(tmpv.c_str());
702 if (ConfValue("connect", "limit", i, tmpv, false))
703 me->limit = atol(tmpv.c_str());
705 ClassMap::iterator oldMask = oldBlocksByMask.find(typeMask);
706 if (oldMask != oldBlocksByMask.end())
708 ConnectClass* old = oldMask->second;
709 oldBlocksByMask.erase(oldMask);
714 newBlocksByMask[typeMask] = me;
721 static const Deprecated ChangedConfig[] = {
722 {"options", "hidelinks", "has been moved to <security:hidelinks> as of 1.2a3"},
723 {"options", "hidewhois", "has been moved to <security:hidewhois> as of 1.2a3"},
724 {"options", "userstats", "has been moved to <security:userstats> as of 1.2a3"},
725 {"options", "customversion", "has been moved to <security:customversion> as of 1.2a3"},
726 {"options", "hidesplits", "has been moved to <security:hidesplits> as of 1.2a3"},
727 {"options", "hidebans", "has been moved to <security:hidebans> as of 1.2a3"},
728 {"options", "hidekills", "has been moved to <security:hidekills> as of 1.2a3"},
729 {"options", "operspywhois", "has been moved to <security:operspywhois> as of 1.2a3"},
730 {"options", "announceinvites", "has been moved to <security:announceinvites> as of 1.2a3"},
731 {"options", "hidemodes", "has been moved to <security:hidemodes> as of 1.2a3"},
732 {"options", "maxtargets", "has been moved to <security:maxtargets> as of 1.2a3"},
733 {"options", "nouserdns", "has been moved to <performance:nouserdns> as of 1.2a3"},
734 {"options", "maxwho", "has been moved to <performance:maxwho> as of 1.2a3"},
735 {"options", "softlimit", "has been moved to <performance:softlimit> as of 1.2a3"},
736 {"options", "somaxconn", "has been moved to <performance:somaxconn> as of 1.2a3"},
737 {"options", "netbuffersize", "has been moved to <performance:netbuffersize> as of 1.2a3"},
738 {"options", "maxwho", "has been moved to <performance:maxwho> as of 1.2a3"},
739 {"options", "loglevel", "1.2 does not use the loglevel value. Please define <log> tags instead."},
740 {"die", "value", "has always been deprecated"},
743 /* These tags can occur ONCE or not at all */
744 static const InitialConfig Values[] = {
745 {"performance", "softlimit", "0", new ValueContainerUInt (&ServerConfig::SoftLimit), DT_INTEGER, ValidateSoftLimit},
746 {"performance", "somaxconn", SOMAXCONN_S, new ValueContainerInt (&ServerConfig::MaxConn), DT_INTEGER, ValidateMaxConn},
747 {"options", "moronbanner", "You're banned!", new ValueContainerString (&ServerConfig::MoronBanner), DT_CHARPTR, NULL},
748 {"server", "name", "", new ValueContainerString (&ServerConfig::ServerName), DT_HOSTNAME, ValidateServerName},
749 {"server", "description", "Configure Me", new ValueContainerString (&ServerConfig::ServerDesc), DT_CHARPTR, NULL},
750 {"server", "network", "Network", new ValueContainerString (&ServerConfig::Network), DT_NOSPACES, NULL},
751 {"server", "id", "", new ValueContainerString (&ServerConfig::sid), DT_CHARPTR, ValidateSID},
752 {"admin", "name", "", new ValueContainerString (&ServerConfig::AdminName), DT_CHARPTR, NULL},
753 {"admin", "email", "Mis@configu.red", new ValueContainerString (&ServerConfig::AdminEmail), DT_CHARPTR, NULL},
754 {"admin", "nick", "Misconfigured", new ValueContainerString (&ServerConfig::AdminNick), DT_CHARPTR, NULL},
755 {"files", "motd", "", new ValueContainerString (&ServerConfig::motd), DT_CHARPTR, ValidateMotd},
756 {"files", "rules", "", new ValueContainerString (&ServerConfig::rules), DT_CHARPTR, ValidateRules},
757 {"power", "diepass", "", new ValueContainerString (&ServerConfig::diepass), DT_CHARPTR, ValidateNotEmpty},
758 {"power", "pause", "", new ValueContainerInt (&ServerConfig::DieDelay), DT_INTEGER, NULL},
759 {"power", "hash", "", new ValueContainerString (&ServerConfig::powerhash), DT_CHARPTR, NULL},
760 {"power", "restartpass", "", new ValueContainerString (&ServerConfig::restartpass), DT_CHARPTR, ValidateNotEmpty},
761 {"options", "prefixquit", "", new ValueContainerString (&ServerConfig::PrefixQuit), DT_CHARPTR, NULL},
762 {"options", "suffixquit", "", new ValueContainerString (&ServerConfig::SuffixQuit), DT_CHARPTR, NULL},
763 {"options", "fixedquit", "", new ValueContainerString (&ServerConfig::FixedQuit), DT_CHARPTR, NULL},
764 {"options", "prefixpart", "", new ValueContainerString (&ServerConfig::PrefixPart), DT_CHARPTR, NULL},
765 {"options", "suffixpart", "", new ValueContainerString (&ServerConfig::SuffixPart), DT_CHARPTR, NULL},
766 {"options", "fixedpart", "", new ValueContainerString (&ServerConfig::FixedPart), DT_CHARPTR, NULL},
767 {"performance", "netbuffersize","10240", new ValueContainerInt (&ServerConfig::NetBufferSize), DT_INTEGER, ValidateNetBufferSize},
768 {"performance", "maxwho", "1024", new ValueContainerInt (&ServerConfig::MaxWhoResults), DT_INTEGER, ValidateMaxWho},
769 {"options", "allowhalfop", "0", new ValueContainerBool (&ServerConfig::AllowHalfop), DT_BOOLEAN, ValidateHalfOp},
770 {"dns", "server", "", new ValueContainerString (&ServerConfig::DNSServer), DT_IPADDRESS,ValidateDnsServer},
771 {"dns", "timeout", "5", new ValueContainerInt (&ServerConfig::dns_timeout), DT_INTEGER, NULL},
772 {"options", "moduledir", MOD_PATH, new ValueContainerString (&ServerConfig::ModPath), DT_CHARPTR, NULL},
773 {"disabled", "commands", "", new ValueContainerString (&ServerConfig::DisabledCommands), DT_CHARPTR, NULL},
774 {"disabled", "usermodes", "", NULL, DT_NOTHING, ValidateDisabledUModes},
775 {"disabled", "chanmodes", "", NULL, DT_NOTHING, ValidateDisabledCModes},
776 {"disabled", "fakenonexistant", "0", new ValueContainerBool (&ServerConfig::DisabledDontExist), DT_BOOLEAN, NULL},
778 {"security", "runasuser", "", new ValueContainerString(&ServerConfig::SetUser), DT_CHARPTR, NULL},
779 {"security", "runasgroup", "", new ValueContainerString(&ServerConfig::SetGroup), DT_CHARPTR, NULL},
780 {"security", "userstats", "", new ValueContainerString (&ServerConfig::UserStats), DT_CHARPTR, NULL},
781 {"security", "customversion","", new ValueContainerString (&ServerConfig::CustomVersion), DT_CHARPTR, NULL},
782 {"security", "hidesplits", "0", new ValueContainerBool (&ServerConfig::HideSplits), DT_BOOLEAN, NULL},
783 {"security", "hidebans", "0", new ValueContainerBool (&ServerConfig::HideBans), DT_BOOLEAN, NULL},
784 {"security", "hidewhois", "", new ValueContainerString (&ServerConfig::HideWhoisServer), DT_NOSPACES, NULL},
785 {"security", "hidekills", "", new ValueContainerString (&ServerConfig::HideKillsServer), DT_NOSPACES, NULL},
786 {"security", "operspywhois", "0", new ValueContainerBool (&ServerConfig::OperSpyWhois), DT_BOOLEAN, NULL},
787 {"security", "restrictbannedusers", "1", new ValueContainerBool (&ServerConfig::RestrictBannedUsers), DT_BOOLEAN, NULL},
788 {"security", "genericoper", "0", new ValueContainerBool (&ServerConfig::GenericOper), DT_BOOLEAN, NULL},
789 {"performance", "nouserdns", "0", new ValueContainerBool (&ServerConfig::NoUserDns), DT_BOOLEAN, NULL},
790 {"options", "syntaxhints", "0", new ValueContainerBool (&ServerConfig::SyntaxHints), DT_BOOLEAN, NULL},
791 {"options", "cyclehosts", "0", new ValueContainerBool (&ServerConfig::CycleHosts), DT_BOOLEAN, NULL},
792 {"options", "ircumsgprefix","0", new ValueContainerBool (&ServerConfig::UndernetMsgPrefix), DT_BOOLEAN, NULL},
793 {"security", "announceinvites", "1", NULL, DT_NOTHING, ValidateInvite},
794 {"options", "hostintopic", "1", new ValueContainerBool (&ServerConfig::FullHostInTopic), DT_BOOLEAN, NULL},
795 {"security", "hidemodes", "", NULL, DT_NOTHING, ValidateModeLists},
796 {"security", "maxtargets", "20", new ValueContainerUInt (&ServerConfig::MaxTargets), DT_INTEGER, ValidateMaxTargets},
797 {"options", "defaultmodes", "nt", new ValueContainerString (&ServerConfig::DefaultModes), DT_CHARPTR, NULL},
798 {"pid", "file", "", new ValueContainerString (&ServerConfig::PID), DT_CHARPTR, NULL},
799 {"whowas", "groupsize", "10", new ValueContainerInt (&ServerConfig::WhoWasGroupSize), DT_INTEGER, NULL},
800 {"whowas", "maxgroups", "10240", new ValueContainerInt (&ServerConfig::WhoWasMaxGroups), DT_INTEGER, NULL},
801 {"whowas", "maxkeep", "3600", NULL, DT_NOTHING, ValidateWhoWas},
802 {"die", "value", "", new ValueContainerString (&ServerConfig::DieValue), DT_CHARPTR, NULL},
803 {"channels", "users", "20", new ValueContainerUInt (&ServerConfig::MaxChans), DT_INTEGER, NULL},
804 {"channels", "opers", "60", new ValueContainerUInt (&ServerConfig::OperMaxChans), DT_INTEGER, NULL},
805 {"cidr", "ipv4clone", "32", new ValueContainerInt (&ServerConfig::c_ipv4_range), DT_INTEGER, NULL},
806 {"cidr", "ipv6clone", "128", new ValueContainerInt (&ServerConfig::c_ipv6_range), DT_INTEGER, NULL},
807 {"limits", "maxnick", "32", new ValueContainerLimit (&ServerLimits::NickMax), DT_LIMIT, NULL},
808 {"limits", "maxchan", "64", new ValueContainerLimit (&ServerLimits::ChanMax), DT_LIMIT, NULL},
809 {"limits", "maxmodes", "20", new ValueContainerLimit (&ServerLimits::MaxModes), DT_LIMIT, NULL},
810 {"limits", "maxident", "11", new ValueContainerLimit (&ServerLimits::IdentMax), DT_LIMIT, NULL},
811 {"limits", "maxquit", "255", new ValueContainerLimit (&ServerLimits::MaxQuit), DT_LIMIT, NULL},
812 {"limits", "maxtopic", "307", new ValueContainerLimit (&ServerLimits::MaxTopic), DT_LIMIT, NULL},
813 {"limits", "maxkick", "255", new ValueContainerLimit (&ServerLimits::MaxKick), DT_LIMIT, NULL},
814 {"limits", "maxgecos", "128", new ValueContainerLimit (&ServerLimits::MaxGecos), DT_LIMIT, NULL},
815 {"limits", "maxaway", "200", new ValueContainerLimit (&ServerLimits::MaxAway), DT_LIMIT, NULL},
816 {"options", "invitebypassmodes", "1", new ValueContainerBool (&ServerConfig::InvBypassModes), DT_BOOLEAN, NULL},
819 InitialConfig::~InitialConfig()
824 /* These tags can occur multiple times, and therefore they have special code to read them
825 * which is different to the code for reading the singular tags listed above.
827 MultiConfig MultiValues[] = {
830 {"allow", "deny", "password", "timeout", "pingfreq",
831 "sendq", "recvq", "localmax", "globalmax", "port",
832 "name", "parent", "maxchans", "limit", "hash",
834 {"", "", "", "", "120",
835 "", "", "3", "3", "0",
836 "", "", "0", "0", "",
838 {DT_IPADDRESS|DT_ALLOW_WILD, DT_IPADDRESS|DT_ALLOW_WILD, DT_CHARPTR, DT_INTEGER, DT_INTEGER,
839 DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER,
840 DT_NOSPACES, DT_NOSPACES, DT_INTEGER, DT_INTEGER, DT_CHARPTR},
844 {"server", "silent", NULL},
846 {DT_HOSTNAME, DT_BOOLEAN},
850 {"chan", "limit", NULL},
852 {DT_CHARPTR, DT_INTEGER},
862 {"reason", "ipmask", NULL},
863 {"No reason", "", NULL},
864 {DT_CHARPTR, DT_IPADDRESS|DT_ALLOW_WILD},
868 {"reason", "nick", NULL},
869 {"No reason", "", NULL},
870 {DT_CHARPTR, DT_CHARPTR},
874 {"reason", "host", NULL},
875 {"No reason", "", NULL},
876 {DT_CHARPTR, DT_CHARPTR},
880 {"reason", "host", NULL},
881 {"No reason", "", NULL},
882 {DT_CHARPTR, DT_CHARPTR},
886 {"name", "classes", NULL},
888 {DT_NOSPACES, DT_CHARPTR},
892 {"name", "commands", "usermodes", "chanmodes", "privs", NULL},
893 {"", "", "", "", "", NULL},
894 {DT_NOSPACES, DT_CHARPTR, DT_CHARPTR, DT_CHARPTR, DT_CHARPTR},
898 /* These tags MUST occur and must ONLY occur once in the config file */
899 static const char* Once[] = { "server", "admin", "files", "power", "options" };
901 // WARNING: it is not safe to use most of the codebase in this function, as it
902 // will run in the config reader thread
903 void ServerConfig::Read()
905 /* Load and parse the config file, if there are any errors then explode */
907 if (!this->DoInclude(ServerInstance->ConfigFileName, true))
914 void ServerConfig::Apply(ServerConfig* old, const std::string &useruid)
917 /* std::ostringstream::clear() does not clear the string itself, only the error flags. */
919 errstr.str().clear();
920 include_stack.clear();
922 /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
925 /* Check we dont have more than one of singular tags, or any of them missing
927 for (int Index = 0; Index * sizeof(*Once) < sizeof(Once); Index++)
928 CheckOnce(Once[Index]);
930 for (int Index = 0; Index * sizeof(Deprecated) < sizeof(ChangedConfig); Index++)
934 if (ConfValue(ChangedConfig[Index].tag, ChangedConfig[Index].value, "", 0, item, MAXBUF, true) || *item)
935 throw CoreException(std::string("Your configuration contains a deprecated value: <") + ChangedConfig[Index].tag + ":" + ChangedConfig[Index].value + "> - " + ChangedConfig[Index].reason);
938 /* Read the values of all the tags which occur once or not at all, and call their callbacks.
940 for (int Index = 0; Index * sizeof(*Values) < sizeof(Values); ++Index)
943 int dt = Values[Index].datatype;
944 bool allow_newlines = ((dt & DT_ALLOW_NEWLINE) > 0);
945 bool allow_wild = ((dt & DT_ALLOW_WILD) > 0);
946 dt &= ~DT_ALLOW_NEWLINE;
947 dt &= ~DT_ALLOW_WILD;
949 ConfValue(Values[Index].tag, Values[Index].value, Values[Index].default_value, 0, item, MAXBUF, allow_newlines);
952 if (Values[Index].validation_function && !Values[Index].validation_function(this, Values[Index].tag, Values[Index].value, vi))
953 throw CoreException("One or more values in your configuration file failed to validate. Please see your ircd.log for more information.");
959 ValueContainerString* vcc = (ValueContainerString*)Values[Index].val;
960 ValidateNoSpaces(vi.GetString(), Values[Index].tag, Values[Index].value);
961 vcc->Set(this, vi.GetValue());
966 ValueContainerString* vcc = (ValueContainerString*)Values[Index].val;
967 ValidateHostname(vi.GetString(), Values[Index].tag, Values[Index].value);
968 vcc->Set(this, vi.GetValue());
973 ValueContainerString* vcc = (ValueContainerString*)Values[Index].val;
974 ValidateIP(vi.GetString(), Values[Index].tag, Values[Index].value, allow_wild);
975 vcc->Set(this, vi.GetValue());
980 ValueContainerString* vcc = (ValueContainerString*)Values[Index].val;
981 if (*(vi.GetString()) && !ServerInstance->IsChannel(vi.GetString(), MAXBUF))
983 throw CoreException("The value of <"+std::string(Values[Index].tag)+":"+Values[Index].value+"> is not a valid channel name");
985 vcc->Set(this, vi.GetValue());
990 ValueContainerString* vcs = dynamic_cast<ValueContainerString*>(Values[Index].val);
992 vcs->Set(this, vi.GetValue());
997 int val = vi.GetInteger();
998 ValueContainerInt* vci = (ValueContainerInt*)Values[Index].val;
1004 int val = vi.GetInteger();
1005 ValueContainerLimit* vci = (ValueContainerLimit*)Values[Index].val;
1006 vci->Set(this, val);
1011 bool val = vi.GetBool();
1012 ValueContainerBool* vcb = (ValueContainerBool*)Values[Index].val;
1013 vcb->Set(this, val);
1019 /* Read the multiple-tag items (class tags, connect tags, etc)
1020 * and call the callbacks associated with them. We have three
1021 * callbacks for these, a 'start', 'item' and 'end' callback.
1023 for (int Index = 0; Index * sizeof(MultiConfig) < sizeof(MultiValues); ++Index)
1025 int number_of_tags = ConfValueEnum(MultiValues[Index].tag);
1027 for (int tagnum = 0; tagnum < number_of_tags; ++tagnum)
1030 for (int valuenum = 0; (MultiValues[Index].items[valuenum]) && (valuenum < MAX_VALUES_PER_TAG); ++valuenum)
1032 int dt = MultiValues[Index].datatype[valuenum];
1033 bool allow_newlines = ((dt & DT_ALLOW_NEWLINE) > 0);
1034 bool allow_wild = ((dt & DT_ALLOW_WILD) > 0);
1035 dt &= ~DT_ALLOW_NEWLINE;
1036 dt &= ~DT_ALLOW_WILD;
1043 if (ConfValue(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1044 vl.push_back(ValueItem(item));
1046 vl.push_back(ValueItem(""));
1047 ValidateNoSpaces(vl[vl.size()-1].GetString(), MultiValues[Index].tag, MultiValues[Index].items[valuenum]);
1053 if (ConfValue(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1054 vl.push_back(ValueItem(item));
1056 vl.push_back(ValueItem(""));
1057 ValidateHostname(vl[vl.size()-1].GetString(), MultiValues[Index].tag, MultiValues[Index].items[valuenum]);
1063 if (ConfValue(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1064 vl.push_back(ValueItem(item));
1066 vl.push_back(ValueItem(""));
1067 ValidateIP(vl[vl.size()-1].GetString(), MultiValues[Index].tag, MultiValues[Index].items[valuenum], allow_wild);
1073 if (ConfValue(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1074 vl.push_back(ValueItem(item));
1076 vl.push_back(ValueItem(""));
1077 if (!ServerInstance->IsChannel(vl[vl.size()-1].GetString(), MAXBUF))
1078 throw CoreException("The value of <"+std::string(MultiValues[Index].tag)+":"+MultiValues[Index].items[valuenum]+"> number "+ConvToStr(tagnum + 1)+" is not a valid channel name");
1084 if (ConfValue(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1085 vl.push_back(ValueItem(item));
1087 vl.push_back(ValueItem(""));
1093 if (ConfValueInteger(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item))
1094 vl.push_back(ValueItem(item));
1096 vl.push_back(ValueItem(0));
1101 bool item = ConfValueBool(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum);
1102 vl.push_back(ValueItem(item));
1107 if (MultiValues[Index].validation_function)
1108 MultiValues[Index].validation_function(this, MultiValues[Index].tag, MultiValues[Index].items, vl, MultiValues[Index].datatype);
1112 /* Finalise the limits, increment them all by one so that we can just put assign(str, 0, val)
1113 * rather than assign(str, 0, val + 1)
1117 // Handle special items
1118 CrossCheckOperClassType();
1119 CrossCheckConnectBlocks(old);
1121 catch (CoreException &ce)
1123 errstr << ce.GetReason();
1127 // write once here, to try it out and make sure its ok
1128 ServerInstance->WritePID(this->PID);
1131 * These values can only be set on boot. Keep their old values. Do it before we send messages so we actually have a servername.
1135 this->ServerName = old->ServerName;
1136 this->sid = old->sid;
1137 this->argv = old->argv;
1138 this->argc = old->argc;
1140 // Same for ports... they're bound later on first run.
1142 ServerInstance->BindPorts(pl);
1145 errstr << "Not all your client ports could be bound.\nThe following port(s) failed to bind:\n";
1148 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
1151 snprintf(buf, MAXBUF, "%d. Address: %s Reason: %s\n", j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
1157 User* user = useruid.empty() ? NULL : ServerInstance->FindNick(useruid);
1159 valid = errstr.str().empty();
1161 ServerInstance->Logs->Log("CONFIG",DEFAULT, "There were errors in your configuration file:");
1163 while (errstr.good())
1166 getline(errstr, line, '\n');
1170 user->WriteServ("NOTICE %s :*** %s", user->nick.c_str(), line.c_str());
1172 ServerInstance->SNO->WriteGlobalSno('a', line);
1177 // Starting up, so print it out so it's seen. XXX this is a bit of a hack.
1178 printf("%s\n", line.c_str());
1183 errstr.str(std::string());
1185 /* No old configuration -> initial boot, nothing more to do here */
1190 ServerInstance->Exit(EXIT_STATUS_CONFIG);
1196 // If there were errors processing configuration, don't touch modules.
1203 void ServerConfig::ApplyModules(User* user)
1205 const std::vector<std::string> v = ServerInstance->Modules->GetAllModuleNames(0);
1206 std::vector<std::string> added_modules;
1207 std::set<std::string> removed_modules(v.begin(), v.end());
1209 int new_module_count = ConfValueEnum("module");
1210 for(int i=0; i < new_module_count; i++)
1213 if (ConfValue("module", "name", i, name, false))
1215 // if this module is already loaded, the erase will succeed, so we need do nothing
1216 // otherwise, we need to add the module (which will be done later)
1217 if (removed_modules.erase(name) == 0)
1218 added_modules.push_back(name);
1222 for (std::set<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
1224 // Don't remove cmd_*.so, just remove m_*.so
1225 if (removing->c_str()[0] == 'c')
1227 Module* m = ServerInstance->Modules->Find(*removing);
1228 if (m && ServerInstance->Modules->Unload(m))
1230 ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH UNLOADED MODULE: %s",removing->c_str());
1233 user->WriteNumeric(RPL_UNLOADEDMODULE, "%s %s :Module %s successfully unloaded.",user->nick.c_str(), removing->c_str(), removing->c_str());
1235 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully unloaded.", removing->c_str());
1240 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());
1242 ServerInstance->SNO->WriteGlobalSno('a', "Failed to unload module %s: %s", removing->c_str(), ServerInstance->Modules->LastError().c_str());
1246 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
1248 if (ServerInstance->Modules->Load(adding->c_str()))
1250 ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH LOADED MODULE: %s",adding->c_str());
1252 user->WriteNumeric(RPL_LOADEDMODULE, "%s %s :Module %s successfully loaded.",user->nick.c_str(), adding->c_str(), adding->c_str());
1254 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully loaded.", adding->c_str());
1259 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());
1261 ServerInstance->SNO->WriteGlobalSno('a', "Failed to load module %s: %s", adding->c_str(), ServerInstance->Modules->LastError().c_str());
1266 user->WriteServ("NOTICE %s :*** Successfully rehashed server.", user->nick.c_str());
1268 ServerInstance->SNO->WriteGlobalSno('a', "*** Successfully rehashed server.");
1271 bool ServerConfig::LoadConf(FILE* &conf, const char* filename, bool allowexeinc)
1275 long linenumber = 1;
1276 long last_successful_parse = 1;
1280 int character_count = 0;
1286 ServerInstance->Logs->Log("CONFIG", DEBUG, "Reading %s", filename);
1288 /* Check if the file open failed first */
1291 errstr << "LoadConf: Couldn't open config file: " << filename << std::endl;
1295 for (unsigned int t = 0; t < include_stack.size(); t++)
1297 if (std::string(filename) == include_stack[t])
1299 errstr << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
1304 /* It's not already included, add it to the list of files we've loaded */
1305 include_stack.push_back(filename);
1307 /* Start reading characters... */
1308 while ((ch = fgetc(conf)) != EOF)
1311 * Fix for moronic windows issue spotted by Adremelech.
1312 * Some windows editors save text files as utf-16, which is
1313 * a total pain in the ass to parse. Users should save in the
1314 * right config format! If we ever see a file where the first
1315 * byte is 0xFF or 0xFE, or the second is 0xFF or 0xFE, then
1316 * this is most likely a utf-16 file. Bail out and insult user.
1318 if ((character_count++ < 2) && (ch == '\xFF' || ch == '\xFE'))
1320 errstr << "File " << filename << " cannot be read, as it is encoded in braindead UTF-16. Save your file as plain ASCII!" << std::endl;
1325 * Here we try and get individual tags on separate lines,
1326 * this would be so easy if we just made people format
1327 * their config files like that, but they don't so...
1328 * We check for a '<' and then know the line is over when
1329 * we get a '>' not inside quotes. If we find two '<' and
1330 * no '>' then die with an error.
1333 if ((ch == '#') && !in_quote)
1354 /* XXX: Added by Brain, May 1st 2006 - Escaping of characters.
1355 * Note that this WILL NOT usually allow insertion of newlines,
1356 * because a newline is two characters long. Use it primarily to
1357 * insert the " symbol.
1359 * Note that this also involves a further check when parsing the line,
1360 * which can be found below.
1362 if ((ch == '\\') && (in_quote) && (in_tag))
1365 char real_character;
1368 real_character = fgetc(conf);
1369 if (real_character == 'n')
1370 real_character = '\n';
1371 line += real_character;
1376 errstr << "End of file after a \\, what did you want to escape?: " << filename << ":" << linenumber << std::endl;
1384 if ((ch != '<') && (!in_tag) && (!in_comment) && (ch > ' ') && (ch != 9))
1386 errstr << "You have stray characters beyond the tag which starts at " << filename << ":" << last_successful_parse << std::endl;
1396 errstr << "The tag at location " << filename << ":" << last_successful_parse << " was valid, but there is an error in the tag which comes after it. You are possibly missing a \" or >. Please check this." << std::endl;
1404 errstr << "Parser error: Inside a quote but not within the last valid tag, which was opened at: " << filename << ":" << last_successful_parse << std::endl;
1409 // errstr << "Opening new config tag on line " << linenumber << std::endl;
1420 // errstr << "Closing quote in config tag on line " << linenumber << std::endl;
1425 // errstr << "Opening quote in config tag on line " << linenumber << std::endl;
1433 errstr << "The tag immediately after the one at " << filename << ":" << last_successful_parse << " has a missing closing \" symbol. Please check this." << std::endl;
1437 errstr << "You have opened a quote (\") beyond the tag at " << filename << ":" << last_successful_parse << " without opening a new tag. Please check this." << std::endl;
1447 // errstr << "Closing config tag on line " << linenumber << std::endl;
1451 * If this finds an <include> then ParseLine can simply call
1452 * LoadConf() and load the included config into the same ConfigDataHash
1454 long bl = linenumber;
1455 if (!this->ParseLine(filename, line, linenumber, allowexeinc))
1457 last_successful_parse = linenumber;
1465 errstr << "You forgot to close the tag which comes immediately after the one at " << filename << ":" << last_successful_parse << std::endl;
1472 /* Fix for bug #392 - if we reach the end of a file and we are still in a quote or comment, most likely the user fucked up */
1473 if (in_comment || in_quote)
1475 errstr << "Reached end of file whilst still inside a quoted section or tag. This is most likely an error or there \
1476 is a newline missing from the end of the file: " << filename << ":" << linenumber << std::endl;
1483 bool ServerConfig::LoadConf(FILE* &conf, const std::string &filename, bool allowexeinc)
1485 return this->LoadConf(conf, filename.c_str(), allowexeinc);
1488 bool ServerConfig::ParseLine(const std::string &filename, std::string &line, long &linenumber, bool allowexeinc)
1490 std::string tagname;
1491 std::string current_key;
1492 std::string current_value;
1499 got_name = got_key = in_quote = false;
1501 for(std::string::iterator c = line.begin(); c != line.end(); c++)
1505 /* We don't know the tag name yet. */
1511 if ((*c >= 'a' && *c <= 'z') || (*c >= 'A' && *c <='Z') || (*c >= '0' && *c <= '9') || *c == '_')
1515 errstr << "Invalid character in value name of tag: '" << *c << "' in value '" << tagname << "' in filename: " << filename << ":" << linenumber << std::endl;
1522 /* We got to a space, we should have the tagname now. */
1523 if(tagname.length())
1531 /* We have the tag name */
1534 /* We're still reading the key name */
1535 if ((*c != '=') && (*c != '>'))
1539 if ((*c >= 'a' && *c <= 'z') || (*c >= 'A' && *c <='Z') || (*c >= '0' && *c <= '9') || *c == '_')
1543 errstr << "Invalid character in key: '" << *c << "' in key '" << current_key << "' in filename: " << filename << ":" << linenumber << std::endl;
1550 /* We got an '=', end of the key name. */
1556 /* We have the key name, now we're looking for quotes and the value */
1558 /* Correctly handle escaped characters here.
1559 * See the XXX'ed section above.
1561 if ((*c == '\\') && (in_quote))
1565 current_value += '\n';
1567 current_value += *c;
1570 else if ((*c == '\\') && (!in_quote))
1572 errstr << "You can't have an escape sequence outside of a quoted section: " << filename << ":" << linenumber << std::endl;
1575 else if ((*c == '\n') && (in_quote))
1577 /* Got a 'real' \n, treat it as part of the value */
1578 current_value += '\n';
1581 else if ((*c == '\r') && (in_quote))
1583 /* Got a \r, drop it */
1591 /* We're not already in a quote. */
1596 /* Leaving the quotes, we have the current value */
1597 results.push_back(KeyVal(current_key, current_value));
1599 // std::cout << "<" << tagname << ":" << current_key << "> " << current_value << std::endl;
1604 if ((tagname == "include") && (current_key == "file"))
1606 if (!this->DoInclude(current_value, allowexeinc))
1609 else if ((tagname == "include") && (current_key == "executable"))
1613 errstr << "Executable includes are not allowed to use <include:executable>\n"
1614 "This could be an attempt to execute commands from a malicious remote include.\n"
1615 "If you need multiple levels of remote include, create a script to assemble the "
1616 "contents locally or include files using <include:file>\n";
1620 /* Pipe an executable and use its stdout as config data */
1621 if (!this->DoPipe(current_value))
1625 current_key.clear();
1626 current_value.clear();
1634 current_value += *c;
1641 /* Finished parsing the tag, add it to the config hash */
1642 config_data.insert(std::pair<std::string, KeyValList > (tagname, results));
1647 bool ServerConfig::DoPipe(const std::string &file)
1649 FILE* conf = popen(file.c_str(), "r");
1654 ret = LoadConf(conf, file.c_str(), false);
1658 errstr << "Couldn't execute: " << file << std::endl;
1663 bool ServerConfig::StartsWithWindowsDriveLetter(const std::string &path)
1665 return (path.length() > 2 && isalpha(path[0]) && path[1] == ':');
1668 bool ServerConfig::DoInclude(const std::string &file, bool allowexeinc)
1670 FILE* conf = fopen(file.c_str(), "r");
1675 ret = LoadConf(conf, file, allowexeinc);
1679 errstr << "Couldn't open config file: " << file << std::endl;
1684 bool ServerConfig::ConfValue(const char* tag, const char* var, int index, char* result, int length, bool allow_linefeeds)
1686 return ConfValue(tag, var, "", index, result, length, allow_linefeeds);
1689 bool ServerConfig::ConfValue(const char* tag, const char* var, const char* default_value, int index, char* result, int length, bool allow_linefeeds)
1692 bool r = ConfValue(std::string(tag), std::string(var), std::string(default_value), index, value, allow_linefeeds);
1693 strlcpy(result, value.c_str(), length);
1697 bool ServerConfig::ConfValue(const std::string &tag, const std::string &var, int index, std::string &result, bool allow_linefeeds)
1699 return ConfValue(tag, var, "", index, result, allow_linefeeds);
1702 bool ServerConfig::ConfValue(const std::string &tag, const std::string &var, const std::string &default_value, int index, std::string &result, bool allow_linefeeds)
1704 ConfigDataHash::size_type pos = index;
1705 if (pos < config_data.count(tag))
1707 ConfigDataHash::iterator iter = config_data.find(tag);
1709 for(int i = 0; i < index; i++)
1712 for(KeyValList::iterator j = iter->second.begin(); j != iter->second.end(); j++)
1716 if ((!allow_linefeeds) && (j->second.find('\n') != std::string::npos))
1718 ServerInstance->Logs->Log("CONFIG",DEFAULT, "Value of <" + tag + ":" + var+ "> contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
1719 for (std::string::iterator n = j->second.begin(); n != j->second.end(); n++)
1730 if (!default_value.empty())
1732 result = default_value;
1738 if (!default_value.empty())
1740 result = default_value;
1747 bool ServerConfig::ConfValueInteger(const char* tag, const char* var, int index, int &result)
1749 return ConfValueInteger(std::string(tag), std::string(var), "", index, result);
1752 bool ServerConfig::ConfValueInteger(const char* tag, const char* var, const char* default_value, int index, int &result)
1754 return ConfValueInteger(std::string(tag), std::string(var), std::string(default_value), index, result);
1757 bool ServerConfig::ConfValueInteger(const std::string &tag, const std::string &var, int index, int &result)
1759 return ConfValueInteger(tag, var, "", index, result);
1762 bool ServerConfig::ConfValueInteger(const std::string &tag, const std::string &var, const std::string &default_value, int index, int &result)
1765 std::istringstream stream;
1766 bool r = ConfValue(tag, var, default_value, index, value);
1768 if(!(stream >> result))
1774 if (value.substr(0,2) == "0x")
1779 result = strtol(value.c_str(), &endptr, 16);
1781 /* No digits found */
1782 if (endptr == value.c_str())
1787 char denominator = *(value.end() - 1);
1788 switch (toupper(denominator))
1791 /* Kilobytes -> bytes */
1792 result = result * 1024;
1795 /* Megabytes -> bytes */
1796 result = result * 1024 * 1024;
1799 /* Gigabytes -> bytes */
1800 result = result * 1024 * 1024 * 1024;
1810 bool ServerConfig::ConfValueBool(const char* tag, const char* var, int index)
1812 return ConfValueBool(std::string(tag), std::string(var), "", index);
1815 bool ServerConfig::ConfValueBool(const char* tag, const char* var, const char* default_value, int index)
1817 return ConfValueBool(std::string(tag), std::string(var), std::string(default_value), index);
1820 bool ServerConfig::ConfValueBool(const std::string &tag, const std::string &var, int index)
1822 return ConfValueBool(tag, var, "", index);
1825 bool ServerConfig::ConfValueBool(const std::string &tag, const std::string &var, const std::string &default_value, int index)
1828 if(!ConfValue(tag, var, default_value, index, result))
1831 return ((result == "yes") || (result == "true") || (result == "1"));
1834 int ServerConfig::ConfValueEnum(const char* tag)
1836 return config_data.count(tag);
1839 int ServerConfig::ConfValueEnum(const std::string &tag)
1841 return config_data.count(tag);
1844 int ServerConfig::ConfVarEnum(const char* tag, int index)
1846 return ConfVarEnum(std::string(tag), index);
1849 int ServerConfig::ConfVarEnum(const std::string &tag, int index)
1851 ConfigDataHash::size_type pos = index;
1853 if (pos < config_data.count(tag))
1855 ConfigDataHash::const_iterator iter = config_data.find(tag);
1857 for(int i = 0; i < index; i++)
1860 return iter->second.size();
1866 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1868 bool ServerConfig::ReadFile(file_cache &F, const char* fname)
1870 if (!fname || !*fname)
1874 char linebuf[MAXBUF];
1878 if (!FileExists(fname))
1880 file = fopen(fname, "r");
1886 if (fgets(linebuf, sizeof(linebuf), file))
1887 linebuf[strlen(linebuf)-1] = 0;
1891 F.push_back(*linebuf ? linebuf : " ");
1902 bool ServerConfig::FileExists(const char* file)
1905 if (stat(file, &sb) == -1)
1908 if ((sb.st_mode & S_IFDIR) > 0)
1911 FILE *input = fopen(file, "r");
1921 const char* ServerConfig::CleanFilename(const char* name)
1923 const char* p = name + strlen(name);
1924 while ((p != name) && (*p != '/') && (*p != '\\')) p--;
1925 return (p != name ? ++p : p);
1929 std::string ServerConfig::GetSID()
1934 ValueItem::ValueItem(int value)
1936 std::stringstream n;
1941 ValueItem::ValueItem(bool value)
1943 std::stringstream n;
1948 void ValueItem::Set(const std::string& value)
1953 void ValueItem::Set(int value)
1955 std::stringstream n;
1960 int ValueItem::GetInteger()
1964 return atoi(v.c_str());
1967 const char* ValueItem::GetString() const
1972 bool ValueItem::GetBool()
1974 return (GetInteger() || v == "yes" || v == "true");
1978 void ConfigReaderThread::Run()
1980 Config = new ServerConfig;
1985 void ConfigReaderThread::Finish()
1987 ServerConfig* old = ServerInstance->Config;
1988 ServerInstance->Logs->Log("CONFIG",DEBUG,"Switching to new configuration...");
1989 ServerInstance->Logs->CloseLogs();
1990 ServerInstance->Config = this->Config;
1991 ServerInstance->Logs->OpenFileLogs();
1992 Config->Apply(old, TheUserUID);
1997 * Apply the changed configuration from the rehash.
1999 * XXX: The order of these is IMPORTANT, do not reorder them without testing
2002 ServerInstance->XLines->CheckELines();
2003 ServerInstance->XLines->CheckELines();
2004 ServerInstance->XLines->ApplyLines();
2005 ServerInstance->Res->Rehash();
2006 ServerInstance->ResetMaxBans();
2007 Config->ApplyDisabledCommands(Config->DisabledCommands);
2008 User* user = TheUserUID.empty() ? ServerInstance->FindNick(TheUserUID) : NULL;
2009 FOREACH_MOD(I_OnRehash, OnRehash(user));
2010 ServerInstance->BuildISupport();
2017 ServerInstance->Logs->CloseLogs();
2018 ServerInstance->Config = old;
2019 ServerInstance->Logs->OpenFileLogs();
2020 delete this->Config;