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: docs/inspircd.conf.example $(CONPATH) */
27 #include "exitcodes.h"
28 #include "commands/cmd_whowas.h"
30 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
32 /* Needs forward declaration */
33 bool ValidateDnsServer(ServerConfig* conf, const char* tag, const char* value, ValueItem &data);
34 bool DoneELine(ServerConfig* conf, const char* tag);
36 ServerConfig::ServerConfig(InspIRCd* Instance) : ServerInstance(Instance)
39 *ServerName = *Network = *ServerDesc = *AdminName = '\0';
40 *HideWhoisServer = *AdminEmail = *AdminNick = *diepass = *restartpass = *FixedQuit = *HideKillsServer = '\0';
41 *DefaultModes = *CustomVersion = *motd = *rules = *PrefixQuit = *DieValue = *DNSServer = '\0';
42 *UserStats = *ModPath = *MyExecutable = *DisabledCommands = *PID = *SuffixQuit = '\0';
43 WhoWasGroupSize = WhoWasMaxGroups = WhoWasMaxKeep = 0;
45 NoUserDns = forcedebug = OperSpyWhois = nofork = HideBans = HideSplits = UndernetMsgPrefix = false;
46 CycleHosts = writelog = AllowHalfop = true;
47 dns_timeout = DieDelay = 5;
49 NetBufferSize = 10240;
50 SoftLimit = Instance->SE->GetMaxFds();
58 DNSServerValidator = &ValidateDnsServer;
61 void ServerConfig::ClearStack()
63 include_stack.clear();
66 Module* ServerConfig::GetIOHook(BufferedSocket* is)
68 std::map<BufferedSocket*,Module*>::iterator x = SocketIOHookModule.find(is);
69 return (x != SocketIOHookModule.end() ? x->second : NULL);
72 bool ServerConfig::AddIOHook(Module* iomod, BufferedSocket* is)
76 SocketIOHookModule[is] = iomod;
77 is->IsIOHooked = true;
82 throw ModuleException("BufferedSocket derived class already hooked by another module");
87 bool ServerConfig::DelIOHook(BufferedSocket* is)
89 std::map<BufferedSocket*,Module*>::iterator x = SocketIOHookModule.find(is);
90 if (x != SocketIOHookModule.end())
92 SocketIOHookModule.erase(x);
98 void ServerConfig::Update005()
100 std::stringstream out(data005);
103 int token_counter = 0;
107 line5 = line5 + token + " ";
109 if (token_counter >= 13)
112 snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
113 isupport.push_back(buf);
121 snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
122 isupport.push_back(buf);
126 void ServerConfig::Send005(User* user)
128 for (std::vector<std::string>::iterator line = ServerInstance->Config->isupport.begin(); line != ServerInstance->Config->isupport.end(); line++)
129 user->WriteNumeric(005, "%s %s", user->nick, line->c_str());
132 bool ServerConfig::CheckOnce(const char* tag)
134 int count = ConfValueEnum(this->config_data, tag);
138 throw CoreException("You have more than one <"+std::string(tag)+"> tag, this is not permitted.");
143 throw CoreException("You have not defined a <"+std::string(tag)+"> tag, this is required.");
149 bool NoValidation(ServerConfig*, const char*, const char*, ValueItem&)
154 bool DoneConfItem(ServerConfig* conf, const char* tag)
159 void ServerConfig::ValidateNoSpaces(const char* p, const std::string &tag, const std::string &val)
161 for (const char* ptr = p; *ptr; ++ptr)
164 throw CoreException("The value of <"+tag+":"+val+"> cannot contain spaces");
168 /* 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,
169 * even in strerror(errno). They just return 'yes' or 'no' to an address without such detail as to whats WRONG with the address.
170 * Because ircd users arent as technical as they used to be (;)) we are going to give more of a useful error message.
172 void ServerConfig::ValidateIP(const char* p, const std::string &tag, const std::string &val, bool wild)
176 int not_numbers = false;
182 throw CoreException("The value of <"+tag+":"+val+"> is not an IP address");
184 for (const char* ptr = p; *ptr; ++ptr)
186 if (wild && (*ptr == '*' || *ptr == '?' || *ptr == '/'))
189 if (*ptr != ':' && *ptr != '.')
191 if (*ptr < '0' || *ptr > '9')
193 if ((*ptr < '0' || *ptr > '9') && (toupper(*ptr) < 'A' || toupper(*ptr) > 'F'))
199 throw CoreException("The value of <"+tag+":"+val+"> is not an IP address");
210 throw CoreException("The value of <"+tag+":"+val+"> is an IPv4 address with too many fields!");
213 throw CoreException("The value of <"+tag+":"+val+"> is an IPv6 address with too many fields!");
215 if (num_seps == 0 && num_dots < 3 && !wild)
216 throw CoreException("The value of <"+tag+":"+val+"> looks to be a malformed IPv4 address");
218 if (num_seps == 0 && num_dots == 3 && not_numbers)
219 throw CoreException("The value of <"+tag+":"+val+"> contains non-numeric characters in an IPv4 address");
221 if (num_seps != 0 && not_hex)
222 throw CoreException("The value of <"+tag+":"+val+"> contains non-hexdecimal characters in an IPv6 address");
224 if (num_seps != 0 && num_dots != 3 && num_dots != 0 && !wild)
225 throw CoreException("The value of <"+tag+":"+val+"> is a malformed IPv6 4in6 address");
229 void ServerConfig::ValidateHostname(const char* p, const std::string &tag, const std::string &val)
235 throw CoreException("The value of <"+tag+":"+val+"> is not a valid hostname");
236 for (const char* ptr = p; *ptr; ++ptr)
241 throw CoreException("The value of <"+tag+":"+val+"> is not a valid hostname");
248 throw CoreException("The value of <"+tag+":"+val+"> is not a valid hostname");
252 bool ValidateMaxTargets(ServerConfig* conf, const char*, const char*, ValueItem &data)
254 if ((data.GetInteger() < 0) || (data.GetInteger() > 31))
256 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
262 bool ValidateSoftLimit(ServerConfig* conf, const char*, const char*, ValueItem &data)
264 if ((data.GetInteger() < 1) || (data.GetInteger() > conf->GetInstance()->SE->GetMaxFds()))
266 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",conf->GetInstance()->SE->GetMaxFds(),conf->GetInstance()->SE->GetMaxFds());
267 data.Set(conf->GetInstance()->SE->GetMaxFds());
272 bool ValidateMaxConn(ServerConfig* conf, const char*, const char*, ValueItem &data)
274 if (data.GetInteger() > SOMAXCONN)
275 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
279 bool InitializeDisabledCommands(const char* data, InspIRCd* ServerInstance)
281 std::stringstream dcmds(data);
284 /* Enable everything first */
285 for (Commandable::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
286 x->second->Disable(false);
288 /* Now disable all the ones which the user wants disabled */
289 while (dcmds >> thiscmd)
291 Commandable::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
292 if (cm != ServerInstance->Parser->cmdlist.end())
294 cm->second->Disable(true);
300 bool ValidateDnsServer(ServerConfig* conf, const char*, const char*, ValueItem &data)
302 if (!*(data.GetString()))
304 std::string nameserver;
305 // attempt to look up their nameserver from /etc/resolv.conf
306 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
307 std::ifstream resolv("/etc/resolv.conf");
308 bool found_server = false;
310 if (resolv.is_open())
312 while (resolv >> nameserver)
314 if ((nameserver == "nameserver") && (!found_server))
316 resolv >> nameserver;
317 data.Set(nameserver.c_str());
319 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
325 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
326 data.Set("127.0.0.1");
331 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
332 data.Set("127.0.0.1");
338 bool ValidateServerName(ServerConfig* conf, const char*, const char*, ValueItem &data)
340 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"Validating server name");
341 /* If we already have a servername, and they changed it, we should throw an exception. */
342 if (!strchr(data.GetString(), '.'))
344 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(),'.');
345 std::string moo = std::string(data.GetString()).append(".");
346 data.Set(moo.c_str());
351 bool ValidateNetBufferSize(ServerConfig* conf, const char*, const char*, ValueItem &data)
353 if ((!data.GetInteger()) || (data.GetInteger() > 65535) || (data.GetInteger() < 1024))
355 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
361 bool ValidateMaxWho(ServerConfig* conf, const char*, const char*, ValueItem &data)
363 if ((data.GetInteger() > 65535) || (data.GetInteger() < 1))
365 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"<options:maxwhoresults> size out of range, setting to default of 128.");
371 bool ValidateLogLevel(ServerConfig* conf, const char*, const char*, ValueItem &data)
373 std::string dbg = data.GetString();
374 conf->LogLevel = DEFAULT;
377 conf->LogLevel = DEBUG;
378 else if (dbg == "verbose")
379 conf->LogLevel = VERBOSE;
380 else if (dbg == "default")
381 conf->LogLevel = DEFAULT;
382 else if (dbg == "sparse")
383 conf->LogLevel = SPARSE;
384 else if (dbg == "none")
385 conf->LogLevel = NONE;
387 conf->debugging = (conf->LogLevel == DEBUG);
392 bool ValidateMotd(ServerConfig* conf, const char*, const char*, ValueItem &data)
394 conf->ReadFile(conf->MOTD, data.GetString());
398 bool ValidateNotEmpty(ServerConfig*, const char* tag, const char*, ValueItem &data)
400 if (!*data.GetString())
401 throw CoreException(std::string("The value for ")+tag+" cannot be empty!");
405 bool ValidateRules(ServerConfig* conf, const char*, const char*, ValueItem &data)
407 conf->ReadFile(conf->RULES, data.GetString());
411 bool ValidateModeLists(ServerConfig* conf, const char*, const char*, ValueItem &data)
413 memset(conf->HideModeLists, 0, 256);
414 for (const unsigned char* x = (const unsigned char*)data.GetString(); *x; ++x)
415 conf->HideModeLists[*x] = true;
419 bool ValidateExemptChanOps(ServerConfig* conf, const char*, const char*, ValueItem &data)
421 memset(conf->ExemptChanOps, 0, 256);
422 for (const unsigned char* x = (const unsigned char*)data.GetString(); *x; ++x)
423 conf->ExemptChanOps[*x] = true;
427 bool ValidateInvite(ServerConfig* conf, const char*, const char*, ValueItem &data)
429 std::string v = data.GetString();
432 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_OPS;
434 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_ALL;
435 else if (v == "dynamic")
436 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_DYNAMIC;
438 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_NONE;
443 bool ValidateSID(ServerConfig* conf, const char*, const char*, ValueItem &data)
445 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"Validating server id");
447 const char *sid = data.GetString();
449 if (*sid && !conf->GetInstance()->IsSID(sid))
451 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.");
454 strlcpy(conf->sid, sid, 5);
459 bool ValidateWhoWas(ServerConfig* conf, const char*, const char*, ValueItem &data)
461 conf->WhoWasMaxKeep = conf->GetInstance()->Duration(data.GetString());
463 if (conf->WhoWasGroupSize < 0)
464 conf->WhoWasGroupSize = 0;
466 if (conf->WhoWasMaxGroups < 0)
467 conf->WhoWasMaxGroups = 0;
469 if (conf->WhoWasMaxKeep < 3600)
471 conf->WhoWasMaxKeep = 3600;
472 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"WARNING: <whowas:maxkeep> value less than 3600, setting to default 3600");
475 Command* whowas_command = conf->GetInstance()->Parser->GetHandler("WHOWAS");
478 std::deque<classbase*> params;
479 whowas_command->HandleInternal(WHOWAS_PRUNE, params);
485 /* Callback called before processing the first <connect> tag
487 bool InitConnect(ServerConfig* conf, const char*)
489 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"Reading connect classes...");
491 for (ClassVector::iterator i = conf->Classes.begin(); i != conf->Classes.end() ; )
493 ConnectClass* c = *i;
495 /* only delete a class with refcount 0 */
496 if (c->RefCount == 0)
498 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT, "Removing connect class, refcount is 0!");
500 /* This was causing a crash, because we'd set i to .begin() just here, but then the for loop's increment would
501 * set it to .begin() + 1. Which if it was already the last thing in the list, wasn't good.
502 * Now the increment is in the else { } below.
504 conf->Classes.erase(i);
505 i = conf->Classes.begin(); // start over so we don't trample on a bad iterator
509 /* also mark all existing classes disabled, if they still exist in the conf, they will be reenabled. */
510 c->SetDisabled(true);
518 /* Callback called to process a single <connect> tag
520 bool DoConnect(ServerConfig* conf, const char*, char**, ValueList &values, int*)
523 const char* allow = values[0].GetString(); /* Yeah, there are a lot of values. Live with it. */
524 const char* deny = values[1].GetString();
525 const char* password = values[2].GetString();
526 int timeout = values[3].GetInteger();
527 int pingfreq = values[4].GetInteger();
528 int flood = values[5].GetInteger();
529 int threshold = values[6].GetInteger();
530 int sendq = values[7].GetInteger();
531 int recvq = values[8].GetInteger();
532 int localmax = values[9].GetInteger();
533 int globalmax = values[10].GetInteger();
534 int port = values[11].GetInteger();
535 const char* name = values[12].GetString();
536 const char* parent = values[13].GetString();
537 int maxchans = values[14].GetInteger();
538 unsigned long limit = values[15].GetInteger();
539 const char* hashtype = values[16].GetString();
542 * duplicates check: Now we don't delete all connect classes on rehash, we need to ensure we don't add dupes.
543 * easier said than done, but for now we'll just disallow anything with a duplicate host or name. -- w00t
545 for (ClassVector::iterator item = conf->Classes.begin(); item != conf->Classes.end(); ++item)
547 ConnectClass* cc = *item;
548 if ((*name && (cc->GetName() == name)) || (*allow && (cc->GetHost() == allow)) || (*deny && (cc->GetHost() == deny)))
550 /* reenable class so users can be shoved into it :P */
551 cc->SetDisabled(false);
552 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT, "Not adding class, it already exists!");
557 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT,"Adding a connect class!");
561 /* Find 'parent' and inherit a new class from it,
562 * then overwrite any values that are set here
564 ClassVector::iterator item = conf->Classes.begin();
565 for (; item != conf->Classes.end(); ++item)
567 ConnectClass* cc = *item;
568 conf->GetInstance()->Logs->Log("CONFIG",DEBUG,"Class: %s", cc->GetName().c_str());
569 if (cc->GetName() == parent)
571 ConnectClass* newclass = new ConnectClass(name, cc);
572 newclass->Update(timeout, flood, *allow ? allow : deny, pingfreq, password, threshold, sendq, recvq, localmax, globalmax, maxchans, port, limit);
573 conf->Classes.push_back(newclass);
577 if (item == conf->Classes.end())
578 throw CoreException("Class name '" + std::string(name) + "' is configured to inherit from class '" + std::string(parent) + "' which cannot be found.");
584 ConnectClass* cc = new ConnectClass(name, timeout, flood, allow, pingfreq, password, hashtype, threshold, sendq, recvq, localmax, globalmax, maxchans);
587 conf->Classes.push_back(cc);
591 ConnectClass* cc = new ConnectClass(name, deny);
593 conf->Classes.push_back(cc);
600 /* Callback called when there are no more <connect> tags
602 bool DoneConnect(ServerConfig *conf, const char*)
604 conf->GetInstance()->Logs->Log("CONFIG",DEFAULT, "Done adding connect classes!");
608 /* Callback called before processing the first <uline> tag
610 bool InitULine(ServerConfig* conf, const char*)
612 conf->ulines.clear();
616 /* Callback called to process a single <uline> tag
618 bool DoULine(ServerConfig* conf, const char*, char**, ValueList &values, int*)
620 const char* server = values[0].GetString();
621 const bool silent = values[1].GetBool();
622 conf->ulines[server] = silent;
626 /* Callback called when there are no more <uline> tags
628 bool DoneULine(ServerConfig*, const char*)
633 /* Callback called before processing the first <module> tag
635 bool InitModule(ServerConfig* conf, const char*)
637 old_module_names = conf->GetInstance()->Modules->GetAllModuleNames(0);
638 new_module_names.clear();
639 added_modules.clear();
640 removed_modules.clear();
644 /* Callback called to process a single <module> tag
646 bool DoModule(ServerConfig*, const char*, char**, ValueList &values, int*)
648 const char* modname = values[0].GetString();
649 new_module_names.push_back(modname);
653 /* Callback called when there are no more <module> tags
655 bool DoneModule(ServerConfig*, const char*)
657 // now create a list of new modules that are due to be loaded
658 // and a seperate list of modules which are due to be unloaded
659 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
663 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
670 added_modules.push_back(*_new);
673 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
676 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
683 removed_modules.push_back(*oldm);
688 /* Callback called before processing the first <banlist> tag
690 bool InitMaxBans(ServerConfig* conf, const char*)
692 conf->maxbans.clear();
696 /* Callback called to process a single <banlist> tag
698 bool DoMaxBans(ServerConfig* conf, const char*, char**, ValueList &values, int*)
700 const char* channel = values[0].GetString();
701 int limit = values[1].GetInteger();
702 conf->maxbans[channel] = limit;
706 /* Callback called when there are no more <banlist> tags.
708 bool DoneMaxBans(ServerConfig*, const char*)
713 void ServerConfig::ReportConfigError(const std::string &errormessage, bool bail, User* user)
715 ServerInstance->Logs->Log("CONFIG",DEFAULT, "There were errors in your configuration file: %s", errormessage.c_str());
718 /* Unneeded because of the ServerInstance->Log() aboive? */
719 printf("There were errors in your configuration:\n%s\n\n",errormessage.c_str());
720 ServerInstance->Exit(EXIT_STATUS_CONFIG);
724 std::string errors = errormessage;
725 std::string::size_type start;
726 unsigned int prefixlen;
728 /* ":ServerInstance->Config->ServerName NOTICE user->nick :" */
731 prefixlen = strlen(this->ServerName) + strlen(user->nick) + 11;
732 user->WriteServ("NOTICE %s :There were errors in the configuration file:",user->nick);
733 while (start < errors.length())
735 user->WriteServ("NOTICE %s :%s",user->nick, errors.substr(start, 510 - prefixlen).c_str());
736 start += 510 - prefixlen;
741 ServerInstance->SNO->WriteToSnoMask('A', "There were errors in the configuration file:");
742 while (start < errors.length())
744 ServerInstance->SNO->WriteToSnoMask('A', errors.substr(start, 360));
752 void ServerConfig::Read(bool bail, User* user)
754 int rem = 0, add = 0; /* Number of modules added, number of modules removed */
756 static char debug[MAXBUF]; /* Temporary buffer for debugging value */
757 static char maxkeep[MAXBUF]; /* Temporary buffer for WhoWasMaxKeep value */
758 static char hidemodes[MAXBUF]; /* Modes to not allow listing from users below halfop */
759 static char exemptchanops[MAXBUF]; /* Exempt channel ops from these modes */
760 static char announceinvites[MAXBUF]; /* options:announceinvites setting */
763 include_stack.clear();
765 /* These tags MUST occur and must ONLY occur once in the config file */
766 static const char* Once[] = { "server", "admin", "files", "power", "options", NULL };
768 /* These tags can occur ONCE or not at all */
769 InitialConfig Values[] = {
770 {"options", "softlimit", "0", new ValueContainerUInt (&this->SoftLimit), DT_INTEGER, ValidateSoftLimit},
771 {"options", "somaxconn", SOMAXCONN_S, new ValueContainerInt (&this->MaxConn), DT_INTEGER, ValidateMaxConn},
772 {"options", "moronbanner", "Youre banned!", new ValueContainerChar (this->MoronBanner), DT_CHARPTR, NoValidation},
773 {"server", "name", "", new ValueContainerChar (this->ServerName), DT_HOSTNAME|DT_BOOTONLY, ValidateServerName},
774 {"server", "description", "Configure Me", new ValueContainerChar (this->ServerDesc), DT_CHARPTR, NoValidation},
775 {"server", "network", "Network", new ValueContainerChar (this->Network), DT_NOSPACES, NoValidation},
776 {"server", "id", "", new ValueContainerChar (this->sid), DT_CHARPTR|DT_BOOTONLY, ValidateSID},
777 {"admin", "name", "", new ValueContainerChar (this->AdminName), DT_CHARPTR, NoValidation},
778 {"admin", "email", "Mis@configu.red", new ValueContainerChar (this->AdminEmail), DT_CHARPTR, NoValidation},
779 {"admin", "nick", "Misconfigured", new ValueContainerChar (this->AdminNick), DT_CHARPTR, NoValidation},
780 {"files", "motd", "", new ValueContainerChar (this->motd), DT_CHARPTR, ValidateMotd},
781 {"files", "rules", "", new ValueContainerChar (this->rules), DT_CHARPTR, ValidateRules},
782 {"power", "diepass", "", new ValueContainerChar (this->diepass), DT_CHARPTR, ValidateNotEmpty},
783 {"power", "pause", "", new ValueContainerInt (&this->DieDelay), DT_INTEGER, NoValidation},
784 {"power", "hash", "", new ValueContainerChar (this->powerhash), DT_CHARPTR, NoValidation},
785 {"power", "restartpass", "", new ValueContainerChar (this->restartpass), DT_CHARPTR, ValidateNotEmpty},
786 {"options", "prefixquit", "", new ValueContainerChar (this->PrefixQuit), DT_CHARPTR, NoValidation},
787 {"options", "suffixquit", "", new ValueContainerChar (this->SuffixQuit), DT_CHARPTR, NoValidation},
788 {"options", "fixedquit", "", new ValueContainerChar (this->FixedQuit), DT_CHARPTR, NoValidation},
789 {"options", "prefixpart", "", new ValueContainerChar (this->PrefixPart), DT_CHARPTR, NoValidation},
790 {"options", "suffixpart", "", new ValueContainerChar (this->SuffixPart), DT_CHARPTR, NoValidation},
791 {"options", "fixedpart", "", new ValueContainerChar (this->FixedPart), DT_CHARPTR, NoValidation},
792 {"options", "loglevel", "default", new ValueContainerChar (debug), DT_CHARPTR, ValidateLogLevel},
793 {"options", "netbuffersize","10240", new ValueContainerInt (&this->NetBufferSize), DT_INTEGER, ValidateNetBufferSize},
794 {"options", "maxwho", "128", new ValueContainerInt (&this->MaxWhoResults), DT_INTEGER, ValidateMaxWho},
795 {"options", "allowhalfop", "0", new ValueContainerBool (&this->AllowHalfop), DT_BOOLEAN, NoValidation},
796 {"dns", "server", "", new ValueContainerChar (this->DNSServer), DT_IPADDRESS,DNSServerValidator},
797 {"dns", "timeout", "5", new ValueContainerInt (&this->dns_timeout), DT_INTEGER, NoValidation},
798 {"options", "moduledir", MOD_PATH, new ValueContainerChar (this->ModPath), DT_CHARPTR, NoValidation},
799 {"disabled", "commands", "", new ValueContainerChar (this->DisabledCommands), DT_CHARPTR, NoValidation},
800 {"options", "userstats", "", new ValueContainerChar (this->UserStats), DT_CHARPTR, NoValidation},
801 {"options", "customversion","", new ValueContainerChar (this->CustomVersion), DT_CHARPTR, NoValidation},
802 {"options", "hidesplits", "0", new ValueContainerBool (&this->HideSplits), DT_BOOLEAN, NoValidation},
803 {"options", "hidebans", "0", new ValueContainerBool (&this->HideBans), DT_BOOLEAN, NoValidation},
804 {"options", "hidewhois", "", new ValueContainerChar (this->HideWhoisServer), DT_NOSPACES, NoValidation},
805 {"options", "hidekills", "", new ValueContainerChar (this->HideKillsServer), DT_NOSPACES, NoValidation},
806 {"options", "operspywhois", "0", new ValueContainerBool (&this->OperSpyWhois), DT_BOOLEAN, NoValidation},
807 {"options", "nouserdns", "0", new ValueContainerBool (&this->NoUserDns), DT_BOOLEAN, NoValidation},
808 {"options", "syntaxhints", "0", new ValueContainerBool (&this->SyntaxHints), DT_BOOLEAN, NoValidation},
809 {"options", "cyclehosts", "0", new ValueContainerBool (&this->CycleHosts), DT_BOOLEAN, NoValidation},
810 {"options", "ircumsgprefix","0", new ValueContainerBool (&this->UndernetMsgPrefix), DT_BOOLEAN, NoValidation},
811 {"options", "announceinvites", "1", new ValueContainerChar (announceinvites), DT_CHARPTR, ValidateInvite},
812 {"options", "hostintopic", "1", new ValueContainerBool (&this->FullHostInTopic), DT_BOOLEAN, NoValidation},
813 {"options", "hidemodes", "", new ValueContainerChar (hidemodes), DT_CHARPTR, ValidateModeLists},
814 {"options", "exemptchanops","", new ValueContainerChar (exemptchanops), DT_CHARPTR, ValidateExemptChanOps},
815 {"options", "maxtargets", "20", new ValueContainerUInt (&this->MaxTargets), DT_INTEGER, ValidateMaxTargets},
816 {"options", "defaultmodes", "nt", new ValueContainerChar (this->DefaultModes), DT_CHARPTR, NoValidation},
817 {"pid", "file", "", new ValueContainerChar (this->PID), DT_CHARPTR, NoValidation},
818 {"whowas", "groupsize", "10", new ValueContainerInt (&this->WhoWasGroupSize), DT_INTEGER, NoValidation},
819 {"whowas", "maxgroups", "10240", new ValueContainerInt (&this->WhoWasMaxGroups), DT_INTEGER, NoValidation},
820 {"whowas", "maxkeep", "3600", new ValueContainerChar (maxkeep), DT_CHARPTR, ValidateWhoWas},
821 {"die", "value", "", new ValueContainerChar (this->DieValue), DT_CHARPTR, NoValidation},
822 {"channels", "users", "20", new ValueContainerUInt (&this->MaxChans), DT_INTEGER, NoValidation},
823 {"channels", "opers", "60", new ValueContainerUInt (&this->OperMaxChans), DT_INTEGER, NoValidation},
824 {NULL, NULL, NULL, NULL, DT_NOTHING, NoValidation}
827 /* These tags can occur multiple times, and therefore they have special code to read them
828 * which is different to the code for reading the singular tags listed above.
830 MultiConfig MultiValues[] = {
833 {"allow", "deny", "password", "timeout", "pingfreq", "flood",
834 "threshold", "sendq", "recvq", "localmax", "globalmax", "port",
835 "name", "parent", "maxchans", "limit", "hash",
837 {"", "", "", "", "120", "",
838 "", "", "", "3", "3", "0",
839 "", "", "0", "0", "",
841 {DT_IPADDRESS|DT_ALLOW_WILD,
842 DT_IPADDRESS|DT_ALLOW_WILD,
843 DT_CHARPTR, DT_INTEGER, DT_INTEGER, DT_INTEGER,
844 DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER,
845 DT_NOSPACES, DT_NOSPACES, DT_INTEGER, DT_INTEGER, DT_CHARPTR},
846 InitConnect, DoConnect, DoneConnect},
849 {"server", "silent", NULL},
851 {DT_HOSTNAME, DT_BOOLEAN},
852 InitULine,DoULine,DoneULine},
855 {"chan", "limit", NULL},
857 {DT_CHARPTR, DT_INTEGER},
858 InitMaxBans, DoMaxBans, DoneMaxBans},
864 InitModule, DoModule, DoneModule},
867 {"reason", "ipmask", NULL},
868 {"No reason", "", NULL},
869 {DT_CHARPTR, DT_IPADDRESS|DT_ALLOW_WILD},
870 InitXLine, DoZLine, DoneConfItem},
873 {"reason", "nick", NULL},
874 {"No reason", "", NULL},
875 {DT_CHARPTR, DT_CHARPTR},
876 InitXLine, DoQLine, DoneConfItem},
879 {"reason", "host", NULL},
880 {"No reason", "", NULL},
881 {DT_CHARPTR, DT_CHARPTR},
882 InitXLine, DoKLine, DoneConfItem},
885 {"reason", "host", NULL},
886 {"No reason", "", NULL},
887 {DT_CHARPTR, DT_CHARPTR},
888 InitXLine, DoELine, DoneELine},
891 {"name", "classes", NULL},
893 {DT_NOSPACES, DT_CHARPTR},
894 InitTypes, DoType, DoneClassesAndTypes},
897 {"name", "commands", "usermodes", "chanmodes", NULL},
898 {"", "", "", "", NULL},
899 {DT_NOSPACES, DT_CHARPTR, DT_CHARPTR, DT_CHARPTR},
900 InitClasses, DoClass, DoneClassesAndTypes},
909 /* Load and parse the config file, if there are any errors then explode */
911 /* Make a copy here so if it fails then we can carry on running with an unaffected config */
914 if (this->DoInclude(newconfig, ServerInstance->ConfigFileName, errstr))
916 /* If we succeeded, set the ircd config to the new one */
917 ServerInstance->Threads->Mutex(true);
918 this->config_data = newconfig;
919 ServerInstance->Threads->Mutex(false);
923 ReportConfigError(errstr.str(), bail, user);
927 /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
930 /* Check we dont have more than one of singular tags, or any of them missing
932 for (int Index = 0; Once[Index]; Index++)
933 if (!CheckOnce(Once[Index]))
936 /* Read the values of all the tags which occur once or not at all, and call their callbacks.
938 for (int Index = 0; Values[Index].tag; Index++)
941 int dt = Values[Index].datatype;
942 bool allow_newlines = ((dt & DT_ALLOW_NEWLINE) > 0);
943 bool allow_wild = ((dt & DT_ALLOW_WILD) > 0);
944 bool bootonly = ((dt & DT_BOOTONLY) > 0);
945 dt &= ~DT_ALLOW_NEWLINE;
946 dt &= ~DT_ALLOW_WILD;
949 /* Silently ignore boot only values */
950 if (bootonly && !bail)
953 ConfValue(this->config_data, Values[Index].tag, Values[Index].value, Values[Index].default_value, 0, item, MAXBUF, allow_newlines);
956 if (!Values[Index].validation_function(this, Values[Index].tag, Values[Index].value, vi))
957 throw CoreException("One or more values in your configuration file failed to validate. Please see your ircd.log for more information.");
959 ServerInstance->Threads->Mutex(true);
964 ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
965 this->ValidateNoSpaces(vi.GetString(), Values[Index].tag, Values[Index].value);
966 vcc->Set(vi.GetString(), strlen(vi.GetString()) + 1);
971 ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
972 this->ValidateHostname(vi.GetString(), Values[Index].tag, Values[Index].value);
973 vcc->Set(vi.GetString(), strlen(vi.GetString()) + 1);
974 ServerInstance->Logs->Log("CONFIG",DEFAULT,"Got %s", vi.GetString());
979 ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
980 this->ValidateIP(vi.GetString(), Values[Index].tag, Values[Index].value, allow_wild);
981 vcc->Set(vi.GetString(), strlen(vi.GetString()) + 1);
986 ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
987 if (*(vi.GetString()) && !ServerInstance->IsChannel(vi.GetString()))
989 ServerInstance->Threads->Mutex(false);
990 throw CoreException("The value of <"+std::string(Values[Index].tag)+":"+Values[Index].value+"> is not a valid channel name");
992 vcc->Set(vi.GetString(), strlen(vi.GetString()) + 1);
997 ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
998 /* Make sure we also copy the null terminator */
999 vcc->Set(vi.GetString(), strlen(vi.GetString()) + 1);
1004 int val = vi.GetInteger();
1005 ValueContainerInt* vci = (ValueContainerInt*)Values[Index].val;
1006 vci->Set(&val, sizeof(int));
1011 bool val = vi.GetBool();
1012 ValueContainerBool* vcb = (ValueContainerBool*)Values[Index].val;
1013 vcb->Set(&val, sizeof(bool));
1017 /* You don't want to know what happens if someones bad code sends us here. */
1020 /* We're done with this now */
1021 delete Values[Index].val;
1022 ServerInstance->Threads->Mutex(false);
1025 /* Read the multiple-tag items (class tags, connect tags, etc)
1026 * and call the callbacks associated with them. We have three
1027 * callbacks for these, a 'start', 'item' and 'end' callback.
1029 for (int Index = 0; MultiValues[Index].tag; Index++)
1031 ServerInstance->Threads->Mutex(true);
1032 MultiValues[Index].init_function(this, MultiValues[Index].tag);
1033 ServerInstance->Threads->Mutex(false);
1035 int number_of_tags = ConfValueEnum(this->config_data, MultiValues[Index].tag);
1037 for (int tagnum = 0; tagnum < number_of_tags; tagnum++)
1040 for (int valuenum = 0; MultiValues[Index].items[valuenum]; valuenum++)
1042 int dt = MultiValues[Index].datatype[valuenum];
1043 bool allow_newlines = ((dt & DT_ALLOW_NEWLINE) > 0);
1044 bool allow_wild = ((dt & DT_ALLOW_WILD) > 0);
1045 dt &= ~DT_ALLOW_NEWLINE;
1046 dt &= ~DT_ALLOW_WILD;
1048 ServerInstance->Threads->Mutex(true);
1049 /* We catch and rethrow any exception here just so we can free our mutex
1058 if (ConfValue(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1059 vl.push_back(ValueItem(item));
1061 vl.push_back(ValueItem(""));
1062 this->ValidateNoSpaces(vl[vl.size()-1].GetString(), MultiValues[Index].tag, MultiValues[Index].items[valuenum]);
1068 if (ConfValue(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1069 vl.push_back(ValueItem(item));
1071 vl.push_back(ValueItem(""));
1072 this->ValidateHostname(vl[vl.size()-1].GetString(), MultiValues[Index].tag, MultiValues[Index].items[valuenum]);
1078 if (ConfValue(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1079 vl.push_back(ValueItem(item));
1081 vl.push_back(ValueItem(""));
1082 this->ValidateIP(vl[vl.size()-1].GetString(), MultiValues[Index].tag, MultiValues[Index].items[valuenum], allow_wild);
1088 if (ConfValue(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
1089 vl.push_back(ValueItem(item));
1091 vl.push_back(ValueItem(""));
1092 if (!ServerInstance->IsChannel(vl[vl.size()-1].GetString()))
1093 throw CoreException("The value of <"+std::string(MultiValues[Index].tag)+":"+MultiValues[Index].items[valuenum]+"> number "+ConvToStr(tagnum + 1)+" is not a valid channel name");
1099 if (ConfValue(this->config_data, 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(""));
1108 if (ConfValueInteger(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item))
1109 vl.push_back(ValueItem(item));
1111 vl.push_back(ValueItem(0));
1116 bool item = ConfValueBool(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum);
1117 vl.push_back(ValueItem(item));
1121 /* Someone was smoking craq if we got here, and we're all gonna die. */
1125 catch (CoreException &e)
1127 ServerInstance->Threads->Mutex(false);
1130 ServerInstance->Threads->Mutex(false);
1132 MultiValues[Index].validation_function(this, MultiValues[Index].tag, (char**)MultiValues[Index].items, vl, MultiValues[Index].datatype);
1134 MultiValues[Index].finish_function(this, MultiValues[Index].tag);
1139 catch (CoreException &ce)
1141 ReportConfigError(ce.GetReason(), bail, user);
1145 // write once here, to try it out and make sure its ok
1146 ServerInstance->WritePID(this->PID);
1148 /* Switch over logfiles */
1149 ServerInstance->Logs->CloseLogs();
1150 ServerInstance->Logs->OpenFileLogs();
1152 ServerInstance->Logs->Log("CONFIG", DEFAULT, "Done reading configuration file.");
1154 /* If we're rehashing, let's load any new modules, and unload old ones
1158 int found_ports = 0;
1160 ServerInstance->BindPorts(false, found_ports, pl);
1162 if (pl.size() && user)
1164 ServerInstance->Threads->Mutex(true);
1165 user->WriteServ("NOTICE %s :*** Not all your client ports could be bound.", user->nick);
1166 user->WriteServ("NOTICE %s :*** The following port(s) failed to bind:", user->nick);
1168 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
1170 user->WriteServ("NOTICE %s :*** %d. IP: %s Port: %lu", user->nick, j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
1172 ServerInstance->Threads->Mutex(false);
1175 ServerInstance->Threads->Mutex(true);
1176 if (!removed_modules.empty())
1178 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
1180 if (ServerInstance->Modules->Unload(removing->c_str()))
1182 ServerInstance->SNO->WriteToSnoMask('A', "*** REHASH UNLOADED MODULE: %s",removing->c_str());
1185 user->WriteNumeric(973, "%s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
1192 user->WriteNumeric(972, "%s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->Modules->LastError().c_str());
1197 if (!added_modules.empty())
1199 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
1201 if (ServerInstance->Modules->Load(adding->c_str()))
1203 ServerInstance->SNO->WriteToSnoMask('A', "*** REHASH LOADED MODULE: %s",adding->c_str());
1206 user->WriteNumeric(975, "%s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
1213 user->WriteNumeric(974, "%s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->Modules->LastError().c_str());
1218 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());
1220 ServerInstance->Threads->Mutex(false);
1224 /** Note: This is safe, the method checks for user == NULL */
1225 ServerInstance->Threads->Mutex(true);
1226 ServerInstance->Parser->SetupCommandTable(user);
1227 ServerInstance->Threads->Mutex(false);
1230 user->WriteServ("NOTICE %s :*** Successfully rehashed server.", user->nick);
1232 ServerInstance->SNO->WriteToSnoMask('A', "*** Successfully rehashed server.");
1237 bool ServerConfig::LoadConf(ConfigDataHash &target, FILE* &conf, const char* filename, std::ostringstream &errorstream)
1245 int character_count = 0;
1252 ServerInstance->Logs->Log("CONFIG", DEBUG, "Reading %s", filename);
1254 /* Check if the file open failed first */
1257 errorstream << "LoadConf: Couldn't open config file: " << filename << std::endl;
1261 for (unsigned int t = 0; t < include_stack.size(); t++)
1263 if (std::string(filename) == include_stack[t])
1265 errorstream << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
1270 /* It's not already included, add it to the list of files we've loaded */
1271 include_stack.push_back(filename);
1273 /* Start reading characters... */
1278 * Fix for moronic windows issue spotted by Adremelech.
1279 * Some windows editors save text files as utf-16, which is
1280 * a total pain in the ass to parse. Users should save in the
1281 * right config format! If we ever see a file where the first
1282 * byte is 0xFF or 0xFE, or the second is 0xFF or 0xFE, then
1283 * this is most likely a utf-16 file. Bail out and insult user.
1285 if ((character_count++ < 2) && (ch == '\xFF' || ch == '\xFE'))
1287 errorstream << "File " << filename << " cannot be read, as it is encoded in braindead UTF-16. Save your file as plain ASCII!" << std::endl;
1292 * Here we try and get individual tags on separate lines,
1293 * this would be so easy if we just made people format
1294 * their config files like that, but they don't so...
1295 * We check for a '<' and then know the line is over when
1296 * we get a '>' not inside quotes. If we find two '<' and
1297 * no '>' then die with an error.
1300 if ((ch == '#') && !in_quote)
1321 /* XXX: Added by Brain, May 1st 2006 - Escaping of characters.
1322 * Note that this WILL NOT usually allow insertion of newlines,
1323 * because a newline is two characters long. Use it primarily to
1324 * insert the " symbol.
1326 * Note that this also involves a further check when parsing the line,
1327 * which can be found below.
1329 if ((ch == '\\') && (in_quote) && (in_tag))
1332 char real_character;
1335 real_character = fgetc(conf);
1336 if (real_character == 'n')
1337 real_character = '\n';
1338 line += real_character;
1343 errorstream << "End of file after a \\, what did you want to escape?: " << filename << ":" << linenumber << std::endl;
1357 errorstream << "Got another opening < when the first one wasn't closed: " << filename << ":" << linenumber << std::endl;
1365 errorstream << "We're in a quote but outside a tag, interesting. " << filename << ":" << linenumber << std::endl;
1370 // errorstream << "Opening new config tag on line " << linenumber << std::endl;
1381 // errorstream << "Closing quote in config tag on line " << linenumber << std::endl;
1386 // errorstream << "Opening quote in config tag on line " << linenumber << std::endl;
1394 errorstream << "Found a (closing) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1398 errorstream << "Found a (opening) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1407 // errorstream << "Closing config tag on line " << linenumber << std::endl;
1411 * If this finds an <include> then ParseLine can simply call
1412 * LoadConf() and load the included config into the same ConfigDataHash
1415 if (!this->ParseLine(target, line, linenumber, errorstream))
1422 errorstream << "Got a closing > when we weren't inside a tag: " << filename << ":" << linenumber << std::endl;
1429 /* 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 */
1430 if (in_comment || in_quote)
1432 errorstream << "Reached end of file whilst still inside a quoted section or tag. This is most likely an error or there \
1433 is a newline missing from the end of the file: " << filename << ":" << linenumber << std::endl;
1440 bool ServerConfig::LoadConf(ConfigDataHash &target, FILE* &conf, const std::string &filename, std::ostringstream &errorstream)
1442 return this->LoadConf(target, conf, filename.c_str(), errorstream);
1445 bool ServerConfig::ParseLine(ConfigDataHash &target, std::string &line, long &linenumber, std::ostringstream &errorstream)
1447 std::string tagname;
1448 std::string current_key;
1449 std::string current_value;
1455 got_name = got_key = in_quote = false;
1457 for(std::string::iterator c = line.begin(); c != line.end(); c++)
1461 /* We don't know the tag name yet. */
1472 /* We got to a space, we should have the tagname now. */
1473 if(tagname.length())
1481 /* We have the tag name */
1484 /* We're still reading the key name */
1494 /* We got an '=', end of the key name. */
1500 /* We have the key name, now we're looking for quotes and the value */
1502 /* Correctly handle escaped characters here.
1503 * See the XXX'ed section above.
1505 if ((*c == '\\') && (in_quote))
1509 current_value += '\n';
1511 current_value += *c;
1514 else if ((*c == '\n') && (in_quote))
1516 /* Got a 'real' \n, treat it as part of the value */
1517 current_value += '\n';
1521 else if ((*c == '\r') && (in_quote))
1522 /* Got a \r, drop it */
1529 /* We're not already in a quote. */
1534 /* Leaving the quotes, we have the current value */
1535 results.push_back(KeyVal(current_key, current_value));
1537 // std::cout << "<" << tagname << ":" << current_key << "> " << current_value << std::endl;
1542 if ((tagname == "include") && (current_key == "file"))
1544 if (!this->DoInclude(target, current_value, errorstream))
1547 else if ((tagname == "include") && (current_key == "executable"))
1549 /* Pipe an executable and use its stdout as config data */
1550 if (!this->DoPipe(target, current_value, errorstream))
1554 current_key.clear();
1555 current_value.clear();
1562 current_value += *c;
1569 /* Finished parsing the tag, add it to the config hash */
1570 target.insert(std::pair<std::string, KeyValList > (tagname, results));
1575 bool ServerConfig::DoPipe(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream)
1577 FILE* conf = popen(file.c_str(), "r");
1582 ret = LoadConf(target, conf, file.c_str(), errorstream);
1586 errorstream << "Couldn't execute: " << file << std::endl;
1591 bool ServerConfig::DoInclude(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream)
1593 std::string confpath;
1594 std::string newfile;
1595 std::string::size_type pos;
1597 confpath = ServerInstance->ConfigFileName;
1600 std::replace(newfile.begin(),newfile.end(),'\\','/');
1601 std::replace(confpath.begin(),confpath.end(),'\\','/');
1603 if ((newfile[0] != '/') && (newfile.find("://") == std::string::npos))
1605 if((pos = confpath.rfind("/")) != std::string::npos)
1607 /* Leaves us with just the path */
1608 newfile = confpath.substr(0, pos) + std::string("/") + newfile;
1612 errorstream << "Couldn't get config path from: " << ServerInstance->ConfigFileName << std::endl;
1617 FILE* conf = fopen(newfile.c_str(), "r");
1622 ret = LoadConf(target, conf, newfile, errorstream);
1626 errorstream << "Couldn't open config file: " << file << std::endl;
1631 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, int index, char* result, int length, bool allow_linefeeds)
1633 return ConfValue(target, tag, var, "", index, result, length, allow_linefeeds);
1636 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index, char* result, int length, bool allow_linefeeds)
1639 bool r = ConfValue(target, std::string(tag), std::string(var), std::string(default_value), index, value, allow_linefeeds);
1640 strlcpy(result, value.c_str(), length);
1644 bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, std::string &result, bool allow_linefeeds)
1646 return ConfValue(target, tag, var, "", index, result, allow_linefeeds);
1649 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)
1651 ConfigDataHash::size_type pos = index;
1652 if (pos < target.count(tag))
1654 ConfigDataHash::iterator iter = target.find(tag);
1656 for(int i = 0; i < index; i++)
1659 for(KeyValList::iterator j = iter->second.begin(); j != iter->second.end(); j++)
1663 if ((!allow_linefeeds) && (j->second.find('\n') != std::string::npos))
1665 ServerInstance->Logs->Log("CONFIG",DEFAULT, "Value of <" + tag + ":" + var+ "> contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
1666 for (std::string::iterator n = j->second.begin(); n != j->second.end(); n++)
1677 if (!default_value.empty())
1679 result = default_value;
1685 if (!default_value.empty())
1687 result = default_value;
1694 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, int index, int &result)
1696 return ConfValueInteger(target, std::string(tag), std::string(var), "", index, result);
1699 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index, int &result)
1701 return ConfValueInteger(target, std::string(tag), std::string(var), std::string(default_value), index, result);
1704 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, int &result)
1706 return ConfValueInteger(target, tag, var, "", index, result);
1709 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index, int &result)
1712 std::istringstream stream;
1713 bool r = ConfValue(target, tag, var, default_value, index, value);
1715 if(!(stream >> result))
1721 if (value.substr(0,2) == "0x")
1726 result = strtol(value.c_str(), &endptr, 16);
1728 /* No digits found */
1729 if (endptr == value.c_str())
1734 char denominator = *(value.end() - 1);
1735 switch (toupper(denominator))
1738 /* Kilobytes -> bytes */
1739 result = result * 1024;
1742 /* Megabytes -> bytes */
1743 result = result * 1024 * 1024;
1746 /* Gigabytes -> bytes */
1747 result = result * 1024 * 1024 * 1024;
1757 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, int index)
1759 return ConfValueBool(target, std::string(tag), std::string(var), "", index);
1762 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index)
1764 return ConfValueBool(target, std::string(tag), std::string(var), std::string(default_value), index);
1767 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, int index)
1769 return ConfValueBool(target, tag, var, "", index);
1772 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index)
1775 if(!ConfValue(target, tag, var, default_value, index, result))
1778 return ((result == "yes") || (result == "true") || (result == "1"));
1781 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const char* tag)
1783 return target.count(tag);
1786 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const std::string &tag)
1788 return target.count(tag);
1791 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const char* tag, int index)
1793 return ConfVarEnum(target, std::string(tag), index);
1796 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const std::string &tag, int index)
1798 ConfigDataHash::size_type pos = index;
1800 if (pos < target.count(tag))
1802 ConfigDataHash::const_iterator iter = target.find(tag);
1804 for(int i = 0; i < index; i++)
1807 return iter->second.size();
1813 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1815 bool ServerConfig::ReadFile(file_cache &F, const char* fname)
1817 if (!fname || !*fname)
1821 char linebuf[MAXBUF];
1825 if ((*fname != '/') && (*fname != '\\'))
1827 std::string::size_type pos;
1828 std::string confpath = ServerInstance->ConfigFileName;
1829 std::string newfile = fname;
1831 if ((pos = confpath.rfind("/")) != std::string::npos)
1832 newfile = confpath.substr(0, pos) + std::string("/") + fname;
1833 else if ((pos = confpath.rfind("\\")) != std::string::npos)
1834 newfile = confpath.substr(0, pos) + std::string("\\") + fname;
1836 if (!FileExists(newfile.c_str()))
1838 file = fopen(newfile.c_str(), "r");
1842 if (!FileExists(fname))
1844 file = fopen(fname, "r");
1851 if (fgets(linebuf, sizeof(linebuf), file))
1852 linebuf[strlen(linebuf)-1] = 0;
1858 F.push_back(*linebuf ? linebuf : " ");
1870 bool ServerConfig::FileExists(const char* file)
1873 if (stat(file, &sb) == -1)
1876 if ((sb.st_mode & S_IFDIR) > 0)
1880 if ((input = fopen (file, "r")) == NULL)
1889 char* ServerConfig::CleanFilename(char* name)
1891 char* p = name + strlen(name);
1892 while ((p != name) && (*p != '/') && (*p != '\\')) p--;
1893 return (p != name ? ++p : p);
1897 bool ServerConfig::DirValid(const char* dirandfile)
1905 char otherdir[1024];
1908 strlcpy(work, dirandfile, 1024);
1911 // we just want the dir
1923 // Get the current working directory
1924 if (getcwd(buffer, 1024 ) == NULL )
1927 if (chdir(work) == -1)
1930 if (getcwd(otherdir, 1024 ) == NULL )
1933 if (chdir(buffer) == -1)
1936 size_t t = strlen(work);
1938 if (strlen(otherdir) >= t)
1941 if (!strcmp(otherdir,work))
1954 std::string ServerConfig::GetFullProgDir()
1956 char buffer[PATH_MAX+1];
1958 /* Windows has specific api calls to get the exe path that never fail.
1959 * For once, windows has something of use, compared to the POSIX code
1960 * for this, this is positively neato.
1962 if (GetModuleFileName(NULL, buffer, MAX_PATH))
1964 std::string fullpath = buffer;
1965 std::string::size_type n = fullpath.rfind("\\inspircd.exe");
1966 return std::string(fullpath, 0, n);
1969 // Get the current working directory
1970 if (getcwd(buffer, PATH_MAX))
1972 std::string remainder = this->argv[0];
1974 /* Does argv[0] start with /? its a full path, use it */
1975 if (remainder[0] == '/')
1977 std::string::size_type n = remainder.rfind("/inspircd");
1978 return std::string(remainder, 0, n);
1981 std::string fullpath = std::string(buffer) + "/" + remainder;
1982 std::string::size_type n = fullpath.rfind("/inspircd");
1983 return std::string(fullpath, 0, n);
1989 InspIRCd* ServerConfig::GetInstance()
1991 return ServerInstance;
1994 std::string ServerConfig::GetSID()
1999 ValueItem::ValueItem(int value)
2001 std::stringstream n;
2006 ValueItem::ValueItem(bool value)
2008 std::stringstream n;
2013 ValueItem::ValueItem(const char* value)
2018 void ValueItem::Set(const char* value)
2023 void ValueItem::Set(int value)
2025 std::stringstream n;
2030 int ValueItem::GetInteger()
2034 return atoi(v.c_str());
2037 char* ValueItem::GetString()
2039 return (char*)v.c_str();
2042 bool ValueItem::GetBool()
2044 return (GetInteger() || v == "yes" || v == "true");
2051 * XXX should this be in a class? -- w00t
2053 bool InitTypes(ServerConfig* conf, const char*)
2055 if (conf->opertypes.size())
2057 for (opertype_t::iterator n = conf->opertypes.begin(); n != conf->opertypes.end(); n++)
2064 conf->opertypes.clear();
2069 * XXX should this be in a class? -- w00t
2071 bool InitClasses(ServerConfig* conf, const char*)
2073 if (conf->operclass.size())
2075 for (operclass_t::iterator n = conf->operclass.begin(); n != conf->operclass.end(); n++)
2077 if (n->second.commandlist)
2078 delete[] n->second.commandlist;
2079 if (n->second.cmodelist)
2080 delete[] n->second.cmodelist;
2081 if (n->second.umodelist)
2082 delete[] n->second.umodelist;
2086 conf->operclass.clear();
2091 * XXX should this be in a class? -- w00t
2093 bool DoType(ServerConfig* conf, const char*, char**, ValueList &values, int*)
2095 const char* TypeName = values[0].GetString();
2096 const char* Classes = values[1].GetString();
2098 conf->opertypes[TypeName] = strnewdup(Classes);
2103 * XXX should this be in a class? -- w00t
2105 bool DoClass(ServerConfig* conf, const char* tag, char**, ValueList &values, int*)
2107 const char* ClassName = values[0].GetString();
2108 const char* CommandList = values[1].GetString();
2109 const char* UModeList = values[2].GetString();
2110 const char* CModeList = values[3].GetString();
2112 for (const char* c = UModeList; *c; ++c)
2114 if ((*c < 'A' || *c > 'z') && *c != '*')
2116 throw CoreException("Character " + std::string(1, *c) + " is not a valid mode in <class:usermodes>");
2119 for (const char* c = CModeList; *c; ++c)
2121 if ((*c < 'A' || *c > 'z') && *c != '*')
2123 throw CoreException("Character " + std::string(1, *c) + " is not a valid mode in <class:chanmodes>");
2127 conf->operclass[ClassName].commandlist = strnewdup(CommandList);
2128 conf->operclass[ClassName].umodelist = strnewdup(UModeList);
2129 conf->operclass[ClassName].cmodelist = strnewdup(CModeList);
2134 * XXX should this be in a class? -- w00t
2136 bool DoneClassesAndTypes(ServerConfig*, const char*)
2143 bool InitXLine(ServerConfig* conf, const char* tag)
2148 bool DoZLine(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
2150 const char* reason = values[0].GetString();
2151 const char* ipmask = values[1].GetString();
2153 ZLine* zl = new ZLine(conf->GetInstance(), conf->GetInstance()->Time(), 0, "<Config>", reason, ipmask);
2154 if (!conf->GetInstance()->XLines->AddLine(zl, NULL))
2160 bool DoQLine(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
2162 const char* reason = values[0].GetString();
2163 const char* nick = values[1].GetString();
2165 QLine* ql = new QLine(conf->GetInstance(), conf->GetInstance()->Time(), 0, "<Config>", reason, nick);
2166 if (!conf->GetInstance()->XLines->AddLine(ql, NULL))
2172 bool DoKLine(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
2174 const char* reason = values[0].GetString();
2175 const char* host = values[1].GetString();
2177 XLineManager* xlm = conf->GetInstance()->XLines;
2179 IdentHostPair ih = xlm->IdentSplit(host);
2181 KLine* kl = new KLine(conf->GetInstance(), conf->GetInstance()->Time(), 0, "<Config>", reason, ih.first.c_str(), ih.second.c_str());
2182 if (!xlm->AddLine(kl, NULL))
2187 bool DoELine(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
2189 const char* reason = values[0].GetString();
2190 const char* host = values[1].GetString();
2192 XLineManager* xlm = conf->GetInstance()->XLines;
2194 IdentHostPair ih = xlm->IdentSplit(host);
2196 ELine* el = new ELine(conf->GetInstance(), conf->GetInstance()->Time(), 0, "<Config>", reason, ih.first.c_str(), ih.second.c_str());
2197 if (!xlm->AddLine(el, NULL))
2202 // this should probably be moved to configreader, but atm it relies on CheckELines above.
2203 bool DoneELine(ServerConfig* conf, const char* tag)
2205 for (std::vector<User*>::const_iterator u2 = conf->GetInstance()->Users->local_users.begin(); u2 != conf->GetInstance()->Users->local_users.end(); u2++)
2207 User* u = (User*)(*u2);
2211 conf->GetInstance()->XLines->CheckELines();
2215 void ConfigReaderThread::Run()
2217 /* TODO: TheUser may be invalid by the time we get here! Check its validity, or pass a UID would be better */
2218 ServerInstance->Config->Read(do_bail, TheUser);
2219 ServerInstance->Threads->Mutex(true);
2220 this->SetExitFlag();
2221 ServerInstance->Threads->Mutex(false);