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 * ---------------------------------------------------
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 = InvBypassModes = 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 void ServerConfig::Update005()
70 std::stringstream out(data005);
73 int token_counter = 0;
77 line5 = line5 + token + " ";
79 if (token_counter >= 13)
82 snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
83 isupport.push_back(buf);
91 snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
92 isupport.push_back(buf);
96 void ServerConfig::Send005(User* user)
98 for (std::vector<std::string>::iterator line = ServerInstance->Config->isupport.begin(); line != ServerInstance->Config->isupport.end(); line++)
99 user->WriteNumeric(RPL_ISUPPORT, "%s %s", user->nick.c_str(), line->c_str());
102 bool ServerConfig::CheckOnce(const char* tag, ConfigDataHash &newconf)
104 int count = ConfValueEnum(newconf, tag);
107 throw CoreException("You have more than one <"+std::string(tag)+"> tag, this is not permitted.");
109 throw CoreException("You have not defined a <"+std::string(tag)+"> tag, this is required.");
113 bool NoValidation(ServerConfig*, const char*, const char*, ValueItem&)
118 bool DoneConfItem(ServerConfig* conf, const char* tag)
123 void ServerConfig::ValidateNoSpaces(const char* p, const std::string &tag, const std::string &val)
125 for (const char* ptr = p; *ptr; ++ptr)
128 throw CoreException("The value of <"+tag+":"+val+"> cannot contain spaces");
132 /* 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,
133 * even in strerror(errno). They just return 'yes' or 'no' to an address without such detail as to whats WRONG with the address.
134 * Because ircd users arent as technical as they used to be (;)) we are going to give more of a useful error message.
136 void ServerConfig::ValidateIP(const char* p, const std::string &tag, const std::string &val, bool wild)
140 int not_numbers = false;
146 throw CoreException("The value of <"+tag+":"+val+"> is not an IP address");
148 for (const char* ptr = p; *ptr; ++ptr)
150 if (wild && (*ptr == '*' || *ptr == '?' || *ptr == '/'))
153 if (*ptr != ':' && *ptr != '.')
155 if (*ptr < '0' || *ptr > '9')
157 if ((*ptr < '0' || *ptr > '9') && (toupper(*ptr) < 'A' || toupper(*ptr) > 'F'))
163 throw CoreException("The value of <"+tag+":"+val+"> is not an IP address");
174 throw CoreException("The value of <"+tag+":"+val+"> is an IPv4 address with too many fields!");
177 throw CoreException("The value of <"+tag+":"+val+"> is an IPv6 address with too many fields!");
179 if (num_seps == 0 && num_dots < 3 && !wild)
180 throw CoreException("The value of <"+tag+":"+val+"> looks to be a malformed IPv4 address");
182 if (num_seps == 0 && num_dots == 3 && not_numbers)
183 throw CoreException("The value of <"+tag+":"+val+"> contains non-numeric characters in an IPv4 address");
185 if (num_seps != 0 && not_hex)
186 throw CoreException("The value of <"+tag+":"+val+"> contains non-hexdecimal characters in an IPv6 address");
188 if (num_seps != 0 && num_dots != 3 && num_dots != 0 && !wild)
189 throw CoreException("The value of <"+tag+":"+val+"> is a malformed IPv6 4in6 address");
193 void ServerConfig::ValidateHostname(const char* p, const std::string &tag, const std::string &val)
199 throw CoreException("The value of <"+tag+":"+val+"> is not a valid hostname");
200 for (const char* ptr = p; *ptr; ++ptr)
205 throw CoreException("The value of <"+tag+":"+val+"> is not a valid hostname");
212 throw CoreException("The value of <"+tag+":"+val+"> is not a valid hostname");
216 bool ValidateMaxTargets(ServerConfig* conf, const char*, const char*, ValueItem &data)
218 if ((data.GetInteger() < 0) || (data.GetInteger() > 31))
220 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"WARNING: <security:maxtargets> value is greater than 31 or less than 0, set to 20.");
226 bool ValidateSoftLimit(ServerConfig* conf, const char*, const char*, ValueItem &data)
228 if ((data.GetInteger() < 1) || (data.GetInteger() > conf->GetInstance()->SE->GetMaxFds()))
230 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());
231 data.Set(conf->GetInstance()->SE->GetMaxFds());
236 bool ValidateMaxConn(ServerConfig* conf, const char*, const char*, ValueItem &data)
238 if (data.GetInteger() > SOMAXCONN)
239 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"WARNING: <performance:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
243 bool InitializeDisabledCommands(const char* data, InspIRCd* ServerInstance)
245 std::stringstream dcmds(data);
248 /* Enable everything first */
249 for (Commandtable::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
250 x->second->Disable(false);
252 /* Now disable all the ones which the user wants disabled */
253 while (dcmds >> thiscmd)
255 Commandtable::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
256 if (cm != ServerInstance->Parser->cmdlist.end())
258 cm->second->Disable(true);
264 bool ValidateDisabledUModes(ServerConfig* conf, const char*, const char*, ValueItem &data)
266 memset(conf->DisabledUModes, 0, sizeof(conf->DisabledUModes));
267 for (const unsigned char* p = (const unsigned char*)data.GetString(); *p; ++p)
269 if (*p < 'A' || *p > ('A' + 64)) throw CoreException(std::string("Invalid usermode ")+(char)*p+" was found.");
270 conf->DisabledUModes[*p - 'A'] = 1;
275 bool ValidateDisabledCModes(ServerConfig* conf, const char*, const char*, ValueItem &data)
277 memset(conf->DisabledCModes, 0, sizeof(conf->DisabledCModes));
278 for (const unsigned char* p = (const unsigned char*)data.GetString(); *p; ++p)
280 if (*p < 'A' || *p > ('A' + 64)) throw CoreException(std::string("Invalid chanmode ")+(char)*p+" was found.");
281 conf->DisabledCModes[*p - 'A'] = 1;
286 bool ValidateDnsServer(ServerConfig* conf, const char*, const char*, ValueItem &data)
288 if (!*(data.GetString()))
290 std::string nameserver;
291 // attempt to look up their nameserver from /etc/resolv.conf
292 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
293 std::ifstream resolv("/etc/resolv.conf");
294 bool found_server = false;
296 if (resolv.is_open())
298 while (resolv >> nameserver)
300 if ((nameserver == "nameserver") && (!found_server))
302 resolv >> nameserver;
303 data.Set(nameserver.c_str());
305 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
311 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
312 data.Set("127.0.0.1");
317 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
318 data.Set("127.0.0.1");
324 bool ValidateServerName(ServerConfig* conf, const char*, const char*, ValueItem &data)
326 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"Validating server name");
327 /* If we already have a servername, and they changed it, we should throw an exception. */
328 if (!strchr(data.GetString(), '.'))
330 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(),'.');
331 std::string moo = std::string(data.GetString()).append(".");
332 data.Set(moo.c_str());
334 conf->ValidateHostname(data.GetString(), "server", "name");
338 bool ValidateNetBufferSize(ServerConfig* conf, const char*, const char*, ValueItem &data)
340 // 65534 not 65535 because of null terminator
341 if ((!data.GetInteger()) || (data.GetInteger() > 65534) || (data.GetInteger() < 1024))
343 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
349 bool ValidateMaxWho(ServerConfig* conf, const char*, const char*, ValueItem &data)
351 if ((data.GetInteger() > 65535) || (data.GetInteger() < 1))
353 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"<performance:maxwho> size out of range, setting to default of 128.");
359 bool ValidateMotd(ServerConfig* conf, const char*, const char*, ValueItem &data)
361 conf->ReadFile(conf->MOTD, data.GetString());
365 bool ValidateNotEmpty(ServerConfig*, const char* tag, const char*, ValueItem &data)
367 if (!*data.GetString())
368 throw CoreException(std::string("The value for ")+tag+" cannot be empty!");
372 bool ValidateRules(ServerConfig* conf, const char*, const char*, ValueItem &data)
374 conf->ReadFile(conf->RULES, data.GetString());
378 bool ValidateModeLists(ServerConfig* conf, const char*, const char*, ValueItem &data)
380 memset(conf->HideModeLists, 0, sizeof(conf->HideModeLists));
381 for (const unsigned char* x = (const unsigned char*)data.GetString(); *x; ++x)
382 conf->HideModeLists[*x] = true;
386 bool ValidateExemptChanOps(ServerConfig* conf, const char*, const char*, ValueItem &data)
388 memset(conf->ExemptChanOps, 0, sizeof(conf->ExemptChanOps));
389 for (const unsigned char* x = (const unsigned char*)data.GetString(); *x; ++x)
390 conf->ExemptChanOps[*x] = true;
394 bool ValidateInvite(ServerConfig* conf, const char*, const char*, ValueItem &data)
396 std::string v = data.GetString();
399 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_OPS;
401 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_ALL;
402 else if (v == "dynamic")
403 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_DYNAMIC;
405 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_NONE;
410 bool ValidateSID(ServerConfig* conf, const char*, const char*, ValueItem &data)
412 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"Validating server id");
414 const char *sid = data.GetString();
416 if (*sid && !conf->GetInstance()->IsSID(sid))
418 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.");
421 strlcpy(conf->sid, sid, 5);
426 bool ValidateWhoWas(ServerConfig* conf, const char*, const char*, ValueItem &data)
428 conf->WhoWasMaxKeep = conf->GetInstance()->Duration(data.GetString());
430 if (conf->WhoWasGroupSize < 0)
431 conf->WhoWasGroupSize = 0;
433 if (conf->WhoWasMaxGroups < 0)
434 conf->WhoWasMaxGroups = 0;
436 if (conf->WhoWasMaxKeep < 3600)
438 conf->WhoWasMaxKeep = 3600;
439 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"WARNING: <whowas:maxkeep> value less than 3600, setting to default 3600");
442 Command* whowas_command = conf->GetInstance()->Parser->GetHandler("WHOWAS");
445 std::deque<classbase*> params;
446 whowas_command->HandleInternal(WHOWAS_PRUNE, params);
452 /* Callback called before processing the first <connect> tag
454 bool InitConnect(ServerConfig* conf, const char*)
456 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"Reading connect classes...");
458 for (ClassVector::iterator i = conf->Classes.begin(); i != conf->Classes.end() ; )
460 ConnectClass* c = *i;
462 /* only delete a class with refcount 0 */
463 if (c->RefCount == 0)
465 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT, "Removing connect class, refcount is 0!");
467 /* This was causing a crash, because we'd set i to .begin() just here, but then the for loop's increment would
468 * set it to .begin() + 1. Which if it was already the last thing in the list, wasn't good.
469 * Now the increment is in the else { } below.
471 conf->Classes.erase(i);
472 i = conf->Classes.begin(); // start over so we don't trample on a bad iterator
476 /* also mark all existing classes disabled, if they still exist in the conf, they will be reenabled. */
477 c->SetDisabled(true);
485 /* Callback called to process a single <connect> tag
487 bool DoConnect(ServerConfig* conf, const char*, char**, ValueList &values, int*)
490 const char* allow = values[0].GetString(); /* Yeah, there are a lot of values. Live with it. */
491 const char* deny = values[1].GetString();
492 const char* password = values[2].GetString();
493 int timeout = values[3].GetInteger();
494 int pingfreq = values[4].GetInteger();
495 int flood = values[5].GetInteger();
496 int threshold = values[6].GetInteger();
497 int sendq = values[7].GetInteger();
498 int recvq = values[8].GetInteger();
499 int localmax = values[9].GetInteger();
500 int globalmax = values[10].GetInteger();
501 int port = values[11].GetInteger();
502 const char* name = values[12].GetString();
503 const char* parent = values[13].GetString();
504 int maxchans = values[14].GetInteger();
505 unsigned long limit = values[15].GetInteger();
506 const char* hashtype = values[16].GetString();
509 * duplicates check: Now we don't delete all connect classes on rehash, we need to ensure we don't add dupes.
510 * easier said than done, but for now we'll just disallow anything with a duplicate host or name. -- w00t
512 for (ClassVector::iterator item = conf->Classes.begin(); item != conf->Classes.end(); ++item)
514 ConnectClass* cc = *item;
516 ((*name && (cc->GetName() == name)) || // if the name is the same
517 (*allow && (cc->GetHost() == allow)) || // or the allow is the same
518 (*deny && (cc->GetHost() == deny))) && // or the deny is the same
519 (!port || (port && (cc->GetPort() == port))) // and there is no port, or there is a port and the port is the same
522 /* reenable class so users can be shoved into it :P */
523 cc->SetDisabled(false);
524 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT, "Not adding class, it already exists!");
529 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"Adding a connect class!");
533 /* Find 'parent' and inherit a new class from it,
534 * then overwrite any values that are set here
536 ClassVector::iterator item = conf->Classes.begin();
537 for (; item != conf->Classes.end(); ++item)
539 ConnectClass* cc = *item;
540 conf->GetInstance()->Logs->Log("CONFIG",DEBUG,"Class: %s", cc->GetName().c_str());
541 if (cc->GetName() == parent)
543 ConnectClass* newclass = new ConnectClass(name, cc);
544 newclass->Update(timeout, flood, *allow ? allow : deny, pingfreq, password, threshold, sendq, recvq, localmax, globalmax, maxchans, port, limit);
545 conf->Classes.push_back(newclass);
549 if (item == conf->Classes.end())
550 throw CoreException("Class name '" + std::string(name) + "' is configured to inherit from class '" + std::string(parent) + "' which cannot be found.");
556 /* Find existing class by mask, the mask should be unique */
557 for (ClassVector::iterator item = conf->Classes.begin(); item != conf->Classes.end(); ++item)
559 if ((*item)->GetHost() == allow)
561 (*item)->Update(timeout, flood, allow, pingfreq, password, threshold, sendq, recvq, localmax, globalmax, maxchans, port, limit);
565 ConnectClass* cc = new ConnectClass(name, timeout, flood, allow, pingfreq, password, hashtype, threshold, sendq, recvq, localmax, globalmax, maxchans);
568 conf->Classes.push_back(cc);
572 /* Find existing class by mask, the mask should be unique */
573 for (ClassVector::iterator item = conf->Classes.begin(); item != conf->Classes.end(); ++item)
575 if ((*item)->GetHost() == deny)
577 (*item)->Update(name, deny);
578 (*item)->SetPort(port);
582 ConnectClass* cc = new ConnectClass(name, deny);
584 conf->Classes.push_back(cc);
591 /* Callback called when there are no more <connect> tags
593 bool DoneConnect(ServerConfig *conf, const char*)
595 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT, "Done adding connect classes!");
599 /* Callback called before processing the first <uline> tag
601 bool InitULine(ServerConfig* conf, const char*)
603 conf->ulines.clear();
607 /* Callback called to process a single <uline> tag
609 bool DoULine(ServerConfig* conf, const char*, char**, ValueList &values, int*)
611 const char* server = values[0].GetString();
612 const bool silent = values[1].GetBool();
613 conf->ulines[server] = silent;
617 /* Callback called when there are no more <uline> tags
619 bool DoneULine(ServerConfig*, const char*)
624 /* Callback called before processing the first <module> tag
626 bool InitModule(ServerConfig* conf, const char*)
628 old_module_names = conf->GetInstance()->Modules->GetAllModuleNames(0);
629 new_module_names.clear();
630 added_modules.clear();
631 removed_modules.clear();
635 /* Callback called to process a single <module> tag
637 bool DoModule(ServerConfig*, const char*, char**, ValueList &values, int*)
639 const char* modname = values[0].GetString();
640 new_module_names.push_back(modname);
644 /* Callback called when there are no more <module> tags
646 bool DoneModule(ServerConfig*, const char*)
648 // now create a list of new modules that are due to be loaded
649 // and a seperate list of modules which are due to be unloaded
650 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
654 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
661 added_modules.push_back(*_new);
664 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
667 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
674 removed_modules.push_back(*oldm);
679 /* Callback called before processing the first <banlist> tag
681 bool InitMaxBans(ServerConfig* conf, const char*)
683 conf->maxbans.clear();
687 /* Callback called to process a single <banlist> tag
689 bool DoMaxBans(ServerConfig* conf, const char*, char**, ValueList &values, int*)
691 const char* channel = values[0].GetString();
692 int limit = values[1].GetInteger();
693 conf->maxbans[channel] = limit;
697 /* Callback called when there are no more <banlist> tags.
699 bool DoneMaxBans(ServerConfig*, const char*)
704 void ServerConfig::ReportConfigError(const std::string &errormessage, bool bail, User* user)
706 ServerInstance->Logs->Log("CONFIG",DEFAULT, "There were errors in your configuration file: %s", errormessage.c_str());
709 /* Unneeded because of the ServerInstance->Log() aboive? */
710 printf("There were errors in your configuration:\n%s\n\n",errormessage.c_str());
711 ServerInstance->Exit(EXIT_STATUS_CONFIG);
715 std::string errors = errormessage;
716 std::string::size_type start;
717 unsigned int prefixlen;
719 /* ":ServerInstance->Config->ServerName NOTICE user->nick :" */
722 prefixlen = strlen(this->ServerName) + user->nick.length() + 11;
723 user->WriteServ("NOTICE %s :There were errors in the configuration file:",user->nick.c_str());
724 while (start < errors.length())
726 user->WriteServ("NOTICE %s :%s",user->nick.c_str(), errors.substr(start, 510 - prefixlen).c_str());
727 start += 510 - prefixlen;
732 ServerInstance->SNO->WriteToSnoMask('A', "There were errors in the configuration file:");
733 while (start < errors.length())
735 ServerInstance->SNO->WriteToSnoMask('A', errors.substr(start, 360));
743 void ServerConfig::Read(bool bail, User* user)
745 int rem = 0, add = 0; /* Number of modules added, number of modules removed */
747 static char maxkeep[MAXBUF]; /* Temporary buffer for WhoWasMaxKeep value */
748 static char hidemodes[MAXBUF]; /* Modes to not allow listing from users below halfop */
749 static char exemptchanops[MAXBUF]; /* Exempt channel ops from these modes */
750 static char announceinvites[MAXBUF]; /* options:announceinvites setting */
751 static char disabledumodes[MAXBUF]; /* Disabled usermodes */
752 static char disabledcmodes[MAXBUF]; /* Disabled chanmodes */
755 include_stack.clear();
757 /* These tags MUST occur and must ONLY occur once in the config file */
758 static const char* Once[] = { "server", "admin", "files", "power", "options", NULL };
760 Deprecated ChangedConfig[] = {
761 {"options", "hidelinks", "has been moved to <security:hidelinks> as of 1.2a3"},
762 {"options", "hidewhois", "has been moved to <security:hidewhois> as of 1.2a3"},
763 {"options", "userstats", "has been moved to <security:userstats> as of 1.2a3"},
764 {"options", "customversion", "has been moved to <security:customversion> as of 1.2a3"},
765 {"options", "hidesplits", "has been moved to <security:hidesplits> as of 1.2a3"},
766 {"options", "hidebans", "has been moved to <security:hidebans> as of 1.2a3"},
767 {"options", "hidekills", "has been moved to <security:hidekills> as of 1.2a3"},
768 {"options", "operspywhois", "has been moved to <security:operspywhois> as of 1.2a3"},
769 {"options", "announceinvites", "has been moved to <security:announceinvites> as of 1.2a3"},
770 {"options", "hidemodes", "has been moved to <security:hidemodes> as of 1.2a3"},
771 {"options", "maxtargets", "has been moved to <security:maxtargets> as of 1.2a3"},
772 {"options", "nouserdns", "has been moved to <performance:nouserdns> as of 1.2a3"},
773 {"options", "maxwho", "has been moved to <performance:maxwho> as of 1.2a3"},
774 {"options", "softlimit", "has been moved to <performance:softlimit> as of 1.2a3"},
775 {"options", "somaxconn", "has been moved to <performance:somaxconn> as of 1.2a3"},
776 {"options", "netbuffersize", "has been moved to <performance:netbuffersize> as of 1.2a3"},
777 {"options", "maxwho", "has been moved to <performance:maxwho> as of 1.2a3"},
778 {"options", "loglevel", "1.2 does not use the loglevel value. Please define <log> tags instead."},
782 /* These tags can occur ONCE or not at all */
783 InitialConfig Values[] = {
784 {"performance", "softlimit", "0", new ValueContainerUInt (&this->SoftLimit), DT_INTEGER, ValidateSoftLimit},
785 {"performance", "somaxconn", SOMAXCONN_S, new ValueContainerInt (&this->MaxConn), DT_INTEGER, ValidateMaxConn},
786 {"options", "moronbanner", "Youre banned!", new ValueContainerChar (this->MoronBanner), DT_CHARPTR, NoValidation},
787 {"server", "name", "", new ValueContainerChar (this->ServerName), DT_HOSTNAME|DT_BOOTONLY, ValidateServerName},
788 {"server", "description", "Configure Me", new ValueContainerChar (this->ServerDesc), DT_CHARPTR, NoValidation},
789 {"server", "network", "Network", new ValueContainerChar (this->Network), DT_NOSPACES, NoValidation},
790 {"server", "id", "", new ValueContainerChar (this->sid), DT_CHARPTR|DT_BOOTONLY, ValidateSID},
791 {"admin", "name", "", new ValueContainerChar (this->AdminName), DT_CHARPTR, NoValidation},
792 {"admin", "email", "Mis@configu.red", new ValueContainerChar (this->AdminEmail), DT_CHARPTR, NoValidation},
793 {"admin", "nick", "Misconfigured", new ValueContainerChar (this->AdminNick), DT_CHARPTR, NoValidation},
794 {"files", "motd", "", new ValueContainerChar (this->motd), DT_CHARPTR, ValidateMotd},
795 {"files", "rules", "", new ValueContainerChar (this->rules), DT_CHARPTR, ValidateRules},
796 {"power", "diepass", "", new ValueContainerChar (this->diepass), DT_CHARPTR, ValidateNotEmpty},
797 {"power", "pause", "", new ValueContainerInt (&this->DieDelay), DT_INTEGER, NoValidation},
798 {"power", "hash", "", new ValueContainerChar (this->powerhash), DT_CHARPTR, NoValidation},
799 {"power", "restartpass", "", new ValueContainerChar (this->restartpass), DT_CHARPTR, ValidateNotEmpty},
800 {"options", "prefixquit", "", new ValueContainerChar (this->PrefixQuit), DT_CHARPTR, NoValidation},
801 {"options", "suffixquit", "", new ValueContainerChar (this->SuffixQuit), DT_CHARPTR, NoValidation},
802 {"options", "fixedquit", "", new ValueContainerChar (this->FixedQuit), DT_CHARPTR, NoValidation},
803 {"options", "prefixpart", "", new ValueContainerChar (this->PrefixPart), DT_CHARPTR, NoValidation},
804 {"options", "suffixpart", "", new ValueContainerChar (this->SuffixPart), DT_CHARPTR, NoValidation},
805 {"options", "fixedpart", "", new ValueContainerChar (this->FixedPart), DT_CHARPTR, NoValidation},
806 {"performance", "netbuffersize","10240", new ValueContainerInt (&this->NetBufferSize), DT_INTEGER, ValidateNetBufferSize},
807 {"performance", "maxwho", "128", new ValueContainerInt (&this->MaxWhoResults), DT_INTEGER, ValidateMaxWho},
808 {"options", "allowhalfop", "0", new ValueContainerBool (&this->AllowHalfop), DT_BOOLEAN, NoValidation},
809 {"dns", "server", "", new ValueContainerChar (this->DNSServer), DT_IPADDRESS,DNSServerValidator},
810 {"dns", "timeout", "5", new ValueContainerInt (&this->dns_timeout), DT_INTEGER, NoValidation},
811 {"options", "moduledir", MOD_PATH, new ValueContainerChar (this->ModPath), DT_CHARPTR, NoValidation},
812 {"disabled", "commands", "", new ValueContainerChar (this->DisabledCommands), DT_CHARPTR, NoValidation},
813 {"disabled", "usermodes", "", new ValueContainerChar (disabledumodes), DT_CHARPTR, ValidateDisabledUModes},
814 {"disabled", "chanmodes", "", new ValueContainerChar (disabledcmodes), DT_CHARPTR, ValidateDisabledCModes},
815 {"disabled", "fakenonexistant", "0", new ValueContainerBool (&this->DisabledDontExist), DT_BOOLEAN, NoValidation},
816 {"security", "userstats", "", new ValueContainerChar (this->UserStats), DT_CHARPTR, NoValidation},
817 {"security", "customversion","", new ValueContainerChar (this->CustomVersion), DT_CHARPTR, NoValidation},
818 {"security", "hidesplits", "0", new ValueContainerBool (&this->HideSplits), DT_BOOLEAN, NoValidation},
819 {"security", "hidebans", "0", new ValueContainerBool (&this->HideBans), DT_BOOLEAN, NoValidation},
820 {"security", "hidewhois", "", new ValueContainerChar (this->HideWhoisServer), DT_NOSPACES, NoValidation},
821 {"security", "hidekills", "", new ValueContainerChar (this->HideKillsServer), DT_NOSPACES, NoValidation},
822 {"security", "operspywhois", "0", new ValueContainerBool (&this->OperSpyWhois), DT_BOOLEAN, NoValidation},
823 {"performance", "nouserdns", "0", new ValueContainerBool (&this->NoUserDns), DT_BOOLEAN, NoValidation},
824 {"options", "syntaxhints", "0", new ValueContainerBool (&this->SyntaxHints), DT_BOOLEAN, NoValidation},
825 {"options", "cyclehosts", "0", new ValueContainerBool (&this->CycleHosts), DT_BOOLEAN, NoValidation},
826 {"options", "ircumsgprefix","0", new ValueContainerBool (&this->UndernetMsgPrefix), DT_BOOLEAN, NoValidation},
827 {"security", "announceinvites", "1", new ValueContainerChar (announceinvites), DT_CHARPTR, ValidateInvite},
828 {"options", "hostintopic", "1", new ValueContainerBool (&this->FullHostInTopic), DT_BOOLEAN, NoValidation},
829 {"security", "hidemodes", "", new ValueContainerChar (hidemodes), DT_CHARPTR, ValidateModeLists},
830 {"options", "exemptchanops","", new ValueContainerChar (exemptchanops), DT_CHARPTR, ValidateExemptChanOps},
831 {"security", "maxtargets", "20", new ValueContainerUInt (&this->MaxTargets), DT_INTEGER, ValidateMaxTargets},
832 {"options", "defaultmodes", "nt", new ValueContainerChar (this->DefaultModes), DT_CHARPTR, NoValidation},
833 {"pid", "file", "", new ValueContainerChar (this->PID), DT_CHARPTR, NoValidation},
834 {"whowas", "groupsize", "10", new ValueContainerInt (&this->WhoWasGroupSize), DT_INTEGER, NoValidation},
835 {"whowas", "maxgroups", "10240", new ValueContainerInt (&this->WhoWasMaxGroups), DT_INTEGER, NoValidation},
836 {"whowas", "maxkeep", "3600", new ValueContainerChar (maxkeep), DT_CHARPTR, ValidateWhoWas},
837 {"die", "value", "", new ValueContainerChar (this->DieValue), DT_CHARPTR, NoValidation},
838 {"channels", "users", "20", new ValueContainerUInt (&this->MaxChans), DT_INTEGER, NoValidation},
839 {"channels", "opers", "60", new ValueContainerUInt (&this->OperMaxChans), DT_INTEGER, NoValidation},
840 {"cidr", "ipv4clone", "32", new ValueContainerInt (&this->c_ipv4_range), DT_INTEGER, NoValidation},
841 {"cidr", "ipv6clone", "128", new ValueContainerInt (&this->c_ipv6_range), DT_INTEGER, NoValidation},
842 {"limits", "maxnick", "32", new ValueContainerST (&this->Limits.NickMax), DT_INTEGER, NoValidation},
843 {"limits", "maxchan", "64", new ValueContainerST (&this->Limits.ChanMax), DT_INTEGER, NoValidation},
844 {"limits", "maxmodes", "20", new ValueContainerST (&this->Limits.MaxModes), DT_INTEGER, NoValidation},
845 {"limits", "maxident", "11", new ValueContainerST (&this->Limits.IdentMax), DT_INTEGER, NoValidation},
846 {"limits", "maxquit", "255", new ValueContainerST (&this->Limits.MaxQuit), DT_INTEGER, NoValidation},
847 {"limits", "maxtopic", "307", new ValueContainerST (&this->Limits.MaxTopic), DT_INTEGER, NoValidation},
848 {"limits", "maxkick", "255", new ValueContainerST (&this->Limits.MaxKick), DT_INTEGER, NoValidation},
849 {"limits", "maxgecos", "128", new ValueContainerST (&this->Limits.MaxGecos), DT_INTEGER, NoValidation},
850 {"limits", "maxaway", "200", new ValueContainerST (&this->Limits.MaxAway), DT_INTEGER, NoValidation},
851 {"options", "invitebypassmodes", "1", new ValueContainerBool (&this->InvBypassModes), DT_BOOLEAN, NoValidation},
852 {NULL, NULL, NULL, NULL, DT_NOTHING, NoValidation}
856 /* These tags can occur multiple times, and therefore they have special code to read them
857 * which is different to the code for reading the singular tags listed above.
859 MultiConfig MultiValues[] = {
862 {"allow", "deny", "password", "timeout", "pingfreq", "flood",
863 "threshold", "sendq", "recvq", "localmax", "globalmax", "port",
864 "name", "parent", "maxchans", "limit", "hash",
866 {"", "", "", "", "120", "",
867 "", "", "", "3", "3", "0",
868 "", "", "0", "0", "",
870 {DT_IPADDRESS|DT_ALLOW_WILD,
871 DT_IPADDRESS|DT_ALLOW_WILD,
872 DT_CHARPTR, DT_INTEGER, DT_INTEGER, DT_INTEGER,
873 DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER,
874 DT_NOSPACES, DT_NOSPACES, DT_INTEGER, DT_INTEGER, DT_CHARPTR},
875 InitConnect, DoConnect, DoneConnect},
878 {"server", "silent", NULL},
880 {DT_HOSTNAME, DT_BOOLEAN},
881 InitULine,DoULine,DoneULine},
884 {"chan", "limit", NULL},
886 {DT_CHARPTR, DT_INTEGER},
887 InitMaxBans, DoMaxBans, DoneMaxBans},
893 InitModule, DoModule, DoneModule},
896 {"reason", "ipmask", NULL},
897 {"No reason", "", NULL},
898 {DT_CHARPTR, DT_IPADDRESS|DT_ALLOW_WILD},
899 InitXLine, DoZLine, DoneConfItem},
902 {"reason", "nick", NULL},
903 {"No reason", "", NULL},
904 {DT_CHARPTR, DT_CHARPTR},
905 InitXLine, DoQLine, DoneConfItem},
908 {"reason", "host", NULL},
909 {"No reason", "", NULL},
910 {DT_CHARPTR, DT_CHARPTR},
911 InitXLine, DoKLine, DoneConfItem},
914 {"reason", "host", NULL},
915 {"No reason", "", NULL},
916 {DT_CHARPTR, DT_CHARPTR},
917 InitXLine, DoELine, DoneELine},
920 {"name", "classes", NULL},
922 {DT_NOSPACES, DT_CHARPTR},
923 InitTypes, DoType, DoneClassesAndTypes},
926 {"name", "commands", "usermodes", "chanmodes", NULL},
927 {"", "", "", "", NULL},
928 {DT_NOSPACES, DT_CHARPTR, DT_CHARPTR, DT_CHARPTR},
929 InitClasses, DoClass, DoneClassesAndTypes},
938 /* Load and parse the config file, if there are any errors then explode */
940 /* Make a copy here so if it fails then we can carry on running with an unaffected config */
943 if (!this->DoInclude(newconfig, ServerInstance->ConfigFileName, errstr))
945 ReportConfigError(errstr.str(), bail, user);
949 /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
952 /* Check we dont have more than one of singular tags, or any of them missing
954 for (int Index = 0; Once[Index]; Index++)
955 if (!CheckOnce(Once[Index], newconfig))
958 for (int Index = 0; ChangedConfig[Index].tag; Index++)
962 if (ConfValue(newconfig, ChangedConfig[Index].tag, ChangedConfig[Index].value, "", 0, item, MAXBUF, true) || *item)
963 throw CoreException(std::string("Your configuration contains a deprecated value: <") + ChangedConfig[Index].tag + ":" + ChangedConfig[Index].value + "> - " + ChangedConfig[Index].reason);
965 ServerInstance->Logs->Log("CONFIG",DEBUG,"Deprecated item <%s:%s> does not exist, good.", ChangedConfig[Index].tag, ChangedConfig[Index].value);
968 /* Read the values of all the tags which occur once or not at all, and call their callbacks.
970 for (int Index = 0; Values[Index].tag; ++Index)
973 int dt = Values[Index].datatype;
974 bool allow_newlines = ((dt & DT_ALLOW_NEWLINE) > 0);
975 bool allow_wild = ((dt & DT_ALLOW_WILD) > 0);
976 bool bootonly = ((dt & DT_BOOTONLY) > 0);
977 dt &= ~DT_ALLOW_NEWLINE;
978 dt &= ~DT_ALLOW_WILD;
981 /* Silently ignore boot only values */
982 if (bootonly && !bail)
985 ConfValue(newconfig, Values[Index].tag, Values[Index].value, Values[Index].default_value, 0, item, MAXBUF, allow_newlines);
988 if (!Values[Index].validation_function(this, Values[Index].tag, Values[Index].value, vi))
989 throw CoreException("One or more values in your configuration file failed to validate. Please see your ircd.log for more information.");
991 ServerInstance->Threads->Lock();
996 ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
997 this->ValidateNoSpaces(vi.GetString(), Values[Index].tag, Values[Index].value);
998 vcc->Set(vi.GetString(), strlen(vi.GetString()) + 1);
1003 ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
1004 this->ValidateHostname(vi.GetString(), Values[Index].tag, Values[Index].value);
1005 vcc->Set(vi.GetString(), strlen(vi.GetString()) + 1);
1010 ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
1011 this->ValidateIP(vi.GetString(), Values[Index].tag, Values[Index].value, allow_wild);
1012 vcc->Set(vi.GetString(), strlen(vi.GetString()) + 1);
1017 ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
1018 if (*(vi.GetString()) && !ServerInstance->IsChannel(vi.GetString(), MAXBUF))
1020 ServerInstance->Threads->Unlock();
1021 throw CoreException("The value of <"+std::string(Values[Index].tag)+":"+Values[Index].value+"> is not a valid channel name");
1023 vcc->Set(vi.GetString(), strlen(vi.GetString()) + 1);
1028 ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
1029 /* Make sure we also copy the null terminator */
1030 vcc->Set(vi.GetString(), strlen(vi.GetString()) + 1);
1035 int val = vi.GetInteger();
1036 ValueContainerInt* vci = (ValueContainerInt*)Values[Index].val;
1037 vci->Set(&val, sizeof(int));
1042 bool val = vi.GetBool();
1043 ValueContainerBool* vcb = (ValueContainerBool*)Values[Index].val;
1044 vcb->Set(&val, sizeof(bool));
1048 /* You don't want to know what happens if someones bad code sends us here. */
1051 /* We're done with this now */
1052 delete Values[Index].val;
1053 ServerInstance->Threads->Unlock();
1056 /* Read the multiple-tag items (class tags, connect tags, etc)
1057 * and call the callbacks associated with them. We have three
1058 * callbacks for these, a 'start', 'item' and 'end' callback.
1060 for (int Index = 0; MultiValues[Index].tag; ++Index)
1062 ServerInstance->Threads->Lock();
1063 MultiValues[Index].init_function(this, MultiValues[Index].tag);
1064 ServerInstance->Threads->Unlock();
1066 int number_of_tags = ConfValueEnum(newconfig, MultiValues[Index].tag);
1068 for (int tagnum = 0; tagnum < number_of_tags; ++tagnum)
1071 for (int valuenum = 0; (MultiValues[Index].items[valuenum]) && (valuenum < MAX_VALUES_PER_TAG); ++valuenum)
1073 int dt = MultiValues[Index].datatype[valuenum];
1074 bool allow_newlines = ((dt & DT_ALLOW_NEWLINE) > 0);
1075 bool allow_wild = ((dt & DT_ALLOW_WILD) > 0);
1076 dt &= ~DT_ALLOW_NEWLINE;
1077 dt &= ~DT_ALLOW_WILD;
1079 ServerInstance->Threads->Lock();
1080 /* We catch and rethrow any exception here just so we can free our mutex
1089 if (ConfValue(newconfig, 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(""));
1093 this->ValidateNoSpaces(vl[vl.size()-1].GetString(), MultiValues[Index].tag, MultiValues[Index].items[valuenum]);
1099 if (ConfValue(newconfig, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1100 vl.push_back(ValueItem(item));
1102 vl.push_back(ValueItem(""));
1103 this->ValidateHostname(vl[vl.size()-1].GetString(), MultiValues[Index].tag, MultiValues[Index].items[valuenum]);
1109 if (ConfValue(newconfig, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1110 vl.push_back(ValueItem(item));
1112 vl.push_back(ValueItem(""));
1113 this->ValidateIP(vl[vl.size()-1].GetString(), MultiValues[Index].tag, MultiValues[Index].items[valuenum], allow_wild);
1119 if (ConfValue(newconfig, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1120 vl.push_back(ValueItem(item));
1122 vl.push_back(ValueItem(""));
1123 if (!ServerInstance->IsChannel(vl[vl.size()-1].GetString(), MAXBUF))
1124 throw CoreException("The value of <"+std::string(MultiValues[Index].tag)+":"+MultiValues[Index].items[valuenum]+"> number "+ConvToStr(tagnum + 1)+" is not a valid channel name");
1130 if (ConfValue(newconfig, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1131 vl.push_back(ValueItem(item));
1133 vl.push_back(ValueItem(""));
1139 if (ConfValueInteger(newconfig, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item))
1140 vl.push_back(ValueItem(item));
1142 vl.push_back(ValueItem(0));
1147 bool item = ConfValueBool(newconfig, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum);
1148 vl.push_back(ValueItem(item));
1152 /* Someone was smoking craq if we got here, and we're all gonna die. */
1156 catch (CoreException &e)
1158 ServerInstance->Threads->Unlock();
1161 ServerInstance->Threads->Unlock();
1163 MultiValues[Index].validation_function(this, MultiValues[Index].tag, (char**)MultiValues[Index].items, vl, MultiValues[Index].datatype);
1165 MultiValues[Index].finish_function(this, MultiValues[Index].tag);
1168 /* Finalise the limits, increment them all by one so that we can just put assign(str, 0, val)
1169 * rather than assign(str, 0, val + 1)
1175 catch (CoreException &ce)
1177 ReportConfigError(ce.GetReason(), bail, user);
1181 ServerInstance->Threads->Lock();
1182 for (int i = 0; i < ConfValueEnum(newconfig, "type"); ++i)
1184 char item[MAXBUF], classn[MAXBUF], classes[MAXBUF];
1185 std::string classname;
1186 ConfValue(newconfig, "type", "classes", "", i, classes, MAXBUF, false);
1187 irc::spacesepstream str(classes);
1188 ConfValue(newconfig, "type", "name", "", i, item, MAXBUF, false);
1189 while (str.GetToken(classname))
1192 bool foundclass = false;
1193 for (int j = 0; j < ConfValueEnum(newconfig, "class"); ++j)
1195 ConfValue(newconfig, "class", "name", "", j, classn, MAXBUF, false);
1196 if (!strcmp(classn, classname.c_str()))
1205 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());
1209 printf("Warning: Oper type '%s' has a missing class named '%s', this does nothing!\n", item, classname.c_str());
1211 ServerInstance->SNO->WriteToSnoMask('A', "Warning: Oper type '%s' has a missing class named '%s', this does nothing!", item, classname.c_str());
1217 /* If we succeeded, set the ircd config to the new one */
1218 this->config_data = newconfig;
1220 ServerInstance->Threads->Unlock();
1222 // write once here, to try it out and make sure its ok
1223 ServerInstance->WritePID(this->PID);
1225 /* Switch over logfiles */
1226 ServerInstance->Logs->CloseLogs();
1227 ServerInstance->Logs->OpenFileLogs();
1229 ServerInstance->Logs->Log("CONFIG", DEFAULT, "Done reading configuration file.");
1231 /* If we're rehashing, let's load any new modules, and unload old ones
1235 int found_ports = 0;
1237 ServerInstance->BindPorts(false, found_ports, pl);
1239 if (pl.size() && user)
1241 ServerInstance->Threads->Lock();
1242 user->WriteServ("NOTICE %s :*** Not all your client ports could be bound.", user->nick.c_str());
1243 user->WriteServ("NOTICE %s :*** The following port(s) failed to bind:", user->nick.c_str());
1245 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
1247 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());
1249 ServerInstance->Threads->Unlock();
1252 ServerInstance->Threads->Lock();
1253 if (!removed_modules.empty())
1255 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
1257 if (ServerInstance->Modules->Unload(removing->c_str()))
1259 ServerInstance->SNO->WriteToSnoMask('A', "*** REHASH UNLOADED MODULE: %s",removing->c_str());
1262 user->WriteNumeric(RPL_UNLOADEDMODULE, "%s %s :Module %s successfully unloaded.",user->nick.c_str(), removing->c_str(), removing->c_str());
1269 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());
1274 if (!added_modules.empty())
1276 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
1278 if (ServerInstance->Modules->Load(adding->c_str()))
1280 ServerInstance->SNO->WriteToSnoMask('A', "*** REHASH LOADED MODULE: %s",adding->c_str());
1283 user->WriteNumeric(RPL_LOADEDMODULE, "%s %s :Module %s successfully loaded.",user->nick.c_str(), adding->c_str(), adding->c_str());
1290 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());
1295 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());
1297 ServerInstance->Threads->Unlock();
1303 /** Note: This is safe, the method checks for user == NULL */
1304 ServerInstance->Threads->Lock();
1305 ServerInstance->Parser->SetupCommandTable(user);
1306 ServerInstance->Threads->Unlock();
1311 user->WriteServ("NOTICE %s :*** Successfully rehashed server.", user->nick.c_str());
1313 ServerInstance->SNO->WriteToSnoMask('A', "*** Successfully rehashed server.");
1319 bool ServerConfig::LoadConf(ConfigDataHash &target, FILE* &conf, const char* filename, std::ostringstream &errorstream)
1323 long linenumber = 1;
1324 long last_successful_parse = 1;
1328 int character_count = 0;
1334 ServerInstance->Logs->Log("CONFIG", DEBUG, "Reading %s", filename);
1336 /* Check if the file open failed first */
1339 errorstream << "LoadConf: Couldn't open config file: " << filename << std::endl;
1343 for (unsigned int t = 0; t < include_stack.size(); t++)
1345 if (std::string(filename) == include_stack[t])
1347 errorstream << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
1352 /* It's not already included, add it to the list of files we've loaded */
1353 include_stack.push_back(filename);
1355 /* Start reading characters... */
1356 while ((ch = fgetc(conf)) != EOF)
1359 * Fix for moronic windows issue spotted by Adremelech.
1360 * Some windows editors save text files as utf-16, which is
1361 * a total pain in the ass to parse. Users should save in the
1362 * right config format! If we ever see a file where the first
1363 * byte is 0xFF or 0xFE, or the second is 0xFF or 0xFE, then
1364 * this is most likely a utf-16 file. Bail out and insult user.
1366 if ((character_count++ < 2) && (ch == '\xFF' || ch == '\xFE'))
1368 errorstream << "File " << filename << " cannot be read, as it is encoded in braindead UTF-16. Save your file as plain ASCII!" << std::endl;
1373 * Here we try and get individual tags on separate lines,
1374 * this would be so easy if we just made people format
1375 * their config files like that, but they don't so...
1376 * We check for a '<' and then know the line is over when
1377 * we get a '>' not inside quotes. If we find two '<' and
1378 * no '>' then die with an error.
1381 if ((ch == '#') && !in_quote)
1402 /* XXX: Added by Brain, May 1st 2006 - Escaping of characters.
1403 * Note that this WILL NOT usually allow insertion of newlines,
1404 * because a newline is two characters long. Use it primarily to
1405 * insert the " symbol.
1407 * Note that this also involves a further check when parsing the line,
1408 * which can be found below.
1410 if ((ch == '\\') && (in_quote) && (in_tag))
1413 char real_character;
1416 real_character = fgetc(conf);
1417 if (real_character == 'n')
1418 real_character = '\n';
1419 line += real_character;
1424 errorstream << "End of file after a \\, what did you want to escape?: " << filename << ":" << linenumber << std::endl;
1432 if ((ch != '<') && (!in_tag) && (!in_comment) && (ch > ' ') && (ch != 9))
1434 errorstream << "You have stray characters beyond the tag which starts at " << filename << ":" << last_successful_parse << std::endl;
1444 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;
1452 errorstream << "Parser error: Inside a quote but not within the last valid tag, which was opened at: " << filename << ":" << last_successful_parse << std::endl;
1457 // errorstream << "Opening new config tag on line " << linenumber << std::endl;
1468 // errorstream << "Closing quote in config tag on line " << linenumber << std::endl;
1473 // errorstream << "Opening quote in config tag on line " << linenumber << std::endl;
1481 errorstream << "The tag immediately after the one at " << filename << ":" << last_successful_parse << " has a missing closing \" symbol. Please check this." << std::endl;
1485 errorstream << "You have opened a quote (\") beyond the tag at " << filename << ":" << last_successful_parse << " without opening a new tag. Please check this." << std::endl;
1495 // errorstream << "Closing config tag on line " << linenumber << std::endl;
1499 * If this finds an <include> then ParseLine can simply call
1500 * LoadConf() and load the included config into the same ConfigDataHash
1502 long bl = linenumber;
1503 if (!this->ParseLine(target, filename, line, linenumber, errorstream))
1505 last_successful_parse = linenumber;
1513 errorstream << "You forgot to close the tag which comes immediately after the one at " << filename << ":" << last_successful_parse << std::endl;
1520 /* 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 */
1521 if (in_comment || in_quote)
1523 errorstream << "Reached end of file whilst still inside a quoted section or tag. This is most likely an error or there \
1524 is a newline missing from the end of the file: " << filename << ":" << linenumber << std::endl;
1531 bool ServerConfig::LoadConf(ConfigDataHash &target, FILE* &conf, const std::string &filename, std::ostringstream &errorstream)
1533 return this->LoadConf(target, conf, filename.c_str(), errorstream);
1536 bool ServerConfig::ParseLine(ConfigDataHash &target, const std::string &filename, std::string &line, long &linenumber, std::ostringstream &errorstream)
1538 std::string tagname;
1539 std::string current_key;
1540 std::string current_value;
1547 got_name = got_key = in_quote = false;
1549 for(std::string::iterator c = line.begin(); c != line.end(); c++)
1553 /* We don't know the tag name yet. */
1559 if ((*c >= 'a' && *c <= 'z') || (*c >= 'A' && *c <='Z') || (*c >= '0' && *c <= '9') || *c == '_')
1563 errorstream << "Invalid character in value name of tag: '" << *c << "' in value '" << tagname << "' in filename: " << filename << ":" << linenumber << std::endl;
1570 /* We got to a space, we should have the tagname now. */
1571 if(tagname.length())
1579 /* We have the tag name */
1582 /* We're still reading the key name */
1583 if ((*c != '=') && (*c != '>'))
1587 if ((*c >= 'a' && *c <= 'z') || (*c >= 'A' && *c <='Z') || (*c >= '0' && *c <= '9') || *c == '_')
1591 errorstream << "Invalid character in key: '" << *c << "' in key '" << current_key << "' in filename: " << filename << ":" << linenumber << std::endl;
1598 /* We got an '=', end of the key name. */
1604 /* We have the key name, now we're looking for quotes and the value */
1606 /* Correctly handle escaped characters here.
1607 * See the XXX'ed section above.
1609 if ((*c == '\\') && (in_quote))
1613 current_value += '\n';
1615 current_value += *c;
1618 else if ((*c == '\\') && (!in_quote))
1620 errorstream << "You can't have an escape sequence outside of a quoted section: " << filename << ":" << linenumber << std::endl;
1623 else if ((*c == '\n') && (in_quote))
1625 /* Got a 'real' \n, treat it as part of the value */
1626 current_value += '\n';
1629 else if ((*c == '\r') && (in_quote))
1631 /* Got a \r, drop it */
1639 /* We're not already in a quote. */
1644 /* Leaving the quotes, we have the current value */
1645 results.push_back(KeyVal(current_key, current_value));
1647 // std::cout << "<" << tagname << ":" << current_key << "> " << current_value << std::endl;
1652 if ((tagname == "include") && (current_key == "file"))
1654 if (!this->DoInclude(target, current_value, errorstream))
1657 else if ((tagname == "include") && (current_key == "executable"))
1659 /* Pipe an executable and use its stdout as config data */
1660 if (!this->DoPipe(target, current_value, errorstream))
1664 current_key.clear();
1665 current_value.clear();
1673 current_value += *c;
1680 /* Finished parsing the tag, add it to the config hash */
1681 target.insert(std::pair<std::string, KeyValList > (tagname, results));
1686 bool ServerConfig::DoPipe(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream)
1688 FILE* conf = popen(file.c_str(), "r");
1693 ret = LoadConf(target, conf, file.c_str(), errorstream);
1697 errorstream << "Couldn't execute: " << file << std::endl;
1702 bool ServerConfig::StartsWithWindowsDriveLetter(const std::string &path)
1704 return (path.length() > 2 && isalpha(path[0]) && path[1] == ':');
1707 bool ServerConfig::DoInclude(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream)
1709 std::string confpath;
1710 std::string newfile;
1711 std::string::size_type pos;
1713 confpath = ServerInstance->ConfigFileName;
1716 std::replace(newfile.begin(),newfile.end(),'\\','/');
1717 std::replace(confpath.begin(),confpath.end(),'\\','/');
1719 if ((newfile[0] != '/') && (!StartsWithWindowsDriveLetter(newfile)))
1721 if((pos = confpath.rfind("/")) != std::string::npos)
1723 /* Leaves us with just the path */
1724 newfile = confpath.substr(0, pos) + std::string("/") + newfile;
1728 errorstream << "Couldn't get config path from: " << ServerInstance->ConfigFileName << std::endl;
1733 FILE* conf = fopen(newfile.c_str(), "r");
1738 ret = LoadConf(target, conf, newfile, errorstream);
1742 errorstream << "Couldn't open config file: " << file << std::endl;
1747 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, int index, char* result, int length, bool allow_linefeeds)
1749 return ConfValue(target, tag, var, "", index, result, length, allow_linefeeds);
1752 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index, char* result, int length, bool allow_linefeeds)
1755 bool r = ConfValue(target, std::string(tag), std::string(var), std::string(default_value), index, value, allow_linefeeds);
1756 strlcpy(result, value.c_str(), length);
1760 bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, std::string &result, bool allow_linefeeds)
1762 return ConfValue(target, tag, var, "", index, result, allow_linefeeds);
1765 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)
1767 ConfigDataHash::size_type pos = index;
1768 if (pos < target.count(tag))
1770 ConfigDataHash::iterator iter = target.find(tag);
1772 for(int i = 0; i < index; i++)
1775 for(KeyValList::iterator j = iter->second.begin(); j != iter->second.end(); j++)
1779 if ((!allow_linefeeds) && (j->second.find('\n') != std::string::npos))
1781 ServerInstance->Logs->Log("CONFIG",DEFAULT, "Value of <" + tag + ":" + var+ "> contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
1782 for (std::string::iterator n = j->second.begin(); n != j->second.end(); n++)
1793 if (!default_value.empty())
1795 result = default_value;
1801 if (!default_value.empty())
1803 result = default_value;
1810 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, int index, int &result)
1812 return ConfValueInteger(target, std::string(tag), std::string(var), "", index, result);
1815 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index, int &result)
1817 return ConfValueInteger(target, std::string(tag), std::string(var), std::string(default_value), index, result);
1820 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, int &result)
1822 return ConfValueInteger(target, tag, var, "", index, result);
1825 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index, int &result)
1828 std::istringstream stream;
1829 bool r = ConfValue(target, tag, var, default_value, index, value);
1831 if(!(stream >> result))
1837 if (value.substr(0,2) == "0x")
1842 result = strtol(value.c_str(), &endptr, 16);
1844 /* No digits found */
1845 if (endptr == value.c_str())
1850 char denominator = *(value.end() - 1);
1851 switch (toupper(denominator))
1854 /* Kilobytes -> bytes */
1855 result = result * 1024;
1858 /* Megabytes -> bytes */
1859 result = result * 1024 * 1024;
1862 /* Gigabytes -> bytes */
1863 result = result * 1024 * 1024 * 1024;
1873 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, int index)
1875 return ConfValueBool(target, std::string(tag), std::string(var), "", index);
1878 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index)
1880 return ConfValueBool(target, std::string(tag), std::string(var), std::string(default_value), index);
1883 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, int index)
1885 return ConfValueBool(target, tag, var, "", index);
1888 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index)
1891 if(!ConfValue(target, tag, var, default_value, index, result))
1894 return ((result == "yes") || (result == "true") || (result == "1"));
1897 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const char* tag)
1899 return target.count(tag);
1902 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const std::string &tag)
1904 return target.count(tag);
1907 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const char* tag, int index)
1909 return ConfVarEnum(target, std::string(tag), index);
1912 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const std::string &tag, int index)
1914 ConfigDataHash::size_type pos = index;
1916 if (pos < target.count(tag))
1918 ConfigDataHash::const_iterator iter = target.find(tag);
1920 for(int i = 0; i < index; i++)
1923 return iter->second.size();
1929 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1931 bool ServerConfig::ReadFile(file_cache &F, const char* fname)
1933 if (!fname || !*fname)
1937 char linebuf[MAXBUF];
1941 if ((*fname != '/') && (*fname != '\\') && (!StartsWithWindowsDriveLetter(fname)))
1943 std::string::size_type pos;
1944 std::string confpath = ServerInstance->ConfigFileName;
1945 std::string newfile = fname;
1947 if (((pos = confpath.rfind("/"))) != std::string::npos)
1948 newfile = confpath.substr(0, pos) + std::string("/") + fname;
1949 else if (((pos = confpath.rfind("\\"))) != std::string::npos)
1950 newfile = confpath.substr(0, pos) + std::string("\\") + fname;
1952 ServerInstance->Logs->Log("config", DEBUG, "Filename: %s", newfile.c_str());
1954 if (!FileExists(newfile.c_str()))
1956 file = fopen(newfile.c_str(), "r");
1960 if (!FileExists(fname))
1962 file = fopen(fname, "r");
1969 if (fgets(linebuf, sizeof(linebuf), file))
1970 linebuf[strlen(linebuf)-1] = 0;
1974 F.push_back(*linebuf ? linebuf : " ");
1985 bool ServerConfig::FileExists(const char* file)
1988 if (stat(file, &sb) == -1)
1991 if ((sb.st_mode & S_IFDIR) > 0)
1995 if ((input = fopen (file, "r")) == NULL)
2004 char* ServerConfig::CleanFilename(char* name)
2006 char* p = name + strlen(name);
2007 while ((p != name) && (*p != '/') && (*p != '\\')) p--;
2008 return (p != name ? ++p : p);
2012 bool ServerConfig::DirValid(const char* dirandfile)
2020 char otherdir[1024];
2023 strlcpy(work, dirandfile, 1024);
2026 // we just want the dir
2038 // Get the current working directory
2039 if (getcwd(buffer, 1024 ) == NULL )
2042 if (chdir(work) == -1)
2045 if (getcwd(otherdir, 1024 ) == NULL )
2048 if (chdir(buffer) == -1)
2051 size_t t = strlen(work);
2053 if (strlen(otherdir) >= t)
2056 if (!strcmp(otherdir,work))
2070 std::string ServerConfig::GetFullProgDir()
2072 char buffer[PATH_MAX];
2074 /* Windows has specific api calls to get the exe path that never fail.
2075 * For once, windows has something of use, compared to the POSIX code
2076 * for this, this is positively neato.
2078 if (GetModuleFileName(NULL, buffer, MAX_PATH))
2080 std::string fullpath = buffer;
2081 std::string::size_type n = fullpath.rfind("\\inspircd.exe");
2082 return std::string(fullpath, 0, n);
2085 // Get the current working directory
2086 if (getcwd(buffer, PATH_MAX))
2088 std::string remainder = this->argv[0];
2090 /* Does argv[0] start with /? its a full path, use it */
2091 if (remainder[0] == '/')
2093 std::string::size_type n = remainder.rfind("/inspircd");
2094 return std::string(remainder, 0, n);
2097 std::string fullpath = std::string(buffer) + "/" + remainder;
2098 std::string::size_type n = fullpath.rfind("/inspircd");
2099 return std::string(fullpath, 0, n);
2105 InspIRCd* ServerConfig::GetInstance()
2107 return ServerInstance;
2110 std::string ServerConfig::GetSID()
2115 ValueItem::ValueItem(int value)
2117 std::stringstream n;
2122 ValueItem::ValueItem(bool value)
2124 std::stringstream n;
2129 ValueItem::ValueItem(const char* value)
2134 void ValueItem::Set(const char* value)
2139 void ValueItem::Set(int value)
2141 std::stringstream n;
2146 int ValueItem::GetInteger()
2150 return atoi(v.c_str());
2153 char* ValueItem::GetString()
2155 return (char*)v.c_str();
2158 bool ValueItem::GetBool()
2160 return (GetInteger() || v == "yes" || v == "true");
2167 * XXX should this be in a class? -- w00t
2169 bool InitTypes(ServerConfig* conf, const char*)
2171 if (conf->opertypes.size())
2173 for (opertype_t::iterator n = conf->opertypes.begin(); n != conf->opertypes.end(); n++)
2180 conf->opertypes.clear();
2185 * XXX should this be in a class? -- w00t
2187 bool InitClasses(ServerConfig* conf, const char*)
2189 if (conf->operclass.size())
2191 for (operclass_t::iterator n = conf->operclass.begin(); n != conf->operclass.end(); n++)
2193 if (n->second.commandlist)
2194 delete[] n->second.commandlist;
2195 if (n->second.cmodelist)
2196 delete[] n->second.cmodelist;
2197 if (n->second.umodelist)
2198 delete[] n->second.umodelist;
2202 conf->operclass.clear();
2207 * XXX should this be in a class? -- w00t
2209 bool DoType(ServerConfig* conf, const char*, char**, ValueList &values, int*)
2211 const char* TypeName = values[0].GetString();
2212 const char* Classes = values[1].GetString();
2214 conf->opertypes[TypeName] = strnewdup(Classes);
2219 * XXX should this be in a class? -- w00t
2221 bool DoClass(ServerConfig* conf, const char* tag, char**, ValueList &values, int*)
2223 const char* ClassName = values[0].GetString();
2224 const char* CommandList = values[1].GetString();
2225 const char* UModeList = values[2].GetString();
2226 const char* CModeList = values[3].GetString();
2228 for (const char* c = UModeList; *c; ++c)
2230 if ((*c < 'A' || *c > 'z') && *c != '*')
2232 throw CoreException("Character " + std::string(1, *c) + " is not a valid mode in <class:usermodes>");
2235 for (const char* c = CModeList; *c; ++c)
2237 if ((*c < 'A' || *c > 'z') && *c != '*')
2239 throw CoreException("Character " + std::string(1, *c) + " is not a valid mode in <class:chanmodes>");
2243 conf->operclass[ClassName].commandlist = strnewdup(CommandList);
2244 conf->operclass[ClassName].umodelist = strnewdup(UModeList);
2245 conf->operclass[ClassName].cmodelist = strnewdup(CModeList);
2250 * XXX should this be in a class? -- w00t
2252 bool DoneClassesAndTypes(ServerConfig*, const char*)
2259 bool InitXLine(ServerConfig* conf, const char* tag)
2264 bool DoZLine(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
2266 const char* reason = values[0].GetString();
2267 const char* ipmask = values[1].GetString();
2269 ZLine* zl = new ZLine(conf->GetInstance(), conf->GetInstance()->Time(), 0, "<Config>", reason, ipmask);
2270 if (!conf->GetInstance()->XLines->AddLine(zl, NULL))
2276 bool DoQLine(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
2278 const char* reason = values[0].GetString();
2279 const char* nick = values[1].GetString();
2281 QLine* ql = new QLine(conf->GetInstance(), conf->GetInstance()->Time(), 0, "<Config>", reason, nick);
2282 if (!conf->GetInstance()->XLines->AddLine(ql, NULL))
2288 bool DoKLine(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
2290 const char* reason = values[0].GetString();
2291 const char* host = values[1].GetString();
2293 XLineManager* xlm = conf->GetInstance()->XLines;
2295 IdentHostPair ih = xlm->IdentSplit(host);
2297 KLine* kl = new KLine(conf->GetInstance(), conf->GetInstance()->Time(), 0, "<Config>", reason, ih.first.c_str(), ih.second.c_str());
2298 if (!xlm->AddLine(kl, NULL))
2303 bool DoELine(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
2305 const char* reason = values[0].GetString();
2306 const char* host = values[1].GetString();
2308 XLineManager* xlm = conf->GetInstance()->XLines;
2310 IdentHostPair ih = xlm->IdentSplit(host);
2312 ELine* el = new ELine(conf->GetInstance(), conf->GetInstance()->Time(), 0, "<Config>", reason, ih.first.c_str(), ih.second.c_str());
2313 if (!xlm->AddLine(el, NULL))
2318 // this should probably be moved to configreader, but atm it relies on CheckELines above.
2319 bool DoneELine(ServerConfig* conf, const char* tag)
2321 for (std::vector<User*>::const_iterator u2 = conf->GetInstance()->Users->local_users.begin(); u2 != conf->GetInstance()->Users->local_users.end(); u2++)
2323 User* u = (User*)(*u2);
2327 conf->GetInstance()->XLines->CheckELines();
2331 void ConfigReaderThread::Run()
2333 /* TODO: TheUser may be invalid by the time we get here! Check its validity, or pass a UID would be better */
2334 ServerInstance->Config->Read(do_bail, TheUser);
2335 ServerInstance->Threads->Lock();
2336 this->SetExitFlag();
2337 ServerInstance->Threads->Unlock();