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 /* These tags can occur multiple times, and therefore they have special code to read them
820 * which is different to the code for reading the singular tags listed above.
822 MultiConfig MultiValues[] = {
825 {"allow", "deny", "password", "timeout", "pingfreq",
826 "sendq", "recvq", "localmax", "globalmax", "port",
827 "name", "parent", "maxchans", "limit", "hash",
829 {"", "", "", "", "120",
830 "", "", "3", "3", "0",
831 "", "", "0", "0", "",
833 {DT_IPADDRESS|DT_ALLOW_WILD, DT_IPADDRESS|DT_ALLOW_WILD, DT_CHARPTR, DT_INTEGER, DT_INTEGER,
834 DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER,
835 DT_NOSPACES, DT_NOSPACES, DT_INTEGER, DT_INTEGER, DT_CHARPTR},
839 {"server", "silent", NULL},
841 {DT_HOSTNAME, DT_BOOLEAN},
845 {"chan", "limit", NULL},
847 {DT_CHARPTR, DT_INTEGER},
857 {"reason", "ipmask", NULL},
858 {"No reason", "", NULL},
859 {DT_CHARPTR, DT_IPADDRESS|DT_ALLOW_WILD},
863 {"reason", "nick", NULL},
864 {"No reason", "", NULL},
865 {DT_CHARPTR, DT_CHARPTR},
869 {"reason", "host", NULL},
870 {"No reason", "", NULL},
871 {DT_CHARPTR, DT_CHARPTR},
875 {"reason", "host", NULL},
876 {"No reason", "", NULL},
877 {DT_CHARPTR, DT_CHARPTR},
881 {"name", "classes", NULL},
883 {DT_NOSPACES, DT_CHARPTR},
887 {"name", "commands", "usermodes", "chanmodes", "privs", NULL},
888 {"", "", "", "", "", NULL},
889 {DT_NOSPACES, DT_CHARPTR, DT_CHARPTR, DT_CHARPTR, DT_CHARPTR},
893 /* These tags MUST occur and must ONLY occur once in the config file */
894 static const char* Once[] = { "server", "admin", "files", "power", "options" };
896 // WARNING: it is not safe to use most of the codebase in this function, as it
897 // will run in the config reader thread
898 void ServerConfig::Read()
900 /* Load and parse the config file, if there are any errors then explode */
902 if (!this->DoInclude(ServerInstance->ConfigFileName, true))
909 void ServerConfig::Apply(ServerConfig* old, const std::string &useruid)
912 /* std::ostringstream::clear() does not clear the string itself, only the error flags. */
914 errstr.str().clear();
915 include_stack.clear();
917 /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
920 /* Check we dont have more than one of singular tags, or any of them missing
922 for (int Index = 0; Index * sizeof(*Once) < sizeof(Once); Index++)
923 CheckOnce(Once[Index]);
925 for (int Index = 0; Index * sizeof(Deprecated) < sizeof(ChangedConfig); Index++)
929 if (ConfValue(ChangedConfig[Index].tag, ChangedConfig[Index].value, "", 0, item, MAXBUF, true) || *item)
930 throw CoreException(std::string("Your configuration contains a deprecated value: <") + ChangedConfig[Index].tag + ":" + ChangedConfig[Index].value + "> - " + ChangedConfig[Index].reason);
933 /* Read the values of all the tags which occur once or not at all, and call their callbacks.
935 for (int Index = 0; Index * sizeof(*Values) < sizeof(Values); ++Index)
938 int dt = Values[Index].datatype;
939 bool allow_newlines = ((dt & DT_ALLOW_NEWLINE) > 0);
940 bool allow_wild = ((dt & DT_ALLOW_WILD) > 0);
941 dt &= ~DT_ALLOW_NEWLINE;
942 dt &= ~DT_ALLOW_WILD;
944 ConfValue(Values[Index].tag, Values[Index].value, Values[Index].default_value, 0, item, MAXBUF, allow_newlines);
947 if (Values[Index].validation_function && !Values[Index].validation_function(this, Values[Index].tag, Values[Index].value, vi))
948 throw CoreException("One or more values in your configuration file failed to validate. Please see your ircd.log for more information.");
954 ValueContainerString* vcc = (ValueContainerString*)Values[Index].val;
955 ValidateNoSpaces(vi.GetString(), Values[Index].tag, Values[Index].value);
956 vcc->Set(this, vi.GetValue());
961 ValueContainerString* vcc = (ValueContainerString*)Values[Index].val;
962 ValidateHostname(vi.GetString(), Values[Index].tag, Values[Index].value);
963 vcc->Set(this, vi.GetValue());
968 ValueContainerString* vcc = (ValueContainerString*)Values[Index].val;
969 ValidateIP(vi.GetString(), Values[Index].tag, Values[Index].value, allow_wild);
970 vcc->Set(this, vi.GetValue());
975 ValueContainerString* vcc = (ValueContainerString*)Values[Index].val;
976 if (*(vi.GetString()) && !ServerInstance->IsChannel(vi.GetString(), MAXBUF))
978 throw CoreException("The value of <"+std::string(Values[Index].tag)+":"+Values[Index].value+"> is not a valid channel name");
980 vcc->Set(this, vi.GetValue());
985 ValueContainerString* vcs = dynamic_cast<ValueContainerString*>(Values[Index].val);
987 vcs->Set(this, vi.GetValue());
992 int val = vi.GetInteger();
993 ValueContainerInt* vci = (ValueContainerInt*)Values[Index].val;
999 int val = vi.GetInteger();
1000 ValueContainerLimit* vci = (ValueContainerLimit*)Values[Index].val;
1001 vci->Set(this, val);
1006 bool val = vi.GetBool();
1007 ValueContainerBool* vcb = (ValueContainerBool*)Values[Index].val;
1008 vcb->Set(this, val);
1014 /* Read the multiple-tag items (class tags, connect tags, etc)
1015 * and call the callbacks associated with them. We have three
1016 * callbacks for these, a 'start', 'item' and 'end' callback.
1018 for (int Index = 0; Index * sizeof(MultiConfig) < sizeof(MultiValues); ++Index)
1020 int number_of_tags = ConfValueEnum(MultiValues[Index].tag);
1022 for (int tagnum = 0; tagnum < number_of_tags; ++tagnum)
1025 for (int valuenum = 0; (MultiValues[Index].items[valuenum]) && (valuenum < MAX_VALUES_PER_TAG); ++valuenum)
1027 int dt = MultiValues[Index].datatype[valuenum];
1028 bool allow_newlines = ((dt & DT_ALLOW_NEWLINE) > 0);
1029 bool allow_wild = ((dt & DT_ALLOW_WILD) > 0);
1030 dt &= ~DT_ALLOW_NEWLINE;
1031 dt &= ~DT_ALLOW_WILD;
1038 if (ConfValue(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1039 vl.push_back(ValueItem(item));
1041 vl.push_back(ValueItem(""));
1042 ValidateNoSpaces(vl[vl.size()-1].GetString(), MultiValues[Index].tag, MultiValues[Index].items[valuenum]);
1048 if (ConfValue(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1049 vl.push_back(ValueItem(item));
1051 vl.push_back(ValueItem(""));
1052 ValidateHostname(vl[vl.size()-1].GetString(), MultiValues[Index].tag, MultiValues[Index].items[valuenum]);
1058 if (ConfValue(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1059 vl.push_back(ValueItem(item));
1061 vl.push_back(ValueItem(""));
1062 ValidateIP(vl[vl.size()-1].GetString(), MultiValues[Index].tag, MultiValues[Index].items[valuenum], allow_wild);
1068 if (ConfValue(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1069 vl.push_back(ValueItem(item));
1071 vl.push_back(ValueItem(""));
1072 if (!ServerInstance->IsChannel(vl[vl.size()-1].GetString(), MAXBUF))
1073 throw CoreException("The value of <"+std::string(MultiValues[Index].tag)+":"+MultiValues[Index].items[valuenum]+"> number "+ConvToStr(tagnum + 1)+" is not a valid channel name");
1079 if (ConfValue(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1080 vl.push_back(ValueItem(item));
1082 vl.push_back(ValueItem(""));
1088 if (ConfValueInteger(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item))
1089 vl.push_back(ValueItem(item));
1091 vl.push_back(ValueItem(0));
1096 bool item = ConfValueBool(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum);
1097 vl.push_back(ValueItem(item));
1102 if (MultiValues[Index].validation_function)
1103 MultiValues[Index].validation_function(this, MultiValues[Index].tag, MultiValues[Index].items, vl, MultiValues[Index].datatype);
1107 /* Finalise the limits, increment them all by one so that we can just put assign(str, 0, val)
1108 * rather than assign(str, 0, val + 1)
1112 // Handle special items
1113 CrossCheckOperClassType();
1114 CrossCheckConnectBlocks(old);
1116 catch (CoreException &ce)
1118 errstr << ce.GetReason();
1122 // write once here, to try it out and make sure its ok
1123 ServerInstance->WritePID(this->PID);
1126 * These values can only be set on boot. Keep their old values. Do it before we send messages so we actually have a servername.
1130 this->ServerName = old->ServerName;
1131 this->sid = old->sid;
1132 this->argv = old->argv;
1133 this->argc = old->argc;
1135 // Same for ports... they're bound later on first run.
1137 ServerInstance->BindPorts(pl);
1140 errstr << "Not all your client ports could be bound.\nThe following port(s) failed to bind:\n";
1143 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
1146 snprintf(buf, MAXBUF, "%d. Address: %s Reason: %s\n", j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
1152 User* user = useruid.empty() ? NULL : ServerInstance->FindNick(useruid);
1154 valid = errstr.str().empty();
1156 ServerInstance->Logs->Log("CONFIG",DEFAULT, "There were errors in your configuration file:");
1158 while (errstr.good())
1161 getline(errstr, line, '\n');
1165 user->WriteServ("NOTICE %s :*** %s", user->nick.c_str(), line.c_str());
1167 ServerInstance->SNO->WriteGlobalSno('a', line);
1172 // Starting up, so print it out so it's seen. XXX this is a bit of a hack.
1173 printf("%s\n", line.c_str());
1178 errstr.str(std::string());
1180 /* No old configuration -> initial boot, nothing more to do here */
1185 ServerInstance->Exit(EXIT_STATUS_CONFIG);
1191 // If there were errors processing configuration, don't touch modules.
1198 void ServerConfig::ApplyModules(User* user)
1200 const std::vector<std::string> v = ServerInstance->Modules->GetAllModuleNames(0);
1201 std::vector<std::string> added_modules;
1202 std::set<std::string> removed_modules(v.begin(), v.end());
1204 int new_module_count = ConfValueEnum("module");
1205 for(int i=0; i < new_module_count; i++)
1208 if (ConfValue("module", "name", i, name, false))
1210 // if this module is already loaded, the erase will succeed, so we need do nothing
1211 // otherwise, we need to add the module (which will be done later)
1212 if (removed_modules.erase(name) == 0)
1213 added_modules.push_back(name);
1217 for (std::set<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
1219 // Don't remove cmd_*.so, just remove m_*.so
1220 if (removing->c_str()[0] == 'c')
1222 if (ServerInstance->Modules->Unload(removing->c_str()))
1224 ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH UNLOADED MODULE: %s",removing->c_str());
1227 user->WriteNumeric(RPL_UNLOADEDMODULE, "%s %s :Module %s successfully unloaded.",user->nick.c_str(), removing->c_str(), removing->c_str());
1229 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully unloaded.", removing->c_str());
1234 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());
1236 ServerInstance->SNO->WriteGlobalSno('a', "Failed to unload module %s: %s", removing->c_str(), ServerInstance->Modules->LastError().c_str());
1240 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
1242 if (ServerInstance->Modules->Load(adding->c_str()))
1244 ServerInstance->SNO->WriteGlobalSno('a', "*** REHASH LOADED MODULE: %s",adding->c_str());
1246 user->WriteNumeric(RPL_LOADEDMODULE, "%s %s :Module %s successfully loaded.",user->nick.c_str(), adding->c_str(), adding->c_str());
1248 ServerInstance->SNO->WriteGlobalSno('a', "Module %s successfully loaded.", adding->c_str());
1253 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());
1255 ServerInstance->SNO->WriteGlobalSno('a', "Failed to load module %s: %s", adding->c_str(), ServerInstance->Modules->LastError().c_str());
1260 user->WriteServ("NOTICE %s :*** Successfully rehashed server.", user->nick.c_str());
1262 ServerInstance->SNO->WriteGlobalSno('a', "*** Successfully rehashed server.");
1265 bool ServerConfig::LoadConf(FILE* &conf, const char* filename, bool allowexeinc)
1269 long linenumber = 1;
1270 long last_successful_parse = 1;
1274 int character_count = 0;
1280 ServerInstance->Logs->Log("CONFIG", DEBUG, "Reading %s", filename);
1282 /* Check if the file open failed first */
1285 errstr << "LoadConf: Couldn't open config file: " << filename << std::endl;
1289 for (unsigned int t = 0; t < include_stack.size(); t++)
1291 if (std::string(filename) == include_stack[t])
1293 errstr << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
1298 /* It's not already included, add it to the list of files we've loaded */
1299 include_stack.push_back(filename);
1301 /* Start reading characters... */
1302 while ((ch = fgetc(conf)) != EOF)
1305 * Fix for moronic windows issue spotted by Adremelech.
1306 * Some windows editors save text files as utf-16, which is
1307 * a total pain in the ass to parse. Users should save in the
1308 * right config format! If we ever see a file where the first
1309 * byte is 0xFF or 0xFE, or the second is 0xFF or 0xFE, then
1310 * this is most likely a utf-16 file. Bail out and insult user.
1312 if ((character_count++ < 2) && (ch == '\xFF' || ch == '\xFE'))
1314 errstr << "File " << filename << " cannot be read, as it is encoded in braindead UTF-16. Save your file as plain ASCII!" << std::endl;
1319 * Here we try and get individual tags on separate lines,
1320 * this would be so easy if we just made people format
1321 * their config files like that, but they don't so...
1322 * We check for a '<' and then know the line is over when
1323 * we get a '>' not inside quotes. If we find two '<' and
1324 * no '>' then die with an error.
1327 if ((ch == '#') && !in_quote)
1348 /* XXX: Added by Brain, May 1st 2006 - Escaping of characters.
1349 * Note that this WILL NOT usually allow insertion of newlines,
1350 * because a newline is two characters long. Use it primarily to
1351 * insert the " symbol.
1353 * Note that this also involves a further check when parsing the line,
1354 * which can be found below.
1356 if ((ch == '\\') && (in_quote) && (in_tag))
1359 char real_character;
1362 real_character = fgetc(conf);
1363 if (real_character == 'n')
1364 real_character = '\n';
1365 line += real_character;
1370 errstr << "End of file after a \\, what did you want to escape?: " << filename << ":" << linenumber << std::endl;
1378 if ((ch != '<') && (!in_tag) && (!in_comment) && (ch > ' ') && (ch != 9))
1380 errstr << "You have stray characters beyond the tag which starts at " << filename << ":" << last_successful_parse << std::endl;
1390 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;
1398 errstr << "Parser error: Inside a quote but not within the last valid tag, which was opened at: " << filename << ":" << last_successful_parse << std::endl;
1403 // errstr << "Opening new config tag on line " << linenumber << std::endl;
1414 // errstr << "Closing quote in config tag on line " << linenumber << std::endl;
1419 // errstr << "Opening quote in config tag on line " << linenumber << std::endl;
1427 errstr << "The tag immediately after the one at " << filename << ":" << last_successful_parse << " has a missing closing \" symbol. Please check this." << std::endl;
1431 errstr << "You have opened a quote (\") beyond the tag at " << filename << ":" << last_successful_parse << " without opening a new tag. Please check this." << std::endl;
1441 // errstr << "Closing config tag on line " << linenumber << std::endl;
1445 * If this finds an <include> then ParseLine can simply call
1446 * LoadConf() and load the included config into the same ConfigDataHash
1448 long bl = linenumber;
1449 if (!this->ParseLine(filename, line, linenumber, allowexeinc))
1451 last_successful_parse = linenumber;
1459 errstr << "You forgot to close the tag which comes immediately after the one at " << filename << ":" << last_successful_parse << std::endl;
1466 /* 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 */
1467 if (in_comment || in_quote)
1469 errstr << "Reached end of file whilst still inside a quoted section or tag. This is most likely an error or there \
1470 is a newline missing from the end of the file: " << filename << ":" << linenumber << std::endl;
1477 bool ServerConfig::LoadConf(FILE* &conf, const std::string &filename, bool allowexeinc)
1479 return this->LoadConf(conf, filename.c_str(), allowexeinc);
1482 bool ServerConfig::ParseLine(const std::string &filename, std::string &line, long &linenumber, bool allowexeinc)
1484 std::string tagname;
1485 std::string current_key;
1486 std::string current_value;
1493 got_name = got_key = in_quote = false;
1495 for(std::string::iterator c = line.begin(); c != line.end(); c++)
1499 /* We don't know the tag name yet. */
1505 if ((*c >= 'a' && *c <= 'z') || (*c >= 'A' && *c <='Z') || (*c >= '0' && *c <= '9') || *c == '_')
1509 errstr << "Invalid character in value name of tag: '" << *c << "' in value '" << tagname << "' in filename: " << filename << ":" << linenumber << std::endl;
1516 /* We got to a space, we should have the tagname now. */
1517 if(tagname.length())
1525 /* We have the tag name */
1528 /* We're still reading the key name */
1529 if ((*c != '=') && (*c != '>'))
1533 if ((*c >= 'a' && *c <= 'z') || (*c >= 'A' && *c <='Z') || (*c >= '0' && *c <= '9') || *c == '_')
1537 errstr << "Invalid character in key: '" << *c << "' in key '" << current_key << "' in filename: " << filename << ":" << linenumber << std::endl;
1544 /* We got an '=', end of the key name. */
1550 /* We have the key name, now we're looking for quotes and the value */
1552 /* Correctly handle escaped characters here.
1553 * See the XXX'ed section above.
1555 if ((*c == '\\') && (in_quote))
1559 current_value += '\n';
1561 current_value += *c;
1564 else if ((*c == '\\') && (!in_quote))
1566 errstr << "You can't have an escape sequence outside of a quoted section: " << filename << ":" << linenumber << std::endl;
1569 else if ((*c == '\n') && (in_quote))
1571 /* Got a 'real' \n, treat it as part of the value */
1572 current_value += '\n';
1575 else if ((*c == '\r') && (in_quote))
1577 /* Got a \r, drop it */
1585 /* We're not already in a quote. */
1590 /* Leaving the quotes, we have the current value */
1591 results.push_back(KeyVal(current_key, current_value));
1593 // std::cout << "<" << tagname << ":" << current_key << "> " << current_value << std::endl;
1598 if ((tagname == "include") && (current_key == "file"))
1600 if (!this->DoInclude(current_value, allowexeinc))
1603 else if ((tagname == "include") && (current_key == "executable"))
1607 errstr << "Executable includes are not allowed to use <include:executable>\n"
1608 "This could be an attempt to execute commands from a malicious remote include.\n"
1609 "If you need multiple levels of remote include, create a script to assemble the "
1610 "contents locally or include files using <include:file>\n";
1614 /* Pipe an executable and use its stdout as config data */
1615 if (!this->DoPipe(current_value))
1619 current_key.clear();
1620 current_value.clear();
1628 current_value += *c;
1635 /* Finished parsing the tag, add it to the config hash */
1636 config_data.insert(std::pair<std::string, KeyValList > (tagname, results));
1641 bool ServerConfig::DoPipe(const std::string &file)
1643 FILE* conf = popen(file.c_str(), "r");
1648 ret = LoadConf(conf, file.c_str(), false);
1652 errstr << "Couldn't execute: " << file << std::endl;
1657 bool ServerConfig::StartsWithWindowsDriveLetter(const std::string &path)
1659 return (path.length() > 2 && isalpha(path[0]) && path[1] == ':');
1662 bool ServerConfig::DoInclude(const std::string &file, bool allowexeinc)
1664 std::string confpath;
1665 std::string newfile;
1666 std::string::size_type pos;
1668 confpath = ServerInstance->ConfigFileName;
1671 std::replace(newfile.begin(),newfile.end(),'\\','/');
1672 std::replace(confpath.begin(),confpath.end(),'\\','/');
1674 if ((newfile[0] != '/') && (!StartsWithWindowsDriveLetter(newfile)))
1676 pos = confpath.rfind("/")
1677 if(pos != std::string::npos)
1679 /* Leaves us with just the path */
1680 newfile = confpath.substr(0, pos) + std::string("/") + newfile;
1684 FILE* conf = fopen(newfile.c_str(), "r");
1689 ret = LoadConf(conf, newfile, allowexeinc);
1693 errstr << "Couldn't open config file: " << file << std::endl;
1698 bool ServerConfig::ConfValue(const char* tag, const char* var, int index, char* result, int length, bool allow_linefeeds)
1700 return ConfValue(tag, var, "", index, result, length, allow_linefeeds);
1703 bool ServerConfig::ConfValue(const char* tag, const char* var, const char* default_value, int index, char* result, int length, bool allow_linefeeds)
1706 bool r = ConfValue(std::string(tag), std::string(var), std::string(default_value), index, value, allow_linefeeds);
1707 strlcpy(result, value.c_str(), length);
1711 bool ServerConfig::ConfValue(const std::string &tag, const std::string &var, int index, std::string &result, bool allow_linefeeds)
1713 return ConfValue(tag, var, "", index, result, allow_linefeeds);
1716 bool ServerConfig::ConfValue(const std::string &tag, const std::string &var, const std::string &default_value, int index, std::string &result, bool allow_linefeeds)
1718 ConfigDataHash::size_type pos = index;
1719 if (pos < config_data.count(tag))
1721 ConfigDataHash::iterator iter = config_data.find(tag);
1723 for(int i = 0; i < index; i++)
1726 for(KeyValList::iterator j = iter->second.begin(); j != iter->second.end(); j++)
1730 if ((!allow_linefeeds) && (j->second.find('\n') != std::string::npos))
1732 ServerInstance->Logs->Log("CONFIG",DEFAULT, "Value of <" + tag + ":" + var+ "> contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
1733 for (std::string::iterator n = j->second.begin(); n != j->second.end(); n++)
1744 if (!default_value.empty())
1746 result = default_value;
1752 if (!default_value.empty())
1754 result = default_value;
1761 bool ServerConfig::ConfValueInteger(const char* tag, const char* var, int index, int &result)
1763 return ConfValueInteger(std::string(tag), std::string(var), "", index, result);
1766 bool ServerConfig::ConfValueInteger(const char* tag, const char* var, const char* default_value, int index, int &result)
1768 return ConfValueInteger(std::string(tag), std::string(var), std::string(default_value), index, result);
1771 bool ServerConfig::ConfValueInteger(const std::string &tag, const std::string &var, int index, int &result)
1773 return ConfValueInteger(tag, var, "", index, result);
1776 bool ServerConfig::ConfValueInteger(const std::string &tag, const std::string &var, const std::string &default_value, int index, int &result)
1779 std::istringstream stream;
1780 bool r = ConfValue(tag, var, default_value, index, value);
1782 if(!(stream >> result))
1788 if (value.substr(0,2) == "0x")
1793 result = strtol(value.c_str(), &endptr, 16);
1795 /* No digits found */
1796 if (endptr == value.c_str())
1801 char denominator = *(value.end() - 1);
1802 switch (toupper(denominator))
1805 /* Kilobytes -> bytes */
1806 result = result * 1024;
1809 /* Megabytes -> bytes */
1810 result = result * 1024 * 1024;
1813 /* Gigabytes -> bytes */
1814 result = result * 1024 * 1024 * 1024;
1824 bool ServerConfig::ConfValueBool(const char* tag, const char* var, int index)
1826 return ConfValueBool(std::string(tag), std::string(var), "", index);
1829 bool ServerConfig::ConfValueBool(const char* tag, const char* var, const char* default_value, int index)
1831 return ConfValueBool(std::string(tag), std::string(var), std::string(default_value), index);
1834 bool ServerConfig::ConfValueBool(const std::string &tag, const std::string &var, int index)
1836 return ConfValueBool(tag, var, "", index);
1839 bool ServerConfig::ConfValueBool(const std::string &tag, const std::string &var, const std::string &default_value, int index)
1842 if(!ConfValue(tag, var, default_value, index, result))
1845 return ((result == "yes") || (result == "true") || (result == "1"));
1848 int ServerConfig::ConfValueEnum(const char* tag)
1850 return config_data.count(tag);
1853 int ServerConfig::ConfValueEnum(const std::string &tag)
1855 return config_data.count(tag);
1858 int ServerConfig::ConfVarEnum(const char* tag, int index)
1860 return ConfVarEnum(std::string(tag), index);
1863 int ServerConfig::ConfVarEnum(const std::string &tag, int index)
1865 ConfigDataHash::size_type pos = index;
1867 if (pos < config_data.count(tag))
1869 ConfigDataHash::const_iterator iter = config_data.find(tag);
1871 for(int i = 0; i < index; i++)
1874 return iter->second.size();
1880 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1882 bool ServerConfig::ReadFile(file_cache &F, const char* fname)
1884 if (!fname || !*fname)
1888 char linebuf[MAXBUF];
1892 if ((*fname != '/') && (*fname != '\\') && (!StartsWithWindowsDriveLetter(fname)))
1894 std::string::size_type pos;
1895 std::string confpath = ServerInstance->ConfigFileName;
1896 std::string newfile = fname;
1898 if (((pos = confpath.rfind("/"))) != std::string::npos)
1899 newfile = confpath.substr(0, pos) + std::string("/") + fname;
1900 else if (((pos = confpath.rfind("\\"))) != std::string::npos)
1901 newfile = confpath.substr(0, pos) + std::string("\\") + fname;
1903 ServerInstance->Logs->Log("config", DEBUG, "Filename: %s", newfile.c_str());
1905 if (!FileExists(newfile.c_str()))
1907 file = fopen(newfile.c_str(), "r");
1911 if (!FileExists(fname))
1913 file = fopen(fname, "r");
1920 if (fgets(linebuf, sizeof(linebuf), file))
1921 linebuf[strlen(linebuf)-1] = 0;
1925 F.push_back(*linebuf ? linebuf : " ");
1936 bool ServerConfig::FileExists(const char* file)
1939 if (stat(file, &sb) == -1)
1942 if ((sb.st_mode & S_IFDIR) > 0)
1946 if ((input = fopen (file, "r")) == NULL)
1955 const char* ServerConfig::CleanFilename(const char* name)
1957 const char* p = name + strlen(name);
1958 while ((p != name) && (*p != '/') && (*p != '\\')) p--;
1959 return (p != name ? ++p : p);
1963 std::string ServerConfig::GetFullProgDir()
1965 char buffer[PATH_MAX];
1967 /* Windows has specific api calls to get the exe path that never fail.
1968 * For once, windows has something of use, compared to the POSIX code
1969 * for this, this is positively neato.
1971 if (GetModuleFileName(NULL, buffer, MAX_PATH))
1973 std::string fullpath = buffer;
1974 std::string::size_type n = fullpath.rfind("\\inspircd.exe");
1975 return std::string(fullpath, 0, n);
1978 // Get the current working directory
1979 if (getcwd(buffer, PATH_MAX))
1981 std::string remainder = this->argv[0];
1983 /* Does argv[0] start with /? its a full path, use it */
1984 if (remainder[0] == '/')
1986 std::string::size_type n = remainder.rfind("/inspircd");
1987 return std::string(remainder, 0, n);
1990 std::string fullpath = std::string(buffer) + "/" + remainder;
1991 std::string::size_type n = fullpath.rfind("/inspircd");
1992 return std::string(fullpath, 0, n);
1998 std::string ServerConfig::GetSID()
2003 ValueItem::ValueItem(int value)
2005 std::stringstream n;
2010 ValueItem::ValueItem(bool value)
2012 std::stringstream n;
2017 void ValueItem::Set(const std::string& value)
2022 void ValueItem::Set(int value)
2024 std::stringstream n;
2029 int ValueItem::GetInteger()
2033 return atoi(v.c_str());
2036 const char* ValueItem::GetString() const
2041 bool ValueItem::GetBool()
2043 return (GetInteger() || v == "yes" || v == "true");
2047 void ConfigReaderThread::Run()
2049 Config = new ServerConfig;
2054 void ConfigReaderThread::Finish()
2056 ServerConfig* old = ServerInstance->Config;
2057 ServerInstance->Logs->Log("CONFIG",DEBUG,"Switching to new configuration...");
2058 ServerInstance->Logs->CloseLogs();
2059 ServerInstance->Config = this->Config;
2060 ServerInstance->Logs->OpenFileLogs();
2061 Config->Apply(old, TheUserUID);
2066 * Apply the changed configuration from the rehash.
2068 * XXX: The order of these is IMPORTANT, do not reorder them without testing
2071 ServerInstance->XLines->CheckELines();
2072 ServerInstance->XLines->CheckELines();
2073 ServerInstance->XLines->ApplyLines();
2074 ServerInstance->Res->Rehash();
2075 ServerInstance->ResetMaxBans();
2076 Config->ApplyDisabledCommands(Config->DisabledCommands);
2077 User* user = TheUserUID.empty() ? ServerInstance->FindNick(TheUserUID) : NULL;
2078 FOREACH_MOD(I_OnRehash, OnRehash(user));
2079 ServerInstance->BuildISupport();
2086 ServerInstance->Logs->CloseLogs();
2087 ServerInstance->Config = old;
2088 ServerInstance->Logs->OpenFileLogs();
2089 delete this->Config;