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);
137 snprintf(buf, MAXBUF, "%s:are supported by this server", line5.c_str());
138 isupport.push_back(buf);
142 void ServerConfig::Send005(userrec* user)
144 for (std::vector<std::string>::iterator line = ServerInstance->Config->isupport.begin(); line != ServerInstance->Config->isupport.end(); line++)
145 user->WriteServ("005 %s %s", user->nick, line->c_str());
148 bool ServerConfig::CheckOnce(char* tag, bool bail, userrec* user)
150 int count = ConfValueEnum(this->config_data, tag);
156 printf("There were errors in your configuration:\nYou have more than one <%s> tag, this is not permitted.\n",tag);
157 InspIRCd::Exit(EXIT_STATUS_CONFIG);
163 user->WriteServ("There were errors in your configuration:");
164 user->WriteServ("You have more than one <%s> tag, this is not permitted.\n",tag);
168 ServerInstance->WriteOpers("There were errors in the configuration file:");
169 ServerInstance->WriteOpers("You have more than one <%s> tag, this is not permitted.\n",tag);
178 printf("There were errors in your configuration:\nYou have not defined a <%s> tag, this is required.\n",tag);
179 InspIRCd::Exit(EXIT_STATUS_CONFIG);
185 user->WriteServ("There were errors in your configuration:");
186 user->WriteServ("You have not defined a <%s> tag, this is required.",tag);
190 ServerInstance->WriteOpers("There were errors in the configuration file:");
191 ServerInstance->WriteOpers("You have not defined a <%s> tag, this is required.",tag);
199 bool NoValidation(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
201 conf->GetInstance()->Log(DEBUG,"No validation for <%s:%s>",tag,value);
205 bool ValidateMaxTargets(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
207 if ((data.GetInteger() < 0) || (data.GetInteger() > 31))
209 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
215 bool ValidateSoftLimit(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
217 if ((data.GetInteger() < 1) || (data.GetInteger() > MAXCLIENTS))
219 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
220 data.Set(MAXCLIENTS);
225 bool ValidateMaxConn(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
227 if (data.GetInteger() > SOMAXCONN)
228 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
232 bool InitializeDisabledCommands(const char* data, InspIRCd* ServerInstance)
234 std::stringstream dcmds(data);
237 /* Enable everything first */
238 for (nspace::hash_map<std::string,command_t*>::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
239 x->second->Disable(false);
241 /* Now disable all the ones which the user wants disabled */
242 while (dcmds >> thiscmd)
244 nspace::hash_map<std::string,command_t*>::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
245 if (cm != ServerInstance->Parser->cmdlist.end())
247 ServerInstance->Log(DEBUG,"Disabling command '%s'",cm->second->command.c_str());
248 cm->second->Disable(true);
254 bool ValidateDnsServer(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
256 if (!*(data.GetString()))
258 // attempt to look up their nameserver from /etc/resolv.conf
259 conf->GetInstance()->Log(DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
260 ifstream resolv("/etc/resolv.conf");
261 std::string nameserver;
262 bool found_server = false;
264 if (resolv.is_open())
266 while (resolv >> nameserver)
268 if ((nameserver == "nameserver") && (!found_server))
270 resolv >> nameserver;
271 data.Set(nameserver.c_str());
273 conf->GetInstance()->Log(DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
279 conf->GetInstance()->Log(DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
280 data.Set("127.0.0.1");
285 conf->GetInstance()->Log(DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
286 data.Set("127.0.0.1");
292 bool ValidateServerName(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
294 if (!strchr(data.GetString(),'.'))
296 conf->GetInstance()->Log(DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s%c'",data.GetString(),data.GetString(),'.');
297 std::string moo = std::string(data.GetString()).append(".");
298 data.Set(moo.c_str());
303 bool ValidateNetBufferSize(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
305 if ((!data.GetInteger()) || (data.GetInteger() > 65535) || (data.GetInteger() < 1024))
307 conf->GetInstance()->Log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
313 bool ValidateMaxWho(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
315 if ((!data.GetInteger()) || (data.GetInteger() > 65535) || (data.GetInteger() < 1))
317 conf->GetInstance()->Log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
323 bool ValidateLogLevel(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
325 std::string dbg = data.GetString();
326 conf->LogLevel = DEFAULT;
329 conf->LogLevel = DEBUG;
330 else if (dbg == "verbose")
331 conf->LogLevel = VERBOSE;
332 else if (dbg == "default")
333 conf->LogLevel = DEFAULT;
334 else if (dbg == "sparse")
335 conf->LogLevel = SPARSE;
336 else if (dbg == "none")
337 conf->LogLevel = NONE;
339 conf->debugging = (conf->LogLevel == DEBUG);
344 bool ValidateMotd(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
346 conf->ReadFile(conf->MOTD, data.GetString());
350 bool ValidateRules(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
352 conf->ReadFile(conf->RULES, data.GetString());
356 bool ValidateWhoWas(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
358 conf->WhoWasMaxKeep = conf->GetInstance()->Duration(data.GetString());
360 if (conf->WhoWasGroupSize < 0)
361 conf->WhoWasGroupSize = 0;
363 if (conf->WhoWasMaxGroups < 0)
364 conf->WhoWasMaxGroups = 0;
366 if (conf->WhoWasMaxKeep < 3600)
368 conf->WhoWasMaxKeep = 3600;
369 conf->GetInstance()->Log(DEFAULT,"WARNING: <whowas:maxkeep> value less than 3600, setting to default 3600");
371 conf->GetInstance()->Log(DEBUG,"whowas:groupsize:%d maxgroups:%d maxkeep:%d",conf->WhoWasGroupSize,conf->WhoWasMaxGroups,conf->WhoWasMaxKeep);
372 irc::whowas::PruneWhoWas(conf->GetInstance(), conf->GetInstance()->Time());
376 /* Callback called before processing the first <connect> tag
378 bool InitConnect(ServerConfig* conf, const char* tag)
380 conf->GetInstance()->Log(DEFAULT,"Reading connect classes...");
381 conf->Classes.clear();
385 /* Callback called to process a single <connect> tag
387 bool DoConnect(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
390 const char* allow = values[0].GetString(); /* Yeah, there are a lot of values. Live with it. */
391 const char* deny = values[1].GetString();
392 const char* password = values[2].GetString();
393 int timeout = values[3].GetInteger();
394 int pingfreq = values[4].GetInteger();
395 int flood = values[5].GetInteger();
396 int threshold = values[6].GetInteger();
397 int sendq = values[7].GetInteger();
398 int recvq = values[8].GetInteger();
399 int localmax = values[9].GetInteger();
400 int globalmax = values[10].GetInteger();
404 ConnectClass c(timeout, flood, allow, pingfreq, password, threshold, sendq, recvq, localmax, globalmax);
405 conf->Classes.push_back(c);
409 ConnectClass c(deny);
410 conf->Classes.push_back(c);
416 /* Callback called when there are no more <connect> tags
418 bool DoneConnect(ServerConfig* conf, const char* tag)
420 conf->GetInstance()->Log(DEBUG,"DoneConnect called for tag: %s",tag);
424 /* Callback called before processing the first <uline> tag
426 bool InitULine(ServerConfig* conf, const char* tag)
428 conf->ulines.clear();
432 /* Callback called to process a single <uline> tag
434 bool DoULine(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
436 const char* server = values[0].GetString();
437 conf->GetInstance()->Log(DEBUG,"Read ULINE '%s'",server);
438 conf->ulines.push_back(server);
442 /* Callback called when there are no more <uline> tags
444 bool DoneULine(ServerConfig* conf, const char* tag)
449 /* Callback called before processing the first <module> tag
451 bool InitModule(ServerConfig* conf, const char* tag)
453 old_module_names.clear();
454 new_module_names.clear();
455 added_modules.clear();
456 removed_modules.clear();
457 for (std::vector<std::string>::iterator t = conf->module_names.begin(); t != conf->module_names.end(); t++)
459 old_module_names.push_back(*t);
464 /* Callback called to process a single <module> tag
466 bool DoModule(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
468 const char* modname = values[0].GetString();
469 new_module_names.push_back(modname);
473 /* Callback called when there are no more <module> tags
475 bool DoneModule(ServerConfig* conf, const char* tag)
477 // now create a list of new modules that are due to be loaded
478 // and a seperate list of modules which are due to be unloaded
479 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
483 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
490 added_modules.push_back(*_new);
493 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
496 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
503 removed_modules.push_back(*oldm);
508 /* Callback called before processing the first <banlist> tag
510 bool InitMaxBans(ServerConfig* conf, const char* tag)
512 conf->maxbans.clear();
516 /* Callback called to process a single <banlist> tag
518 bool DoMaxBans(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
520 const char* channel = values[0].GetString();
521 int limit = values[1].GetInteger();
522 conf->maxbans[channel] = limit;
526 /* Callback called when there are no more <banlist> tags.
528 bool DoneMaxBans(ServerConfig* conf, const char* tag)
533 void ServerConfig::ReportConfigError(const std::string &errormessage, bool bail, userrec* user)
535 ServerInstance->Log(DEFAULT, "There were errors in your configuration file: %s", errormessage.c_str());
538 /* Unneeded because of the ServerInstance->Log() aboive? */
539 printf("There were errors in your configuration:\n%s\n\n",errormessage.c_str());
540 InspIRCd::Exit(EXIT_STATUS_CONFIG);
544 std::string errors = errormessage;
545 std::string::size_type start;
546 unsigned int prefixlen;
548 /* ":ServerInstance->Config->ServerName NOTICE user->nick :" */
549 prefixlen = strlen(this->ServerName) + strlen(user->nick) + 11;
552 user->WriteServ("NOTICE %s :There were errors in the configuration file:",user->nick);
553 while (start < errors.length())
555 user->WriteServ("NOTICE %s :%s",user->nick, errors.substr(start, 510 - prefixlen).c_str());
556 start += 510 - prefixlen;
561 ServerInstance->WriteOpers("There were errors in the configuration file:");
562 while (start < errors.length())
564 ServerInstance->WriteOpers(errors.substr(start, 360).c_str());
572 void ServerConfig::Read(bool bail, userrec* user)
574 static char debug[MAXBUF]; /* Temporary buffer for debugging value */
575 static char maxkeep[MAXBUF]; /* Temporary buffer for WhoWasMaxKeep value */
576 int rem = 0, add = 0; /* Number of modules added, number of modules removed */
577 std::ostringstream errstr; /* String stream containing the error output */
579 /* These tags MUST occur and must ONLY occur once in the config file */
580 static char* Once[] = { "server", "admin", "files", "power", "options", NULL };
582 /* These tags can occur ONCE or not at all */
583 InitialConfig Values[] = {
584 {"options", "softlimit", MAXCLIENTS_S, new ValueContainerUInt (&this->SoftLimit), DT_INTEGER, ValidateSoftLimit},
585 {"options", "somaxconn", SOMAXCONN_S, new ValueContainerInt (&this->MaxConn), DT_INTEGER, ValidateMaxConn},
586 {"server", "name", "", new ValueContainerChar (this->ServerName), DT_CHARPTR, ValidateServerName},
587 {"server", "description", "Configure Me", new ValueContainerChar (this->ServerDesc), DT_CHARPTR, NoValidation},
588 {"server", "network", "Network", new ValueContainerChar (this->Network), DT_CHARPTR, NoValidation},
589 {"admin", "name", "Miss Configured", new ValueContainerChar (this->AdminName), DT_CHARPTR, NoValidation},
590 {"admin", "email", "Mis@configu.red", new ValueContainerChar (this->AdminEmail), DT_CHARPTR, NoValidation},
591 {"admin", "nick", "Misconfigured", new ValueContainerChar (this->AdminNick), DT_CHARPTR, NoValidation},
592 {"files", "motd", "", new ValueContainerChar (this->motd), DT_CHARPTR, ValidateMotd},
593 {"files", "rules", "", new ValueContainerChar (this->rules), DT_CHARPTR, ValidateRules},
594 {"power", "diepass", "", new ValueContainerChar (this->diepass), DT_CHARPTR, NoValidation},
595 {"power", "pause", "", new ValueContainerInt (&this->DieDelay), DT_INTEGER, NoValidation},
596 {"power", "restartpass", "", new ValueContainerChar (this->restartpass), DT_CHARPTR, NoValidation},
597 {"options", "prefixquit", "", new ValueContainerChar (this->PrefixQuit), DT_CHARPTR, NoValidation},
598 {"options", "loglevel", "default", new ValueContainerChar (debug), DT_CHARPTR, ValidateLogLevel},
599 {"options", "netbuffersize","10240", new ValueContainerInt (&this->NetBufferSize), DT_INTEGER, ValidateNetBufferSize},
600 {"options", "maxwho", "128", new ValueContainerInt (&this->MaxWhoResults), DT_INTEGER, ValidateMaxWho},
601 {"options", "allowhalfop", "0", new ValueContainerBool (&this->AllowHalfop), DT_BOOLEAN, NoValidation},
602 {"dns", "server", "", new ValueContainerChar (this->DNSServer), DT_CHARPTR, ValidateDnsServer},
603 {"dns", "timeout", "5", new ValueContainerInt (&this->dns_timeout), DT_INTEGER, NoValidation},
604 {"options", "moduledir", MOD_PATH, new ValueContainerChar (this->ModPath), DT_CHARPTR, NoValidation},
605 {"disabled", "commands", "", new ValueContainerChar (this->DisabledCommands), DT_CHARPTR, NoValidation},
606 {"options", "userstats", "", new ValueContainerChar (this->UserStats), DT_CHARPTR, NoValidation},
607 {"options", "customversion","", new ValueContainerChar (this->CustomVersion), DT_CHARPTR, NoValidation},
608 {"options", "hidesplits", "0", new ValueContainerBool (&this->HideSplits), DT_BOOLEAN, NoValidation},
609 {"options", "hidebans", "0", new ValueContainerBool (&this->HideBans), DT_BOOLEAN, NoValidation},
610 {"options", "hidewhois", "", new ValueContainerChar (this->HideWhoisServer), DT_CHARPTR, NoValidation},
611 {"options", "operspywhois", "0", new ValueContainerBool (&this->OperSpyWhois), DT_BOOLEAN, NoValidation},
612 {"options", "nouserdns", "0", new ValueContainerBool (&this->NoUserDns), DT_BOOLEAN, NoValidation},
613 {"options", "syntaxhints", "0", new ValueContainerBool (&this->SyntaxHints), DT_BOOLEAN, NoValidation},
614 {"options", "cyclehosts", "0", new ValueContainerBool (&this->CycleHosts), DT_BOOLEAN, NoValidation},
615 {"options", "ircumsgprefix","0", new ValueContainerBool (&this->UndernetMsgPrefix), DT_BOOLEAN, NoValidation},
616 {"pid", "file", "", new ValueContainerChar (this->PID), DT_CHARPTR, NoValidation},
617 {"whowas", "groupsize", "10", new ValueContainerInt (&this->WhoWasGroupSize), DT_INTEGER, NoValidation},
618 {"whowas", "maxgroups", "10240", new ValueContainerInt (&this->WhoWasMaxGroups), DT_INTEGER, NoValidation},
619 {"whowas", "maxkeep", "3600", new ValueContainerChar (maxkeep), DT_CHARPTR, ValidateWhoWas},
620 {"die", "value", "", new ValueContainerChar (this->DieValue), DT_CHARPTR, NoValidation},
624 /* These tags can occur multiple times, and therefore they have special code to read them
625 * which is different to the code for reading the singular tags listed above.
627 MultiConfig MultiValues[] = {
630 {"allow", "deny", "password", "timeout", "pingfreq", "flood",
631 "threshold", "sendq", "recvq", "localmax", "globalmax", NULL},
632 {"", "", "", "", "", "",
633 "", "", "", "", "", NULL},
634 {DT_CHARPTR, DT_CHARPTR, DT_CHARPTR, DT_INTEGER, DT_INTEGER, DT_INTEGER,
635 DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER},
636 InitConnect, DoConnect, DoneConnect},
642 InitULine,DoULine,DoneULine},
645 {"chan", "limit", NULL},
647 {DT_CHARPTR, DT_INTEGER},
648 InitMaxBans, DoMaxBans, DoneMaxBans},
654 InitModule, DoModule, DoneModule},
657 {"reason", "ipmask", NULL},
658 {"No reason", "", NULL},
659 {DT_CHARPTR, DT_CHARPTR},
660 InitXLine, DoZLine, DoneZLine},
663 {"reason", "nick", NULL},
664 {"No reason", "", NULL},
665 {DT_CHARPTR, DT_CHARPTR},
666 InitXLine, DoQLine, DoneQLine},
669 {"reason", "host", NULL},
670 {"No reason", "", NULL},
671 {DT_CHARPTR, DT_CHARPTR},
672 InitXLine, DoKLine, DoneKLine},
675 {"reason", "host", NULL},
676 {"No reason", "", NULL},
677 {DT_CHARPTR, DT_CHARPTR},
678 InitXLine, DoELine, DoneELine},
681 {"name", "classes", NULL},
683 {DT_CHARPTR, DT_CHARPTR},
684 InitTypes, DoType, DoneClassesAndTypes},
687 {"name", "commands", NULL},
689 {DT_CHARPTR, DT_CHARPTR},
690 InitClasses, DoClass, DoneClassesAndTypes},
695 include_stack.clear();
697 /* Load and parse the config file, if there are any errors then explode */
699 /* Make a copy here so if it fails then we can carry on running with an unaffected config */
700 ConfigDataHash newconfig;
702 if (this->LoadConf(newconfig, CONFIG_FILE, errstr))
704 /* If we succeeded, set the ircd config to the new one */
705 this->config_data = newconfig;
709 ReportConfigError(errstr.str(), bail, user);
713 /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
716 /* Check we dont have more than one of singular tags, or any of them missing
718 for (int Index = 0; Once[Index]; Index++)
719 if (!CheckOnce(Once[Index], bail, user))
722 /* Read the values of all the tags which occur once or not at all, and call their callbacks.
724 for (int Index = 0; Values[Index].tag; Index++)
727 int dt = Values[Index].datatype;
728 bool allow_newlines = ((dt & DT_ALLOW_NEWLINE) > 0);
729 dt &= ~DT_ALLOW_NEWLINE;
731 ConfValue(this->config_data, Values[Index].tag, Values[Index].value, Values[Index].default_value, 0, item, MAXBUF, allow_newlines);
734 Values[Index].validation_function(this, Values[Index].tag, Values[Index].value, vi);
736 switch (Values[Index].datatype)
740 ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
741 vcc->Set(vi.GetString(), strlen(vi.GetString()));
746 int val = vi.GetInteger();
747 ValueContainerInt* vci = (ValueContainerInt*)Values[Index].val;
748 vci->Set(&val, sizeof(int));
753 bool val = vi.GetBool();
754 ValueContainerBool* vcb = (ValueContainerBool*)Values[Index].val;
755 vcb->Set(&val, sizeof(bool));
759 /* You don't want to know what happens if someones bad code sends us here. */
763 /* We're done with this now */
764 delete Values[Index].val;
767 /* Read the multiple-tag items (class tags, connect tags, etc)
768 * and call the callbacks associated with them. We have three
769 * callbacks for these, a 'start', 'item' and 'end' callback.
771 for (int Index = 0; MultiValues[Index].tag; Index++)
773 MultiValues[Index].init_function(this, MultiValues[Index].tag);
775 int number_of_tags = ConfValueEnum(this->config_data, MultiValues[Index].tag);
777 for (int tagnum = 0; tagnum < number_of_tags; tagnum++)
780 for (int valuenum = 0; MultiValues[Index].items[valuenum]; valuenum++)
782 int dt = MultiValues[Index].datatype[valuenum];
783 bool allow_newlines = ((dt & DT_ALLOW_NEWLINE) > 0);
784 dt &= ~DT_ALLOW_NEWLINE;
791 if (ConfValue(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
792 vl.push_back(ValueItem(item));
794 vl.push_back(ValueItem(""));
800 if (ConfValueInteger(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item))
801 vl.push_back(ValueItem(item));
803 vl.push_back(ValueItem(0));
808 bool item = ConfValueBool(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum);
809 vl.push_back(ValueItem(item));
813 /* Someone was smoking craq if we got here, and we're all gonna die. */
818 MultiValues[Index].validation_function(this, MultiValues[Index].tag, (char**)MultiValues[Index].items, vl, MultiValues[Index].datatype);
821 MultiValues[Index].finish_function(this, MultiValues[Index].tag);
826 catch (CoreException &ce)
828 ReportConfigError(ce.GetReason(), bail, user);
832 // write once here, to try it out and make sure its ok
833 ServerInstance->WritePID(this->PID);
835 ServerInstance->Log(DEFAULT,"Done reading configuration file.");
837 /* If we're rehashing, let's load any new modules, and unload old ones
843 ServerInstance->stats->BoundPortCount = ServerInstance->BindPorts(false, found_ports, pl);
847 user->WriteServ("NOTICE %s :*** Not all your client ports could be bound.", user->nick);
848 user->WriteServ("NOTICE %s :*** The following port%s failed to bind:", user->nick, found_ports - ServerInstance->stats->BoundPortCount != 1 ? "s" : "");
850 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
852 user->WriteServ("NOTICE %s :*** %d. IP: %s Port: %lu", user->nick, j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
856 if (!removed_modules.empty())
858 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
860 if (ServerInstance->UnloadModule(removing->c_str()))
862 ServerInstance->WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
865 user->WriteServ("973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
872 user->WriteServ("972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
877 if (!added_modules.empty())
879 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
881 if (ServerInstance->LoadModule(adding->c_str()))
883 ServerInstance->WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
886 user->WriteServ("975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
893 user->WriteServ("974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
898 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());
902 bool ServerConfig::LoadConf(ConfigDataHash &target, const char* filename, std::ostringstream &errorstream)
904 std::ifstream conf(filename);
917 /* Check if the file open failed first */
920 errorstream << "LoadConf: Couldn't open config file: " << filename << std::endl;
924 /* Fix the chmod of the file to restrict it to the current user and group */
925 chmod(filename,0600);
927 for (unsigned int t = 0; t < include_stack.size(); t++)
929 if (std::string(filename) == include_stack[t])
931 errorstream << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
936 /* It's not already included, add it to the list of files we've loaded */
937 include_stack.push_back(filename);
939 /* Start reading characters... */
943 * Here we try and get individual tags on separate lines,
944 * this would be so easy if we just made people format
945 * their config files like that, but they don't so...
946 * We check for a '<' and then know the line is over when
947 * we get a '>' not inside quotes. If we find two '<' and
948 * no '>' then die with an error.
951 if((ch == '#') && !in_quote)
954 /*if(((ch == '\n') || (ch == '\r')) && in_quote)
956 errorstream << "Got a newline within a quoted section, this is probably a typo: " << filename << ":" << linenumber << std::endl;
965 ServerInstance->Log(DEBUG, "Got \\n inside value");
981 /* XXX: Added by Brain, May 1st 2006 - Escaping of characters.
982 * Note that this WILL NOT usually allow insertion of newlines,
983 * because a newline is two characters long. Use it primarily to
984 * insert the " symbol.
986 * Note that this also involves a further check when parsing the line,
987 * which can be found below.
989 if ((ch == '\\') && (in_quote) && (in_tag))
992 ServerInstance->Log(DEBUG,"Escape sequence in config line.");
994 if (conf.get(real_character))
996 ServerInstance->Log(DEBUG,"Escaping %c", real_character);
997 if (real_character == 'n')
998 real_character = '\n';
999 line += real_character;
1004 errorstream << "End of file after a \\, what did you want to escape?: " << filename << ":" << linenumber << std::endl;
1018 errorstream << "Got another opening < when the first one wasn't closed: " << filename << ":" << linenumber << std::endl;
1026 errorstream << "We're in a quote but outside a tag, interesting. " << filename << ":" << linenumber << std::endl;
1031 // errorstream << "Opening new config tag on line " << linenumber << std::endl;
1042 // errorstream << "Closing quote in config tag on line " << linenumber << std::endl;
1047 // errorstream << "Opening quote in config tag on line " << linenumber << std::endl;
1055 errorstream << "Found a (closing) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1059 errorstream << "Found a (opening) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1069 // errorstream << "Closing config tag on line " << linenumber << std::endl;
1073 * If this finds an <include> then ParseLine can simply call
1074 * LoadConf() and load the included config into the same ConfigDataHash
1077 if(!this->ParseLine(target, line, linenumber, errorstream))
1084 errorstream << "Got a closing > when we weren't inside a tag: " << filename << ":" << linenumber << std::endl;
1094 bool ServerConfig::LoadConf(ConfigDataHash &target, const std::string &filename, std::ostringstream &errorstream)
1096 return this->LoadConf(target, filename.c_str(), errorstream);
1099 bool ServerConfig::ParseLine(ConfigDataHash &target, std::string &line, long linenumber, std::ostringstream &errorstream)
1101 std::string tagname;
1102 std::string current_key;
1103 std::string current_value;
1109 got_name = got_key = in_quote = false;
1111 //std::cout << "ParseLine(data, '" << line << "', " << linenumber << ", stream)" << std::endl;
1113 for(std::string::iterator c = line.begin(); c != line.end(); c++)
1117 /* We don't know the tag name yet. */
1128 /* We got to a space, we should have the tagname now. */
1129 if(tagname.length())
1137 /* We have the tag name */
1140 /* We're still reading the key name */
1150 /* We got an '=', end of the key name. */
1156 /* We have the key name, now we're looking for quotes and the value */
1158 /* Correctly handle escaped characters here.
1159 * See the XXX'ed section above.
1161 if ((*c == '\\') && (in_quote))
1165 current_value += '\n';
1167 current_value += *c;
1170 else if ((*c == '\n') && (in_quote))
1172 /* Got a 'real' \n, treat it as part of the value */
1173 current_value += '\n';
1176 else if ((*c == '\r') && (in_quote))
1177 /* Got a \r, drop it */
1184 /* We're not already in a quote. */
1189 /* Leaving quotes, we have the value */
1190 results.push_back(KeyVal(current_key, current_value));
1192 // std::cout << "<" << tagname << ":" << current_key << "> " << current_value << std::endl;
1197 if((tagname == "include") && (current_key == "file"))
1199 if(!this->DoInclude(target, current_value, errorstream))
1203 current_key.clear();
1204 current_value.clear();
1211 current_value += *c;
1218 /* Finished parsing the tag, add it to the config hash */
1219 target.insert(std::pair<std::string, KeyValList > (tagname, results));
1224 bool ServerConfig::DoInclude(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream)
1226 std::string confpath;
1227 std::string newfile;
1228 std::string::size_type pos;
1230 confpath = CONFIG_FILE;
1233 for (std::string::iterator c = newfile.begin(); c != newfile.end(); c++)
1243 if((pos = confpath.find("/inspircd.conf")) != std::string::npos)
1245 /* Leaves us with just the path */
1246 newfile = confpath.substr(0, pos) + std::string("/") + newfile;
1250 errorstream << "Couldn't get config path from: " << confpath << std::endl;
1255 return LoadConf(target, newfile, errorstream);
1258 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, int index, char* result, int length, bool allow_linefeeds)
1260 return ConfValue(target, tag, var, "", index, result, length, allow_linefeeds);
1263 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index, char* result, int length, bool allow_linefeeds)
1266 bool r = ConfValue(target, std::string(tag), std::string(var), std::string(default_value), index, value, allow_linefeeds);
1267 strlcpy(result, value.c_str(), length);
1271 bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, std::string &result, bool allow_linefeeds)
1273 return ConfValue(target, tag, var, "", index, result, allow_linefeeds);
1276 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)
1278 ConfigDataHash::size_type pos = index;
1279 if((pos >= 0) && (pos < target.count(tag)))
1281 ConfigDataHash::iterator iter = target.find(tag);
1283 for(int i = 0; i < index; i++)
1286 for(KeyValList::iterator j = iter->second.begin(); j != iter->second.end(); j++)
1290 if ((!allow_linefeeds) && (j->second.find('\n') != std::string::npos))
1292 ServerInstance->Log(DEFAULT, "Value of <" + tag + ":" + var+ "> contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
1293 for (std::string::iterator n = j->second.begin(); n != j->second.end(); n++)
1304 if (!default_value.empty())
1306 result = default_value;
1307 ServerInstance->Log(DEBUG, "No config option for '%s' in tag <%s> using default: %s", var.c_str(), tag.c_str(), default_value.c_str());
1313 if (!default_value.empty())
1315 result = default_value;
1316 ServerInstance->Log(DEBUG, "No <%s:%s> tags in config file using default: %s", tag.c_str(), var.c_str(), default_value.c_str());
1319 ServerInstance->Log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1323 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());
1328 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, int index, int &result)
1330 return ConfValueInteger(target, std::string(tag), std::string(var), "", index, result);
1333 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index, int &result)
1335 return ConfValueInteger(target, std::string(tag), std::string(var), std::string(default_value), index, result);
1338 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, int &result)
1340 return ConfValueInteger(target, tag, var, "", index, result);
1343 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index, int &result)
1346 std::istringstream stream;
1347 bool r = ConfValue(target, tag, var, default_value, index, value);
1349 if(!(stream >> result))
1355 if (value.substr(0,2) == "0x")
1360 result = strtol(value.c_str(), &endptr, 16);
1362 /* No digits found */
1363 if (endptr == value.c_str())
1368 char denominator = *(value.end() - 1);
1369 switch (toupper(denominator))
1372 /* Kilobytes -> bytes */
1373 result = result * 1024;
1376 /* Megabytes -> bytes */
1377 result = result * 1024 * 1024;
1380 /* Gigabytes -> bytes */
1381 result = result * 1024 * 1024 * 1024;
1391 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, int index)
1393 return ConfValueBool(target, std::string(tag), std::string(var), "", index);
1396 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index)
1398 return ConfValueBool(target, std::string(tag), std::string(var), std::string(default_value), index);
1401 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, int index)
1403 return ConfValueBool(target, tag, var, "", index);
1406 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index)
1409 if(!ConfValue(target, tag, var, default_value, index, result))
1412 return ((result == "yes") || (result == "true") || (result == "1"));
1415 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const char* tag)
1417 return target.count(tag);
1420 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const std::string &tag)
1422 return target.count(tag);
1425 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const char* tag, int index)
1427 return ConfVarEnum(target, std::string(tag), index);
1430 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const std::string &tag, int index)
1432 ConfigDataHash::size_type pos = index;
1434 if((pos >= 0) && (pos < target.count(tag)))
1436 ConfigDataHash::const_iterator iter = target.find(tag);
1438 for(int i = 0; i < index; i++)
1441 return iter->second.size();
1445 ServerInstance->Log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1449 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());
1455 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1457 bool ServerConfig::ReadFile(file_cache &F, const char* fname)
1460 char linebuf[MAXBUF];
1466 std::string::size_type pos;
1467 std::string confpath = CONFIG_FILE;
1468 if((pos = confpath.find("/inspircd.conf")) != std::string::npos)
1470 /* Leaves us with just the path */
1471 std::string newfile = confpath.substr(0, pos) + std::string("/") + fname;
1472 file = fopen(newfile.c_str(), "r");
1477 file = fopen(fname, "r");
1483 if (fgets(linebuf, sizeof(linebuf), file))
1484 linebuf[strlen(linebuf)-1] = 0;
1490 F.push_back(*linebuf ? linebuf : " ");
1502 bool ServerConfig::FileExists(const char* file)
1505 if ((input = fopen (file, "r")) == NULL)
1516 char* ServerConfig::CleanFilename(char* name)
1518 char* p = name + strlen(name);
1519 while ((p != name) && (*p != '/')) p--;
1520 return (p != name ? ++p : p);
1524 bool ServerConfig::DirValid(const char* dirandfile)
1527 char buffer[MAXBUF];
1528 char otherdir[MAXBUF];
1531 strlcpy(work, dirandfile, MAXBUF);
1534 // we just want the dir
1546 // Get the current working directory
1547 if (getcwd(buffer, MAXBUF ) == NULL )
1550 if (chdir(work) == -1)
1553 if (getcwd(otherdir, MAXBUF ) == NULL )
1556 if (chdir(buffer) == -1)
1559 size_t t = strlen(work);
1561 if (strlen(otherdir) >= t)
1565 if (!strcmp(otherdir,work))
1578 std::string ServerConfig::GetFullProgDir(char** argv, int argc)
1581 char buffer[MAXBUF];
1582 char otherdir[MAXBUF];
1585 strlcpy(work,argv[0],MAXBUF);
1588 // we just want the dir
1600 // Get the current working directory
1601 if (getcwd(buffer, MAXBUF) == NULL)
1604 if (chdir(work) == -1)
1607 if (getcwd(otherdir, MAXBUF) == NULL)
1610 if (chdir(buffer) == -1)
1616 InspIRCd* ServerConfig::GetInstance()
1618 return ServerInstance;
1622 ValueItem::ValueItem(int value)
1624 std::stringstream n;
1629 ValueItem::ValueItem(bool value)
1631 std::stringstream n;
1636 ValueItem::ValueItem(char* value)
1641 void ValueItem::Set(char* value)
1646 void ValueItem::Set(const char* value)
1651 void ValueItem::Set(int value)
1653 std::stringstream n;
1658 int ValueItem::GetInteger()
1662 return atoi(v.c_str());
1665 char* ValueItem::GetString()
1667 return (char*)v.c_str();
1670 bool ValueItem::GetBool()
1672 return (GetInteger() || v == "yes" || v == "true");