1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2008 InspIRCd Development Team
6 * See: http://www.inspircd.org/wiki/index.php/Credits
8 * This program is free but copyrighted software; see
9 * the file COPYING for details.
11 * ---------------------------------------------------
14 /* $Core: libIRCDconfigreader */
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) */
28 #include "exitcodes.h"
29 #include "commands/cmd_whowas.h"
31 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
33 /* Needs forward declaration */
34 bool ValidateDnsServer(ServerConfig* conf, const char* tag, const char* value, ValueItem &data);
35 bool DoneELine(ServerConfig* conf, const char* tag);
37 ServerConfig::ServerConfig(InspIRCd* Instance) : ServerInstance(Instance)
40 *sid = *ServerName = *Network = *ServerDesc = *AdminName = '\0';
41 *HideWhoisServer = *AdminEmail = *AdminNick = *diepass = *restartpass = *FixedQuit = *HideKillsServer = '\0';
42 *DefaultModes = *CustomVersion = *motd = *rules = *PrefixQuit = *DieValue = *DNSServer = '\0';
43 *UserStats = *ModPath = *MyExecutable = *DisabledCommands = *PID = *SuffixQuit = '\0';
44 WhoWasGroupSize = WhoWasMaxGroups = WhoWasMaxKeep = 0;
46 NoUserDns = forcedebug = OperSpyWhois = nofork = HideBans = HideSplits = UndernetMsgPrefix = false;
47 CycleHosts = writelog = AllowHalfop = true;
48 dns_timeout = DieDelay = 5;
50 NetBufferSize = 10240;
51 SoftLimit = Instance->SE->GetMaxFds();
60 DNSServerValidator = &ValidateDnsServer;
63 void ServerConfig::ClearStack()
65 include_stack.clear();
68 Module* ServerConfig::GetIOHook(BufferedSocket* is)
70 std::map<BufferedSocket*,Module*>::iterator x = SocketIOHookModule.find(is);
71 return (x != SocketIOHookModule.end() ? x->second : NULL);
74 bool ServerConfig::AddIOHook(Module* iomod, BufferedSocket* is)
78 SocketIOHookModule[is] = iomod;
79 is->IsIOHooked = true;
84 throw ModuleException("BufferedSocket derived class already hooked by another module");
89 bool ServerConfig::DelIOHook(BufferedSocket* is)
91 std::map<BufferedSocket*,Module*>::iterator x = SocketIOHookModule.find(is);
92 if (x != SocketIOHookModule.end())
94 SocketIOHookModule.erase(x);
100 void ServerConfig::Update005()
102 std::stringstream out(data005);
105 int token_counter = 0;
109 line5 = line5 + token + " ";
111 if (token_counter >= 13)
114 snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
115 isupport.push_back(buf);
123 snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
124 isupport.push_back(buf);
128 void ServerConfig::Send005(User* user)
130 for (std::vector<std::string>::iterator line = ServerInstance->Config->isupport.begin(); line != ServerInstance->Config->isupport.end(); line++)
131 user->WriteNumeric(RPL_ISUPPORT, "%s %s", user->nick.c_str(), line->c_str());
134 bool ServerConfig::CheckOnce(const char* tag, ConfigDataHash &newconf)
136 int count = ConfValueEnum(newconf, tag);
140 throw CoreException("You have more than one <"+std::string(tag)+"> tag, this is not permitted.");
145 throw CoreException("You have not defined a <"+std::string(tag)+"> tag, this is required.");
151 bool NoValidation(ServerConfig*, const char*, const char*, ValueItem&)
156 bool DoneConfItem(ServerConfig* conf, const char* tag)
161 void ServerConfig::ValidateNoSpaces(const char* p, const std::string &tag, const std::string &val)
163 for (const char* ptr = p; *ptr; ++ptr)
166 throw CoreException("The value of <"+tag+":"+val+"> cannot contain spaces");
170 /* 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,
171 * even in strerror(errno). They just return 'yes' or 'no' to an address without such detail as to whats WRONG with the address.
172 * Because ircd users arent as technical as they used to be (;)) we are going to give more of a useful error message.
174 void ServerConfig::ValidateIP(const char* p, const std::string &tag, const std::string &val, bool wild)
178 int not_numbers = false;
184 throw CoreException("The value of <"+tag+":"+val+"> is not an IP address");
186 for (const char* ptr = p; *ptr; ++ptr)
188 if (wild && (*ptr == '*' || *ptr == '?' || *ptr == '/'))
191 if (*ptr != ':' && *ptr != '.')
193 if (*ptr < '0' || *ptr > '9')
195 if ((*ptr < '0' || *ptr > '9') && (toupper(*ptr) < 'A' || toupper(*ptr) > 'F'))
201 throw CoreException("The value of <"+tag+":"+val+"> is not an IP address");
212 throw CoreException("The value of <"+tag+":"+val+"> is an IPv4 address with too many fields!");
215 throw CoreException("The value of <"+tag+":"+val+"> is an IPv6 address with too many fields!");
217 if (num_seps == 0 && num_dots < 3 && !wild)
218 throw CoreException("The value of <"+tag+":"+val+"> looks to be a malformed IPv4 address");
220 if (num_seps == 0 && num_dots == 3 && not_numbers)
221 throw CoreException("The value of <"+tag+":"+val+"> contains non-numeric characters in an IPv4 address");
223 if (num_seps != 0 && not_hex)
224 throw CoreException("The value of <"+tag+":"+val+"> contains non-hexdecimal characters in an IPv6 address");
226 if (num_seps != 0 && num_dots != 3 && num_dots != 0 && !wild)
227 throw CoreException("The value of <"+tag+":"+val+"> is a malformed IPv6 4in6 address");
231 void ServerConfig::ValidateHostname(const char* p, const std::string &tag, const std::string &val)
237 throw CoreException("The value of <"+tag+":"+val+"> is not a valid hostname");
238 for (const char* ptr = p; *ptr; ++ptr)
243 throw CoreException("The value of <"+tag+":"+val+"> is not a valid hostname");
250 throw CoreException("The value of <"+tag+":"+val+"> is not a valid hostname");
254 bool ValidateMaxTargets(ServerConfig* conf, const char*, const char*, ValueItem &data)
256 if ((data.GetInteger() < 0) || (data.GetInteger() > 31))
258 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"WARNING: <security:maxtargets> value is greater than 31 or less than 0, set to 20.");
264 bool ValidateSoftLimit(ServerConfig* conf, const char*, const char*, ValueItem &data)
266 if ((data.GetInteger() < 1) || (data.GetInteger() > conf->GetInstance()->SE->GetMaxFds()))
268 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());
269 data.Set(conf->GetInstance()->SE->GetMaxFds());
274 bool ValidateMaxConn(ServerConfig* conf, const char*, const char*, ValueItem &data)
276 if (data.GetInteger() > SOMAXCONN)
277 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"WARNING: <performance:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
281 bool InitializeDisabledCommands(const char* data, InspIRCd* ServerInstance)
283 std::stringstream dcmds(data);
286 /* Enable everything first */
287 for (Commandtable::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
288 x->second->Disable(false);
290 /* Now disable all the ones which the user wants disabled */
291 while (dcmds >> thiscmd)
293 Commandtable::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
294 if (cm != ServerInstance->Parser->cmdlist.end())
296 cm->second->Disable(true);
302 bool ValidateDisabledUModes(ServerConfig* conf, const char*, const char*, ValueItem &data)
304 memset(conf->DisabledUModes, 0, 64);
305 for (const unsigned char* p = (const unsigned char*)data.GetString(); *p; ++p)
307 if (*p < 'A' || *p > ('A' + 64)) throw CoreException(std::string("Invalid usermode ")+(char)*p+" was found.");
308 conf->DisabledUModes[*p - 'A'] = 1;
313 bool ValidateDisabledCModes(ServerConfig* conf, const char*, const char*, ValueItem &data)
315 memset(conf->DisabledCModes, 0, 64);
316 for (const unsigned char* p = (const unsigned char*)data.GetString(); *p; ++p)
318 if (*p < 'A' || *p > ('A' + 64)) throw CoreException(std::string("Invalid chanmode ")+(char)*p+" was found.");
319 conf->DisabledCModes[*p - 'A'] = 1;
324 bool ValidateDnsServer(ServerConfig* conf, const char*, const char*, ValueItem &data)
326 if (!*(data.GetString()))
328 std::string nameserver;
329 // attempt to look up their nameserver from /etc/resolv.conf
330 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
331 std::ifstream resolv("/etc/resolv.conf");
332 bool found_server = false;
334 if (resolv.is_open())
336 while (resolv >> nameserver)
338 if ((nameserver == "nameserver") && (!found_server))
340 resolv >> nameserver;
341 data.Set(nameserver.c_str());
343 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
349 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
350 data.Set("127.0.0.1");
355 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
356 data.Set("127.0.0.1");
362 bool ValidateServerName(ServerConfig* conf, const char*, const char*, ValueItem &data)
364 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"Validating server name");
365 /* If we already have a servername, and they changed it, we should throw an exception. */
366 if (!strchr(data.GetString(), '.'))
368 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s%c'",data.GetString(),data.GetString(),'.');
369 std::string moo = std::string(data.GetString()).append(".");
370 data.Set(moo.c_str());
372 conf->ValidateHostname(data.GetString(), "server", "name");
376 bool ValidateNetBufferSize(ServerConfig* conf, const char*, const char*, ValueItem &data)
378 if ((!data.GetInteger()) || (data.GetInteger() > 65535) || (data.GetInteger() < 1024))
380 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
386 bool ValidateMaxWho(ServerConfig* conf, const char*, const char*, ValueItem &data)
388 if ((data.GetInteger() > 65535) || (data.GetInteger() < 1))
390 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"<performance:maxwho> size out of range, setting to default of 128.");
396 bool ValidateMotd(ServerConfig* conf, const char*, const char*, ValueItem &data)
398 conf->ReadFile(conf->MOTD, data.GetString());
402 bool ValidateNotEmpty(ServerConfig*, const char* tag, const char*, ValueItem &data)
404 if (!*data.GetString())
405 throw CoreException(std::string("The value for ")+tag+" cannot be empty!");
409 bool ValidateRules(ServerConfig* conf, const char*, const char*, ValueItem &data)
411 conf->ReadFile(conf->RULES, data.GetString());
415 bool ValidateModeLists(ServerConfig* conf, const char*, const char*, ValueItem &data)
417 memset(conf->HideModeLists, 0, 256);
418 for (const unsigned char* x = (const unsigned char*)data.GetString(); *x; ++x)
419 conf->HideModeLists[*x] = true;
423 bool ValidateExemptChanOps(ServerConfig* conf, const char*, const char*, ValueItem &data)
425 memset(conf->ExemptChanOps, 0, 256);
426 for (const unsigned char* x = (const unsigned char*)data.GetString(); *x; ++x)
427 conf->ExemptChanOps[*x] = true;
431 bool ValidateInvite(ServerConfig* conf, const char*, const char*, ValueItem &data)
433 std::string v = data.GetString();
436 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_OPS;
438 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_ALL;
439 else if (v == "dynamic")
440 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_DYNAMIC;
442 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_NONE;
447 bool ValidateSID(ServerConfig* conf, const char*, const char*, ValueItem &data)
449 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"Validating server id");
451 const char *sid = data.GetString();
453 if (*sid && !conf->GetInstance()->IsSID(sid))
455 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.");
458 strlcpy(conf->sid, sid, 5);
463 bool ValidateWhoWas(ServerConfig* conf, const char*, const char*, ValueItem &data)
465 conf->WhoWasMaxKeep = conf->GetInstance()->Duration(data.GetString());
467 if (conf->WhoWasGroupSize < 0)
468 conf->WhoWasGroupSize = 0;
470 if (conf->WhoWasMaxGroups < 0)
471 conf->WhoWasMaxGroups = 0;
473 if (conf->WhoWasMaxKeep < 3600)
475 conf->WhoWasMaxKeep = 3600;
476 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"WARNING: <whowas:maxkeep> value less than 3600, setting to default 3600");
479 Command* whowas_command = conf->GetInstance()->Parser->GetHandler("WHOWAS");
482 std::deque<classbase*> params;
483 whowas_command->HandleInternal(WHOWAS_PRUNE, params);
489 /* Callback called before processing the first <connect> tag
491 bool InitConnect(ServerConfig* conf, const char*)
493 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"Reading connect classes...");
495 for (ClassVector::iterator i = conf->Classes.begin(); i != conf->Classes.end() ; )
497 ConnectClass* c = *i;
499 /* only delete a class with refcount 0 */
500 if (c->RefCount == 0)
502 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT, "Removing connect class, refcount is 0!");
504 /* This was causing a crash, because we'd set i to .begin() just here, but then the for loop's increment would
505 * set it to .begin() + 1. Which if it was already the last thing in the list, wasn't good.
506 * Now the increment is in the else { } below.
508 conf->Classes.erase(i);
509 i = conf->Classes.begin(); // start over so we don't trample on a bad iterator
513 /* also mark all existing classes disabled, if they still exist in the conf, they will be reenabled. */
514 c->SetDisabled(true);
522 /* Callback called to process a single <connect> tag
524 bool DoConnect(ServerConfig* conf, const char*, char**, ValueList &values, int*)
527 const char* allow = values[0].GetString(); /* Yeah, there are a lot of values. Live with it. */
528 const char* deny = values[1].GetString();
529 const char* password = values[2].GetString();
530 int timeout = values[3].GetInteger();
531 int pingfreq = values[4].GetInteger();
532 int flood = values[5].GetInteger();
533 int threshold = values[6].GetInteger();
534 int sendq = values[7].GetInteger();
535 int recvq = values[8].GetInteger();
536 int localmax = values[9].GetInteger();
537 int globalmax = values[10].GetInteger();
538 int port = values[11].GetInteger();
539 const char* name = values[12].GetString();
540 const char* parent = values[13].GetString();
541 int maxchans = values[14].GetInteger();
542 unsigned long limit = values[15].GetInteger();
543 const char* hashtype = values[16].GetString();
546 * duplicates check: Now we don't delete all connect classes on rehash, we need to ensure we don't add dupes.
547 * easier said than done, but for now we'll just disallow anything with a duplicate host or name. -- w00t
549 for (ClassVector::iterator item = conf->Classes.begin(); item != conf->Classes.end(); ++item)
551 ConnectClass* cc = *item;
553 ((*name && (cc->GetName() == name)) || // if the name is the same
554 (*allow && (cc->GetHost() == allow)) || // or the allow is the same
555 (*deny && (cc->GetHost() == deny))) && // or the deny is the same
556 (!port || (port && (cc->GetPort() == port))) // and there is no port, or there is a port and the port is the same
559 /* reenable class so users can be shoved into it :P */
560 cc->SetDisabled(false);
561 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT, "Not adding class, it already exists!");
566 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"Adding a connect class!");
570 /* Find 'parent' and inherit a new class from it,
571 * then overwrite any values that are set here
573 ClassVector::iterator item = conf->Classes.begin();
574 for (; item != conf->Classes.end(); ++item)
576 ConnectClass* cc = *item;
577 conf->GetInstance()->Logs->Log("CONFIG",DEBUG,"Class: %s", cc->GetName().c_str());
578 if (cc->GetName() == parent)
580 ConnectClass* newclass = new ConnectClass(name, cc);
581 newclass->Update(timeout, flood, *allow ? allow : deny, pingfreq, password, threshold, sendq, recvq, localmax, globalmax, maxchans, port, limit);
582 conf->Classes.push_back(newclass);
586 if (item == conf->Classes.end())
587 throw CoreException("Class name '" + std::string(name) + "' is configured to inherit from class '" + std::string(parent) + "' which cannot be found.");
593 /* Find existing class by mask, the mask should be unique */
594 for (ClassVector::iterator item = conf->Classes.begin(); item != conf->Classes.end(); ++item)
596 if ((*item)->GetHost() == allow)
598 (*item)->Update(timeout, flood, allow, pingfreq, password, threshold, sendq, recvq, localmax, globalmax, maxchans, port, limit);
602 ConnectClass* cc = new ConnectClass(name, timeout, flood, allow, pingfreq, password, hashtype, threshold, sendq, recvq, localmax, globalmax, maxchans);
605 conf->Classes.push_back(cc);
609 /* Find existing class by mask, the mask should be unique */
610 for (ClassVector::iterator item = conf->Classes.begin(); item != conf->Classes.end(); ++item)
612 if ((*item)->GetHost() == deny)
614 (*item)->Update(name, deny);
615 (*item)->SetPort(port);
619 ConnectClass* cc = new ConnectClass(name, deny);
621 conf->Classes.push_back(cc);
628 /* Callback called when there are no more <connect> tags
630 bool DoneConnect(ServerConfig *conf, const char*)
632 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT, "Done adding connect classes!");
636 /* Callback called before processing the first <uline> tag
638 bool InitULine(ServerConfig* conf, const char*)
640 conf->ulines.clear();
644 /* Callback called to process a single <uline> tag
646 bool DoULine(ServerConfig* conf, const char*, char**, ValueList &values, int*)
648 const char* server = values[0].GetString();
649 const bool silent = values[1].GetBool();
650 conf->ulines[server] = silent;
654 /* Callback called when there are no more <uline> tags
656 bool DoneULine(ServerConfig*, const char*)
661 /* Callback called before processing the first <module> tag
663 bool InitModule(ServerConfig* conf, const char*)
665 old_module_names = conf->GetInstance()->Modules->GetAllModuleNames(0);
666 new_module_names.clear();
667 added_modules.clear();
668 removed_modules.clear();
672 /* Callback called to process a single <module> tag
674 bool DoModule(ServerConfig*, const char*, char**, ValueList &values, int*)
676 const char* modname = values[0].GetString();
677 new_module_names.push_back(modname);
681 /* Callback called when there are no more <module> tags
683 bool DoneModule(ServerConfig*, const char*)
685 // now create a list of new modules that are due to be loaded
686 // and a seperate list of modules which are due to be unloaded
687 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
691 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
698 added_modules.push_back(*_new);
701 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
704 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
711 removed_modules.push_back(*oldm);
716 /* Callback called before processing the first <banlist> tag
718 bool InitMaxBans(ServerConfig* conf, const char*)
720 conf->maxbans.clear();
724 /* Callback called to process a single <banlist> tag
726 bool DoMaxBans(ServerConfig* conf, const char*, char**, ValueList &values, int*)
728 const char* channel = values[0].GetString();
729 int limit = values[1].GetInteger();
730 conf->maxbans[channel] = limit;
734 /* Callback called when there are no more <banlist> tags.
736 bool DoneMaxBans(ServerConfig*, const char*)
741 void ServerConfig::ReportConfigError(const std::string &errormessage, bool bail, User* user)
743 ServerInstance->Logs->Log("CONFIG",DEFAULT, "There were errors in your configuration file: %s", errormessage.c_str());
746 /* Unneeded because of the ServerInstance->Log() aboive? */
747 printf("There were errors in your configuration:\n%s\n\n",errormessage.c_str());
748 ServerInstance->Exit(EXIT_STATUS_CONFIG);
752 std::string errors = errormessage;
753 std::string::size_type start;
754 unsigned int prefixlen;
756 /* ":ServerInstance->Config->ServerName NOTICE user->nick :" */
759 prefixlen = strlen(this->ServerName) + user->nick.length() + 11;
760 user->WriteServ("NOTICE %s :There were errors in the configuration file:",user->nick.c_str());
761 while (start < errors.length())
763 user->WriteServ("NOTICE %s :%s",user->nick.c_str(), errors.substr(start, 510 - prefixlen).c_str());
764 start += 510 - prefixlen;
769 ServerInstance->SNO->WriteToSnoMask('A', "There were errors in the configuration file:");
770 while (start < errors.length())
772 ServerInstance->SNO->WriteToSnoMask('A', errors.substr(start, 360));
780 void ServerConfig::Read(bool bail, User* user)
782 int rem = 0, add = 0; /* Number of modules added, number of modules removed */
784 static char maxkeep[MAXBUF]; /* Temporary buffer for WhoWasMaxKeep value */
785 static char hidemodes[MAXBUF]; /* Modes to not allow listing from users below halfop */
786 static char exemptchanops[MAXBUF]; /* Exempt channel ops from these modes */
787 static char announceinvites[MAXBUF]; /* options:announceinvites setting */
788 static char disabledumodes[MAXBUF]; /* Disabled usermodes */
789 static char disabledcmodes[MAXBUF]; /* Disabled chanmodes */
792 include_stack.clear();
794 /* These tags MUST occur and must ONLY occur once in the config file */
795 static const char* Once[] = { "server", "admin", "files", "power", "options", NULL };
797 Deprecated ChangedConfig[] = {
798 {"options", "hidelinks", "has been moved to <security:hidelinks> as of 1.2a3"},
799 {"options", "hidewhois", "has been moved to <security:hidewhois> as of 1.2a3"},
800 {"options", "userstats", "has been moved to <security:userstats> as of 1.2a3"},
801 {"options", "customversion", "has been moved to <security:customversion> as of 1.2a3"},
802 {"options", "hidesplits", "has been moved to <security:hidesplits> as of 1.2a3"},
803 {"options", "hidebans", "has been moved to <security:hidebans> as of 1.2a3"},
804 {"options", "hidekills", "has been moved to <security:hidekills> as of 1.2a3"},
805 {"options", "operspywhois", "has been moved to <security:operspywhois> as of 1.2a3"},
806 {"options", "announceinvites", "has been moved to <security:announceinvites> as of 1.2a3"},
807 {"options", "hidemodes", "has been moved to <security:hidemodes> as of 1.2a3"},
808 {"options", "maxtargets", "has been moved to <security:maxtargets> as of 1.2a3"},
809 {"options", "nouserdns", "has been moved to <performance:nouserdns> as of 1.2a3"},
810 {"options", "maxwho", "has been moved to <performance:maxwho> as of 1.2a3"},
811 {"options", "softlimit", "has been moved to <performance:softlimit> as of 1.2a3"},
812 {"options", "somaxconn", "has been moved to <performance:somaxconn> as of 1.2a3"},
813 {"options", "netbuffersize", "has been moved to <performance:netbuffersize> as of 1.2a3"},
814 {"options", "maxwho", "has been moved to <performance:maxwho> as of 1.2a3"},
815 {"options", "loglevel", "1.2 does not use the loglevel value. Please define <log> tags instead."},
819 /* These tags can occur ONCE or not at all */
820 InitialConfig Values[] = {
821 {"performance", "softlimit", "0", new ValueContainerUInt (&this->SoftLimit), DT_INTEGER, ValidateSoftLimit},
822 {"performance", "somaxconn", SOMAXCONN_S, new ValueContainerInt (&this->MaxConn), DT_INTEGER, ValidateMaxConn},
823 {"options", "moronbanner", "Youre banned!", new ValueContainerChar (this->MoronBanner), DT_CHARPTR, NoValidation},
824 {"server", "name", "", new ValueContainerChar (this->ServerName), DT_HOSTNAME|DT_BOOTONLY, ValidateServerName},
825 {"server", "description", "Configure Me", new ValueContainerChar (this->ServerDesc), DT_CHARPTR, NoValidation},
826 {"server", "network", "Network", new ValueContainerChar (this->Network), DT_NOSPACES, NoValidation},
827 {"server", "id", "", new ValueContainerChar (this->sid), DT_CHARPTR|DT_BOOTONLY, ValidateSID},
828 {"admin", "name", "", new ValueContainerChar (this->AdminName), DT_CHARPTR, NoValidation},
829 {"admin", "email", "Mis@configu.red", new ValueContainerChar (this->AdminEmail), DT_CHARPTR, NoValidation},
830 {"admin", "nick", "Misconfigured", new ValueContainerChar (this->AdminNick), DT_CHARPTR, NoValidation},
831 {"files", "motd", "", new ValueContainerChar (this->motd), DT_CHARPTR, ValidateMotd},
832 {"files", "rules", "", new ValueContainerChar (this->rules), DT_CHARPTR, ValidateRules},
833 {"power", "diepass", "", new ValueContainerChar (this->diepass), DT_CHARPTR, ValidateNotEmpty},
834 {"power", "pause", "", new ValueContainerInt (&this->DieDelay), DT_INTEGER, NoValidation},
835 {"power", "hash", "", new ValueContainerChar (this->powerhash), DT_CHARPTR, NoValidation},
836 {"power", "restartpass", "", new ValueContainerChar (this->restartpass), DT_CHARPTR, ValidateNotEmpty},
837 {"options", "prefixquit", "", new ValueContainerChar (this->PrefixQuit), DT_CHARPTR, NoValidation},
838 {"options", "suffixquit", "", new ValueContainerChar (this->SuffixQuit), DT_CHARPTR, NoValidation},
839 {"options", "fixedquit", "", new ValueContainerChar (this->FixedQuit), DT_CHARPTR, NoValidation},
840 {"options", "prefixpart", "", new ValueContainerChar (this->PrefixPart), DT_CHARPTR, NoValidation},
841 {"options", "suffixpart", "", new ValueContainerChar (this->SuffixPart), DT_CHARPTR, NoValidation},
842 {"options", "fixedpart", "", new ValueContainerChar (this->FixedPart), DT_CHARPTR, NoValidation},
843 {"performance", "netbuffersize","10240", new ValueContainerInt (&this->NetBufferSize), DT_INTEGER, ValidateNetBufferSize},
844 {"performance", "maxwho", "128", new ValueContainerInt (&this->MaxWhoResults), DT_INTEGER, ValidateMaxWho},
845 {"options", "allowhalfop", "0", new ValueContainerBool (&this->AllowHalfop), DT_BOOLEAN, NoValidation},
846 {"dns", "server", "", new ValueContainerChar (this->DNSServer), DT_IPADDRESS,DNSServerValidator},
847 {"dns", "timeout", "5", new ValueContainerInt (&this->dns_timeout), DT_INTEGER, NoValidation},
848 {"options", "moduledir", MOD_PATH, new ValueContainerChar (this->ModPath), DT_CHARPTR, NoValidation},
849 {"disabled", "commands", "", new ValueContainerChar (this->DisabledCommands), DT_CHARPTR, NoValidation},
850 {"disabled", "usermodes", "", new ValueContainerChar (disabledumodes), DT_CHARPTR, ValidateDisabledUModes},
851 {"disabled", "chanmodes", "", new ValueContainerChar (disabledcmodes), DT_CHARPTR, ValidateDisabledCModes},
852 {"security", "userstats", "", new ValueContainerChar (this->UserStats), DT_CHARPTR, NoValidation},
853 {"security", "customversion","", new ValueContainerChar (this->CustomVersion), DT_CHARPTR, NoValidation},
854 {"security", "hidesplits", "0", new ValueContainerBool (&this->HideSplits), DT_BOOLEAN, NoValidation},
855 {"security", "hidebans", "0", new ValueContainerBool (&this->HideBans), DT_BOOLEAN, NoValidation},
856 {"security", "hidewhois", "", new ValueContainerChar (this->HideWhoisServer), DT_NOSPACES, NoValidation},
857 {"security", "hidekills", "", new ValueContainerChar (this->HideKillsServer), DT_NOSPACES, NoValidation},
858 {"security", "operspywhois", "0", new ValueContainerBool (&this->OperSpyWhois), DT_BOOLEAN, NoValidation},
859 {"performance", "nouserdns", "0", new ValueContainerBool (&this->NoUserDns), DT_BOOLEAN, NoValidation},
860 {"options", "syntaxhints", "0", new ValueContainerBool (&this->SyntaxHints), DT_BOOLEAN, NoValidation},
861 {"options", "cyclehosts", "0", new ValueContainerBool (&this->CycleHosts), DT_BOOLEAN, NoValidation},
862 {"options", "ircumsgprefix","0", new ValueContainerBool (&this->UndernetMsgPrefix), DT_BOOLEAN, NoValidation},
863 {"security", "announceinvites", "1", new ValueContainerChar (announceinvites), DT_CHARPTR, ValidateInvite},
864 {"options", "hostintopic", "1", new ValueContainerBool (&this->FullHostInTopic), DT_BOOLEAN, NoValidation},
865 {"security", "hidemodes", "", new ValueContainerChar (hidemodes), DT_CHARPTR, ValidateModeLists},
866 {"options", "exemptchanops","", new ValueContainerChar (exemptchanops), DT_CHARPTR, ValidateExemptChanOps},
867 {"security", "maxtargets", "20", new ValueContainerUInt (&this->MaxTargets), DT_INTEGER, ValidateMaxTargets},
868 {"options", "defaultmodes", "nt", new ValueContainerChar (this->DefaultModes), DT_CHARPTR, NoValidation},
869 {"pid", "file", "", new ValueContainerChar (this->PID), DT_CHARPTR, NoValidation},
870 {"whowas", "groupsize", "10", new ValueContainerInt (&this->WhoWasGroupSize), DT_INTEGER, NoValidation},
871 {"whowas", "maxgroups", "10240", new ValueContainerInt (&this->WhoWasMaxGroups), DT_INTEGER, NoValidation},
872 {"whowas", "maxkeep", "3600", new ValueContainerChar (maxkeep), DT_CHARPTR, ValidateWhoWas},
873 {"die", "value", "", new ValueContainerChar (this->DieValue), DT_CHARPTR, NoValidation},
874 {"channels", "users", "20", new ValueContainerUInt (&this->MaxChans), DT_INTEGER, NoValidation},
875 {"channels", "opers", "60", new ValueContainerUInt (&this->OperMaxChans), DT_INTEGER, NoValidation},
876 {"cidr", "ipv4clone", "32", new ValueContainerInt (&this->c_ipv4_range), DT_INTEGER, NoValidation},
877 {"cidr", "ipv6clone", "128", new ValueContainerInt (&this->c_ipv6_range), DT_INTEGER, NoValidation},
878 {"limits", "maxnick", "32", new ValueContainerST (&this->Limits.NickMax), DT_INTEGER, NoValidation},
879 {"limits", "maxchan", "64", new ValueContainerST (&this->Limits.ChanMax), DT_INTEGER, NoValidation},
880 {"limits", "maxmodes", "20", new ValueContainerST (&this->Limits.MaxModes), DT_INTEGER, NoValidation},
881 {"limits", "maxident", "11", new ValueContainerST (&this->Limits.IdentMax), DT_INTEGER, NoValidation},
882 {"limits", "maxquit", "255", new ValueContainerST (&this->Limits.MaxQuit), DT_INTEGER, NoValidation},
883 {"limits", "maxtopic", "307", new ValueContainerST (&this->Limits.MaxTopic), DT_INTEGER, NoValidation},
884 {"limits", "maxkick", "255", new ValueContainerST (&this->Limits.MaxKick), DT_INTEGER, NoValidation},
885 {"limits", "maxgecos", "128", new ValueContainerST (&this->Limits.MaxGecos), DT_INTEGER, NoValidation},
886 {"limits", "maxaway", "200", new ValueContainerST (&this->Limits.MaxAway), DT_INTEGER, NoValidation},
887 {NULL, NULL, NULL, NULL, DT_NOTHING, NoValidation}
891 /* These tags can occur multiple times, and therefore they have special code to read them
892 * which is different to the code for reading the singular tags listed above.
894 MultiConfig MultiValues[] = {
897 {"allow", "deny", "password", "timeout", "pingfreq", "flood",
898 "threshold", "sendq", "recvq", "localmax", "globalmax", "port",
899 "name", "parent", "maxchans", "limit", "hash",
901 {"", "", "", "", "120", "",
902 "", "", "", "3", "3", "0",
903 "", "", "0", "0", "",
905 {DT_IPADDRESS|DT_ALLOW_WILD,
906 DT_IPADDRESS|DT_ALLOW_WILD,
907 DT_CHARPTR, DT_INTEGER, DT_INTEGER, DT_INTEGER,
908 DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER,
909 DT_NOSPACES, DT_NOSPACES, DT_INTEGER, DT_INTEGER, DT_CHARPTR},
910 InitConnect, DoConnect, DoneConnect},
913 {"server", "silent", NULL},
915 {DT_HOSTNAME, DT_BOOLEAN},
916 InitULine,DoULine,DoneULine},
919 {"chan", "limit", NULL},
921 {DT_CHARPTR, DT_INTEGER},
922 InitMaxBans, DoMaxBans, DoneMaxBans},
928 InitModule, DoModule, DoneModule},
931 {"reason", "ipmask", NULL},
932 {"No reason", "", NULL},
933 {DT_CHARPTR, DT_IPADDRESS|DT_ALLOW_WILD},
934 InitXLine, DoZLine, DoneConfItem},
937 {"reason", "nick", NULL},
938 {"No reason", "", NULL},
939 {DT_CHARPTR, DT_CHARPTR},
940 InitXLine, DoQLine, DoneConfItem},
943 {"reason", "host", NULL},
944 {"No reason", "", NULL},
945 {DT_CHARPTR, DT_CHARPTR},
946 InitXLine, DoKLine, DoneConfItem},
949 {"reason", "host", NULL},
950 {"No reason", "", NULL},
951 {DT_CHARPTR, DT_CHARPTR},
952 InitXLine, DoELine, DoneELine},
955 {"name", "classes", NULL},
957 {DT_NOSPACES, DT_CHARPTR},
958 InitTypes, DoType, DoneClassesAndTypes},
961 {"name", "commands", "usermodes", "chanmodes", NULL},
962 {"", "", "", "", NULL},
963 {DT_NOSPACES, DT_CHARPTR, DT_CHARPTR, DT_CHARPTR},
964 InitClasses, DoClass, DoneClassesAndTypes},
973 /* Load and parse the config file, if there are any errors then explode */
975 /* Make a copy here so if it fails then we can carry on running with an unaffected config */
978 if (!this->DoInclude(newconfig, ServerInstance->ConfigFileName, errstr))
980 ReportConfigError(errstr.str(), bail, user);
984 /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
987 /* Check we dont have more than one of singular tags, or any of them missing
989 for (int Index = 0; Once[Index]; Index++)
990 if (!CheckOnce(Once[Index], newconfig))
993 for (int Index = 0; ChangedConfig[Index].tag; Index++)
997 if (ConfValue(newconfig, ChangedConfig[Index].tag, ChangedConfig[Index].value, "", 0, item, MAXBUF, true) || *item)
998 throw CoreException(std::string("Your configuration contains a deprecated value: <") + ChangedConfig[Index].tag + ":" + ChangedConfig[Index].value + "> - " + ChangedConfig[Index].reason);
1000 ServerInstance->Logs->Log("CONFIG",DEBUG,"Deprecated item <%s:%s> does not exist, good.", ChangedConfig[Index].tag, ChangedConfig[Index].value);
1003 /* Read the values of all the tags which occur once or not at all, and call their callbacks.
1005 for (int Index = 0; Values[Index].tag; ++Index)
1008 int dt = Values[Index].datatype;
1009 bool allow_newlines = ((dt & DT_ALLOW_NEWLINE) > 0);
1010 bool allow_wild = ((dt & DT_ALLOW_WILD) > 0);
1011 bool bootonly = ((dt & DT_BOOTONLY) > 0);
1012 dt &= ~DT_ALLOW_NEWLINE;
1013 dt &= ~DT_ALLOW_WILD;
1016 /* Silently ignore boot only values */
1017 if (bootonly && !bail)
1020 ConfValue(newconfig, Values[Index].tag, Values[Index].value, Values[Index].default_value, 0, item, MAXBUF, allow_newlines);
1023 if (!Values[Index].validation_function(this, Values[Index].tag, Values[Index].value, vi))
1024 throw CoreException("One or more values in your configuration file failed to validate. Please see your ircd.log for more information.");
1026 ServerInstance->Threads->Mutex(true);
1031 ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
1032 this->ValidateNoSpaces(vi.GetString(), Values[Index].tag, Values[Index].value);
1033 vcc->Set(vi.GetString(), strlen(vi.GetString()) + 1);
1038 ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
1039 this->ValidateHostname(vi.GetString(), Values[Index].tag, Values[Index].value);
1040 vcc->Set(vi.GetString(), strlen(vi.GetString()) + 1);
1045 ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
1046 this->ValidateIP(vi.GetString(), Values[Index].tag, Values[Index].value, allow_wild);
1047 vcc->Set(vi.GetString(), strlen(vi.GetString()) + 1);
1052 ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
1053 if (*(vi.GetString()) && !ServerInstance->IsChannel(vi.GetString(), MAXBUF))
1055 ServerInstance->Threads->Mutex(false);
1056 throw CoreException("The value of <"+std::string(Values[Index].tag)+":"+Values[Index].value+"> is not a valid channel name");
1058 vcc->Set(vi.GetString(), strlen(vi.GetString()) + 1);
1063 ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
1064 /* Make sure we also copy the null terminator */
1065 vcc->Set(vi.GetString(), strlen(vi.GetString()) + 1);
1070 int val = vi.GetInteger();
1071 ValueContainerInt* vci = (ValueContainerInt*)Values[Index].val;
1072 vci->Set(&val, sizeof(int));
1077 bool val = vi.GetBool();
1078 ValueContainerBool* vcb = (ValueContainerBool*)Values[Index].val;
1079 vcb->Set(&val, sizeof(bool));
1083 /* You don't want to know what happens if someones bad code sends us here. */
1086 /* We're done with this now */
1087 delete Values[Index].val;
1088 ServerInstance->Threads->Mutex(false);
1091 /* Read the multiple-tag items (class tags, connect tags, etc)
1092 * and call the callbacks associated with them. We have three
1093 * callbacks for these, a 'start', 'item' and 'end' callback.
1095 for (int Index = 0; MultiValues[Index].tag; ++Index)
1097 ServerInstance->Threads->Mutex(true);
1098 MultiValues[Index].init_function(this, MultiValues[Index].tag);
1099 ServerInstance->Threads->Mutex(false);
1101 int number_of_tags = ConfValueEnum(newconfig, MultiValues[Index].tag);
1103 for (int tagnum = 0; tagnum < number_of_tags; ++tagnum)
1106 for (int valuenum = 0; (MultiValues[Index].items[valuenum]) && (valuenum < MAX_VALUES_PER_TAG); ++valuenum)
1108 int dt = MultiValues[Index].datatype[valuenum];
1109 bool allow_newlines = ((dt & DT_ALLOW_NEWLINE) > 0);
1110 bool allow_wild = ((dt & DT_ALLOW_WILD) > 0);
1111 dt &= ~DT_ALLOW_NEWLINE;
1112 dt &= ~DT_ALLOW_WILD;
1114 ServerInstance->Threads->Mutex(true);
1115 /* We catch and rethrow any exception here just so we can free our mutex
1124 if (ConfValue(newconfig, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1125 vl.push_back(ValueItem(item));
1127 vl.push_back(ValueItem(""));
1128 this->ValidateNoSpaces(vl[vl.size()-1].GetString(), MultiValues[Index].tag, MultiValues[Index].items[valuenum]);
1134 if (ConfValue(newconfig, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1135 vl.push_back(ValueItem(item));
1137 vl.push_back(ValueItem(""));
1138 this->ValidateHostname(vl[vl.size()-1].GetString(), MultiValues[Index].tag, MultiValues[Index].items[valuenum]);
1144 if (ConfValue(newconfig, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1145 vl.push_back(ValueItem(item));
1147 vl.push_back(ValueItem(""));
1148 this->ValidateIP(vl[vl.size()-1].GetString(), MultiValues[Index].tag, MultiValues[Index].items[valuenum], allow_wild);
1154 if (ConfValue(newconfig, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1155 vl.push_back(ValueItem(item));
1157 vl.push_back(ValueItem(""));
1158 if (!ServerInstance->IsChannel(vl[vl.size()-1].GetString(), MAXBUF))
1159 throw CoreException("The value of <"+std::string(MultiValues[Index].tag)+":"+MultiValues[Index].items[valuenum]+"> number "+ConvToStr(tagnum + 1)+" is not a valid channel name");
1165 if (ConfValue(newconfig, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1166 vl.push_back(ValueItem(item));
1168 vl.push_back(ValueItem(""));
1174 if (ConfValueInteger(newconfig, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item))
1175 vl.push_back(ValueItem(item));
1177 vl.push_back(ValueItem(0));
1182 bool item = ConfValueBool(newconfig, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum);
1183 vl.push_back(ValueItem(item));
1187 /* Someone was smoking craq if we got here, and we're all gonna die. */
1191 catch (CoreException &e)
1193 ServerInstance->Threads->Mutex(false);
1196 ServerInstance->Threads->Mutex(false);
1198 MultiValues[Index].validation_function(this, MultiValues[Index].tag, (char**)MultiValues[Index].items, vl, MultiValues[Index].datatype);
1200 MultiValues[Index].finish_function(this, MultiValues[Index].tag);
1203 /* Finalise the limits, increment them all by one so that we can just put assign(str, 0, val)
1204 * rather than assign(str, 0, val + 1)
1210 catch (CoreException &ce)
1212 ReportConfigError(ce.GetReason(), bail, user);
1216 ServerInstance->Threads->Mutex(true);
1217 for (int i = 0; i < ConfValueEnum(newconfig, "type"); ++i)
1219 char item[MAXBUF], classn[MAXBUF], classes[MAXBUF];
1220 std::string classname;
1221 ConfValue(newconfig, "type", "classes", "", i, classes, MAXBUF, false);
1222 irc::spacesepstream str(classes);
1223 ConfValue(newconfig, "type", "name", "", i, item, MAXBUF, false);
1224 while (str.GetToken(classname))
1227 bool foundclass = false;
1228 for (int j = 0; j < ConfValueEnum(newconfig, "class"); ++j)
1230 ConfValue(newconfig, "class", "name", "", j, classn, MAXBUF, false);
1231 if (!strcmp(classn, classname.c_str()))
1240 user->WriteServ("NOTICE %s :*** Warning: Oper type '%s' has a missing class named '%s', this does nothing!", user->nick.c_str(), item, classname.c_str());
1244 printf("Warning: Oper type '%s' has a missing class named '%s', this does nothing!\n", item, classname.c_str());
1246 ServerInstance->SNO->WriteToSnoMask('A', "Warning: Oper type '%s' has a missing class named '%s', this does nothing!", item, classname.c_str());
1252 /* If we succeeded, set the ircd config to the new one */
1253 this->config_data = newconfig;
1255 ServerInstance->Threads->Mutex(false);
1257 // write once here, to try it out and make sure its ok
1258 ServerInstance->WritePID(this->PID);
1260 /* Switch over logfiles */
1261 ServerInstance->Logs->CloseLogs();
1262 ServerInstance->Logs->OpenFileLogs();
1264 ServerInstance->Logs->Log("CONFIG", DEFAULT, "Done reading configuration file.");
1266 /* If we're rehashing, let's load any new modules, and unload old ones
1270 int found_ports = 0;
1272 ServerInstance->BindPorts(false, found_ports, pl);
1274 if (pl.size() && user)
1276 ServerInstance->Threads->Mutex(true);
1277 user->WriteServ("NOTICE %s :*** Not all your client ports could be bound.", user->nick.c_str());
1278 user->WriteServ("NOTICE %s :*** The following port(s) failed to bind:", user->nick.c_str());
1280 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
1282 user->WriteServ("NOTICE %s :*** %d. Address: %s Reason: %s", user->nick.c_str(), j, i->first.empty() ? "<all>" : i->first.c_str(), i->second.c_str());
1284 ServerInstance->Threads->Mutex(false);
1287 ServerInstance->Threads->Mutex(true);
1288 if (!removed_modules.empty())
1290 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
1292 if (ServerInstance->Modules->Unload(removing->c_str()))
1294 ServerInstance->SNO->WriteToSnoMask('A', "*** REHASH UNLOADED MODULE: %s",removing->c_str());
1297 user->WriteNumeric(RPL_UNLOADEDMODULE, "%s %s :Module %s successfully unloaded.",user->nick.c_str(), removing->c_str(), removing->c_str());
1304 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());
1309 if (!added_modules.empty())
1311 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
1313 if (ServerInstance->Modules->Load(adding->c_str()))
1315 ServerInstance->SNO->WriteToSnoMask('A', "*** REHASH LOADED MODULE: %s",adding->c_str());
1318 user->WriteNumeric(RPL_LOADEDMODULE, "%s %s :Module %s successfully loaded.",user->nick.c_str(), adding->c_str(), adding->c_str());
1325 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());
1330 ServerInstance->Logs->Log("CONFIG", DEFAULT, "Successfully unloaded %lu of %lu modules and loaded %lu of %lu modules.",(unsigned long)rem,(unsigned long)removed_modules.size(),(unsigned long)add,(unsigned long)added_modules.size());
1332 ServerInstance->Threads->Mutex(false);
1338 /** Note: This is safe, the method checks for user == NULL */
1339 ServerInstance->Threads->Mutex(true);
1340 ServerInstance->Parser->SetupCommandTable(user);
1341 ServerInstance->Threads->Mutex(false);
1346 user->WriteServ("NOTICE %s :*** Successfully rehashed server.", user->nick.c_str());
1348 ServerInstance->SNO->WriteToSnoMask('A', "*** Successfully rehashed server.");
1354 bool ServerConfig::LoadConf(ConfigDataHash &target, FILE* &conf, const char* filename, std::ostringstream &errorstream)
1358 long linenumber = 1;
1359 long last_successful_parse = 1;
1363 int character_count = 0;
1369 ServerInstance->Logs->Log("CONFIG", DEBUG, "Reading %s", filename);
1371 /* Check if the file open failed first */
1374 errorstream << "LoadConf: Couldn't open config file: " << filename << std::endl;
1378 for (unsigned int t = 0; t < include_stack.size(); t++)
1380 if (std::string(filename) == include_stack[t])
1382 errorstream << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
1387 /* It's not already included, add it to the list of files we've loaded */
1388 include_stack.push_back(filename);
1390 /* Start reading characters... */
1391 while ((ch = fgetc(conf)) != EOF)
1394 * Fix for moronic windows issue spotted by Adremelech.
1395 * Some windows editors save text files as utf-16, which is
1396 * a total pain in the ass to parse. Users should save in the
1397 * right config format! If we ever see a file where the first
1398 * byte is 0xFF or 0xFE, or the second is 0xFF or 0xFE, then
1399 * this is most likely a utf-16 file. Bail out and insult user.
1401 if ((character_count++ < 2) && (ch == '\xFF' || ch == '\xFE'))
1403 errorstream << "File " << filename << " cannot be read, as it is encoded in braindead UTF-16. Save your file as plain ASCII!" << std::endl;
1408 * Here we try and get individual tags on separate lines,
1409 * this would be so easy if we just made people format
1410 * their config files like that, but they don't so...
1411 * We check for a '<' and then know the line is over when
1412 * we get a '>' not inside quotes. If we find two '<' and
1413 * no '>' then die with an error.
1416 if ((ch == '#') && !in_quote)
1437 /* XXX: Added by Brain, May 1st 2006 - Escaping of characters.
1438 * Note that this WILL NOT usually allow insertion of newlines,
1439 * because a newline is two characters long. Use it primarily to
1440 * insert the " symbol.
1442 * Note that this also involves a further check when parsing the line,
1443 * which can be found below.
1445 if ((ch == '\\') && (in_quote) && (in_tag))
1448 char real_character;
1451 real_character = fgetc(conf);
1452 if (real_character == 'n')
1453 real_character = '\n';
1454 line += real_character;
1459 errorstream << "End of file after a \\, what did you want to escape?: " << filename << ":" << linenumber << std::endl;
1467 if ((ch != '<') && (!in_tag) && (!in_comment) && (ch > ' ') && (ch != 9))
1469 errorstream << "You have stray characters beyond the tag which starts at " << filename << ":" << last_successful_parse << std::endl;
1479 errorstream << "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;
1487 errorstream << "Parser error: Inside a quote but not within the last valid tag, which was opened at: " << filename << ":" << last_successful_parse << std::endl;
1492 // errorstream << "Opening new config tag on line " << linenumber << std::endl;
1503 // errorstream << "Closing quote in config tag on line " << linenumber << std::endl;
1508 // errorstream << "Opening quote in config tag on line " << linenumber << std::endl;
1516 errorstream << "The tag immediately after the one at " << filename << ":" << last_successful_parse << " has a missing closing \" symbol. Please check this." << std::endl;
1520 errorstream << "You have opened a quote (\") beyond the tag at " << filename << ":" << last_successful_parse << " without opening a new tag. Please check this." << std::endl;
1530 // errorstream << "Closing config tag on line " << linenumber << std::endl;
1534 * If this finds an <include> then ParseLine can simply call
1535 * LoadConf() and load the included config into the same ConfigDataHash
1537 long bl = linenumber;
1538 if (!this->ParseLine(target, filename, line, linenumber, errorstream))
1540 last_successful_parse = linenumber;
1548 errorstream << "You forgot to close the tag which comes immediately after the one at " << filename << ":" << last_successful_parse << std::endl;
1555 /* 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 */
1556 if (in_comment || in_quote)
1558 errorstream << "Reached end of file whilst still inside a quoted section or tag. This is most likely an error or there \
1559 is a newline missing from the end of the file: " << filename << ":" << linenumber << std::endl;
1566 bool ServerConfig::LoadConf(ConfigDataHash &target, FILE* &conf, const std::string &filename, std::ostringstream &errorstream)
1568 return this->LoadConf(target, conf, filename.c_str(), errorstream);
1571 bool ServerConfig::ParseLine(ConfigDataHash &target, const std::string &filename, std::string &line, long &linenumber, std::ostringstream &errorstream)
1573 std::string tagname;
1574 std::string current_key;
1575 std::string current_value;
1582 got_name = got_key = in_quote = false;
1584 for(std::string::iterator c = line.begin(); c != line.end(); c++)
1588 /* We don't know the tag name yet. */
1594 if ((*c >= 'a' && *c <= 'z') || (*c >= 'A' && *c <='Z') || (*c >= '0' && *c <= '9') || *c == '_')
1598 errorstream << "Invalid character in value name of tag: '" << *c << "' in value '" << tagname << "' in filename: " << filename << ":" << linenumber << std::endl;
1605 /* We got to a space, we should have the tagname now. */
1606 if(tagname.length())
1614 /* We have the tag name */
1617 /* We're still reading the key name */
1618 if ((*c != '=') && (*c != '>'))
1622 if ((*c >= 'a' && *c <= 'z') || (*c >= 'A' && *c <='Z') || (*c >= '0' && *c <= '9') || *c == '_')
1626 errorstream << "Invalid character in key: '" << *c << "' in key '" << current_key << "' in filename: " << filename << ":" << linenumber << std::endl;
1633 /* We got an '=', end of the key name. */
1639 /* We have the key name, now we're looking for quotes and the value */
1641 /* Correctly handle escaped characters here.
1642 * See the XXX'ed section above.
1644 if ((*c == '\\') && (in_quote))
1648 current_value += '\n';
1650 current_value += *c;
1653 else if ((*c == '\\') && (!in_quote))
1655 errorstream << "You can't have an escape sequence outside of a quoted section: " << filename << ":" << linenumber << std::endl;
1658 else if ((*c == '\n') && (in_quote))
1660 /* Got a 'real' \n, treat it as part of the value */
1661 current_value += '\n';
1664 else if ((*c == '\r') && (in_quote))
1666 /* Got a \r, drop it */
1674 /* We're not already in a quote. */
1679 /* Leaving the quotes, we have the current value */
1680 results.push_back(KeyVal(current_key, current_value));
1682 // std::cout << "<" << tagname << ":" << current_key << "> " << current_value << std::endl;
1687 if ((tagname == "include") && (current_key == "file"))
1689 if (!this->DoInclude(target, current_value, errorstream))
1692 else if ((tagname == "include") && (current_key == "executable"))
1694 /* Pipe an executable and use its stdout as config data */
1695 if (!this->DoPipe(target, current_value, errorstream))
1699 current_key.clear();
1700 current_value.clear();
1708 current_value += *c;
1715 /* Finished parsing the tag, add it to the config hash */
1716 target.insert(std::pair<std::string, KeyValList > (tagname, results));
1721 bool ServerConfig::DoPipe(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream)
1723 FILE* conf = popen(file.c_str(), "r");
1728 ret = LoadConf(target, conf, file.c_str(), errorstream);
1732 errorstream << "Couldn't execute: " << file << std::endl;
1737 bool ServerConfig::StartsWithWindowsDriveLetter(const std::string &path)
1739 return (path.length() > 2 && isalpha(path[0]) && path[1] == ':');
1742 bool ServerConfig::DoInclude(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream)
1744 std::string confpath;
1745 std::string newfile;
1746 std::string::size_type pos;
1748 confpath = ServerInstance->ConfigFileName;
1751 std::replace(newfile.begin(),newfile.end(),'\\','/');
1752 std::replace(confpath.begin(),confpath.end(),'\\','/');
1754 if ((newfile[0] != '/') && (!StartsWithWindowsDriveLetter(newfile)))
1756 if((pos = confpath.rfind("/")) != std::string::npos)
1758 /* Leaves us with just the path */
1759 newfile = confpath.substr(0, pos) + std::string("/") + newfile;
1763 errorstream << "Couldn't get config path from: " << ServerInstance->ConfigFileName << std::endl;
1768 FILE* conf = fopen(newfile.c_str(), "r");
1773 ret = LoadConf(target, conf, newfile, errorstream);
1777 errorstream << "Couldn't open config file: " << file << std::endl;
1782 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, int index, char* result, int length, bool allow_linefeeds)
1784 return ConfValue(target, tag, var, "", index, result, length, allow_linefeeds);
1787 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index, char* result, int length, bool allow_linefeeds)
1790 bool r = ConfValue(target, std::string(tag), std::string(var), std::string(default_value), index, value, allow_linefeeds);
1791 strlcpy(result, value.c_str(), length);
1795 bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, std::string &result, bool allow_linefeeds)
1797 return ConfValue(target, tag, var, "", index, result, allow_linefeeds);
1800 bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index, std::string &result, bool allow_linefeeds)
1802 ConfigDataHash::size_type pos = index;
1803 if (pos < target.count(tag))
1805 ConfigDataHash::iterator iter = target.find(tag);
1807 for(int i = 0; i < index; i++)
1810 for(KeyValList::iterator j = iter->second.begin(); j != iter->second.end(); j++)
1814 if ((!allow_linefeeds) && (j->second.find('\n') != std::string::npos))
1816 ServerInstance->Logs->Log("CONFIG",DEFAULT, "Value of <" + tag + ":" + var+ "> contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
1817 for (std::string::iterator n = j->second.begin(); n != j->second.end(); n++)
1828 if (!default_value.empty())
1830 result = default_value;
1836 if (!default_value.empty())
1838 result = default_value;
1845 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, int index, int &result)
1847 return ConfValueInteger(target, std::string(tag), std::string(var), "", index, result);
1850 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index, int &result)
1852 return ConfValueInteger(target, std::string(tag), std::string(var), std::string(default_value), index, result);
1855 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, int &result)
1857 return ConfValueInteger(target, tag, var, "", index, result);
1860 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index, int &result)
1863 std::istringstream stream;
1864 bool r = ConfValue(target, tag, var, default_value, index, value);
1866 if(!(stream >> result))
1872 if (value.substr(0,2) == "0x")
1877 result = strtol(value.c_str(), &endptr, 16);
1879 /* No digits found */
1880 if (endptr == value.c_str())
1885 char denominator = *(value.end() - 1);
1886 switch (toupper(denominator))
1889 /* Kilobytes -> bytes */
1890 result = result * 1024;
1893 /* Megabytes -> bytes */
1894 result = result * 1024 * 1024;
1897 /* Gigabytes -> bytes */
1898 result = result * 1024 * 1024 * 1024;
1908 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, int index)
1910 return ConfValueBool(target, std::string(tag), std::string(var), "", index);
1913 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index)
1915 return ConfValueBool(target, std::string(tag), std::string(var), std::string(default_value), index);
1918 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, int index)
1920 return ConfValueBool(target, tag, var, "", index);
1923 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index)
1926 if(!ConfValue(target, tag, var, default_value, index, result))
1929 return ((result == "yes") || (result == "true") || (result == "1"));
1932 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const char* tag)
1934 return target.count(tag);
1937 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const std::string &tag)
1939 return target.count(tag);
1942 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const char* tag, int index)
1944 return ConfVarEnum(target, std::string(tag), index);
1947 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const std::string &tag, int index)
1949 ConfigDataHash::size_type pos = index;
1951 if (pos < target.count(tag))
1953 ConfigDataHash::const_iterator iter = target.find(tag);
1955 for(int i = 0; i < index; i++)
1958 return iter->second.size();
1964 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1966 bool ServerConfig::ReadFile(file_cache &F, const char* fname)
1968 if (!fname || !*fname)
1972 char linebuf[MAXBUF];
1976 if ((*fname != '/') && (*fname != '\\') && (!StartsWithWindowsDriveLetter(fname)))
1978 std::string::size_type pos;
1979 std::string confpath = ServerInstance->ConfigFileName;
1980 std::string newfile = fname;
1982 if (((pos = confpath.rfind("/"))) != std::string::npos)
1983 newfile = confpath.substr(0, pos) + std::string("/") + fname;
1984 else if (((pos = confpath.rfind("\\"))) != std::string::npos)
1985 newfile = confpath.substr(0, pos) + std::string("\\") + fname;
1987 ServerInstance->Logs->Log("config", DEBUG, "Filename: %s", newfile.c_str());
1989 if (!FileExists(newfile.c_str()))
1991 file = fopen(newfile.c_str(), "r");
1995 if (!FileExists(fname))
1997 file = fopen(fname, "r");
2004 if (fgets(linebuf, sizeof(linebuf), file))
2005 linebuf[strlen(linebuf)-1] = 0;
2009 F.push_back(*linebuf ? linebuf : " ");
2020 bool ServerConfig::FileExists(const char* file)
2023 if (stat(file, &sb) == -1)
2026 if ((sb.st_mode & S_IFDIR) > 0)
2030 if ((input = fopen (file, "r")) == NULL)
2039 char* ServerConfig::CleanFilename(char* name)
2041 char* p = name + strlen(name);
2042 while ((p != name) && (*p != '/') && (*p != '\\')) p--;
2043 return (p != name ? ++p : p);
2047 bool ServerConfig::DirValid(const char* dirandfile)
2055 char otherdir[1024];
2058 strlcpy(work, dirandfile, 1024);
2061 // we just want the dir
2073 // Get the current working directory
2074 if (getcwd(buffer, 1024 ) == NULL )
2077 if (chdir(work) == -1)
2080 if (getcwd(otherdir, 1024 ) == NULL )
2083 if (chdir(buffer) == -1)
2086 size_t t = strlen(work);
2088 if (strlen(otherdir) >= t)
2091 if (!strcmp(otherdir,work))
2105 std::string ServerConfig::GetFullProgDir()
2107 char buffer[PATH_MAX];
2109 /* Windows has specific api calls to get the exe path that never fail.
2110 * For once, windows has something of use, compared to the POSIX code
2111 * for this, this is positively neato.
2113 if (GetModuleFileName(NULL, buffer, MAX_PATH))
2115 std::string fullpath = buffer;
2116 std::string::size_type n = fullpath.rfind("\\inspircd.exe");
2117 return std::string(fullpath, 0, n);
2120 // Get the current working directory
2121 if (getcwd(buffer, PATH_MAX))
2123 std::string remainder = this->argv[0];
2125 /* Does argv[0] start with /? its a full path, use it */
2126 if (remainder[0] == '/')
2128 std::string::size_type n = remainder.rfind("/inspircd");
2129 return std::string(remainder, 0, n);
2132 std::string fullpath = std::string(buffer) + "/" + remainder;
2133 std::string::size_type n = fullpath.rfind("/inspircd");
2134 return std::string(fullpath, 0, n);
2140 InspIRCd* ServerConfig::GetInstance()
2142 return ServerInstance;
2145 std::string ServerConfig::GetSID()
2150 ValueItem::ValueItem(int value)
2152 std::stringstream n;
2157 ValueItem::ValueItem(bool value)
2159 std::stringstream n;
2164 ValueItem::ValueItem(const char* value)
2169 void ValueItem::Set(const char* value)
2174 void ValueItem::Set(int value)
2176 std::stringstream n;
2181 int ValueItem::GetInteger()
2185 return atoi(v.c_str());
2188 char* ValueItem::GetString()
2190 return (char*)v.c_str();
2193 bool ValueItem::GetBool()
2195 return (GetInteger() || v == "yes" || v == "true");
2202 * XXX should this be in a class? -- w00t
2204 bool InitTypes(ServerConfig* conf, const char*)
2206 if (conf->opertypes.size())
2208 for (opertype_t::iterator n = conf->opertypes.begin(); n != conf->opertypes.end(); n++)
2215 conf->opertypes.clear();
2220 * XXX should this be in a class? -- w00t
2222 bool InitClasses(ServerConfig* conf, const char*)
2224 if (conf->operclass.size())
2226 for (operclass_t::iterator n = conf->operclass.begin(); n != conf->operclass.end(); n++)
2228 if (n->second.commandlist)
2229 delete[] n->second.commandlist;
2230 if (n->second.cmodelist)
2231 delete[] n->second.cmodelist;
2232 if (n->second.umodelist)
2233 delete[] n->second.umodelist;
2237 conf->operclass.clear();
2242 * XXX should this be in a class? -- w00t
2244 bool DoType(ServerConfig* conf, const char*, char**, ValueList &values, int*)
2246 const char* TypeName = values[0].GetString();
2247 const char* Classes = values[1].GetString();
2249 conf->opertypes[TypeName] = strnewdup(Classes);
2254 * XXX should this be in a class? -- w00t
2256 bool DoClass(ServerConfig* conf, const char* tag, char**, ValueList &values, int*)
2258 const char* ClassName = values[0].GetString();
2259 const char* CommandList = values[1].GetString();
2260 const char* UModeList = values[2].GetString();
2261 const char* CModeList = values[3].GetString();
2263 for (const char* c = UModeList; *c; ++c)
2265 if ((*c < 'A' || *c > 'z') && *c != '*')
2267 throw CoreException("Character " + std::string(1, *c) + " is not a valid mode in <class:usermodes>");
2270 for (const char* c = CModeList; *c; ++c)
2272 if ((*c < 'A' || *c > 'z') && *c != '*')
2274 throw CoreException("Character " + std::string(1, *c) + " is not a valid mode in <class:chanmodes>");
2278 conf->operclass[ClassName].commandlist = strnewdup(CommandList);
2279 conf->operclass[ClassName].umodelist = strnewdup(UModeList);
2280 conf->operclass[ClassName].cmodelist = strnewdup(CModeList);
2285 * XXX should this be in a class? -- w00t
2287 bool DoneClassesAndTypes(ServerConfig*, const char*)
2294 bool InitXLine(ServerConfig* conf, const char* tag)
2299 bool DoZLine(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
2301 const char* reason = values[0].GetString();
2302 const char* ipmask = values[1].GetString();
2304 ZLine* zl = new ZLine(conf->GetInstance(), conf->GetInstance()->Time(), 0, "<Config>", reason, ipmask);
2305 if (!conf->GetInstance()->XLines->AddLine(zl, NULL))
2311 bool DoQLine(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
2313 const char* reason = values[0].GetString();
2314 const char* nick = values[1].GetString();
2316 QLine* ql = new QLine(conf->GetInstance(), conf->GetInstance()->Time(), 0, "<Config>", reason, nick);
2317 if (!conf->GetInstance()->XLines->AddLine(ql, NULL))
2323 bool DoKLine(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
2325 const char* reason = values[0].GetString();
2326 const char* host = values[1].GetString();
2328 XLineManager* xlm = conf->GetInstance()->XLines;
2330 IdentHostPair ih = xlm->IdentSplit(host);
2332 KLine* kl = new KLine(conf->GetInstance(), conf->GetInstance()->Time(), 0, "<Config>", reason, ih.first.c_str(), ih.second.c_str());
2333 if (!xlm->AddLine(kl, NULL))
2338 bool DoELine(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
2340 const char* reason = values[0].GetString();
2341 const char* host = values[1].GetString();
2343 XLineManager* xlm = conf->GetInstance()->XLines;
2345 IdentHostPair ih = xlm->IdentSplit(host);
2347 ELine* el = new ELine(conf->GetInstance(), conf->GetInstance()->Time(), 0, "<Config>", reason, ih.first.c_str(), ih.second.c_str());
2348 if (!xlm->AddLine(el, NULL))
2353 // this should probably be moved to configreader, but atm it relies on CheckELines above.
2354 bool DoneELine(ServerConfig* conf, const char* tag)
2356 for (std::vector<User*>::const_iterator u2 = conf->GetInstance()->Users->local_users.begin(); u2 != conf->GetInstance()->Users->local_users.end(); u2++)
2358 User* u = (User*)(*u2);
2362 conf->GetInstance()->XLines->CheckELines();
2366 void ConfigReaderThread::Run()
2368 /* TODO: TheUser may be invalid by the time we get here! Check its validity, or pass a UID would be better */
2369 ServerInstance->Config->Read(do_bail, TheUser);
2370 ServerInstance->Threads->Mutex(true);
2371 this->SetExitFlag();
2372 ServerInstance->Threads->Mutex(false);