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 static char somax[MAXBUF]; /* Temporary buffer for SOMAXCONN default */
577 int rem = 0, add = 0; /* Number of modules added, number of modules removed */
578 std::ostringstream errstr; /* String stream containing the error output */
580 /* These tags MUST occur and must ONLY occur once in the config file */
581 static char* Once[] = { "server", "admin", "files", "power", "options", NULL };
583 /* These tags can occur ONCE or not at all */
584 InitialConfig Values[] = {
585 {"options", "softlimit", MAXCLIENTS_S, new ValueContainerUInt (&this->SoftLimit), DT_INTEGER, ValidateSoftLimit},
586 {"options", "somaxconn", SOMAXCONN_S, new ValueContainerInt (&this->MaxConn), DT_INTEGER, ValidateMaxConn},
587 {"server", "name", "", new ValueContainerChar (this->ServerName), DT_CHARPTR, ValidateServerName},
588 {"server", "description", "Configure Me", new ValueContainerChar (this->ServerDesc), DT_CHARPTR, NoValidation},
589 {"server", "network", "Network", new ValueContainerChar (this->Network), DT_CHARPTR, NoValidation},
590 {"admin", "name", "Miss Configured", new ValueContainerChar (this->AdminName), DT_CHARPTR, NoValidation},
591 {"admin", "email", "Mis@configu.red", new ValueContainerChar (this->AdminEmail), DT_CHARPTR, NoValidation},
592 {"admin", "nick", "Misconfigured", new ValueContainerChar (this->AdminNick), DT_CHARPTR, NoValidation},
593 {"files", "motd", "", new ValueContainerChar (this->motd), DT_CHARPTR, ValidateMotd},
594 {"files", "rules", "", new ValueContainerChar (this->rules), DT_CHARPTR, ValidateRules},
595 {"power", "diepass", "", new ValueContainerChar (this->diepass), DT_CHARPTR, NoValidation},
596 {"power", "pause", "", new ValueContainerInt (&this->DieDelay), DT_INTEGER, NoValidation},
597 {"power", "restartpass", "", new ValueContainerChar (this->restartpass), DT_CHARPTR, NoValidation},
598 {"options", "prefixquit", "", new ValueContainerChar (this->PrefixQuit), DT_CHARPTR, NoValidation},
599 {"options", "loglevel", "default", new ValueContainerChar (debug), DT_CHARPTR, ValidateLogLevel},
600 {"options", "netbuffersize","10240", new ValueContainerInt (&this->NetBufferSize), DT_INTEGER, ValidateNetBufferSize},
601 {"options", "maxwho", "128", new ValueContainerInt (&this->MaxWhoResults), DT_INTEGER, ValidateMaxWho},
602 {"options", "allowhalfop", "0", new ValueContainerBool (&this->AllowHalfop), DT_BOOLEAN, NoValidation},
603 {"dns", "server", "", new ValueContainerChar (this->DNSServer), DT_CHARPTR, ValidateDnsServer},
604 {"dns", "timeout", "5", new ValueContainerInt (&this->dns_timeout), DT_INTEGER, NoValidation},
605 {"options", "moduledir", MOD_PATH, new ValueContainerChar (this->ModPath), DT_CHARPTR, NoValidation},
606 {"disabled", "commands", "", new ValueContainerChar (this->DisabledCommands), DT_CHARPTR, NoValidation},
607 {"options", "userstats", "", new ValueContainerChar (this->UserStats), DT_CHARPTR, NoValidation},
608 {"options", "customversion","", new ValueContainerChar (this->CustomVersion), DT_CHARPTR, NoValidation},
609 {"options", "hidesplits", "0", new ValueContainerBool (&this->HideSplits), DT_BOOLEAN, NoValidation},
610 {"options", "hidebans", "0", new ValueContainerBool (&this->HideBans), DT_BOOLEAN, NoValidation},
611 {"options", "hidewhois", "", new ValueContainerChar (this->HideWhoisServer), DT_CHARPTR, NoValidation},
612 {"options", "operspywhois", "0", new ValueContainerBool (&this->OperSpyWhois), DT_BOOLEAN, NoValidation},
613 {"options", "nouserdns", "0", new ValueContainerBool (&this->NoUserDns), DT_BOOLEAN, NoValidation},
614 {"options", "syntaxhints", "0", new ValueContainerBool (&this->SyntaxHints), DT_BOOLEAN, NoValidation},
615 {"options", "cyclehosts", "0", new ValueContainerBool (&this->CycleHosts), DT_BOOLEAN, NoValidation},
616 {"options", "ircumsgprefix","0", new ValueContainerBool (&this->UndernetMsgPrefix), DT_BOOLEAN, NoValidation},
617 {"pid", "file", "", new ValueContainerChar (this->PID), DT_CHARPTR, NoValidation},
618 {"whowas", "groupsize", "10", new ValueContainerInt (&this->WhoWasGroupSize), DT_INTEGER, NoValidation},
619 {"whowas", "maxgroups", "10240", new ValueContainerInt (&this->WhoWasMaxGroups), DT_INTEGER, NoValidation},
620 {"whowas", "maxkeep", "3600", new ValueContainerChar (maxkeep), DT_CHARPTR, ValidateWhoWas},
621 {"die", "value", "", new ValueContainerChar (this->DieValue), DT_CHARPTR, NoValidation},
625 /* These tags can occur multiple times, and therefore they have special code to read them
626 * which is different to the code for reading the singular tags listed above.
628 MultiConfig MultiValues[] = {
631 {"allow", "deny", "password", "timeout", "pingfreq", "flood",
632 "threshold", "sendq", "recvq", "localmax", "globalmax", NULL},
633 {"", "", "", "", "", "",
634 "", "", "", "", "", NULL},
635 {DT_CHARPTR, DT_CHARPTR, DT_CHARPTR, DT_INTEGER, DT_INTEGER, DT_INTEGER,
636 DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER},
637 InitConnect, DoConnect, DoneConnect},
643 InitULine,DoULine,DoneULine},
646 {"chan", "limit", NULL},
648 {DT_CHARPTR, DT_INTEGER},
649 InitMaxBans, DoMaxBans, DoneMaxBans},
655 InitModule, DoModule, DoneModule},
658 {"reason", "ipmask", NULL},
659 {"No reason", "", NULL},
660 {DT_CHARPTR, DT_CHARPTR},
661 InitXLine, DoZLine, DoneXLine},
664 {"reason", "nick", NULL},
665 {"No reason", "", NULL},
666 {DT_CHARPTR, DT_CHARPTR},
667 InitXLine, DoQLine, DoneXLine},
670 {"reason", "host", NULL},
671 {"No reason", "", NULL},
672 {DT_CHARPTR, DT_CHARPTR},
673 InitXLine, DoKLine, DoneXLine},
676 {"reason", "host", NULL},
677 {"No reason", "", NULL},
678 {DT_CHARPTR, DT_CHARPTR},
679 InitXLine, DoELine, DoneXLine},
682 {"name", "classes", NULL},
684 {DT_CHARPTR, DT_CHARPTR},
685 InitTypes, DoType, DoneClassesAndTypes},
688 {"name", "commands", NULL},
690 {DT_CHARPTR, DT_CHARPTR},
691 InitClasses, DoClass, DoneClassesAndTypes},
696 include_stack.clear();
698 /* Load and parse the config file, if there are any errors then explode */
700 /* Make a copy here so if it fails then we can carry on running with an unaffected config */
701 ConfigDataHash newconfig;
703 if (this->LoadConf(newconfig, CONFIG_FILE, errstr))
705 /* If we succeeded, set the ircd config to the new one */
706 this->config_data = newconfig;
710 ReportConfigError(errstr.str(), bail, user);
714 /* The stuff in here may throw CoreException, be sure we're in a position to catch it. */
717 /* Check we dont have more than one of singular tags, or any of them missing
719 for (int Index = 0; Once[Index]; Index++)
720 if (!CheckOnce(Once[Index], bail, user))
723 /* Read the values of all the tags which occur once or not at all, and call their callbacks.
725 for (int Index = 0; Values[Index].tag; Index++)
728 int dt = Values[Index].datatype;
729 bool allow_newlines = ((dt & DT_ALLOW_NEWLINE) > 0);
730 dt &= ~DT_ALLOW_NEWLINE;
732 ConfValue(this->config_data, Values[Index].tag, Values[Index].value, Values[Index].default_value, 0, item, MAXBUF, allow_newlines);
735 Values[Index].validation_function(this, Values[Index].tag, Values[Index].value, vi);
737 switch (Values[Index].datatype)
741 ValueContainerChar* vcc = (ValueContainerChar*)Values[Index].val;
742 vcc->Set(vi.GetString(), strlen(vi.GetString()));
747 int val = vi.GetInteger();
748 ValueContainerInt* vci = (ValueContainerInt*)Values[Index].val;
749 vci->Set(&val, sizeof(int));
754 bool val = vi.GetBool();
755 ValueContainerBool* vcb = (ValueContainerBool*)Values[Index].val;
756 vcb->Set(&val, sizeof(bool));
760 /* You don't want to know what happens if someones bad code sends us here. */
764 /* We're done with this now */
765 delete Values[Index].val;
768 /* Read the multiple-tag items (class tags, connect tags, etc)
769 * and call the callbacks associated with them. We have three
770 * callbacks for these, a 'start', 'item' and 'end' callback.
772 for (int Index = 0; MultiValues[Index].tag; Index++)
774 MultiValues[Index].init_function(this, MultiValues[Index].tag);
776 int number_of_tags = ConfValueEnum(this->config_data, MultiValues[Index].tag);
778 for (int tagnum = 0; tagnum < number_of_tags; tagnum++)
781 for (int valuenum = 0; MultiValues[Index].items[valuenum]; valuenum++)
783 int dt = MultiValues[Index].datatype[valuenum];
784 bool allow_newlines = ((dt & DT_ALLOW_NEWLINE) > 0);
785 dt &= ~DT_ALLOW_NEWLINE;
792 if (ConfValue(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item, MAXBUF, allow_newlines))
793 vl.push_back(ValueItem(item));
795 vl.push_back(ValueItem(""));
801 if (ConfValueInteger(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum, item))
802 vl.push_back(ValueItem(item));
804 vl.push_back(ValueItem(0));
809 bool item = ConfValueBool(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], MultiValues[Index].items_default[valuenum], tagnum);
810 vl.push_back(ValueItem(item));
814 /* Someone was smoking craq if we got here, and we're all gonna die. */
819 MultiValues[Index].validation_function(this, MultiValues[Index].tag, (char**)MultiValues[Index].items, vl, MultiValues[Index].datatype);
822 MultiValues[Index].finish_function(this, MultiValues[Index].tag);
827 catch (CoreException &ce)
829 ReportConfigError(ce.GetReason(), bail, user);
833 // write once here, to try it out and make sure its ok
834 ServerInstance->WritePID(this->PID);
836 ServerInstance->Log(DEFAULT,"Done reading configuration file.");
838 /* If we're rehashing, let's load any new modules, and unload old ones
844 ServerInstance->stats->BoundPortCount = ServerInstance->BindPorts(false, found_ports, pl);
848 user->WriteServ("NOTICE %s :*** Not all your client ports could be bound.", user->nick);
849 user->WriteServ("NOTICE %s :*** The following port%s failed to bind:", user->nick, found_ports - ServerInstance->stats->BoundPortCount != 1 ? "s" : "");
851 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
853 user->WriteServ("NOTICE %s :*** %d. IP: %s Port: %lu", user->nick, j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
857 if (!removed_modules.empty())
859 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
861 if (ServerInstance->UnloadModule(removing->c_str()))
863 ServerInstance->WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
866 user->WriteServ("973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
873 user->WriteServ("972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
878 if (!added_modules.empty())
880 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
882 if (ServerInstance->LoadModule(adding->c_str()))
884 ServerInstance->WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
887 user->WriteServ("975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
894 user->WriteServ("974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
899 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());
903 bool ServerConfig::LoadConf(ConfigDataHash &target, const char* filename, std::ostringstream &errorstream)
905 std::ifstream conf(filename);
918 /* Check if the file open failed first */
921 errorstream << "LoadConf: Couldn't open config file: " << filename << std::endl;
925 /* Fix the chmod of the file to restrict it to the current user and group */
926 chmod(filename,0600);
928 for (unsigned int t = 0; t < include_stack.size(); t++)
930 if (std::string(filename) == include_stack[t])
932 errorstream << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
937 /* It's not already included, add it to the list of files we've loaded */
938 include_stack.push_back(filename);
940 /* Start reading characters... */
944 * Here we try and get individual tags on separate lines,
945 * this would be so easy if we just made people format
946 * their config files like that, but they don't so...
947 * We check for a '<' and then know the line is over when
948 * we get a '>' not inside quotes. If we find two '<' and
949 * no '>' then die with an error.
952 if((ch == '#') && !in_quote)
955 /*if(((ch == '\n') || (ch == '\r')) && in_quote)
957 errorstream << "Got a newline within a quoted section, this is probably a typo: " << filename << ":" << linenumber << std::endl;
966 ServerInstance->Log(DEBUG, "Got \\n inside value");
982 /* XXX: Added by Brain, May 1st 2006 - Escaping of characters.
983 * Note that this WILL NOT usually allow insertion of newlines,
984 * because a newline is two characters long. Use it primarily to
985 * insert the " symbol.
987 * Note that this also involves a further check when parsing the line,
988 * which can be found below.
990 if ((ch == '\\') && (in_quote) && (in_tag))
993 ServerInstance->Log(DEBUG,"Escape sequence in config line.");
995 if (conf.get(real_character))
997 ServerInstance->Log(DEBUG,"Escaping %c", real_character);
998 if (real_character == 'n')
999 real_character = '\n';
1000 line += real_character;
1005 errorstream << "End of file after a \\, what did you want to escape?: " << filename << ":" << linenumber << std::endl;
1019 errorstream << "Got another opening < when the first one wasn't closed: " << filename << ":" << linenumber << std::endl;
1027 errorstream << "We're in a quote but outside a tag, interesting. " << filename << ":" << linenumber << std::endl;
1032 // errorstream << "Opening new config tag on line " << linenumber << std::endl;
1043 // errorstream << "Closing quote in config tag on line " << linenumber << std::endl;
1048 // errorstream << "Opening quote in config tag on line " << linenumber << std::endl;
1056 errorstream << "Found a (closing) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1060 errorstream << "Found a (opening) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1070 // errorstream << "Closing config tag on line " << linenumber << std::endl;
1074 * If this finds an <include> then ParseLine can simply call
1075 * LoadConf() and load the included config into the same ConfigDataHash
1078 if(!this->ParseLine(target, line, linenumber, errorstream))
1085 errorstream << "Got a closing > when we weren't inside a tag: " << filename << ":" << linenumber << std::endl;
1095 bool ServerConfig::LoadConf(ConfigDataHash &target, const std::string &filename, std::ostringstream &errorstream)
1097 return this->LoadConf(target, filename.c_str(), errorstream);
1100 bool ServerConfig::ParseLine(ConfigDataHash &target, std::string &line, long linenumber, std::ostringstream &errorstream)
1102 std::string tagname;
1103 std::string current_key;
1104 std::string current_value;
1110 got_name = got_key = in_quote = false;
1112 //std::cout << "ParseLine(data, '" << line << "', " << linenumber << ", stream)" << std::endl;
1114 for(std::string::iterator c = line.begin(); c != line.end(); c++)
1118 /* We don't know the tag name yet. */
1129 /* We got to a space, we should have the tagname now. */
1130 if(tagname.length())
1138 /* We have the tag name */
1141 /* We're still reading the key name */
1151 /* We got an '=', end of the key name. */
1157 /* We have the key name, now we're looking for quotes and the value */
1159 /* Correctly handle escaped characters here.
1160 * See the XXX'ed section above.
1162 if ((*c == '\\') && (in_quote))
1166 current_value += '\n';
1168 current_value += *c;
1171 else if ((*c == '\n') && (in_quote))
1173 /* Got a 'real' \n, treat it as part of the value */
1174 current_value += '\n';
1177 else if ((*c == '\r') && (in_quote))
1178 /* Got a \r, drop it */
1185 /* We're not already in a quote. */
1190 /* Leaving quotes, we have the value */
1191 results.push_back(KeyVal(current_key, current_value));
1193 // std::cout << "<" << tagname << ":" << current_key << "> " << current_value << std::endl;
1198 if((tagname == "include") && (current_key == "file"))
1200 if(!this->DoInclude(target, current_value, errorstream))
1204 current_key.clear();
1205 current_value.clear();
1212 current_value += *c;
1219 /* Finished parsing the tag, add it to the config hash */
1220 target.insert(std::pair<std::string, KeyValList > (tagname, results));
1225 bool ServerConfig::DoInclude(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream)
1227 std::string confpath;
1228 std::string newfile;
1229 std::string::size_type pos;
1231 confpath = CONFIG_FILE;
1234 for (std::string::iterator c = newfile.begin(); c != newfile.end(); c++)
1244 if((pos = confpath.find("/inspircd.conf")) != std::string::npos)
1246 /* Leaves us with just the path */
1247 newfile = confpath.substr(0, pos) + std::string("/") + newfile;
1251 errorstream << "Couldn't get config path from: " << confpath << std::endl;
1256 return LoadConf(target, newfile, errorstream);
1259 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, int index, char* result, int length, bool allow_linefeeds)
1261 return ConfValue(target, tag, var, "", index, result, length, allow_linefeeds);
1264 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index, char* result, int length, bool allow_linefeeds)
1267 bool r = ConfValue(target, std::string(tag), std::string(var), std::string(default_value), index, value, allow_linefeeds);
1268 strlcpy(result, value.c_str(), length);
1272 bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, std::string &result, bool allow_linefeeds)
1274 return ConfValue(target, tag, var, "", index, result, allow_linefeeds);
1277 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)
1279 ConfigDataHash::size_type pos = index;
1280 if((pos >= 0) && (pos < target.count(tag)))
1282 ConfigDataHash::iterator iter = target.find(tag);
1284 for(int i = 0; i < index; i++)
1287 for(KeyValList::iterator j = iter->second.begin(); j != iter->second.end(); j++)
1291 if ((!allow_linefeeds) && (j->second.find('\n') != std::string::npos))
1293 ServerInstance->Log(DEFAULT, "Value of <" + tag + ":" + var+ "> contains a linefeed, and linefeeds in this value are not permitted -- stripped to spaces.");
1294 for (std::string::iterator n = j->second.begin(); n != j->second.end(); n++)
1305 if (!default_value.empty())
1307 result = default_value;
1308 ServerInstance->Log(DEBUG, "No config option for '%s' in tag <%s> using default: %s", var.c_str(), tag.c_str(), default_value.c_str());
1314 if (!default_value.empty())
1316 result = default_value;
1317 ServerInstance->Log(DEBUG, "No <%s:%s> tags in config file using default: %s", tag.c_str(), var.c_str(), default_value.c_str());
1320 ServerInstance->Log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1324 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());
1329 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, int index, int &result)
1331 return ConfValueInteger(target, std::string(tag), std::string(var), "", index, result);
1334 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index, int &result)
1336 return ConfValueInteger(target, std::string(tag), std::string(var), std::string(default_value), index, result);
1339 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, int &result)
1341 return ConfValueInteger(target, tag, var, "", index, result);
1344 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index, int &result)
1347 std::istringstream stream;
1348 bool r = ConfValue(target, tag, var, default_value, index, value);
1350 if(!(stream >> result))
1356 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, int index)
1358 return ConfValueBool(target, std::string(tag), std::string(var), "", index);
1361 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, const char* default_value, int index)
1363 return ConfValueBool(target, std::string(tag), std::string(var), std::string(default_value), index);
1366 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, int index)
1368 return ConfValueBool(target, tag, var, "", index);
1371 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, const std::string &default_value, int index)
1374 if(!ConfValue(target, tag, var, default_value, index, result))
1377 return ((result == "yes") || (result == "true") || (result == "1"));
1380 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const char* tag)
1382 return target.count(tag);
1385 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const std::string &tag)
1387 return target.count(tag);
1390 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const char* tag, int index)
1392 return ConfVarEnum(target, std::string(tag), index);
1395 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const std::string &tag, int index)
1397 ConfigDataHash::size_type pos = index;
1399 if((pos >= 0) && (pos < target.count(tag)))
1401 ConfigDataHash::const_iterator iter = target.find(tag);
1403 for(int i = 0; i < index; i++)
1406 return iter->second.size();
1410 ServerInstance->Log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1414 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());
1420 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1422 bool ServerConfig::ReadFile(file_cache &F, const char* fname)
1425 char linebuf[MAXBUF];
1431 std::string::size_type pos;
1432 std::string confpath = CONFIG_FILE;
1433 if((pos = confpath.find("/inspircd.conf")) != std::string::npos)
1435 /* Leaves us with just the path */
1436 std::string newfile = confpath.substr(0, pos) + std::string("/") + fname;
1437 file = fopen(newfile.c_str(), "r");
1442 file = fopen(fname, "r");
1448 if (fgets(linebuf, sizeof(linebuf), file))
1449 linebuf[strlen(linebuf)-1] = 0;
1455 F.push_back(*linebuf ? linebuf : " ");
1467 bool ServerConfig::FileExists(const char* file)
1470 if ((input = fopen (file, "r")) == NULL)
1481 char* ServerConfig::CleanFilename(char* name)
1483 char* p = name + strlen(name);
1484 while ((p != name) && (*p != '/')) p--;
1485 return (p != name ? ++p : p);
1489 bool ServerConfig::DirValid(const char* dirandfile)
1492 char buffer[MAXBUF];
1493 char otherdir[MAXBUF];
1496 strlcpy(work, dirandfile, MAXBUF);
1499 // we just want the dir
1511 // Get the current working directory
1512 if (getcwd(buffer, MAXBUF ) == NULL )
1515 if (chdir(work) == -1)
1518 if (getcwd(otherdir, MAXBUF ) == NULL )
1521 if (chdir(buffer) == -1)
1524 size_t t = strlen(work);
1526 if (strlen(otherdir) >= t)
1530 if (!strcmp(otherdir,work))
1543 std::string ServerConfig::GetFullProgDir(char** argv, int argc)
1546 char buffer[MAXBUF];
1547 char otherdir[MAXBUF];
1550 strlcpy(work,argv[0],MAXBUF);
1553 // we just want the dir
1565 // Get the current working directory
1566 if (getcwd(buffer, MAXBUF) == NULL)
1569 if (chdir(work) == -1)
1572 if (getcwd(otherdir, MAXBUF) == NULL)
1575 if (chdir(buffer) == -1)
1581 InspIRCd* ServerConfig::GetInstance()
1583 return ServerInstance;
1587 ValueItem::ValueItem(int value)
1589 std::stringstream n;
1594 ValueItem::ValueItem(bool value)
1596 std::stringstream n;
1601 ValueItem::ValueItem(char* value)
1606 void ValueItem::Set(char* value)
1611 void ValueItem::Set(const char* value)
1616 void ValueItem::Set(int value)
1618 std::stringstream n;
1623 int ValueItem::GetInteger()
1627 return atoi(v.c_str());
1630 char* ValueItem::GetString()
1632 return (char*)v.c_str();
1635 bool ValueItem::GetBool()
1637 return (GetInteger() || v == "yes" || v == "true");