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 * ---------------------------------------------------
14 #include "configreader.h"
19 #include "exitcodes.h"
21 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
23 ServerConfig::ServerConfig(InspIRCd* Instance) : ServerInstance(Instance)
26 *ServerName = *Network = *ServerDesc = *AdminName = '\0';
27 *HideWhoisServer = *AdminEmail = *AdminNick = *diepass = *restartpass = '\0';
28 *CustomVersion = *motd = *rules = *PrefixQuit = *DieValue = *DNSServer = '\0';
29 *UserStats = *ModPath = *MyExecutable = *DisabledCommands = *PID = '\0';
30 WhoWasGroupSize = WhoWasMaxGroups = WhoWasMaxKeep = 0;
32 NoUserDns = forcedebug = OperSpyWhois = nofork = HideBans = HideSplits = UndernetMsgPrefix = false;
33 CycleHosts = writelog = AllowHalfop = true;
34 dns_timeout = DieDelay = 5;
36 NetBufferSize = 10240;
37 SoftLimit = MAXCLIENTS;
45 void ServerConfig::ClearStack()
47 include_stack.clear();
50 Module* ServerConfig::GetIOHook(int port)
52 std::map<int,Module*>::iterator x = IOHookModule.find(port);
53 return (x != IOHookModule.end() ? x->second : NULL);
56 Module* ServerConfig::GetIOHook(InspSocket* is)
58 std::map<InspSocket*,Module*>::iterator x = SocketIOHookModule.find(is);
59 return (x != SocketIOHookModule.end() ? x->second : NULL);
62 bool ServerConfig::AddIOHook(int port, Module* iomod)
66 IOHookModule[port] = iomod;
71 throw ModuleException("Port already hooked by another module");
76 bool ServerConfig::AddIOHook(Module* iomod, InspSocket* is)
80 ServerInstance->Log(DEBUG,"Hooked inspsocket %08x", is);
81 SocketIOHookModule[is] = iomod;
82 is->IsIOHooked = true;
87 throw ModuleException("InspSocket derived class already hooked by another module");
92 bool ServerConfig::DelIOHook(int port)
94 std::map<int,Module*>::iterator x = IOHookModule.find(port);
95 if (x != IOHookModule.end())
97 IOHookModule.erase(x);
103 bool ServerConfig::DelIOHook(InspSocket* is)
105 std::map<InspSocket*,Module*>::iterator x = SocketIOHookModule.find(is);
106 if (x != SocketIOHookModule.end())
108 SocketIOHookModule.erase(x);
114 void ServerConfig::Update005()
116 std::stringstream out(data005);
119 int token_counter = 0;
123 line5 = line5 + token + " ";
125 if (token_counter >= 13)
128 snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
129 isupport.push_back(buf);
135 snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
136 isupport.push_back(buf);
139 void ServerConfig::Send005(userrec* user)
141 for (std::vector<std::string>::iterator line = ServerInstance->Config->isupport.begin(); line != ServerInstance->Config->isupport.end(); line++)
142 user->WriteServ("005 %s %s", user->nick, line->c_str());
145 bool ServerConfig::CheckOnce(char* tag, bool bail, userrec* user)
147 int count = ConfValueEnum(this->config_data, tag);
153 printf("There were errors in your configuration:\nYou have more than one <%s> tag, this is not permitted.\n",tag);
154 InspIRCd::Exit(EXIT_STATUS_CONFIG);
160 user->WriteServ("There were errors in your configuration:");
161 user->WriteServ("You have more than one <%s> tag, this is not permitted.\n",tag);
165 ServerInstance->WriteOpers("There were errors in the configuration file:");
166 ServerInstance->WriteOpers("You have more than one <%s> tag, this is not permitted.\n",tag);
175 printf("There were errors in your configuration:\nYou have not defined a <%s> tag, this is required.\n",tag);
176 InspIRCd::Exit(EXIT_STATUS_CONFIG);
182 user->WriteServ("There were errors in your configuration:");
183 user->WriteServ("You have not defined a <%s> tag, this is required.",tag);
187 ServerInstance->WriteOpers("There were errors in the configuration file:");
188 ServerInstance->WriteOpers("You have not defined a <%s> tag, this is required.",tag);
196 bool NoValidation(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
198 conf->GetInstance()->Log(DEBUG,"No validation for <%s:%s>",tag,value);
202 bool ValidateMaxTargets(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
204 if ((data.GetInteger() < 0) || (data.GetInteger() > 31))
206 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
212 bool ValidateSoftLimit(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
214 if ((data.GetInteger() < 1) || (data.GetInteger() > MAXCLIENTS))
216 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
217 data.Set(MAXCLIENTS);
222 bool ValidateMaxConn(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
224 if (data.GetInteger() > SOMAXCONN)
225 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
229 bool InitializeDisabledCommands(const char* data, InspIRCd* ServerInstance)
231 std::stringstream dcmds(data);
234 /* Enable everything first */
235 for (nspace::hash_map<std::string,command_t*>::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
236 x->second->Disable(false);
238 /* Now disable all the ones which the user wants disabled */
239 while (dcmds >> thiscmd)
241 nspace::hash_map<std::string,command_t*>::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
242 if (cm != ServerInstance->Parser->cmdlist.end())
244 ServerInstance->Log(DEBUG,"Disabling command '%s'",cm->second->command.c_str());
245 cm->second->Disable(true);
251 bool ValidateDnsServer(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
253 if (!*(data.GetString()))
255 // attempt to look up their nameserver from /etc/resolv.conf
256 conf->GetInstance()->Log(DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
257 ifstream resolv("/etc/resolv.conf");
258 std::string nameserver;
259 bool found_server = false;
261 if (resolv.is_open())
263 while (resolv >> nameserver)
265 if ((nameserver == "nameserver") && (!found_server))
267 resolv >> nameserver;
268 data.Set(nameserver.c_str());
270 conf->GetInstance()->Log(DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
276 conf->GetInstance()->Log(DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
277 data.Set("127.0.0.1");
282 conf->GetInstance()->Log(DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
283 data.Set("127.0.0.1");
289 bool ValidateServerName(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
291 if (!strchr(data.GetString(),'.'))
293 conf->GetInstance()->Log(DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s%c'",data.GetString(),data.GetString(),'.');
294 std::string moo = std::string(data.GetString()).append(".");
295 data.Set(moo.c_str());
300 bool ValidateNetBufferSize(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
302 if ((!data.GetInteger()) || (data.GetInteger() > 65535) || (data.GetInteger() < 1024))
304 conf->GetInstance()->Log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
310 bool ValidateMaxWho(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
312 if ((!data.GetInteger()) || (data.GetInteger() > 65535) || (data.GetInteger() < 1))
314 conf->GetInstance()->Log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
320 bool ValidateLogLevel(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
322 std::string dbg = data.GetString();
323 conf->LogLevel = DEFAULT;
326 conf->LogLevel = DEBUG;
327 else if (dbg == "verbose")
328 conf->LogLevel = VERBOSE;
329 else if (dbg == "default")
330 conf->LogLevel = DEFAULT;
331 else if (dbg == "sparse")
332 conf->LogLevel = SPARSE;
333 else if (dbg == "none")
334 conf->LogLevel = NONE;
336 conf->debugging = (conf->LogLevel == DEBUG);
341 bool ValidateMotd(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
343 conf->ReadFile(conf->MOTD, data.GetString());
347 bool ValidateRules(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
349 conf->ReadFile(conf->RULES, data.GetString());
353 bool ValidateWhoWas(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
355 conf->WhoWasMaxKeep = conf->GetInstance()->Duration(data.GetString());
357 if (conf->WhoWasGroupSize < 0)
358 conf->WhoWasGroupSize = 0;
360 if (conf->WhoWasMaxGroups < 0)
361 conf->WhoWasMaxGroups = 0;
363 if (conf->WhoWasMaxKeep < 3600)
365 conf->WhoWasMaxKeep = 3600;
366 conf->GetInstance()->Log(DEFAULT,"WARNING: <whowas:maxkeep> value less than 3600, setting to default 3600");
368 conf->GetInstance()->Log(DEBUG,"whowas:groupsize:%d maxgroups:%d maxkeep:%d",conf->WhoWasGroupSize,conf->WhoWasMaxGroups,conf->WhoWasMaxKeep);
369 irc::whowas::PruneWhoWas(conf->GetInstance(), conf->GetInstance()->Time());
373 /* Callback called before processing the first <connect> tag
375 bool InitConnect(ServerConfig* conf, const char* tag)
377 conf->GetInstance()->Log(DEFAULT,"Reading connect classes...");
378 conf->Classes.clear();
382 /* Callback called to process a single <connect> tag
384 bool DoConnect(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
387 const char* allow = values[0].GetString(); /* Yeah, there are a lot of values. Live with it. */
388 const char* deny = values[1].GetString();
389 const char* password = values[2].GetString();
390 int timeout = values[3].GetInteger();
391 int pingfreq = values[4].GetInteger();
392 int flood = values[5].GetInteger();
393 int threshold = values[6].GetInteger();
394 int sendq = values[7].GetInteger();
395 int recvq = values[8].GetInteger();
396 int localmax = values[9].GetInteger();
397 int globalmax = values[10].GetInteger();
401 ConnectClass c(timeout, flood, allow, pingfreq, password, threshold, sendq, recvq, localmax, globalmax);
402 conf->Classes.push_back(c);
406 ConnectClass c(deny);
407 conf->Classes.push_back(c);
413 /* Callback called when there are no more <connect> tags
415 bool DoneConnect(ServerConfig* conf, const char* tag)
417 conf->GetInstance()->Log(DEBUG,"DoneConnect called for tag: %s",tag);
421 /* Callback called before processing the first <uline> tag
423 bool InitULine(ServerConfig* conf, const char* tag)
425 conf->ulines.clear();
429 /* Callback called to process a single <uline> tag
431 bool DoULine(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
433 const char* server = values[0].GetString();
434 conf->GetInstance()->Log(DEBUG,"Read ULINE '%s'",server);
435 conf->ulines.push_back(server);
439 /* Callback called when there are no more <uline> tags
441 bool DoneULine(ServerConfig* conf, const char* tag)
446 /* Callback called before processing the first <module> tag
448 bool InitModule(ServerConfig* conf, const char* tag)
450 old_module_names.clear();
451 new_module_names.clear();
452 added_modules.clear();
453 removed_modules.clear();
454 for (std::vector<std::string>::iterator t = conf->module_names.begin(); t != conf->module_names.end(); t++)
456 old_module_names.push_back(*t);
461 /* Callback called to process a single <module> tag
463 bool DoModule(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
465 const char* modname = values[0].GetString();
466 new_module_names.push_back(modname);
470 /* Callback called when there are no more <module> tags
472 bool DoneModule(ServerConfig* conf, const char* tag)
474 // now create a list of new modules that are due to be loaded
475 // and a seperate list of modules which are due to be unloaded
476 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
480 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
487 added_modules.push_back(*_new);
490 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
493 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
500 removed_modules.push_back(*oldm);
505 /* Callback called before processing the first <banlist> tag
507 bool InitMaxBans(ServerConfig* conf, const char* tag)
509 conf->maxbans.clear();
513 /* Callback called to process a single <banlist> tag
515 bool DoMaxBans(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
517 const char* channel = values[0].GetString();
518 int limit = values[1].GetInteger();
519 conf->maxbans[channel] = limit;
523 /* Callback called when there are no more <banlist> tags.
525 bool DoneMaxBans(ServerConfig* conf, const char* tag)
530 void ServerConfig::ReportConfigError(const std::string &errormessage, bool bail, userrec* user)
532 ServerInstance->Log(DEFAULT, "There were errors in your configuration file: %s", errormessage.c_str());
535 /* Unneeded because of the ServerInstance->Log() aboive? */
536 printf("There were errors in your configuration:\n%s\n\n",errormessage.c_str());
537 InspIRCd::Exit(EXIT_STATUS_CONFIG);
541 std::string errors = errormessage;
542 std::string::size_type start;
543 unsigned int prefixlen;
545 /* ":ServerInstance->Config->ServerName NOTICE user->nick :" */
546 prefixlen = strlen(this->ServerName) + strlen(user->nick) + 11;
549 user->WriteServ("NOTICE %s :There were errors in the configuration file:",user->nick);
550 while (start < errors.length())
552 user->WriteServ("NOTICE %s :%s",user->nick, errors.substr(start, 510 - prefixlen).c_str());
553 start += 510 - prefixlen;
558 ServerInstance->WriteOpers("There were errors in the configuration file:");
559 while (start < errors.length())
561 ServerInstance->WriteOpers(errors.substr(start, 360).c_str());
569 void ServerConfig::Read(bool bail, userrec* user)
571 static char debug[MAXBUF]; /* Temporary buffer for debugging value */
572 static char maxkeep[MAXBUF]; /* Temporary buffer for WhoWasMaxKeep value */
573 static char somax[MAXBUF]; /* Temporary buffer for SOMAXCONN default */
574 int rem = 0, add = 0; /* Number of modules added, number of modules removed */
575 std::ostringstream errstr; /* String stream containing the error output */
577 /* These tags MUST occur and must ONLY occur once in the config file */
578 static char* Once[] = { "server", "admin", "files", "power", "options", NULL };
580 /* These tags can occur ONCE or not at all */
581 InitialConfig Values[] = {
582 {"options", "softlimit", MAXCLIENTS_S, new ValueContainerUInt (&this->SoftLimit), DT_INTEGER, ValidateSoftLimit},
583 {"options", "somaxconn", itoa(SOMAXCONN, somax, 10), new ValueContainerInt (&this->MaxConn), DT_INTEGER, ValidateMaxConn},
584 {"server", "name", "", new ValueContainerChar (this->ServerName), DT_CHARPTR, ValidateServerName},
585 {"server", "description", "Configure Me", new ValueContainerChar (this->ServerDesc), DT_CHARPTR, NoValidation},
586 {"server", "network", "Network", new ValueContainerChar (this->Network), DT_CHARPTR, NoValidation},
587 {"admin", "name", "Miss Configured", new ValueContainerChar (this->AdminName), DT_CHARPTR, NoValidation},
588 {"admin", "email", "Mis@configu.red", new ValueContainerChar (this->AdminEmail), DT_CHARPTR, NoValidation},
589 {"admin", "nick", "Misconfigured", new ValueContainerChar (this->AdminNick), DT_CHARPTR, NoValidation},
590 {"files", "motd", "", new ValueContainerChar (this->motd), DT_CHARPTR, ValidateMotd},
591 {"files", "rules", "", new ValueContainerChar (this->rules), DT_CHARPTR, ValidateRules},
592 {"power", "diepass", "", new ValueContainerChar (this->diepass), DT_CHARPTR, NoValidation},
593 {"power", "pause", "", new ValueContainerInt (&this->DieDelay), DT_INTEGER, NoValidation},
594 {"power", "restartpass", "", new ValueContainerChar (this->restartpass), DT_CHARPTR, NoValidation},
595 {"options", "prefixquit", "", new ValueContainerChar (this->PrefixQuit), DT_CHARPTR, NoValidation},
596 {"options", "loglevel", "default", new ValueContainerChar (debug), DT_CHARPTR, ValidateLogLevel},
597 {"options", "netbuffersize","10240", new ValueContainerInt (&this->NetBufferSize), DT_INTEGER, ValidateNetBufferSize},
598 {"options", "maxwho", "128", new ValueContainerInt (&this->MaxWhoResults), DT_INTEGER, ValidateMaxWho},
599 {"options", "allowhalfop", "0", new ValueContainerBool (&this->AllowHalfop), DT_BOOLEAN, NoValidation},
600 {"dns", "server", "", new ValueContainerChar (this->DNSServer), DT_CHARPTR, ValidateDnsServer},
601 {"dns", "timeout", "5", new ValueContainerInt (&this->dns_timeout), DT_INTEGER, NoValidation},
602 {"options", "moduledir", MOD_PATH, new ValueContainerChar (this->ModPath), DT_CHARPTR, NoValidation},
603 {"disabled", "commands", "", new ValueContainerChar (this->DisabledCommands), DT_CHARPTR, NoValidation},
604 {"options", "userstats", "", new ValueContainerChar (this->UserStats), DT_CHARPTR, NoValidation},
605 {"options", "customversion","", new ValueContainerChar (this->CustomVersion), DT_CHARPTR, NoValidation},
606 {"options", "hidesplits", "0", new ValueContainerBool (&this->HideSplits), DT_BOOLEAN, NoValidation},
607 {"options", "hidebans", "0", new ValueContainerBool (&this->HideBans), DT_BOOLEAN, NoValidation},
608 {"options", "hidewhois", "", new ValueContainerChar (this->HideWhoisServer), DT_CHARPTR, NoValidation},
609 {"options", "operspywhois", "0", new ValueContainerBool (&this->OperSpyWhois), DT_BOOLEAN, NoValidation},
610 {"options", "nouserdns", "0", new ValueContainerBool (&this->NoUserDns), DT_BOOLEAN, NoValidation},
611 {"options", "syntaxhints", "0", new ValueContainerBool (&this->SyntaxHints), DT_BOOLEAN, NoValidation},
612 {"options", "cyclehosts", "0", new ValueContainerBool (&this->CycleHosts), DT_BOOLEAN, NoValidation},
613 {"options", "ircumsgprefix","0", new ValueContainerBool (&this->UndernetMsgPrefix), DT_BOOLEAN, NoValidation},
614 {"pid", "file", "", new ValueContainerChar (this->PID), DT_CHARPTR, NoValidation},
615 {"whowas", "groupsize", "10", new ValueContainerInt (&this->WhoWasGroupSize), DT_INTEGER, NoValidation},
616 {"whowas", "maxgroups", "10240", new ValueContainerInt (&this->WhoWasMaxGroups), DT_INTEGER, NoValidation},
617 {"whowas", "maxkeep", "3600", new ValueContainerChar (maxkeep), DT_CHARPTR, ValidateWhoWas},
618 {"die", "value", "", new ValueContainerChar (this->DieValue), DT_CHARPTR, NoValidation},
622 /* These tags can occur multiple times, and therefore they have special code to read them
623 * which is different to the code for reading the singular tags listed above.
625 MultiConfig MultiValues[] = {
628 {"allow", "deny", "password", "timeout", "pingfreq", "flood",
629 "threshold", "sendq", "recvq", "localmax", "globalmax", NULL},
630 {"", "", "", "", "", "",
631 "", "", "", "", "", NULL},
632 {DT_CHARPTR, DT_CHARPTR, DT_CHARPTR, DT_INTEGER, DT_INTEGER, DT_INTEGER,
633 DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER},
634 InitConnect, DoConnect, DoneConnect},
640 InitULine,DoULine,DoneULine},
643 {"chan", "limit", NULL},
645 {DT_CHARPTR, DT_INTEGER},
646 InitMaxBans, DoMaxBans, DoneMaxBans},
652 InitModule, DoModule, DoneModule},
655 {"reason", "ipmask", NULL},
656 {"No reason", "", NULL},
657 {DT_CHARPTR, DT_CHARPTR},
658 InitXLine, DoZLine, DoneXLine},
661 {"reason", "nick", NULL},
662 {"No reason", "", NULL},
663 {DT_CHARPTR, DT_CHARPTR},
664 InitXLine, DoQLine, DoneXLine},
667 {"reason", "host", NULL},
668 {"No reason", "", NULL},
669 {DT_CHARPTR, DT_CHARPTR},
670 InitXLine, DoKLine, DoneXLine},
673 {"reason", "host", NULL},
674 {"No reason", "", NULL},
675 {DT_CHARPTR, DT_CHARPTR},
676 InitXLine, DoELine, DoneXLine},
679 {"name", "classes", NULL},
681 {DT_CHARPTR, DT_CHARPTR},
682 InitTypes, DoType, DoneClassesAndTypes},
685 {"name", "commands", NULL},
687 {DT_CHARPTR, DT_CHARPTR},
688 InitClasses, DoClass, DoneClassesAndTypes},
693 include_stack.clear();
695 /* Load and parse the config file, if there are any errors then explode */
697 /* Make a copy here so if it fails then we can carry on running with an unaffected config */
698 ConfigDataHash newconfig;
700 if (this->LoadConf(newconfig, CONFIG_FILE, errstr))
702 /* If we succeeded, set the ircd config to the new one */
703 this->config_data = newconfig;
707 ReportConfigError(errstr.str(), bail, user);
711 /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
714 /* Check we dont have more than one of singular tags, or any of them missing
716 for (int Index = 0; Once[Index]; Index++)
717 if (!CheckOnce(Once[Index], bail, user))
720 /* Read the values of all the tags which occur once or not at all, and call their callbacks.
722 for (int Index = 0; Values[Index].tag; Index++)
725 int dt = Values[Index].datatype;
726 bool allow_newlines = ((dt & DT_ALLOW_NEWLINE) > 0);
727 dt &= ~DT_ALLOW_NEWLINE;
729 ConfValue(this->config_data, Values[Index].tag, Values[Index].value, Values[Index].default_value, 0, item, MAXBUF, allow_newlines);
732 Values[Index].validation_function(this, Values[Index].tag, Values[Index].value, vi);
734 switch (Values[Index].datatype)
738 ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
739 vcc->Set(vi.GetString(), strlen(vi.GetString()));
744 int val = vi.GetInteger();
745 ValueContainerInt* vci = (ValueContainerInt*)Values[Index].val;
746 vci->Set(&val, sizeof(int));
751 bool val = vi.GetBool();
752 ValueContainerBool* vcb = (ValueContainerBool*)Values[Index].val;
753 vcb->Set(&val, sizeof(bool));
757 /* You don't want to know what happens if someones bad code sends us here. */
761 /* We're done with this now */
762 delete Values[Index].val;
765 /* Read the multiple-tag items (class tags, connect tags, etc)
766 * and call the callbacks associated with them. We have three
767 * callbacks for these, a 'start', 'item' and 'end' callback.
769 for (int Index = 0; MultiValues[Index].tag; Index++)
771 MultiValues[Index].init_function(this, MultiValues[Index].tag);
773 int number_of_tags = ConfValueEnum(this->config_data, MultiValues[Index].tag);
775 for (int tagnum = 0; tagnum < number_of_tags; tagnum++)
778 for (int valuenum = 0; MultiValues[Index].items[valuenum]; valuenum++)
780 int dt = MultiValues[Index].datatype[valuenum];
781 bool allow_newlines = ((dt & DT_ALLOW_NEWLINE) > 0);
782 dt &= ~DT_ALLOW_NEWLINE;
789 if (ConfValue(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
790 vl.push_back(ValueItem(item));
792 vl.push_back(ValueItem(""));
798 if (ConfValueInteger(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item))
799 vl.push_back(ValueItem(item));
801 vl.push_back(ValueItem(0));
806 bool item = ConfValueBool(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum);
807 vl.push_back(ValueItem(item));
811 /* Someone was smoking craq if we got here, and we're all gonna die. */
816 MultiValues[Index].validation_function(this, MultiValues[Index].tag, (char**)MultiValues[Index].items, vl, MultiValues[Index].datatype);
819 MultiValues[Index].finish_function(this, MultiValues[Index].tag);
824 catch (CoreException &ce)
826 ReportConfigError(ce.GetReason(), bail, user);
830 // write once here, to try it out and make sure its ok
831 ServerInstance->WritePID(this->PID);
833 ServerInstance->Log(DEFAULT,"Done reading configuration file.");
835 /* If we're rehashing, let's load any new modules, and unload old ones
841 ServerInstance->stats->BoundPortCount = ServerInstance->BindPorts(false, found_ports, pl);
845 user->WriteServ("NOTICE %s :*** Not all your client ports could be bound.", user->nick);
846 user->WriteServ("NOTICE %s :*** The following port%s failed to bind:", user->nick, found_ports - ServerInstance->stats->BoundPortCount != 1 ? "s" : "");
848 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
850 user->WriteServ("NOTICE %s :*** %d. IP: %s Port: %lu", user->nick, j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
854 if (!removed_modules.empty())
856 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
858 if (ServerInstance->UnloadModule(removing->c_str()))
860 ServerInstance->WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
863 user->WriteServ("973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
870 user->WriteServ("972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
875 if (!added_modules.empty())
877 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
879 if (ServerInstance->LoadModule(adding->c_str()))
881 ServerInstance->WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
884 user->WriteServ("975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
891 user->WriteServ("974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
896 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());
900 bool ServerConfig::LoadConf(ConfigDataHash &target, const char* filename, std::ostringstream &errorstream)
902 std::ifstream conf(filename);
915 /* Check if the file open failed first */
918 errorstream << "LoadConf: Couldn't open config file: " << filename << std::endl;
922 /* Fix the chmod of the file to restrict it to the current user and group */
923 chmod(filename,0600);
925 for (unsigned int t = 0; t < include_stack.size(); t++)
927 if (std::string(filename) == include_stack[t])
929 errorstream << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
934 /* It's not already included, add it to the list of files we've loaded */
935 include_stack.push_back(filename);
937 /* Start reading characters... */
941 * Here we try and get individual tags on separate lines,
942 * this would be so easy if we just made people format
943 * their config files like that, but they don't so...
944 * We check for a '<' and then know the line is over when
945 * we get a '>' not inside quotes. If we find two '<' and
946 * no '>' then die with an error.
949 if((ch == '#') && !in_quote)
952 /*if(((ch == '\n') || (ch == '\r')) && in_quote)
954 errorstream << "Got a newline within a quoted section, this is probably a typo: " << filename << ":" << linenumber << std::endl;
963 ServerInstance->Log(DEBUG, "Got \\n inside value");
979 /* XXX: Added by Brain, May 1st 2006 - Escaping of characters.
980 * Note that this WILL NOT usually allow insertion of newlines,
981 * because a newline is two characters long. Use it primarily to
982 * insert the " symbol.
984 * Note that this also involves a further check when parsing the line,
985 * which can be found below.
987 if ((ch == '\\') && (in_quote) && (in_tag))
990 ServerInstance->Log(DEBUG,"Escape sequence in config line.");
992 if (conf.get(real_character))
994 ServerInstance->Log(DEBUG,"Escaping %c", real_character);
995 if (real_character == 'n')
996 real_character = '\n';
997 line += real_character;
1002 errorstream << "End of file after a \\, what did you want to escape?: " << filename << ":" << linenumber << std::endl;
1016 errorstream << "Got another opening < when the first one wasn't closed: " << filename << ":" << linenumber << std::endl;
1024 errorstream << "We're in a quote but outside a tag, interesting. " << filename << ":" << linenumber << std::endl;
1029 // errorstream << "Opening new config tag on line " << linenumber << std::endl;
1040 // errorstream << "Closing quote in config tag on line " << linenumber << std::endl;
1045 // errorstream << "Opening quote in config tag on line " << linenumber << std::endl;
1053 errorstream << "Found a (closing) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1057 errorstream << "Found a (opening) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1067 // errorstream << "Closing config tag on line " << linenumber << std::endl;
1071 * If this finds an <include> then ParseLine can simply call
1072 * LoadConf() and load the included config into the same ConfigDataHash
1075 if(!this->ParseLine(target, line, linenumber, errorstream))
1082 errorstream << "Got a closing > when we weren't inside a tag: " << filename << ":" << linenumber << std::endl;
1092 bool ServerConfig::LoadConf(ConfigDataHash &target, const std::string &filename, std::ostringstream &errorstream)
1094 return this->LoadConf(target, filename.c_str(), errorstream);
1097 bool ServerConfig::ParseLine(ConfigDataHash &target, std::string &line, long linenumber, std::ostringstream &errorstream)
1099 std::string tagname;
1100 std::string current_key;
1101 std::string current_value;
1107 got_name = got_key = in_quote = false;
1109 //std::cout << "ParseLine(data, '" << line << "', " << linenumber << ", stream)" << std::endl;
1111 for(std::string::iterator c = line.begin(); c != line.end(); c++)
1115 /* We don't know the tag name yet. */
1126 /* We got to a space, we should have the tagname now. */
1127 if(tagname.length())
1135 /* We have the tag name */
1138 /* We're still reading the key name */
1148 /* We got an '=', end of the key name. */
1154 /* We have the key name, now we're looking for quotes and the value */
1156 /* Correctly handle escaped characters here.
1157 * See the XXX'ed section above.
1159 if ((*c == '\\') && (in_quote))
1163 current_value += '\n';
1165 current_value += *c;
1168 else if ((*c == '\n') && (in_quote))
1170 /* Got a 'real' \n, treat it as part of the value */
1171 current_value += '\n';
1174 else if ((*c == '\r') && (in_quote))
1175 /* Got a \r, drop it */
1182 /* We're not already in a quote. */
1187 /* Leaving quotes, we have the value */
1188 results.push_back(KeyVal(current_key, current_value));
1190 // std::cout << "<" << tagname << ":" << current_key << "> " << current_value << std::endl;
1195 if((tagname == "include") && (current_key == "file"))
1197 if(!this->DoInclude(target, current_value, errorstream))
1201 current_key.clear();
1202 current_value.clear();
1209 current_value += *c;
1216 /* Finished parsing the tag, add it to the config hash */
1217 target.insert(std::pair<std::string, KeyValList > (tagname, results));
1222 bool ServerConfig::DoInclude(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream)
1224 std::string confpath;
1225 std::string newfile;
1226 std::string::size_type pos;
1228 confpath = CONFIG_FILE;
1231 for (std::string::iterator c = newfile.begin(); c != newfile.end(); c++)
1241 if((pos = confpath.find("/inspircd.conf")) != std::string::npos)
1243 /* Leaves us with just the path */
1244 newfile = confpath.substr(0, pos) + std::string("/") + newfile;
1248 errorstream << "Couldn't get config path from: " << confpath << std::endl;
1253 return LoadConf(target, newfile, errorstream);
1256 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, int index, char* result, int length, bool allow_linefeeds)
1258 return ConfValue(target, tag, var, "", index, result, length, allow_linefeeds);
1261 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index, char* result, int length, bool allow_linefeeds)
1264 bool r = ConfValue(target, std::string(tag), std::string(var), std::string(default_value), index, value, allow_linefeeds);
1265 strlcpy(result, value.c_str(), length);
1269 bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, std::string &result, bool allow_linefeeds)
1271 return ConfValue(target, tag, var, "", index, result, allow_linefeeds);
1274 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)
1276 ConfigDataHash::size_type pos = index;
1277 if((pos >= 0) && (pos < target.count(tag)))
1279 ConfigDataHash::iterator iter = target.find(tag);
1281 for(int i = 0; i < index; i++)
1284 for(KeyValList::iterator j = iter->second.begin(); j != iter->second.end(); j++)
1288 if ((!allow_linefeeds) && (j->second.find('\n') != std::string::npos))
1290 ServerInstance->Log(DEFAULT, "Value of <" + tag + ":" + var+ "> contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
1291 for (std::string::iterator n = j->second.begin(); n != j->second.end(); n++)
1302 if (!default_value.empty())
1304 result = default_value;
1305 ServerInstance->Log(DEBUG, "No config option for '%s' in tag <%s> using default: %s", var.c_str(), tag.c_str(), default_value.c_str());
1311 if (!default_value.empty())
1313 result = default_value;
1314 ServerInstance->Log(DEBUG, "No <%s:%s> tags in config file using default: %s", tag.c_str(), var.c_str(), default_value.c_str());
1317 ServerInstance->Log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1321 ServerInstance->Log(DEBUG, "ConfValue got an out-of-range index %d, there are only %d occurences of %s", pos, target.count(tag), tag.c_str());
1326 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, int index, int &result)
1328 return ConfValueInteger(target, std::string(tag), std::string(var), "", index, result);
1331 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index, int &result)
1333 return ConfValueInteger(target, std::string(tag), std::string(var), std::string(default_value), index, result);
1336 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, int &result)
1338 return ConfValueInteger(target, tag, var, "", index, result);
1341 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index, int &result)
1344 std::istringstream stream;
1345 bool r = ConfValue(target, tag, var, default_value, index, value);
1347 if(!(stream >> result))
1353 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, int index)
1355 return ConfValueBool(target, std::string(tag), std::string(var), "", index);
1358 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index)
1360 return ConfValueBool(target, std::string(tag), std::string(var), std::string(default_value), index);
1363 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, int index)
1365 return ConfValueBool(target, tag, var, "", index);
1368 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index)
1371 if(!ConfValue(target, tag, var, default_value, index, result))
1374 return ((result == "yes") || (result == "true") || (result == "1"));
1377 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const char* tag)
1379 return target.count(tag);
1382 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const std::string &tag)
1384 return target.count(tag);
1387 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const char* tag, int index)
1389 return ConfVarEnum(target, std::string(tag), index);
1392 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const std::string &tag, int index)
1394 ConfigDataHash::size_type pos = index;
1396 if((pos >= 0) && (pos < target.count(tag)))
1398 ConfigDataHash::const_iterator iter = target.find(tag);
1400 for(int i = 0; i < index; i++)
1403 return iter->second.size();
1407 ServerInstance->Log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1411 ServerInstance->Log(DEBUG, "ConfVarEnum got an out-of-range index %d, there are only %d occurences of %s", pos, target.count(tag), tag.c_str());
1417 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1419 bool ServerConfig::ReadFile(file_cache &F, const char* fname)
1422 char linebuf[MAXBUF];
1428 std::string::size_type pos;
1429 std::string confpath = CONFIG_FILE;
1430 if((pos = confpath.find("/inspircd.conf")) != std::string::npos)
1432 /* Leaves us with just the path */
1433 std::string newfile = confpath.substr(0, pos) + std::string("/") + fname;
1434 file = fopen(newfile.c_str(), "r");
1439 file = fopen(fname, "r");
1445 if (fgets(linebuf, sizeof(linebuf), file))
1446 linebuf[strlen(linebuf)-1] = 0;
1452 F.push_back(*linebuf ? linebuf : " ");
1464 bool ServerConfig::FileExists(const char* file)
1467 if ((input = fopen (file, "r")) == NULL)
1478 char* ServerConfig::CleanFilename(char* name)
1480 char* p = name + strlen(name);
1481 while ((p != name) && (*p != '/')) p--;
1482 return (p != name ? ++p : p);
1486 bool ServerConfig::DirValid(const char* dirandfile)
1489 char buffer[MAXBUF];
1490 char otherdir[MAXBUF];
1493 strlcpy(work, dirandfile, MAXBUF);
1496 // we just want the dir
1508 // Get the current working directory
1509 if (getcwd(buffer, MAXBUF ) == NULL )
1512 if (chdir(work) == -1)
1515 if (getcwd(otherdir, MAXBUF ) == NULL )
1518 if (chdir(buffer) == -1)
1521 size_t t = strlen(work);
1523 if (strlen(otherdir) >= t)
1527 if (!strcmp(otherdir,work))
1540 std::string ServerConfig::GetFullProgDir(char** argv, int argc)
1543 char buffer[MAXBUF];
1544 char otherdir[MAXBUF];
1547 strlcpy(work,argv[0],MAXBUF);
1550 // we just want the dir
1562 // Get the current working directory
1563 if (getcwd(buffer, MAXBUF) == NULL)
1566 if (chdir(work) == -1)
1569 if (getcwd(otherdir, MAXBUF) == NULL)
1572 if (chdir(buffer) == -1)
1578 InspIRCd* ServerConfig::GetInstance()
1580 return ServerInstance;
1584 ValueItem::ValueItem(int value)
1586 std::stringstream n;
1591 ValueItem::ValueItem(bool value)
1593 std::stringstream n;
1598 ValueItem::ValueItem(char* value)
1603 void ValueItem::Set(char* value)
1608 void ValueItem::Set(const char* value)
1613 void ValueItem::Set(int value)
1615 std::stringstream n;
1620 int ValueItem::GetInteger()
1624 return atoi(v.c_str());
1627 char* ValueItem::GetString()
1629 return (char*)v.c_str();
1632 bool ValueItem::GetBool()
1634 return (GetInteger() || v == "yes" || v == "true");