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(InspIRCd* Instance) : ServerInstance(Instance)
37 *sid = *ServerName = *Network = *ServerDesc = *AdminName = '\0';
38 *HideWhoisServer = *AdminEmail = *AdminNick = *diepass = *restartpass = *FixedQuit = *HideKillsServer = '\0';
39 *DefaultModes = *CustomVersion = *motd = *rules = *PrefixQuit = *DieValue = *DNSServer = '\0';
40 *UserStats = *DisabledCommands = *SuffixQuit = '\0';
41 WhoWasGroupSize = WhoWasMaxGroups = WhoWasMaxKeep = 0;
43 NoUserDns = forcedebug = OperSpyWhois = nofork = HideBans = HideSplits = UndernetMsgPrefix = false;
44 CycleHosts = writelog = AllowHalfop = InvBypassModes = true;
45 dns_timeout = DieDelay = 5;
47 NetBufferSize = 10240;
48 SoftLimit = Instance->SE->GetMaxFds();
58 void ServerConfig::Update005()
60 std::stringstream out(data005);
63 int token_counter = 0;
67 line5 = line5 + token + " ";
69 if (token_counter >= 13)
72 snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
73 isupport.push_back(buf);
81 snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
82 isupport.push_back(buf);
86 void ServerConfig::Send005(User* user)
88 for (std::vector<std::string>::iterator line = ServerInstance->Config->isupport.begin(); line != ServerInstance->Config->isupport.end(); line++)
89 user->WriteNumeric(RPL_ISUPPORT, "%s %s", user->nick.c_str(), line->c_str());
92 bool ServerConfig::CheckOnce(const char* tag)
94 int count = ConfValueEnum(tag);
97 throw CoreException("You have more than one <"+std::string(tag)+"> tag, this is not permitted.");
99 throw CoreException("You have not defined a <"+std::string(tag)+"> tag, this is required.");
103 static void ValidateNoSpaces(const char* p, const std::string &tag, const std::string &val)
105 for (const char* ptr = p; *ptr; ++ptr)
108 throw CoreException("The value of <"+tag+":"+val+"> cannot contain spaces");
112 /* 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,
113 * even in strerror(errno). They just return 'yes' or 'no' to an address without such detail as to whats WRONG with the address.
114 * Because ircd users arent as technical as they used to be (;)) we are going to give more of a useful error message.
116 static void ValidateIP(const char* p, const std::string &tag, const std::string &val, bool wild)
120 int not_numbers = false;
126 throw CoreException("The value of <"+tag+":"+val+"> is not an IP address");
128 for (const char* ptr = p; *ptr; ++ptr)
130 if (wild && (*ptr == '*' || *ptr == '?' || *ptr == '/'))
133 if (*ptr != ':' && *ptr != '.')
135 if (*ptr < '0' || *ptr > '9')
137 if ((*ptr < '0' || *ptr > '9') && (toupper(*ptr) < 'A' || toupper(*ptr) > 'F'))
143 throw CoreException("The value of <"+tag+":"+val+"> is not an IP address");
154 throw CoreException("The value of <"+tag+":"+val+"> is an IPv4 address with too many fields!");
157 throw CoreException("The value of <"+tag+":"+val+"> is an IPv6 address with too many fields!");
159 if (num_seps == 0 && num_dots < 3 && !wild)
160 throw CoreException("The value of <"+tag+":"+val+"> looks to be a malformed IPv4 address");
162 if (num_seps == 0 && num_dots == 3 && not_numbers)
163 throw CoreException("The value of <"+tag+":"+val+"> contains non-numeric characters in an IPv4 address");
165 if (num_seps != 0 && not_hex)
166 throw CoreException("The value of <"+tag+":"+val+"> contains non-hexdecimal characters in an IPv6 address");
168 if (num_seps != 0 && num_dots != 3 && num_dots != 0 && !wild)
169 throw CoreException("The value of <"+tag+":"+val+"> is a malformed IPv6 4in6 address");
173 static void ValidateHostname(const char* p, const std::string &tag, const std::string &val)
179 throw CoreException("The value of <"+tag+":"+val+"> is not a valid hostname");
180 for (const char* ptr = p; *ptr; ++ptr)
185 throw CoreException("The value of <"+tag+":"+val+"> is not a valid hostname");
192 throw CoreException("The value of <"+tag+":"+val+"> is not a valid hostname");
196 // Specialized validators
198 static bool ValidateMaxTargets(ServerConfig* conf, const char*, const char*, ValueItem &data)
200 if ((data.GetInteger() < 1) || (data.GetInteger() > 31))
202 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"WARNING: <security:maxtargets> value is greater than 31 or less than 1, set to 20.");
208 static bool ValidateSoftLimit(ServerConfig* conf, const char*, const char*, ValueItem &data)
210 if ((data.GetInteger() < 1) || (data.GetInteger() > conf->GetInstance()->SE->GetMaxFds()))
212 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"WARNING: <performance:softlimit> value is greater than %d or less than 0, set to %d.",conf->GetInstance()->SE->GetMaxFds(),conf->GetInstance()->SE->GetMaxFds());
213 data.Set(conf->GetInstance()->SE->GetMaxFds());
218 static bool ValidateMaxConn(ServerConfig* conf, const char*, const char*, ValueItem &data)
220 if (data.GetInteger() > SOMAXCONN)
221 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"WARNING: <performance:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
225 bool ServerConfig::ApplyDisabledCommands(const char* data)
227 std::stringstream dcmds(data);
230 /* Enable everything first */
231 for (Commandtable::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
232 x->second->Disable(false);
234 /* Now disable all the ones which the user wants disabled */
235 while (dcmds >> thiscmd)
237 Commandtable::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
238 if (cm != ServerInstance->Parser->cmdlist.end())
240 cm->second->Disable(true);
246 static bool ValidateDisabledUModes(ServerConfig* conf, const char*, const char*, ValueItem &data)
248 memset(conf->DisabledUModes, 0, sizeof(conf->DisabledUModes));
249 for (const unsigned char* p = (const unsigned char*)data.GetString(); *p; ++p)
251 if (*p < 'A' || *p > ('A' + 64)) throw CoreException(std::string("Invalid usermode ")+(char)*p+" was found.");
252 conf->DisabledUModes[*p - 'A'] = 1;
257 static bool ValidateDisabledCModes(ServerConfig* conf, const char*, const char*, ValueItem &data)
259 memset(conf->DisabledCModes, 0, sizeof(conf->DisabledCModes));
260 for (const unsigned char* p = (const unsigned char*)data.GetString(); *p; ++p)
262 if (*p < 'A' || *p > ('A' + 64)) throw CoreException(std::string("Invalid chanmode ")+(char)*p+" was found.");
263 conf->DisabledCModes[*p - 'A'] = 1;
269 // Note: the windows validator is in win32wrapper.cpp
270 bool ValidateDnsServer(ServerConfig* conf, const char*, const char*, ValueItem &data);
272 static bool ValidateDnsServer(ServerConfig* conf, const char*, const char*, ValueItem &data)
274 if (!*(data.GetString()))
276 std::string nameserver;
277 // attempt to look up their nameserver from /etc/resolv.conf
278 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
279 std::ifstream resolv("/etc/resolv.conf");
280 bool found_server = false;
282 if (resolv.is_open())
284 while (resolv >> nameserver)
286 if ((nameserver == "nameserver") && (!found_server))
288 resolv >> nameserver;
289 data.Set(nameserver.c_str());
291 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
297 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
298 data.Set("127.0.0.1");
303 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
304 data.Set("127.0.0.1");
311 static bool ValidateServerName(ServerConfig* conf, const char*, const char*, ValueItem &data)
313 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"Validating server name");
314 /* If we already have a servername, and they changed it, we should throw an exception. */
315 if (!strchr(data.GetString(), '.'))
317 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s.'",
318 data.GetString(),data.GetString());
319 std::string moo = data.GetValue();
320 data.Set(moo.append("."));
322 ValidateHostname(data.GetString(), "server", "name");
326 static bool ValidateNetBufferSize(ServerConfig* conf, const char*, const char*, ValueItem &data)
328 // 65534 not 65535 because of null terminator
329 if ((!data.GetInteger()) || (data.GetInteger() > 65534) || (data.GetInteger() < 1024))
331 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
337 static bool ValidateMaxWho(ServerConfig* conf, const char*, const char*, ValueItem &data)
339 if ((data.GetInteger() > 65535) || (data.GetInteger() < 1))
341 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"<performance:maxwho> size out of range, setting to default of 128.");
347 static bool ValidateHalfOp(ServerConfig* conf, const char*, const char*, ValueItem &data)
349 ModeHandler* mh = conf->GetInstance()->Modes->FindMode('h', MODETYPE_CHANNEL);
350 if (data.GetBool() && !mh) {
351 conf->GetInstance()->Logs->Log("CONFIG", DEFAULT, "Enabling halfop mode.");
352 mh = new ModeChannelHalfOp(conf->GetInstance());
353 conf->GetInstance()->Modes->AddMode(mh);
354 } else if (!data.GetBool() && mh) {
355 conf->GetInstance()->Logs->Log("CONFIG", DEFAULT, "Disabling halfop mode.");
356 conf->GetInstance()->Modes->DelMode(mh);
362 static bool ValidateMotd(ServerConfig* conf, const char*, const char*, ValueItem &data)
364 conf->ReadFile(conf->MOTD, data.GetString());
368 static bool ValidateNotEmpty(ServerConfig*, const char* tag, const char* val, ValueItem &data)
370 if (data.GetValue().empty())
371 throw CoreException(std::string("The value for <")+tag+":"+val+"> cannot be empty!");
375 static bool ValidateRules(ServerConfig* conf, const char*, const char*, ValueItem &data)
377 conf->ReadFile(conf->RULES, data.GetString());
381 static bool ValidateModeLists(ServerConfig* conf, const char*, const char*, ValueItem &data)
383 memset(conf->HideModeLists, 0, sizeof(conf->HideModeLists));
384 for (const unsigned char* x = (const unsigned char*)data.GetString(); *x; ++x)
385 conf->HideModeLists[*x] = true;
389 static bool ValidateExemptChanOps(ServerConfig* conf, const char*, const char*, ValueItem &data)
391 memset(conf->ExemptChanOps, 0, sizeof(conf->ExemptChanOps));
392 for (const unsigned char* x = (const unsigned char*)data.GetString(); *x; ++x)
393 conf->ExemptChanOps[*x] = true;
397 static bool ValidateInvite(ServerConfig* conf, const char*, const char*, ValueItem &data)
399 const std::string& v = data.GetValue();
402 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_OPS;
404 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_ALL;
405 else if (v == "dynamic")
406 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_DYNAMIC;
408 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_NONE;
413 static bool ValidateSID(ServerConfig* conf, const char*, const char*, ValueItem &data)
415 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"Validating server id");
417 const char *sid = data.GetString();
419 if (*sid && !conf->GetInstance()->IsSID(sid))
421 throw CoreException(std::string(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.");
424 strlcpy(conf->sid, sid, 5);
429 static bool ValidateWhoWas(ServerConfig* conf, const char*, const char*, ValueItem &data)
431 conf->WhoWasMaxKeep = conf->GetInstance()->Duration(data.GetString());
433 if (conf->WhoWasGroupSize < 0)
434 conf->WhoWasGroupSize = 0;
436 if (conf->WhoWasMaxGroups < 0)
437 conf->WhoWasMaxGroups = 0;
439 if (conf->WhoWasMaxKeep < 3600)
441 conf->WhoWasMaxKeep = 3600;
442 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"WARNING: <whowas:maxkeep> value less than 3600, setting to default 3600");
445 Command* whowas_command = conf->GetInstance()->Parser->GetHandler("WHOWAS");
448 std::deque<classbase*> params;
449 whowas_command->HandleInternal(WHOWAS_PRUNE, params);
455 /* Callback called to process a single <uline> tag
457 static bool DoULine(ServerConfig* conf, const char*, const char**, ValueList &values, int*)
459 const char* server = values[0].GetString();
460 const bool silent = values[1].GetBool();
461 conf->ulines[server] = silent;
465 /* Callback called to process a single <banlist> tag
467 static bool DoMaxBans(ServerConfig* conf, const char*, const char**, ValueList &values, int*)
469 const char* channel = values[0].GetString();
470 int limit = values[1].GetInteger();
471 conf->maxbans[channel] = limit;
475 static bool DoZLine(ServerConfig* conf, const char* tag, const char** entries, ValueList &values, int* types)
477 const char* reason = values[0].GetString();
478 const char* ipmask = values[1].GetString();
480 ZLine* zl = new ZLine(conf->GetInstance(), conf->GetInstance()->Time(), 0, "<Config>", reason, ipmask);
481 if (!conf->GetInstance()->XLines->AddLine(zl, NULL))
487 static bool DoQLine(ServerConfig* conf, const char* tag, const char** entries, ValueList &values, int* types)
489 const char* reason = values[0].GetString();
490 const char* nick = values[1].GetString();
492 QLine* ql = new QLine(conf->GetInstance(), conf->GetInstance()->Time(), 0, "<Config>", reason, nick);
493 if (!conf->GetInstance()->XLines->AddLine(ql, NULL))
499 static bool DoKLine(ServerConfig* conf, const char* tag, const char** entries, ValueList &values, int* types)
501 const char* reason = values[0].GetString();
502 const char* host = values[1].GetString();
504 XLineManager* xlm = conf->GetInstance()->XLines;
506 IdentHostPair ih = xlm->IdentSplit(host);
508 KLine* kl = new KLine(conf->GetInstance(), conf->GetInstance()->Time(), 0, "<Config>", reason, ih.first.c_str(), ih.second.c_str());
509 if (!xlm->AddLine(kl, NULL))
514 static bool DoELine(ServerConfig* conf, const char* tag, const char** entries, ValueList &values, int* types)
516 const char* reason = values[0].GetString();
517 const char* host = values[1].GetString();
519 XLineManager* xlm = conf->GetInstance()->XLines;
521 IdentHostPair ih = xlm->IdentSplit(host);
523 ELine* el = new ELine(conf->GetInstance(), conf->GetInstance()->Time(), 0, "<Config>", reason, ih.first.c_str(), ih.second.c_str());
524 if (!xlm->AddLine(el, NULL))
529 static bool DoType(ServerConfig* conf, const char*, const char**, ValueList &values, int*)
531 const char* TypeName = values[0].GetString();
532 const char* Classes = values[1].GetString();
534 conf->opertypes[TypeName] = std::string(Classes);
538 static bool DoClass(ServerConfig* conf, const char* tag, const char**, ValueList &values, int*)
540 const char* ClassName = values[0].GetString();
541 const char* CommandList = values[1].GetString();
542 const char* UModeList = values[2].GetString();
543 const char* CModeList = values[3].GetString();
544 const char *PrivsList = values[4].GetString();
546 for (const char* c = UModeList; *c; ++c)
548 if ((*c < 'A' || *c > 'z') && *c != '*')
550 throw CoreException("Character " + std::string(1, *c) + " is not a valid mode in <class:usermodes>");
553 for (const char* c = CModeList; *c; ++c)
555 if ((*c < 'A' || *c > 'z') && *c != '*')
557 throw CoreException("Character " + std::string(1, *c) + " is not a valid mode in <class:chanmodes>");
561 conf->operclass[ClassName].commandlist = strnewdup(CommandList);
562 conf->operclass[ClassName].umodelist = strnewdup(UModeList);
563 conf->operclass[ClassName].cmodelist = strnewdup(CModeList);
564 conf->operclass[ClassName].privs = strnewdup(PrivsList);
568 void ServerConfig::CrossCheckOperClassType()
570 for (int i = 0; i < ConfValueEnum("type"); ++i)
572 char item[MAXBUF], classn[MAXBUF], classes[MAXBUF];
573 std::string classname;
574 ConfValue("type", "classes", "", i, classes, MAXBUF, false);
575 irc::spacesepstream str(classes);
576 ConfValue("type", "name", "", i, item, MAXBUF, false);
577 while (str.GetToken(classname))
580 bool foundclass = false;
581 for (int j = 0; j < ConfValueEnum("class"); ++j)
583 ConfValue("class", "name", "", j, classn, MAXBUF, false);
584 if (!strcmp(classn, classname.c_str()))
593 snprintf(msg, MAXBUF, " Warning: Oper type '%s' has a missing class named '%s', this does nothing!\n",
594 item, classname.c_str());
595 throw CoreException(msg);
601 void ServerConfig::CrossCheckConnectBlocks(ServerConfig* current)
603 typedef std::map<std::string, ConnectClass*> ClassMap;
604 ClassMap oldBlocksByMask;
607 for(ClassVector::iterator i = current->Classes.begin(); i != current->Classes.end(); ++i)
609 ConnectClass* c = *i;
610 std::string typeMask = (c->type == CC_ALLOW) ? "a" : "d";
612 oldBlocksByMask[typeMask] = c;
616 int block_count = ConfValueEnum("connect");
617 ClassMap newBlocksByMask;
618 Classes.resize(block_count, NULL);
619 std::map<std::string, int> names;
621 bool try_again = true;
622 for(int tries=0; try_again && tries < block_count + 1; tries++)
625 for(int i=0; i < block_count; i++)
630 ConnectClass* parent = NULL;
631 std::string parentName;
632 if (ConfValue("connect", "parent", i, parentName, false))
634 std::map<std::string,int>::iterator parentIter = names.find(parentName);
635 if (parentIter == names.end())
638 // couldn't find parent this time. If it's the last time, we'll never find it.
639 if (tries == block_count)
640 throw CoreException("Could not find parent connect class \"" + parentName + "\" for connect block " + ConvToStr(i));
643 parent = Classes[parentIter->second];
647 if (ConfValue("connect", "name", i, name, false))
649 if (names.find(name) != names.end())
650 throw CoreException("Two connect classes with name \"" + name + "\" defined!");
654 std::string mask, typeMask;
657 if (ConfValue("connect", "allow", i, mask, false))
660 typeMask = 'a' + mask;
662 else if (ConfValue("connect", "deny", i, mask, false))
665 typeMask = 'd' + mask;
669 throw CoreException("Connect class must have an allow or deny mask (#" + ConvToStr(i) + ")");
671 ClassMap::iterator dupMask = newBlocksByMask.find(typeMask);
672 if (dupMask != newBlocksByMask.end())
673 throw CoreException("Two connect classes cannot have the same mask (" + mask + ")");
675 ConnectClass* me = parent ?
676 new ConnectClass(type, mask, *parent) :
677 new ConnectClass(type, mask);
683 if (ConfValue("connect", "password", i, tmpv, false))
685 if (ConfValue("connect", "hash", i, tmpv, false))
687 if (ConfValue("connect", "timeout", i, tmpv, false))
688 me->registration_timeout = atol(tmpv.c_str());
689 if (ConfValue("connect", "pingfreq", i, tmpv, false))
690 me->pingtime = atol(tmpv.c_str());
691 if (ConfValue("connect", "sendq", i, tmpv, false))
692 me->sendqmax = atol(tmpv.c_str());
693 if (ConfValue("connect", "recvq", i, tmpv, false))
694 me->recvqmax = atol(tmpv.c_str());
695 if (ConfValue("connect", "localmax", i, tmpv, false))
696 me->maxlocal = atol(tmpv.c_str());
697 if (ConfValue("connect", "globalmax", i, tmpv, false))
698 me->maxglobal = atol(tmpv.c_str());
699 if (ConfValue("connect", "port", i, tmpv, false))
700 me->port = atol(tmpv.c_str());
701 if (ConfValue("connect", "maxchans", i, tmpv, false))
702 me->maxchans = atol(tmpv.c_str());
703 if (ConfValue("connect", "limit", i, tmpv, false))
704 me->limit = atol(tmpv.c_str());
706 ClassMap::iterator oldMask = oldBlocksByMask.find(typeMask);
707 if (oldMask != oldBlocksByMask.end())
709 oldBlocksByMask.erase(oldMask);
710 ConnectClass* old = oldMask->second;
715 newBlocksByMask[typeMask] = me;
720 for(ClassMap::iterator toRemove = oldBlocksByMask.begin(); toRemove != oldBlocksByMask.end(); toRemove++)
722 removed_classes.push_back(toRemove->second);
727 static const Deprecated ChangedConfig[] = {
728 {"options", "hidelinks", "has been moved to <security:hidelinks> as of 1.2a3"},
729 {"options", "hidewhois", "has been moved to <security:hidewhois> as of 1.2a3"},
730 {"options", "userstats", "has been moved to <security:userstats> as of 1.2a3"},
731 {"options", "customversion", "has been moved to <security:customversion> as of 1.2a3"},
732 {"options", "hidesplits", "has been moved to <security:hidesplits> as of 1.2a3"},
733 {"options", "hidebans", "has been moved to <security:hidebans> as of 1.2a3"},
734 {"options", "hidekills", "has been moved to <security:hidekills> as of 1.2a3"},
735 {"options", "operspywhois", "has been moved to <security:operspywhois> as of 1.2a3"},
736 {"options", "announceinvites", "has been moved to <security:announceinvites> as of 1.2a3"},
737 {"options", "hidemodes", "has been moved to <security:hidemodes> as of 1.2a3"},
738 {"options", "maxtargets", "has been moved to <security:maxtargets> as of 1.2a3"},
739 {"options", "nouserdns", "has been moved to <performance:nouserdns> as of 1.2a3"},
740 {"options", "maxwho", "has been moved to <performance:maxwho> as of 1.2a3"},
741 {"options", "softlimit", "has been moved to <performance:softlimit> as of 1.2a3"},
742 {"options", "somaxconn", "has been moved to <performance:somaxconn> as of 1.2a3"},
743 {"options", "netbuffersize", "has been moved to <performance:netbuffersize> as of 1.2a3"},
744 {"options", "maxwho", "has been moved to <performance:maxwho> as of 1.2a3"},
745 {"options", "loglevel", "1.2 does not use the loglevel value. Please define <log> tags instead."},
746 {"die", "value", "has always been deprecated"},
749 /* These tags can occur ONCE or not at all */
750 static const InitialConfig Values[] = {
751 {"performance", "softlimit", "0", new ValueContainerUInt (&ServerConfig::SoftLimit), DT_INTEGER, ValidateSoftLimit},
752 {"performance", "somaxconn", SOMAXCONN_S, new ValueContainerInt (&ServerConfig::MaxConn), DT_INTEGER, ValidateMaxConn},
753 {"options", "moronbanner", "You're banned!", new ValueContainerChar (&ServerConfig::MoronBanner), DT_CHARPTR, NULL},
754 {"server", "name", "", new ValueContainerChar (&ServerConfig::ServerName), DT_HOSTNAME, ValidateServerName},
755 {"server", "description", "Configure Me", new ValueContainerChar (&ServerConfig::ServerDesc), DT_CHARPTR, NULL},
756 {"server", "network", "Network", new ValueContainerChar (&ServerConfig::Network), DT_NOSPACES, NULL},
757 {"server", "id", "", new ValueContainerChar (&ServerConfig::sid), DT_CHARPTR, ValidateSID},
758 {"admin", "name", "", new ValueContainerChar (&ServerConfig::AdminName), DT_CHARPTR, NULL},
759 {"admin", "email", "Mis@configu.red", new ValueContainerChar (&ServerConfig::AdminEmail), DT_CHARPTR, NULL},
760 {"admin", "nick", "Misconfigured", new ValueContainerChar (&ServerConfig::AdminNick), DT_CHARPTR, NULL},
761 {"files", "motd", "", new ValueContainerChar (&ServerConfig::motd), DT_CHARPTR, ValidateMotd},
762 {"files", "rules", "", new ValueContainerChar (&ServerConfig::rules), DT_CHARPTR, ValidateRules},
763 {"power", "diepass", "", new ValueContainerChar (&ServerConfig::diepass), DT_CHARPTR, ValidateNotEmpty},
764 {"power", "pause", "", new ValueContainerInt (&ServerConfig::DieDelay), DT_INTEGER, NULL},
765 {"power", "hash", "", new ValueContainerChar (&ServerConfig::powerhash), DT_CHARPTR, NULL},
766 {"power", "restartpass", "", new ValueContainerChar (&ServerConfig::restartpass), DT_CHARPTR, ValidateNotEmpty},
767 {"options", "prefixquit", "", new ValueContainerChar (&ServerConfig::PrefixQuit), DT_CHARPTR, NULL},
768 {"options", "suffixquit", "", new ValueContainerChar (&ServerConfig::SuffixQuit), DT_CHARPTR, NULL},
769 {"options", "fixedquit", "", new ValueContainerChar (&ServerConfig::FixedQuit), DT_CHARPTR, NULL},
770 {"options", "prefixpart", "", new ValueContainerChar (&ServerConfig::PrefixPart), DT_CHARPTR, NULL},
771 {"options", "suffixpart", "", new ValueContainerChar (&ServerConfig::SuffixPart), DT_CHARPTR, NULL},
772 {"options", "fixedpart", "", new ValueContainerChar (&ServerConfig::FixedPart), DT_CHARPTR, NULL},
773 {"performance", "netbuffersize","10240", new ValueContainerInt (&ServerConfig::NetBufferSize), DT_INTEGER, ValidateNetBufferSize},
774 {"performance", "maxwho", "128", new ValueContainerInt (&ServerConfig::MaxWhoResults), DT_INTEGER, ValidateMaxWho},
775 {"options", "allowhalfop", "0", new ValueContainerBool (&ServerConfig::AllowHalfop), DT_BOOLEAN, ValidateHalfOp},
776 {"dns", "server", "", new ValueContainerChar (&ServerConfig::DNSServer), DT_IPADDRESS,ValidateDnsServer},
777 {"dns", "timeout", "5", new ValueContainerInt (&ServerConfig::dns_timeout), DT_INTEGER, NULL},
778 {"options", "moduledir", MOD_PATH, new ValueContainerString (&ServerConfig::ModPath), DT_CHARPTR, NULL},
779 {"disabled", "commands", "", new ValueContainerChar (&ServerConfig::DisabledCommands), DT_CHARPTR, NULL},
780 {"disabled", "usermodes", "", NULL, DT_NOTHING, ValidateDisabledUModes},
781 {"disabled", "chanmodes", "", NULL, DT_NOTHING, ValidateDisabledCModes},
782 {"disabled", "fakenonexistant", "0", new ValueContainerBool (&ServerConfig::DisabledDontExist), DT_BOOLEAN, NULL},
784 {"security", "runasuser", "", new ValueContainerChar(&ServerConfig::SetUser), DT_CHARPTR, NULL},
785 {"security", "runasgroup", "", new ValueContainerChar(&ServerConfig::SetGroup), DT_CHARPTR, NULL},
786 {"security", "userstats", "", new ValueContainerChar (&ServerConfig::UserStats), DT_CHARPTR, NULL},
787 {"security", "customversion","", new ValueContainerChar (&ServerConfig::CustomVersion), DT_CHARPTR, NULL},
788 {"security", "hidesplits", "0", new ValueContainerBool (&ServerConfig::HideSplits), DT_BOOLEAN, NULL},
789 {"security", "hidebans", "0", new ValueContainerBool (&ServerConfig::HideBans), DT_BOOLEAN, NULL},
790 {"security", "hidewhois", "", new ValueContainerChar (&ServerConfig::HideWhoisServer), DT_NOSPACES, NULL},
791 {"security", "hidekills", "", new ValueContainerChar (&ServerConfig::HideKillsServer), DT_NOSPACES, NULL},
792 {"security", "operspywhois", "0", new ValueContainerBool (&ServerConfig::OperSpyWhois), DT_BOOLEAN, NULL},
793 {"security", "restrictbannedusers", "1", new ValueContainerBool (&ServerConfig::RestrictBannedUsers), DT_BOOLEAN, NULL},
794 {"security", "genericoper", "0", new ValueContainerBool (&ServerConfig::GenericOper), DT_BOOLEAN, NULL},
795 {"performance", "nouserdns", "0", new ValueContainerBool (&ServerConfig::NoUserDns), DT_BOOLEAN, NULL},
796 {"options", "syntaxhints", "0", new ValueContainerBool (&ServerConfig::SyntaxHints), DT_BOOLEAN, NULL},
797 {"options", "cyclehosts", "0", new ValueContainerBool (&ServerConfig::CycleHosts), DT_BOOLEAN, NULL},
798 {"options", "ircumsgprefix","0", new ValueContainerBool (&ServerConfig::UndernetMsgPrefix), DT_BOOLEAN, NULL},
799 {"security", "announceinvites", "1", NULL, DT_NOTHING, ValidateInvite},
800 {"options", "hostintopic", "1", new ValueContainerBool (&ServerConfig::FullHostInTopic), DT_BOOLEAN, NULL},
801 {"security", "hidemodes", "", NULL, DT_NOTHING, ValidateModeLists},
802 {"options", "exemptchanops","", NULL, DT_NOTHING, ValidateExemptChanOps},
803 {"security", "maxtargets", "20", new ValueContainerUInt (&ServerConfig::MaxTargets), DT_INTEGER, ValidateMaxTargets},
804 {"options", "defaultmodes", "nt", new ValueContainerChar (&ServerConfig::DefaultModes), DT_CHARPTR, NULL},
805 {"pid", "file", "", new ValueContainerString (&ServerConfig::PID), DT_CHARPTR, NULL},
806 {"whowas", "groupsize", "10", new ValueContainerInt (&ServerConfig::WhoWasGroupSize), DT_INTEGER, NULL},
807 {"whowas", "maxgroups", "10240", new ValueContainerInt (&ServerConfig::WhoWasMaxGroups), DT_INTEGER, NULL},
808 {"whowas", "maxkeep", "3600", NULL, DT_NOTHING, ValidateWhoWas},
809 {"die", "value", "", new ValueContainerChar (&ServerConfig::DieValue), DT_CHARPTR, NULL},
810 {"channels", "users", "20", new ValueContainerUInt (&ServerConfig::MaxChans), DT_INTEGER, NULL},
811 {"channels", "opers", "60", new ValueContainerUInt (&ServerConfig::OperMaxChans), DT_INTEGER, NULL},
812 {"cidr", "ipv4clone", "32", new ValueContainerInt (&ServerConfig::c_ipv4_range), DT_INTEGER, NULL},
813 {"cidr", "ipv6clone", "128", new ValueContainerInt (&ServerConfig::c_ipv6_range), DT_INTEGER, NULL},
814 {"limits", "maxnick", "32", new ValueContainerLimit (&ServerLimits::NickMax), DT_LIMIT, NULL},
815 {"limits", "maxchan", "64", new ValueContainerLimit (&ServerLimits::ChanMax), DT_LIMIT, NULL},
816 {"limits", "maxmodes", "20", new ValueContainerLimit (&ServerLimits::MaxModes), DT_LIMIT, NULL},
817 {"limits", "maxident", "11", new ValueContainerLimit (&ServerLimits::IdentMax), DT_LIMIT, NULL},
818 {"limits", "maxquit", "255", new ValueContainerLimit (&ServerLimits::MaxQuit), DT_LIMIT, NULL},
819 {"limits", "maxtopic", "307", new ValueContainerLimit (&ServerLimits::MaxTopic), DT_LIMIT, NULL},
820 {"limits", "maxkick", "255", new ValueContainerLimit (&ServerLimits::MaxKick), DT_LIMIT, NULL},
821 {"limits", "maxgecos", "128", new ValueContainerLimit (&ServerLimits::MaxGecos), DT_LIMIT, NULL},
822 {"limits", "maxaway", "200", new ValueContainerLimit (&ServerLimits::MaxAway), DT_LIMIT, NULL},
823 {"options", "invitebypassmodes", "1", new ValueContainerBool (&ServerConfig::InvBypassModes), DT_BOOLEAN, NULL},
826 /* These tags can occur multiple times, and therefore they have special code to read them
827 * which is different to the code for reading the singular tags listed above.
829 MultiConfig MultiValues[] = {
832 {"allow", "deny", "password", "timeout", "pingfreq",
833 "sendq", "recvq", "localmax", "globalmax", "port",
834 "name", "parent", "maxchans", "limit", "hash",
836 {"", "", "", "", "120",
837 "", "", "3", "3", "0",
838 "", "", "0", "0", "",
840 {DT_IPADDRESS|DT_ALLOW_WILD, DT_IPADDRESS|DT_ALLOW_WILD, DT_CHARPTR, DT_INTEGER, DT_INTEGER,
841 DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER,
842 DT_NOSPACES, DT_NOSPACES, DT_INTEGER, DT_INTEGER, DT_CHARPTR},
846 {"server", "silent", NULL},
848 {DT_HOSTNAME, DT_BOOLEAN},
852 {"chan", "limit", NULL},
854 {DT_CHARPTR, DT_INTEGER},
864 {"reason", "ipmask", NULL},
865 {"No reason", "", NULL},
866 {DT_CHARPTR, DT_IPADDRESS|DT_ALLOW_WILD},
870 {"reason", "nick", NULL},
871 {"No reason", "", NULL},
872 {DT_CHARPTR, DT_CHARPTR},
876 {"reason", "host", NULL},
877 {"No reason", "", NULL},
878 {DT_CHARPTR, DT_CHARPTR},
882 {"reason", "host", NULL},
883 {"No reason", "", NULL},
884 {DT_CHARPTR, DT_CHARPTR},
888 {"name", "classes", NULL},
890 {DT_NOSPACES, DT_CHARPTR},
894 {"name", "commands", "usermodes", "chanmodes", "privs", NULL},
895 {"", "", "", "", "", NULL},
896 {DT_NOSPACES, DT_CHARPTR, DT_CHARPTR, DT_CHARPTR, DT_CHARPTR},
900 /* These tags MUST occur and must ONLY occur once in the config file */
901 static const char* Once[] = { "server", "admin", "files", "power", "options" };
903 // WARNING: it is not safe to use most of the codebase in this function, as it
904 // will run in the config reader thread
905 void ServerConfig::Read()
907 /* Load and parse the config file, if there are any errors then explode */
909 if (!this->DoInclude(ServerInstance->ConfigFileName))
916 void ServerConfig::Apply(ServerConfig* old, const std::string &useruid)
919 /* std::ostringstream::clear() does not clear the string itself, only the error flags. */
921 errstr.str().clear();
922 include_stack.clear();
924 /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
927 /* Check we dont have more than one of singular tags, or any of them missing
929 for (int Index = 0; Index * sizeof(*Once) < sizeof(Once); Index++)
930 CheckOnce(Once[Index]);
932 for (int Index = 0; Index * sizeof(Deprecated) < sizeof(ChangedConfig); Index++)
936 if (ConfValue(ChangedConfig[Index].tag, ChangedConfig[Index].value, "", 0, item, MAXBUF, true) || *item)
937 throw CoreException(std::string("Your configuration contains a deprecated value: <") + ChangedConfig[Index].tag + ":" + ChangedConfig[Index].value + "> - " + ChangedConfig[Index].reason);
940 /* Read the values of all the tags which occur once or not at all, and call their callbacks.
942 for (int Index = 0; Index * sizeof(*Values) < sizeof(Values); ++Index)
945 int dt = Values[Index].datatype;
946 bool allow_newlines = ((dt & DT_ALLOW_NEWLINE) > 0);
947 bool allow_wild = ((dt & DT_ALLOW_WILD) > 0);
948 dt &= ~DT_ALLOW_NEWLINE;
949 dt &= ~DT_ALLOW_WILD;
951 ConfValue(Values[Index].tag, Values[Index].value, Values[Index].default_value, 0, item, MAXBUF, allow_newlines);
954 if (Values[Index].validation_function && !Values[Index].validation_function(this, Values[Index].tag, Values[Index].value, vi))
955 throw CoreException("One or more values in your configuration file failed to validate. Please see your ircd.log for more information.");
961 ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
962 ValidateNoSpaces(vi.GetString(), Values[Index].tag, Values[Index].value);
968 ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
969 ValidateHostname(vi.GetString(), Values[Index].tag, Values[Index].value);
975 ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
976 ValidateIP(vi.GetString(), Values[Index].tag, Values[Index].value, allow_wild);
982 ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
983 if (*(vi.GetString()) && !ServerInstance->IsChannel(vi.GetString(), MAXBUF))
985 throw CoreException("The value of <"+std::string(Values[Index].tag)+":"+Values[Index].value+"> is not a valid channel name");
992 ValueContainerChar* vcc = dynamic_cast<ValueContainerChar*>(Values[Index].val);
995 ValueContainerString* vcs = dynamic_cast<ValueContainerString*>(Values[Index].val);
997 vcs->Set(this, vi.GetValue());
1002 int val = vi.GetInteger();
1003 ValueContainerInt* vci = (ValueContainerInt*)Values[Index].val;
1004 vci->Set(this, val);
1009 int val = vi.GetInteger();
1010 ValueContainerLimit* vci = (ValueContainerLimit*)Values[Index].val;
1011 vci->Set(this, val);
1016 bool val = vi.GetBool();
1017 ValueContainerBool* vcb = (ValueContainerBool*)Values[Index].val;
1018 vcb->Set(this, val);
1024 /* Read the multiple-tag items (class tags, connect tags, etc)
1025 * and call the callbacks associated with them. We have three
1026 * callbacks for these, a 'start', 'item' and 'end' callback.
1028 for (int Index = 0; Index * sizeof(MultiConfig) < sizeof(MultiValues); ++Index)
1030 int number_of_tags = ConfValueEnum(MultiValues[Index].tag);
1032 for (int tagnum = 0; tagnum < number_of_tags; ++tagnum)
1035 for (int valuenum = 0; (MultiValues[Index].items[valuenum]) && (valuenum < MAX_VALUES_PER_TAG); ++valuenum)
1037 int dt = MultiValues[Index].datatype[valuenum];
1038 bool allow_newlines = ((dt & DT_ALLOW_NEWLINE) > 0);
1039 bool allow_wild = ((dt & DT_ALLOW_WILD) > 0);
1040 dt &= ~DT_ALLOW_NEWLINE;
1041 dt &= ~DT_ALLOW_WILD;
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 ValidateNoSpaces(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 ValidateHostname(vl[vl.size()-1].GetString(), MultiValues[Index].tag, MultiValues[Index].items[valuenum]);
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 ValidateIP(vl[vl.size()-1].GetString(), MultiValues[Index].tag, MultiValues[Index].items[valuenum], allow_wild);
1078 if (ConfValue(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1079 vl.push_back(ValueItem(item));
1081 vl.push_back(ValueItem(""));
1082 if (!ServerInstance->IsChannel(vl[vl.size()-1].GetString(), MAXBUF))
1083 throw CoreException("The value of <"+std::string(MultiValues[Index].tag)+":"+MultiValues[Index].items[valuenum]+"> number "+ConvToStr(tagnum + 1)+" is not a valid channel name");
1089 if (ConfValue(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1090 vl.push_back(ValueItem(item));
1092 vl.push_back(ValueItem(""));
1098 if (ConfValueInteger(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item))
1099 vl.push_back(ValueItem(item));
1101 vl.push_back(ValueItem(0));
1106 bool item = ConfValueBool(MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum);
1107 vl.push_back(ValueItem(item));
1112 if (MultiValues[Index].validation_function)
1113 MultiValues[Index].validation_function(this, MultiValues[Index].tag, MultiValues[Index].items, vl, MultiValues[Index].datatype);
1117 /* Finalise the limits, increment them all by one so that we can just put assign(str, 0, val)
1118 * rather than assign(str, 0, val + 1)
1122 // Handle special items
1123 CrossCheckOperClassType();
1124 CrossCheckConnectBlocks(old);
1126 catch (CoreException &ce)
1128 errstr << ce.GetReason();
1132 // write once here, to try it out and make sure its ok
1133 ServerInstance->WritePID(this->PID);
1136 ServerInstance->BindPorts(pl);
1139 * These values can only be set on boot. Keep their old values. Do it before we send messages so we actually have a servername.
1143 memcpy(this->ServerName, old->ServerName, sizeof(this->ServerName));
1144 memcpy(this->sid, old->sid, sizeof(this->sid));
1149 errstr << "Not all your client ports could be bound.\nThe following port(s) failed to bind:\n";
1152 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
1155 snprintf(buf, MAXBUF, "%d. Address: %s Reason: %s\n", j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
1160 User* user = useruid.empty() ? NULL : ServerInstance->FindNick(useruid);
1162 valid = errstr.str().empty();
1164 ServerInstance->Logs->Log("CONFIG",DEFAULT, "There were errors in your configuration file:");
1166 while (errstr.good())
1169 getline(errstr, line, '\n');
1173 user->WriteServ("NOTICE %s :*** %s", user->nick.c_str(), line.c_str());
1175 ServerInstance->SNO->WriteGlobalSno('a', line);
1180 // Starting up, so print it out so it's seen. XXX this is a bit of a hack.
1181 printf("%s\n", line.c_str());
1186 errstr.str(std::string());
1188 /* No old configuration -> initial boot, nothing more to do here */
1193 ServerInstance->Exit(EXIT_STATUS_CONFIG);
1199 // If there were errors processing configuration, don't touch modules.
1204 for (std::vector<ConnectClass*>::iterator i = removed_classes.begin(); i != removed_classes.end(); i++)
1206 ConnectClass* c = *i;
1207 if (0 == --c->RefCount)
1212 void ServerConfig::ApplyModules(User* user)
1214 const std::vector<std::string> v = ServerInstance->Modules->GetAllModuleNames(0);
1215 std::vector<std::string> added_modules;
1216 std::set<std::string> removed_modules(v.begin(), v.end());
1218 int new_module_count = ConfValueEnum("module");
1219 for(int i=0; i < new_module_count; i++)
1222 if (ConfValue("module", "name", i, name, false))
1224 // if this module is already loaded, the erase will succeed, so we need do nothing
1225 // otherwise, we need to add the module (which will be done later)
1226 if (removed_modules.erase(name) == 0)
1227 added_modules.push_back(name);
1231 for (std::set<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
1233 if (ServerInstance->Modules->Unload(removing->c_str()))
1235 ServerInstance->SNO->WriteToSnoMask('a', "*** REHASH UNLOADED MODULE: %s",removing->c_str());
1238 user->WriteNumeric(RPL_UNLOADEDMODULE, "%s %s :Module %s successfully unloaded.",user->nick.c_str(), removing->c_str(), removing->c_str());
1240 ServerInstance->SNO->WriteToSnoMask('a', "Module %s successfully unloaded.", removing->c_str());
1245 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());
1247 ServerInstance->SNO->WriteToSnoMask('a', "Failed to unload module %s: %s", removing->c_str(), ServerInstance->Modules->LastError().c_str());
1251 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
1253 if (ServerInstance->Modules->Load(adding->c_str()))
1255 ServerInstance->SNO->WriteToSnoMask('a', "*** REHASH LOADED MODULE: %s",adding->c_str());
1257 user->WriteNumeric(RPL_LOADEDMODULE, "%s %s :Module %s successfully loaded.",user->nick.c_str(), adding->c_str(), adding->c_str());
1259 ServerInstance->SNO->WriteToSnoMask('a', "Module %s successfully loaded.", adding->c_str());
1264 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());
1266 ServerInstance->SNO->WriteToSnoMask('a', "Failed to load module %s: %s", adding->c_str(), ServerInstance->Modules->LastError().c_str());
1271 user->WriteServ("NOTICE %s :*** Successfully rehashed server.", user->nick.c_str());
1273 ServerInstance->SNO->WriteToSnoMask('a', "*** Successfully rehashed server.");
1276 bool ServerConfig::LoadConf(FILE* &conf, const char* filename)
1280 long linenumber = 1;
1281 long last_successful_parse = 1;
1285 int character_count = 0;
1291 ServerInstance->Logs->Log("CONFIG", DEBUG, "Reading %s", filename);
1293 /* Check if the file open failed first */
1296 errstr << "LoadConf: Couldn't open config file: " << filename << std::endl;
1300 for (unsigned int t = 0; t < include_stack.size(); t++)
1302 if (std::string(filename) == include_stack[t])
1304 errstr << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
1309 /* It's not already included, add it to the list of files we've loaded */
1310 include_stack.push_back(filename);
1312 /* Start reading characters... */
1313 while ((ch = fgetc(conf)) != EOF)
1316 * Fix for moronic windows issue spotted by Adremelech.
1317 * Some windows editors save text files as utf-16, which is
1318 * a total pain in the ass to parse. Users should save in the
1319 * right config format! If we ever see a file where the first
1320 * byte is 0xFF or 0xFE, or the second is 0xFF or 0xFE, then
1321 * this is most likely a utf-16 file. Bail out and insult user.
1323 if ((character_count++ < 2) && (ch == '\xFF' || ch == '\xFE'))
1325 errstr << "File " << filename << " cannot be read, as it is encoded in braindead UTF-16. Save your file as plain ASCII!" << std::endl;
1330 * Here we try and get individual tags on separate lines,
1331 * this would be so easy if we just made people format
1332 * their config files like that, but they don't so...
1333 * We check for a '<' and then know the line is over when
1334 * we get a '>' not inside quotes. If we find two '<' and
1335 * no '>' then die with an error.
1338 if ((ch == '#') && !in_quote)
1359 /* XXX: Added by Brain, May 1st 2006 - Escaping of characters.
1360 * Note that this WILL NOT usually allow insertion of newlines,
1361 * because a newline is two characters long. Use it primarily to
1362 * insert the " symbol.
1364 * Note that this also involves a further check when parsing the line,
1365 * which can be found below.
1367 if ((ch == '\\') && (in_quote) && (in_tag))
1370 char real_character;
1373 real_character = fgetc(conf);
1374 if (real_character == 'n')
1375 real_character = '\n';
1376 line += real_character;
1381 errstr << "End of file after a \\, what did you want to escape?: " << filename << ":" << linenumber << std::endl;
1389 if ((ch != '<') && (!in_tag) && (!in_comment) && (ch > ' ') && (ch != 9))
1391 errstr << "You have stray characters beyond the tag which starts at " << filename << ":" << last_successful_parse << std::endl;
1401 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;
1409 errstr << "Parser error: Inside a quote but not within the last valid tag, which was opened at: " << filename << ":" << last_successful_parse << std::endl;
1414 // errstr << "Opening new config tag on line " << linenumber << std::endl;
1425 // errstr << "Closing quote in config tag on line " << linenumber << std::endl;
1430 // errstr << "Opening quote in config tag on line " << linenumber << std::endl;
1438 errstr << "The tag immediately after the one at " << filename << ":" << last_successful_parse << " has a missing closing \" symbol. Please check this." << std::endl;
1442 errstr << "You have opened a quote (\") beyond the tag at " << filename << ":" << last_successful_parse << " without opening a new tag. Please check this." << std::endl;
1452 // errstr << "Closing config tag on line " << linenumber << std::endl;
1456 * If this finds an <include> then ParseLine can simply call
1457 * LoadConf() and load the included config into the same ConfigDataHash
1459 long bl = linenumber;
1460 if (!this->ParseLine(filename, line, linenumber))
1462 last_successful_parse = linenumber;
1470 errstr << "You forgot to close the tag which comes immediately after the one at " << filename << ":" << last_successful_parse << std::endl;
1477 /* 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 */
1478 if (in_comment || in_quote)
1480 errstr << "Reached end of file whilst still inside a quoted section or tag. This is most likely an error or there \
1481 is a newline missing from the end of the file: " << filename << ":" << linenumber << std::endl;
1488 bool ServerConfig::LoadConf(FILE* &conf, const std::string &filename)
1490 return this->LoadConf(conf, filename.c_str());
1493 bool ServerConfig::ParseLine(const std::string &filename, std::string &line, long &linenumber)
1495 std::string tagname;
1496 std::string current_key;
1497 std::string current_value;
1504 got_name = got_key = in_quote = false;
1506 for(std::string::iterator c = line.begin(); c != line.end(); c++)
1510 /* We don't know the tag name yet. */
1516 if ((*c >= 'a' && *c <= 'z') || (*c >= 'A' && *c <='Z') || (*c >= '0' && *c <= '9') || *c == '_')
1520 errstr << "Invalid character in value name of tag: '" << *c << "' in value '" << tagname << "' in filename: " << filename << ":" << linenumber << std::endl;
1527 /* We got to a space, we should have the tagname now. */
1528 if(tagname.length())
1536 /* We have the tag name */
1539 /* We're still reading the key name */
1540 if ((*c != '=') && (*c != '>'))
1544 if ((*c >= 'a' && *c <= 'z') || (*c >= 'A' && *c <='Z') || (*c >= '0' && *c <= '9') || *c == '_')
1548 errstr << "Invalid character in key: '" << *c << "' in key '" << current_key << "' in filename: " << filename << ":" << linenumber << std::endl;
1555 /* We got an '=', end of the key name. */
1561 /* We have the key name, now we're looking for quotes and the value */
1563 /* Correctly handle escaped characters here.
1564 * See the XXX'ed section above.
1566 if ((*c == '\\') && (in_quote))
1570 current_value += '\n';
1572 current_value += *c;
1575 else if ((*c == '\\') && (!in_quote))
1577 errstr << "You can't have an escape sequence outside of a quoted section: " << filename << ":" << linenumber << std::endl;
1580 else if ((*c == '\n') && (in_quote))
1582 /* Got a 'real' \n, treat it as part of the value */
1583 current_value += '\n';
1586 else if ((*c == '\r') && (in_quote))
1588 /* Got a \r, drop it */
1596 /* We're not already in a quote. */
1601 /* Leaving the quotes, we have the current value */
1602 results.push_back(KeyVal(current_key, current_value));
1604 // std::cout << "<" << tagname << ":" << current_key << "> " << current_value << std::endl;
1609 if ((tagname == "include") && (current_key == "file"))
1611 if (!this->DoInclude(current_value))
1614 else if ((tagname == "include") && (current_key == "executable"))
1616 /* Pipe an executable and use its stdout as config data */
1617 if (!this->DoPipe(current_value))
1621 current_key.clear();
1622 current_value.clear();
1630 current_value += *c;
1637 /* Finished parsing the tag, add it to the config hash */
1638 config_data.insert(std::pair<std::string, KeyValList > (tagname, results));
1643 bool ServerConfig::DoPipe(const std::string &file)
1645 FILE* conf = popen(file.c_str(), "r");
1650 ret = LoadConf(conf, file.c_str());
1654 errstr << "Couldn't execute: " << file << std::endl;
1659 bool ServerConfig::StartsWithWindowsDriveLetter(const std::string &path)
1661 return (path.length() > 2 && isalpha(path[0]) && path[1] == ':');
1664 bool ServerConfig::DoInclude(const std::string &file)
1666 std::string confpath;
1667 std::string newfile;
1668 std::string::size_type pos;
1670 confpath = ServerInstance->ConfigFileName;
1673 std::replace(newfile.begin(),newfile.end(),'\\','/');
1674 std::replace(confpath.begin(),confpath.end(),'\\','/');
1676 if ((newfile[0] != '/') && (!StartsWithWindowsDriveLetter(newfile)))
1678 if((pos = confpath.rfind("/")) != std::string::npos)
1680 /* Leaves us with just the path */
1681 newfile = confpath.substr(0, pos) + std::string("/") + newfile;
1685 errstr << "Couldn't get config path from: " << ServerInstance->ConfigFileName << std::endl;
1690 FILE* conf = fopen(newfile.c_str(), "r");
1695 ret = LoadConf(conf, newfile);
1699 errstr << "Couldn't open config file: " << file << std::endl;
1704 bool ServerConfig::ConfValue(const char* tag, const char* var, int index, char* result, int length, bool allow_linefeeds)
1706 return ConfValue(tag, var, "", index, result, length, allow_linefeeds);
1709 bool ServerConfig::ConfValue(const char* tag, const char* var, const char* default_value, int index, char* result, int length, bool allow_linefeeds)
1712 bool r = ConfValue(std::string(tag), std::string(var), std::string(default_value), index, value, allow_linefeeds);
1713 strlcpy(result, value.c_str(), length);
1717 bool ServerConfig::ConfValue(const std::string &tag, const std::string &var, int index, std::string &result, bool allow_linefeeds)
1719 return ConfValue(tag, var, "", index, result, allow_linefeeds);
1722 bool ServerConfig::ConfValue(const std::string &tag, const std::string &var, const std::string &default_value, int index, std::string &result, bool allow_linefeeds)
1724 ConfigDataHash::size_type pos = index;
1725 if (pos < config_data.count(tag))
1727 ConfigDataHash::iterator iter = config_data.find(tag);
1729 for(int i = 0; i < index; i++)
1732 for(KeyValList::iterator j = iter->second.begin(); j != iter->second.end(); j++)
1736 if ((!allow_linefeeds) && (j->second.find('\n') != std::string::npos))
1738 ServerInstance->Logs->Log("CONFIG",DEFAULT, "Value of <" + tag + ":" + var+ "> contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
1739 for (std::string::iterator n = j->second.begin(); n != j->second.end(); n++)
1750 if (!default_value.empty())
1752 result = default_value;
1758 if (!default_value.empty())
1760 result = default_value;
1767 bool ServerConfig::ConfValueInteger(const char* tag, const char* var, int index, int &result)
1769 return ConfValueInteger(std::string(tag), std::string(var), "", index, result);
1772 bool ServerConfig::ConfValueInteger(const char* tag, const char* var, const char* default_value, int index, int &result)
1774 return ConfValueInteger(std::string(tag), std::string(var), std::string(default_value), index, result);
1777 bool ServerConfig::ConfValueInteger(const std::string &tag, const std::string &var, int index, int &result)
1779 return ConfValueInteger(tag, var, "", index, result);
1782 bool ServerConfig::ConfValueInteger(const std::string &tag, const std::string &var, const std::string &default_value, int index, int &result)
1785 std::istringstream stream;
1786 bool r = ConfValue(tag, var, default_value, index, value);
1788 if(!(stream >> result))
1794 if (value.substr(0,2) == "0x")
1799 result = strtol(value.c_str(), &endptr, 16);
1801 /* No digits found */
1802 if (endptr == value.c_str())
1807 char denominator = *(value.end() - 1);
1808 switch (toupper(denominator))
1811 /* Kilobytes -> bytes */
1812 result = result * 1024;
1815 /* Megabytes -> bytes */
1816 result = result * 1024 * 1024;
1819 /* Gigabytes -> bytes */
1820 result = result * 1024 * 1024 * 1024;
1830 bool ServerConfig::ConfValueBool(const char* tag, const char* var, int index)
1832 return ConfValueBool(std::string(tag), std::string(var), "", index);
1835 bool ServerConfig::ConfValueBool(const char* tag, const char* var, const char* default_value, int index)
1837 return ConfValueBool(std::string(tag), std::string(var), std::string(default_value), index);
1840 bool ServerConfig::ConfValueBool(const std::string &tag, const std::string &var, int index)
1842 return ConfValueBool(tag, var, "", index);
1845 bool ServerConfig::ConfValueBool(const std::string &tag, const std::string &var, const std::string &default_value, int index)
1848 if(!ConfValue(tag, var, default_value, index, result))
1851 return ((result == "yes") || (result == "true") || (result == "1"));
1854 int ServerConfig::ConfValueEnum(const char* tag)
1856 return config_data.count(tag);
1859 int ServerConfig::ConfValueEnum(const std::string &tag)
1861 return config_data.count(tag);
1864 int ServerConfig::ConfVarEnum(const char* tag, int index)
1866 return ConfVarEnum(std::string(tag), index);
1869 int ServerConfig::ConfVarEnum(const std::string &tag, int index)
1871 ConfigDataHash::size_type pos = index;
1873 if (pos < config_data.count(tag))
1875 ConfigDataHash::const_iterator iter = config_data.find(tag);
1877 for(int i = 0; i < index; i++)
1880 return iter->second.size();
1886 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1888 bool ServerConfig::ReadFile(file_cache &F, const char* fname)
1890 if (!fname || !*fname)
1894 char linebuf[MAXBUF];
1898 if ((*fname != '/') && (*fname != '\\') && (!StartsWithWindowsDriveLetter(fname)))
1900 std::string::size_type pos;
1901 std::string confpath = ServerInstance->ConfigFileName;
1902 std::string newfile = fname;
1904 if (((pos = confpath.rfind("/"))) != std::string::npos)
1905 newfile = confpath.substr(0, pos) + std::string("/") + fname;
1906 else if (((pos = confpath.rfind("\\"))) != std::string::npos)
1907 newfile = confpath.substr(0, pos) + std::string("\\") + fname;
1909 ServerInstance->Logs->Log("config", DEBUG, "Filename: %s", newfile.c_str());
1911 if (!FileExists(newfile.c_str()))
1913 file = fopen(newfile.c_str(), "r");
1917 if (!FileExists(fname))
1919 file = fopen(fname, "r");
1926 if (fgets(linebuf, sizeof(linebuf), file))
1927 linebuf[strlen(linebuf)-1] = 0;
1931 F.push_back(*linebuf ? linebuf : " ");
1942 bool ServerConfig::FileExists(const char* file)
1945 if (stat(file, &sb) == -1)
1948 if ((sb.st_mode & S_IFDIR) > 0)
1952 if ((input = fopen (file, "r")) == NULL)
1961 char* ServerConfig::CleanFilename(char* name)
1963 char* p = name + strlen(name);
1964 while ((p != name) && (*p != '/') && (*p != '\\')) p--;
1965 return (p != name ? ++p : p);
1969 std::string ServerConfig::GetFullProgDir()
1971 char buffer[PATH_MAX];
1973 /* Windows has specific api calls to get the exe path that never fail.
1974 * For once, windows has something of use, compared to the POSIX code
1975 * for this, this is positively neato.
1977 if (GetModuleFileName(NULL, buffer, MAX_PATH))
1979 std::string fullpath = buffer;
1980 std::string::size_type n = fullpath.rfind("\\inspircd.exe");
1981 return std::string(fullpath, 0, n);
1984 // Get the current working directory
1985 if (getcwd(buffer, PATH_MAX))
1987 std::string remainder = this->argv[0];
1989 /* Does argv[0] start with /? its a full path, use it */
1990 if (remainder[0] == '/')
1992 std::string::size_type n = remainder.rfind("/inspircd");
1993 return std::string(remainder, 0, n);
1996 std::string fullpath = std::string(buffer) + "/" + remainder;
1997 std::string::size_type n = fullpath.rfind("/inspircd");
1998 return std::string(fullpath, 0, n);
2004 InspIRCd* ServerConfig::GetInstance()
2006 return ServerInstance;
2009 std::string ServerConfig::GetSID()
2014 ValueItem::ValueItem(int value)
2016 std::stringstream n;
2021 ValueItem::ValueItem(bool value)
2023 std::stringstream n;
2028 void ValueItem::Set(const std::string& value)
2033 void ValueItem::Set(int value)
2035 std::stringstream n;
2040 int ValueItem::GetInteger()
2044 return atoi(v.c_str());
2047 const char* ValueItem::GetString() const
2052 bool ValueItem::GetBool()
2054 return (GetInteger() || v == "yes" || v == "true");
2058 void ConfigReaderThread::Run()
2060 Config = new ServerConfig(ServerInstance);
2065 void ConfigReaderThread::Finish()
2067 ServerConfig* old = ServerInstance->Config;
2068 ServerInstance->Logs->Log("CONFIG",DEBUG,"Switching to new configuration...");
2069 ServerInstance->Logs->CloseLogs();
2070 ServerInstance->Config = this->Config;
2071 ServerInstance->Logs->OpenFileLogs();
2072 Config->Apply(old, TheUserUID);
2077 * Apply the changed configuration from the rehash.
2079 * XXX: The order of these is IMPORTANT, do not reorder them without testing
2082 ServerInstance->XLines->CheckELines();
2083 ServerInstance->XLines->CheckELines();
2084 ServerInstance->XLines->ApplyLines();
2085 ServerInstance->Res->Rehash();
2086 ServerInstance->ResetMaxBans();
2087 Config->ApplyDisabledCommands(Config->DisabledCommands);
2088 User* user = TheUserUID.empty() ? ServerInstance->FindNick(TheUserUID) : NULL;
2089 FOREACH_MOD_I(ServerInstance, I_OnRehash, OnRehash(user));
2090 ServerInstance->BuildISupport();
2097 ServerInstance->Logs->CloseLogs();
2098 ServerInstance->Config = old;
2099 ServerInstance->Logs->OpenFileLogs();
2100 delete this->Config;
2105 void ValueContainer<char[MAXBUF]>::Set(ServerConfig* conf, ValueItem const& item)
2107 strlcpy(conf->*vptr, item.GetString(), MAXBUF);