1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd: (C) 2002-2007 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 * ---------------------------------------------------
17 #include "exitcodes.h"
18 #include "commands/cmd_whowas.h"
20 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
22 /* Needs forward declaration */
23 bool ValidateDnsServer(ServerConfig* conf, const char* tag, const char* value, ValueItem &data);
25 ServerConfig::ServerConfig(InspIRCd* Instance) : ServerInstance(Instance)
28 *ServerName = *Network = *ServerDesc = *AdminName = '\0';
29 *HideWhoisServer = *AdminEmail = *AdminNick = *diepass = *restartpass = *FixedQuit = *HideKillsServer = '\0';
30 *DefaultModes = *CustomVersion = *motd = *rules = *PrefixQuit = *DieValue = *DNSServer = '\0';
31 *UserStats = *ModPath = *MyExecutable = *DisabledCommands = *PID = *SuffixQuit = '\0';
32 WhoWasGroupSize = WhoWasMaxGroups = WhoWasMaxKeep = 0;
34 NoUserDns = forcedebug = OperSpyWhois = nofork = HideBans = HideSplits = UndernetMsgPrefix = false;
35 CycleHosts = writelog = AllowHalfop = true;
36 dns_timeout = DieDelay = 5;
38 NetBufferSize = 10240;
39 SoftLimit = MAXCLIENTS;
47 DNSServerValidator = &ValidateDnsServer;
50 void ServerConfig::ClearStack()
52 include_stack.clear();
55 Module* ServerConfig::GetIOHook(int port)
57 std::map<int,Module*>::iterator x = IOHookModule.find(port);
58 return (x != IOHookModule.end() ? x->second : NULL);
61 Module* ServerConfig::GetIOHook(InspSocket* is)
63 std::map<InspSocket*,Module*>::iterator x = SocketIOHookModule.find(is);
64 return (x != SocketIOHookModule.end() ? x->second : NULL);
67 bool ServerConfig::AddIOHook(int port, Module* iomod)
71 IOHookModule[port] = iomod;
76 throw ModuleException("Port already hooked by another module");
81 bool ServerConfig::AddIOHook(Module* iomod, InspSocket* is)
85 SocketIOHookModule[is] = iomod;
86 is->IsIOHooked = true;
91 throw ModuleException("InspSocket derived class already hooked by another module");
96 bool ServerConfig::DelIOHook(int port)
98 std::map<int,Module*>::iterator x = IOHookModule.find(port);
99 if (x != IOHookModule.end())
101 IOHookModule.erase(x);
107 bool ServerConfig::DelIOHook(InspSocket* is)
109 std::map<InspSocket*,Module*>::iterator x = SocketIOHookModule.find(is);
110 if (x != SocketIOHookModule.end())
112 SocketIOHookModule.erase(x);
118 void ServerConfig::Update005()
120 std::stringstream out(data005);
123 int token_counter = 0;
127 line5 = line5 + token + " ";
129 if (token_counter >= 13)
132 snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
133 isupport.push_back(buf);
141 snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
142 isupport.push_back(buf);
146 void ServerConfig::Send005(userrec* user)
148 for (std::vector<std::string>::iterator line = ServerInstance->Config->isupport.begin(); line != ServerInstance->Config->isupport.end(); line++)
149 user->WriteServ("005 %s %s", user->nick, line->c_str());
152 bool ServerConfig::CheckOnce(char* tag, bool bail, userrec* user)
154 int count = ConfValueEnum(this->config_data, tag);
158 throw CoreException("You have more than one <"+std::string(tag)+"> tag, this is not permitted.");
163 throw CoreException("You have not defined a <"+std::string(tag)+"> tag, this is required.");
169 bool NoValidation(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
174 bool ValidateMaxTargets(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
176 if ((data.GetInteger() < 0) || (data.GetInteger() > 31))
178 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
184 bool ValidateSoftLimit(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
186 if ((data.GetInteger() < 1) || (data.GetInteger() > MAXCLIENTS))
188 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
189 data.Set(MAXCLIENTS);
194 bool ValidateMaxConn(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
196 if (data.GetInteger() > SOMAXCONN)
197 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
201 bool InitializeDisabledCommands(const char* data, InspIRCd* ServerInstance)
203 std::stringstream dcmds(data);
206 /* Enable everything first */
207 for (command_table::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
208 x->second->Disable(false);
210 /* Now disable all the ones which the user wants disabled */
211 while (dcmds >> thiscmd)
213 command_table::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
214 if (cm != ServerInstance->Parser->cmdlist.end())
216 cm->second->Disable(true);
222 bool ValidateDnsServer(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
224 if (!*(data.GetString()))
226 std::string nameserver;
227 // attempt to look up their nameserver from /etc/resolv.conf
228 conf->GetInstance()->Log(DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
229 ifstream resolv("/etc/resolv.conf");
230 bool found_server = false;
232 if (resolv.is_open())
234 while (resolv >> nameserver)
236 if ((nameserver == "nameserver") && (!found_server))
238 resolv >> nameserver;
239 data.Set(nameserver.c_str());
241 conf->GetInstance()->Log(DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
247 conf->GetInstance()->Log(DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
248 data.Set("127.0.0.1");
253 conf->GetInstance()->Log(DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
254 data.Set("127.0.0.1");
260 bool ValidateServerName(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
262 /* If we already have a servername, and they changed it, we should throw an exception. */
263 if ((strcasecmp(conf->ServerName, data.GetString())) && (*conf->ServerName))
265 throw CoreException("Configuration error: You cannot change your servername at runtime! Please restart your server for this change to be applied.");
266 /* XXX: We don't actually reach this return of course... */
269 if (!strchr(data.GetString(),'.'))
271 conf->GetInstance()->Log(DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s%c'",data.GetString(),data.GetString(),'.');
272 std::string moo = std::string(data.GetString()).append(".");
273 data.Set(moo.c_str());
278 bool ValidateNetBufferSize(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
280 if ((!data.GetInteger()) || (data.GetInteger() > 65535) || (data.GetInteger() < 1024))
282 conf->GetInstance()->Log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
288 bool ValidateMaxWho(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
290 if ((data.GetInteger() > 65535) || (data.GetInteger() < 1))
292 conf->GetInstance()->Log(DEFAULT,"<options:maxwhoresults> size out of range, setting to default of 128.");
298 bool ValidateLogLevel(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
300 std::string dbg = data.GetString();
301 conf->LogLevel = DEFAULT;
304 conf->LogLevel = DEBUG;
305 else if (dbg == "verbose")
306 conf->LogLevel = VERBOSE;
307 else if (dbg == "default")
308 conf->LogLevel = DEFAULT;
309 else if (dbg == "sparse")
310 conf->LogLevel = SPARSE;
311 else if (dbg == "none")
312 conf->LogLevel = NONE;
314 conf->debugging = (conf->LogLevel == DEBUG);
319 bool ValidateMotd(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
321 conf->ReadFile(conf->MOTD, data.GetString());
325 bool ValidateNotEmpty(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
327 if (!*data.GetString())
328 throw CoreException(std::string("The value for ")+tag+" cannot be empty!");
332 bool ValidateRules(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
334 conf->ReadFile(conf->RULES, data.GetString());
338 bool ValidateModeLists(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
340 memset(conf->HideModeLists, 0, 256);
341 for (const unsigned char* x = (const unsigned char*)data.GetString(); *x; ++x)
342 conf->HideModeLists[*x] = true;
346 bool ValidateExemptChanOps(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
348 memset(conf->ExemptChanOps, 0, 256);
349 for (const unsigned char* x = (const unsigned char*)data.GetString(); *x; ++x)
350 conf->ExemptChanOps[*x] = true;
354 bool ValidateInvite(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
356 std::string v = data.GetString();
359 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_OPS;
361 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_ALL;
362 else if (v == "dynamic")
363 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_DYNAMIC;
365 conf->AnnounceInvites = ServerConfig::INVITE_ANNOUNCE_NONE;
370 bool ValidateSID(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
372 int sid = data.GetInteger();
373 if ((sid > 999) || (sid < 0))
377 conf->GetInstance()->Log(DEFAULT,"WARNING: Server ID is less than 0 or greater than 999. Set to %d", sid);
382 bool ValidateWhoWas(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
384 conf->WhoWasMaxKeep = conf->GetInstance()->Duration(data.GetString());
386 if (conf->WhoWasGroupSize < 0)
387 conf->WhoWasGroupSize = 0;
389 if (conf->WhoWasMaxGroups < 0)
390 conf->WhoWasMaxGroups = 0;
392 if (conf->WhoWasMaxKeep < 3600)
394 conf->WhoWasMaxKeep = 3600;
395 conf->GetInstance()->Log(DEFAULT,"WARNING: <whowas:maxkeep> value less than 3600, setting to default 3600");
398 command_t* whowas_command = conf->GetInstance()->Parser->GetHandler("WHOWAS");
401 std::deque<classbase*> params;
402 whowas_command->HandleInternal(WHOWAS_PRUNE, params);
408 /* Callback called before processing the first <connect> tag
410 bool InitConnect(ServerConfig* conf, const char* tag)
412 conf->GetInstance()->Log(DEFAULT,"Reading connect classes...");
413 conf->Classes.clear();
417 /* Callback called to process a single <connect> tag
419 bool DoConnect(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
422 const char* allow = values[0].GetString(); /* Yeah, there are a lot of values. Live with it. */
423 const char* deny = values[1].GetString();
424 const char* password = values[2].GetString();
425 int timeout = values[3].GetInteger();
426 int pingfreq = values[4].GetInteger();
427 int flood = values[5].GetInteger();
428 int threshold = values[6].GetInteger();
429 int sendq = values[7].GetInteger();
430 int recvq = values[8].GetInteger();
431 int localmax = values[9].GetInteger();
432 int globalmax = values[10].GetInteger();
433 int port = values[11].GetInteger();
434 const char* name = values[12].GetString();
435 const char* parent = values[13].GetString();
436 int maxchans = values[14].GetInteger();
440 /* Find 'parent' and inherit a new class from it,
441 * then overwrite any values that are set here
443 for (ClassVector::iterator item = conf->Classes.begin(); item != conf->Classes.end(); ++item)
445 if (item->GetName() == parent)
447 ConnectClass c(name, *item);
448 c.Update(timeout, flood, *allow ? allow : deny, pingfreq, password, threshold, sendq, recvq, localmax, globalmax, maxchans, port);
449 conf->Classes.push_back(c);
452 throw CoreException("Class name '" + std::string(name) + "' is configured to inherit from class '" + std::string(parent) + "' which cannot be found.");
458 ConnectClass c(name, timeout, flood, allow, pingfreq, password, threshold, sendq, recvq, localmax, globalmax, maxchans);
460 conf->Classes.push_back(c);
464 ConnectClass c(name, deny);
466 conf->Classes.push_back(c);
473 /* Callback called when there are no more <connect> tags
475 bool DoneConnect(ServerConfig* conf, const char* tag)
480 /* Callback called before processing the first <uline> tag
482 bool InitULine(ServerConfig* conf, const char* tag)
484 conf->ulines.clear();
488 /* Callback called to process a single <uline> tag
490 bool DoULine(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
492 const char* server = values[0].GetString();
493 const bool silent = values[1].GetBool();
494 conf->ulines[server] = silent;
498 /* Callback called when there are no more <uline> tags
500 bool DoneULine(ServerConfig* conf, const char* tag)
505 /* Callback called before processing the first <module> tag
507 bool InitModule(ServerConfig* conf, const char* tag)
509 old_module_names.clear();
510 new_module_names.clear();
511 added_modules.clear();
512 removed_modules.clear();
513 for (std::vector<std::string>::iterator t = conf->module_names.begin(); t != conf->module_names.end(); t++)
515 old_module_names.push_back(*t);
520 /* Callback called to process a single <module> tag
522 bool DoModule(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
524 const char* modname = values[0].GetString();
525 new_module_names.push_back(modname);
529 /* Callback called when there are no more <module> tags
531 bool DoneModule(ServerConfig* conf, const char* tag)
533 // now create a list of new modules that are due to be loaded
534 // and a seperate list of modules which are due to be unloaded
535 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
539 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
546 added_modules.push_back(*_new);
549 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
552 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
559 removed_modules.push_back(*oldm);
564 /* Callback called before processing the first <banlist> tag
566 bool InitMaxBans(ServerConfig* conf, const char* tag)
568 conf->maxbans.clear();
572 /* Callback called to process a single <banlist> tag
574 bool DoMaxBans(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
576 const char* channel = values[0].GetString();
577 int limit = values[1].GetInteger();
578 conf->maxbans[channel] = limit;
582 /* Callback called when there are no more <banlist> tags.
584 bool DoneMaxBans(ServerConfig* conf, const char* tag)
589 void ServerConfig::ReportConfigError(const std::string &errormessage, bool bail, userrec* user)
591 ServerInstance->Log(DEFAULT, "There were errors in your configuration file: %s", errormessage.c_str());
594 /* Unneeded because of the ServerInstance->Log() aboive? */
595 printf("There were errors in your configuration:\n%s\n\n",errormessage.c_str());
596 ServerInstance->Exit(EXIT_STATUS_CONFIG);
600 std::string errors = errormessage;
601 std::string::size_type start;
602 unsigned int prefixlen;
604 /* ":ServerInstance->Config->ServerName NOTICE user->nick :" */
607 prefixlen = strlen(this->ServerName) + strlen(user->nick) + 11;
608 user->WriteServ("NOTICE %s :There were errors in the configuration file:",user->nick);
609 while (start < errors.length())
611 user->WriteServ("NOTICE %s :%s",user->nick, errors.substr(start, 510 - prefixlen).c_str());
612 start += 510 - prefixlen;
617 ServerInstance->WriteOpers("There were errors in the configuration file:");
618 while (start < errors.length())
620 ServerInstance->WriteOpers(errors.substr(start, 360).c_str());
628 void ServerConfig::Read(bool bail, userrec* user)
630 static char debug[MAXBUF]; /* Temporary buffer for debugging value */
631 static char maxkeep[MAXBUF]; /* Temporary buffer for WhoWasMaxKeep value */
632 static char hidemodes[MAXBUF]; /* Modes to not allow listing from users below halfop */
633 static char exemptchanops[MAXBUF]; /* Exempt channel ops from these modes */
634 static char announceinvites[MAXBUF]; /* options:announceinvites setting */
635 int rem = 0, add = 0; /* Number of modules added, number of modules removed */
636 std::ostringstream errstr; /* String stream containing the error output */
638 /* These tags MUST occur and must ONLY occur once in the config file */
639 static char* Once[] = { "server", "admin", "files", "power", "options", NULL };
641 /* These tags can occur ONCE or not at all */
642 InitialConfig Values[] = {
643 {"options", "softlimit", MAXCLIENTS_S, new ValueContainerUInt (&this->SoftLimit), DT_INTEGER, ValidateSoftLimit},
644 {"options", "somaxconn", SOMAXCONN_S, new ValueContainerInt (&this->MaxConn), DT_INTEGER, ValidateMaxConn},
645 {"options", "moronbanner", "Youre banned!", new ValueContainerChar (this->MoronBanner), DT_CHARPTR, NoValidation},
646 {"server", "name", "", new ValueContainerChar (this->ServerName), DT_CHARPTR, ValidateServerName},
647 {"server", "description", "Configure Me", new ValueContainerChar (this->ServerDesc), DT_CHARPTR, NoValidation},
648 {"server", "network", "Network", new ValueContainerChar (this->Network), DT_CHARPTR, NoValidation},
649 {"server", "id", "0", new ValueContainerInt (&this->sid), DT_INTEGER, ValidateSID},
650 {"admin", "name", "", new ValueContainerChar (this->AdminName), DT_CHARPTR, NoValidation},
651 {"admin", "email", "Mis@configu.red", new ValueContainerChar (this->AdminEmail), DT_CHARPTR, NoValidation},
652 {"admin", "nick", "Misconfigured", new ValueContainerChar (this->AdminNick), DT_CHARPTR, NoValidation},
653 {"files", "motd", "", new ValueContainerChar (this->motd), DT_CHARPTR, ValidateMotd},
654 {"files", "rules", "", new ValueContainerChar (this->rules), DT_CHARPTR, ValidateRules},
655 {"power", "diepass", "", new ValueContainerChar (this->diepass), DT_CHARPTR, ValidateNotEmpty},
656 {"power", "pause", "", new ValueContainerInt (&this->DieDelay), DT_INTEGER, NoValidation},
657 {"power", "restartpass", "", new ValueContainerChar (this->restartpass), DT_CHARPTR, ValidateNotEmpty},
658 {"options", "prefixquit", "", new ValueContainerChar (this->PrefixQuit), DT_CHARPTR, NoValidation},
659 {"options", "suffixquit", "", new ValueContainerChar (this->SuffixQuit), DT_CHARPTR, NoValidation},
660 {"options", "fixedquit", "", new ValueContainerChar (this->FixedQuit), DT_CHARPTR, NoValidation},
661 {"options", "loglevel", "default", new ValueContainerChar (debug), DT_CHARPTR, ValidateLogLevel},
662 {"options", "netbuffersize","10240", new ValueContainerInt (&this->NetBufferSize), DT_INTEGER, ValidateNetBufferSize},
663 {"options", "maxwho", "128", new ValueContainerInt (&this->MaxWhoResults), DT_INTEGER, ValidateMaxWho},
664 {"options", "allowhalfop", "0", new ValueContainerBool (&this->AllowHalfop), DT_BOOLEAN, NoValidation},
665 {"dns", "server", "", new ValueContainerChar (this->DNSServer), DT_CHARPTR, DNSServerValidator},
666 {"dns", "timeout", "5", new ValueContainerInt (&this->dns_timeout), DT_INTEGER, NoValidation},
667 {"options", "moduledir", MOD_PATH, new ValueContainerChar (this->ModPath), DT_CHARPTR, NoValidation},
668 {"disabled", "commands", "", new ValueContainerChar (this->DisabledCommands), DT_CHARPTR, NoValidation},
669 {"options", "userstats", "", new ValueContainerChar (this->UserStats), DT_CHARPTR, NoValidation},
670 {"options", "customversion","", new ValueContainerChar (this->CustomVersion), DT_CHARPTR, NoValidation},
671 {"options", "hidesplits", "0", new ValueContainerBool (&this->HideSplits), DT_BOOLEAN, NoValidation},
672 {"options", "hidebans", "0", new ValueContainerBool (&this->HideBans), DT_BOOLEAN, NoValidation},
673 {"options", "hidewhois", "", new ValueContainerChar (this->HideWhoisServer), DT_CHARPTR, NoValidation},
674 {"options", "hidekills", "", new ValueContainerChar (this->HideKillsServer), DT_CHARPTR, NoValidation},
675 {"options", "operspywhois", "0", new ValueContainerBool (&this->OperSpyWhois), DT_BOOLEAN, NoValidation},
676 {"options", "nouserdns", "0", new ValueContainerBool (&this->NoUserDns), DT_BOOLEAN, NoValidation},
677 {"options", "syntaxhints", "0", new ValueContainerBool (&this->SyntaxHints), DT_BOOLEAN, NoValidation},
678 {"options", "cyclehosts", "0", new ValueContainerBool (&this->CycleHosts), DT_BOOLEAN, NoValidation},
679 {"options", "ircumsgprefix","0", new ValueContainerBool (&this->UndernetMsgPrefix), DT_BOOLEAN, NoValidation},
680 {"options", "announceinvites", "1", new ValueContainerChar (announceinvites), DT_CHARPTR, ValidateInvite},
681 {"options", "hostintopic", "1", new ValueContainerBool (&this->FullHostInTopic), DT_BOOLEAN, NoValidation},
682 {"options", "hidemodes", "", new ValueContainerChar (hidemodes), DT_CHARPTR, ValidateModeLists},
683 {"options", "exemptchanops","", new ValueContainerChar (exemptchanops), DT_CHARPTR, ValidateExemptChanOps},
684 {"options", "maxtargets", "20", new ValueContainerUInt (&this->MaxTargets), DT_INTEGER, ValidateMaxTargets},
685 {"options", "defaultmodes", "nt", new ValueContainerChar (this->DefaultModes), DT_CHARPTR, NoValidation},
686 {"pid", "file", "", new ValueContainerChar (this->PID), DT_CHARPTR, NoValidation},
687 {"whowas", "groupsize", "10", new ValueContainerInt (&this->WhoWasGroupSize), DT_INTEGER, NoValidation},
688 {"whowas", "maxgroups", "10240", new ValueContainerInt (&this->WhoWasMaxGroups), DT_INTEGER, NoValidation},
689 {"whowas", "maxkeep", "3600", new ValueContainerChar (maxkeep), DT_CHARPTR, ValidateWhoWas},
690 {"die", "value", "", new ValueContainerChar (this->DieValue), DT_CHARPTR, NoValidation},
691 {"channels", "users", "20", new ValueContainerUInt (&this->MaxChans), DT_INTEGER, NoValidation},
692 {"channels", "opers", "60", new ValueContainerUInt (&this->OperMaxChans), DT_INTEGER, NoValidation},
696 /* These tags can occur multiple times, and therefore they have special code to read them
697 * which is different to the code for reading the singular tags listed above.
699 MultiConfig MultiValues[] = {
702 {"allow", "deny", "password", "timeout", "pingfreq", "flood",
703 "threshold", "sendq", "recvq", "localmax", "globalmax", "port",
704 "name", "parent", "maxchans",
706 {"", "", "", "", "120", "",
707 "", "", "", "3", "3", "0",
710 {DT_CHARPTR, DT_CHARPTR, DT_CHARPTR, DT_INTEGER, DT_INTEGER, DT_INTEGER,
711 DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER,
712 DT_CHARPTR, DT_CHARPTR, DT_INTEGER},
713 InitConnect, DoConnect, DoneConnect},
716 {"server", "silent", NULL},
718 {DT_CHARPTR, DT_BOOLEAN},
719 InitULine,DoULine,DoneULine},
722 {"chan", "limit", NULL},
724 {DT_CHARPTR, DT_INTEGER},
725 InitMaxBans, DoMaxBans, DoneMaxBans},
731 InitModule, DoModule, DoneModule},
734 {"reason", "ipmask", NULL},
735 {"No reason", "", NULL},
736 {DT_CHARPTR, DT_CHARPTR},
737 InitXLine, DoZLine, DoneZLine},
740 {"reason", "nick", NULL},
741 {"No reason", "", NULL},
742 {DT_CHARPTR, DT_CHARPTR},
743 InitXLine, DoQLine, DoneQLine},
746 {"reason", "host", NULL},
747 {"No reason", "", NULL},
748 {DT_CHARPTR, DT_CHARPTR},
749 InitXLine, DoKLine, DoneKLine},
752 {"reason", "host", NULL},
753 {"No reason", "", NULL},
754 {DT_CHARPTR, DT_CHARPTR},
755 InitXLine, DoELine, DoneELine},
758 {"name", "classes", NULL},
760 {DT_CHARPTR, DT_CHARPTR},
761 InitTypes, DoType, DoneClassesAndTypes},
764 {"name", "commands", NULL},
766 {DT_CHARPTR, DT_CHARPTR},
767 InitClasses, DoClass, DoneClassesAndTypes},
772 include_stack.clear();
774 /* Load and parse the config file, if there are any errors then explode */
776 /* Make a copy here so if it fails then we can carry on running with an unaffected config */
777 ConfigDataHash newconfig;
779 if (this->LoadConf(newconfig, ServerInstance->ConfigFileName, errstr))
781 /* If we succeeded, set the ircd config to the new one */
782 this->config_data = newconfig;
786 ReportConfigError(errstr.str(), bail, user);
790 /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
793 /* Check we dont have more than one of singular tags, or any of them missing
795 for (int Index = 0; Once[Index]; Index++)
796 if (!CheckOnce(Once[Index], bail, user))
799 /* Read the values of all the tags which occur once or not at all, and call their callbacks.
801 for (int Index = 0; Values[Index].tag; Index++)
804 int dt = Values[Index].datatype;
805 bool allow_newlines = ((dt & DT_ALLOW_NEWLINE) > 0);
806 dt &= ~DT_ALLOW_NEWLINE;
808 ConfValue(this->config_data, Values[Index].tag, Values[Index].value, Values[Index].default_value, 0, item, MAXBUF, allow_newlines);
811 if (!Values[Index].validation_function(this, Values[Index].tag, Values[Index].value, vi))
812 throw CoreException("One or more values in your configuration file failed to validate. Please see your ircd.log for more information.");
814 switch (Values[Index].datatype)
818 ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
819 /* Make sure we also copy the null terminator */
820 vcc->Set(vi.GetString(), strlen(vi.GetString()) + 1);
825 int val = vi.GetInteger();
826 ValueContainerInt* vci = (ValueContainerInt*)Values[Index].val;
827 vci->Set(&val, sizeof(int));
832 bool val = vi.GetBool();
833 ValueContainerBool* vcb = (ValueContainerBool*)Values[Index].val;
834 vcb->Set(&val, sizeof(bool));
838 /* You don't want to know what happens if someones bad code sends us here. */
842 /* We're done with this now */
843 delete Values[Index].val;
846 /* Read the multiple-tag items (class tags, connect tags, etc)
847 * and call the callbacks associated with them. We have three
848 * callbacks for these, a 'start', 'item' and 'end' callback.
850 for (int Index = 0; MultiValues[Index].tag; Index++)
852 MultiValues[Index].init_function(this, MultiValues[Index].tag);
854 int number_of_tags = ConfValueEnum(this->config_data, MultiValues[Index].tag);
856 for (int tagnum = 0; tagnum < number_of_tags; tagnum++)
859 for (int valuenum = 0; MultiValues[Index].items[valuenum]; valuenum++)
861 int dt = MultiValues[Index].datatype[valuenum];
862 bool allow_newlines = ((dt & DT_ALLOW_NEWLINE) > 0);
863 dt &= ~DT_ALLOW_NEWLINE;
870 if (ConfValue(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
871 vl.push_back(ValueItem(item));
873 vl.push_back(ValueItem(""));
879 if (ConfValueInteger(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item))
880 vl.push_back(ValueItem(item));
882 vl.push_back(ValueItem(0));
887 bool item = ConfValueBool(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum);
888 vl.push_back(ValueItem(item));
892 /* Someone was smoking craq if we got here, and we're all gonna die. */
897 MultiValues[Index].validation_function(this, MultiValues[Index].tag, (char**)MultiValues[Index].items, vl, MultiValues[Index].datatype);
900 MultiValues[Index].finish_function(this, MultiValues[Index].tag);
905 catch (CoreException &ce)
907 ReportConfigError(ce.GetReason(), bail, user);
911 // write once here, to try it out and make sure its ok
912 ServerInstance->WritePID(this->PID);
914 ServerInstance->Log(DEFAULT,"Done reading configuration file.");
916 /* If we're rehashing, let's load any new modules, and unload old ones
922 ServerInstance->BindPorts(false, found_ports, pl);
924 if (pl.size() && user)
926 user->WriteServ("NOTICE %s :*** Not all your client ports could be bound.", user->nick);
927 user->WriteServ("NOTICE %s :*** The following port(s) failed to bind:", user->nick);
929 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
931 user->WriteServ("NOTICE %s :*** %d. IP: %s Port: %lu", user->nick, j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
935 if (!removed_modules.empty())
937 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
939 if (ServerInstance->UnloadModule(removing->c_str()))
941 ServerInstance->WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
944 user->WriteServ("973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
951 user->WriteServ("972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
956 if (!added_modules.empty())
958 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
960 if (ServerInstance->LoadModule(adding->c_str()))
962 ServerInstance->WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
965 user->WriteServ("975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
972 user->WriteServ("974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
977 ServerInstance->Log(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());
980 /** Note: This is safe, the method checks for user == NULL */
981 ServerInstance->Parser->SetupCommandTable(user);
984 user->WriteServ("NOTICE %s :*** Successfully rehashed server.", user->nick);
986 ServerInstance->WriteOpers("*** Successfully rehashed server.");
989 bool ServerConfig::LoadConf(ConfigDataHash &target, const char* filename, std::ostringstream &errorstream)
991 std::ifstream conf(filename);
998 int character_count = 0;
1005 /* Check if the file open failed first */
1008 errorstream << "LoadConf: Couldn't open config file: " << filename << std::endl;
1012 /* Fix the chmod of the file to restrict it to the current user and group */
1013 chmod(filename,0600);
1015 for (unsigned int t = 0; t < include_stack.size(); t++)
1017 if (std::string(filename) == include_stack[t])
1019 errorstream << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
1024 /* It's not already included, add it to the list of files we've loaded */
1025 include_stack.push_back(filename);
1027 /* Start reading characters... */
1028 while (conf.get(ch))
1032 * Fix for moronic windows issue spotted by Adremelech.
1033 * Some windows editors save text files as utf-16, which is
1034 * a total pain in the ass to parse. Users should save in the
1035 * right config format! If we ever see a file where the first
1036 * byte is 0xFF or 0xFE, or the second is 0xFF or 0xFE, then
1037 * this is most likely a utf-16 file. Bail out and insult user.
1039 if ((character_count++ < 2) && (ch == '\xFF' || ch == '\xFE'))
1041 errorstream << "File " << filename << " cannot be read, as it is encoded in braindead UTF-16. Save your file as plain ASCII!" << std::endl;
1046 * Here we try and get individual tags on separate lines,
1047 * this would be so easy if we just made people format
1048 * their config files like that, but they don't so...
1049 * We check for a '<' and then know the line is over when
1050 * we get a '>' not inside quotes. If we find two '<' and
1051 * no '>' then die with an error.
1054 if ((ch == '#') && !in_quote)
1075 /* XXX: Added by Brain, May 1st 2006 - Escaping of characters.
1076 * Note that this WILL NOT usually allow insertion of newlines,
1077 * because a newline is two characters long. Use it primarily to
1078 * insert the " symbol.
1080 * Note that this also involves a further check when parsing the line,
1081 * which can be found below.
1083 if ((ch == '\\') && (in_quote) && (in_tag))
1086 char real_character;
1087 if (conf.get(real_character))
1089 if (real_character == 'n')
1090 real_character = '\n';
1091 line += real_character;
1096 errorstream << "End of file after a \\, what did you want to escape?: " << filename << ":" << linenumber << std::endl;
1110 errorstream << "Got another opening < when the first one wasn't closed: " << filename << ":" << linenumber << std::endl;
1118 errorstream << "We're in a quote but outside a tag, interesting. " << filename << ":" << linenumber << std::endl;
1123 // errorstream << "Opening new config tag on line " << linenumber << std::endl;
1134 // errorstream << "Closing quote in config tag on line " << linenumber << std::endl;
1139 // errorstream << "Opening quote in config tag on line " << linenumber << std::endl;
1147 errorstream << "Found a (closing) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1151 errorstream << "Found a (opening) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1161 // errorstream << "Closing config tag on line " << linenumber << std::endl;
1165 * If this finds an <include> then ParseLine can simply call
1166 * LoadConf() and load the included config into the same ConfigDataHash
1169 if (!this->ParseLine(target, line, linenumber, errorstream))
1176 errorstream << "Got a closing > when we weren't inside a tag: " << filename << ":" << linenumber << std::endl;
1183 /* 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 */
1184 if (in_comment || in_quote)
1186 errorstream << "Reached end of file whilst still inside a quoted section or tag. This is most likely an error or there \
1187 is a newline missing from the end of the file: " << filename << ":" << linenumber << std::endl;
1193 bool ServerConfig::LoadConf(ConfigDataHash &target, const std::string &filename, std::ostringstream &errorstream)
1195 return this->LoadConf(target, filename.c_str(), errorstream);
1198 bool ServerConfig::ParseLine(ConfigDataHash &target, std::string &line, long &linenumber, std::ostringstream &errorstream)
1200 std::string tagname;
1201 std::string current_key;
1202 std::string current_value;
1208 got_name = got_key = in_quote = false;
1210 for(std::string::iterator c = line.begin(); c != line.end(); c++)
1214 /* We don't know the tag name yet. */
1225 /* We got to a space, we should have the tagname now. */
1226 if(tagname.length())
1234 /* We have the tag name */
1237 /* We're still reading the key name */
1247 /* We got an '=', end of the key name. */
1253 /* We have the key name, now we're looking for quotes and the value */
1255 /* Correctly handle escaped characters here.
1256 * See the XXX'ed section above.
1258 if ((*c == '\\') && (in_quote))
1262 current_value += '\n';
1264 current_value += *c;
1267 else if ((*c == '\n') && (in_quote))
1269 /* Got a 'real' \n, treat it as part of the value */
1270 current_value += '\n';
1274 else if ((*c == '\r') && (in_quote))
1275 /* Got a \r, drop it */
1282 /* We're not already in a quote. */
1287 /* Leaving quotes, we have the value */
1288 results.push_back(KeyVal(current_key, current_value));
1290 // std::cout << "<" << tagname << ":" << current_key << "> " << current_value << std::endl;
1295 if ((tagname == "include") && (current_key == "file"))
1297 if (!this->DoInclude(target, current_value, errorstream))
1301 current_key.clear();
1302 current_value.clear();
1309 current_value += *c;
1316 /* Finished parsing the tag, add it to the config hash */
1317 target.insert(std::pair<std::string, KeyValList > (tagname, results));
1322 bool ServerConfig::DoInclude(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream)
1324 std::string confpath;
1325 std::string newfile;
1326 std::string::size_type pos;
1328 confpath = ServerInstance->ConfigFileName;
1331 for (std::string::iterator c = newfile.begin(); c != newfile.end(); c++)
1341 if((pos = confpath.rfind("/")) != std::string::npos)
1343 /* Leaves us with just the path */
1344 newfile = confpath.substr(0, pos) + std::string("/") + newfile;
1348 errorstream << "Couldn't get config path from: " << confpath << std::endl;
1353 return LoadConf(target, newfile, errorstream);
1356 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, int index, char* result, int length, bool allow_linefeeds)
1358 return ConfValue(target, tag, var, "", index, result, length, allow_linefeeds);
1361 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index, char* result, int length, bool allow_linefeeds)
1364 bool r = ConfValue(target, std::string(tag), std::string(var), std::string(default_value), index, value, allow_linefeeds);
1365 strlcpy(result, value.c_str(), length);
1369 bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, std::string &result, bool allow_linefeeds)
1371 return ConfValue(target, tag, var, "", index, result, allow_linefeeds);
1374 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)
1376 ConfigDataHash::size_type pos = index;
1377 if((pos >= 0) && (pos < target.count(tag)))
1379 ConfigDataHash::iterator iter = target.find(tag);
1381 for(int i = 0; i < index; i++)
1384 for(KeyValList::iterator j = iter->second.begin(); j != iter->second.end(); j++)
1388 if ((!allow_linefeeds) && (j->second.find('\n') != std::string::npos))
1390 ServerInstance->Log(DEFAULT, "Value of <" + tag + ":" + var+ "> contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
1391 for (std::string::iterator n = j->second.begin(); n != j->second.end(); n++)
1402 if (!default_value.empty())
1404 result = default_value;
1410 if (!default_value.empty())
1412 result = default_value;
1419 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, int index, int &result)
1421 return ConfValueInteger(target, std::string(tag), std::string(var), "", index, result);
1424 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index, int &result)
1426 return ConfValueInteger(target, std::string(tag), std::string(var), std::string(default_value), index, result);
1429 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, int &result)
1431 return ConfValueInteger(target, tag, var, "", index, result);
1434 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index, int &result)
1437 std::istringstream stream;
1438 bool r = ConfValue(target, tag, var, default_value, index, value);
1440 if(!(stream >> result))
1446 if (value.substr(0,2) == "0x")
1451 result = strtol(value.c_str(), &endptr, 16);
1453 /* No digits found */
1454 if (endptr == value.c_str())
1459 char denominator = *(value.end() - 1);
1460 switch (toupper(denominator))
1463 /* Kilobytes -> bytes */
1464 result = result * 1024;
1467 /* Megabytes -> bytes */
1468 result = result * 1024 * 1024;
1471 /* Gigabytes -> bytes */
1472 result = result * 1024 * 1024 * 1024;
1482 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, int index)
1484 return ConfValueBool(target, std::string(tag), std::string(var), "", index);
1487 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index)
1489 return ConfValueBool(target, std::string(tag), std::string(var), std::string(default_value), index);
1492 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, int index)
1494 return ConfValueBool(target, tag, var, "", index);
1497 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index)
1500 if(!ConfValue(target, tag, var, default_value, index, result))
1503 return ((result == "yes") || (result == "true") || (result == "1"));
1506 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const char* tag)
1508 return target.count(tag);
1511 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const std::string &tag)
1513 return target.count(tag);
1516 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const char* tag, int index)
1518 return ConfVarEnum(target, std::string(tag), index);
1521 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const std::string &tag, int index)
1523 ConfigDataHash::size_type pos = index;
1525 if((pos >= 0) && (pos < target.count(tag)))
1527 ConfigDataHash::const_iterator iter = target.find(tag);
1529 for(int i = 0; i < index; i++)
1532 return iter->second.size();
1538 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1540 bool ServerConfig::ReadFile(file_cache &F, const char* fname)
1542 if (!fname || !*fname)
1546 char linebuf[MAXBUF];
1550 if ((*fname != '/') && (*fname != '\\'))
1552 std::string::size_type pos;
1553 std::string confpath = ServerInstance->ConfigFileName;
1554 std::string newfile = fname;
1556 if ((pos = confpath.rfind("/")) != std::string::npos)
1557 newfile = confpath.substr(0, pos) + std::string("/") + fname;
1558 else if ((pos = confpath.rfind("\\")) != std::string::npos)
1559 newfile = confpath.substr(0, pos) + std::string("\\") + fname;
1561 if (!FileExists(newfile.c_str()))
1563 file = fopen(newfile.c_str(), "r");
1567 if (!FileExists(fname))
1569 file = fopen(fname, "r");
1576 if (fgets(linebuf, sizeof(linebuf), file))
1577 linebuf[strlen(linebuf)-1] = 0;
1583 F.push_back(*linebuf ? linebuf : " ");
1595 bool ServerConfig::FileExists(const char* file)
1598 if (stat(file, &sb) == -1)
1601 if ((sb.st_mode & S_IFDIR) > 0)
1605 if ((input = fopen (file, "r")) == NULL)
1614 char* ServerConfig::CleanFilename(char* name)
1616 char* p = name + strlen(name);
1617 while ((p != name) && (*p != '/') && (*p != '\\')) p--;
1618 return (p != name ? ++p : p);
1622 bool ServerConfig::DirValid(const char* dirandfile)
1630 char otherdir[1024];
1633 strlcpy(work, dirandfile, 1024);
1636 // we just want the dir
1648 // Get the current working directory
1649 if (getcwd(buffer, 1024 ) == NULL )
1652 if (chdir(work) == -1)
1655 if (getcwd(otherdir, 1024 ) == NULL )
1658 if (chdir(buffer) == -1)
1661 size_t t = strlen(work);
1663 if (strlen(otherdir) >= t)
1666 if (!strcmp(otherdir,work))
1679 std::string ServerConfig::GetFullProgDir()
1681 char buffer[PATH_MAX+1];
1683 /* Windows has specific api calls to get the exe path that never fail.
1684 * For once, windows has something of use, compared to the POSIX code
1685 * for this, this is positively neato.
1687 if (GetModuleFileName(NULL, buffer, MAX_PATH))
1689 std::string fullpath = buffer;
1690 std::string::size_type n = fullpath.rfind("\\inspircd.exe");
1691 return std::string(fullpath, 0, n);
1694 // Get the current working directory
1695 if (getcwd(buffer, PATH_MAX))
1697 std::string remainder = this->argv[0];
1699 /* Does argv[0] start with /? its a full path, use it */
1700 if (remainder[0] == '/')
1702 std::string::size_type n = remainder.rfind("/inspircd");
1703 return std::string(remainder, 0, n);
1706 std::string fullpath = std::string(buffer) + "/" + remainder;
1707 std::string::size_type n = fullpath.rfind("/inspircd");
1708 return std::string(fullpath, 0, n);
1714 InspIRCd* ServerConfig::GetInstance()
1716 return ServerInstance;
1719 std::string ServerConfig::GetSID()
1722 OurSID += (char)((Instance->Config->sid / 100) + 48);
1723 OurSID += (char)((Instance->Config->sid / 10) % 10 + 48);
1724 OurSID += (char)(Instance->Config->sid % 10 + 48);
1728 ValueItem::ValueItem(int value)
1730 std::stringstream n;
1735 ValueItem::ValueItem(bool value)
1737 std::stringstream n;
1742 ValueItem::ValueItem(char* value)
1747 void ValueItem::Set(char* value)
1752 void ValueItem::Set(const char* value)
1757 void ValueItem::Set(int value)
1759 std::stringstream n;
1764 int ValueItem::GetInteger()
1768 return atoi(v.c_str());
1771 char* ValueItem::GetString()
1773 return (char*)v.c_str();
1776 bool ValueItem::GetBool()
1778 return (GetInteger() || v == "yes" || v == "true");