1 /* +------------------------------------+
2 * | Inspire Internet Relay Chat Daemon |
3 * +------------------------------------+
5 * InspIRCd is copyright (C) 2002-2006 ChatSpike-Dev.
7 * <brain@chatspike.net>
8 * <Craig@chatspike.net>
10 * Written by Craig Edwards, Craig McLure, and others.
11 * This program is free but copyrighted software; see
12 * the file COPYING for details.
14 * ---------------------------------------------------
17 #include "configreader.h"
23 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
25 ServerConfig::ServerConfig(InspIRCd* Instance) : ServerInstance(Instance)
28 *ServerName = *Network = *ServerDesc = *AdminName = '\0';
29 *HideWhoisServer = *AdminEmail = *AdminNick = *diepass = *restartpass = '\0';
30 *CustomVersion = *motd = *rules = *PrefixQuit = *DieValue = *DNSServer = '\0';
31 *UserStats = *ModPath = *MyExecutable = *DisabledCommands = *PID = '\0';
33 NoUserDns = forcedebug = OperSpyWhois = nofork = HideBans = HideSplits = false;
34 CycleHosts = writelog = AllowHalfop = true;
35 dns_timeout = DieDelay = 5;
37 NetBufferSize = 10240;
38 SoftLimit = MAXCLIENTS;
45 WhoWasMaxGroups = WhoWasGroupSize * MAXCLIENTS;
46 WhoWasMaxKeep = 3600*24*3; // 3 days
49 void ServerConfig::ClearStack()
51 include_stack.clear();
54 Module* ServerConfig::GetIOHook(int port)
56 std::map<int,Module*>::iterator x = IOHookModule.find(port);
57 return (x != IOHookModule.end() ? x->second : NULL);
60 Module* ServerConfig::GetIOHook(InspSocket* is)
62 std::map<InspSocket*,Module*>::iterator x = SocketIOHookModule.find(is);
63 return (x != SocketIOHookModule.end() ? x->second : NULL);
66 bool ServerConfig::AddIOHook(int port, Module* iomod)
70 IOHookModule[port] = iomod;
75 throw ModuleException("Port already hooked by another module");
80 bool ServerConfig::AddIOHook(Module* iomod, InspSocket* is)
84 ServerInstance->Log(DEBUG,"Hooked inspsocket %08x", is);
85 SocketIOHookModule[is] = iomod;
86 is->IsIOHooked = true;
91 throw ModuleException("InspSocket derived class already hooked by another module");
96 bool ServerConfig::DelIOHook(int port)
98 std::map<int,Module*>::iterator x = IOHookModule.find(port);
99 if (x != IOHookModule.end())
101 IOHookModule.erase(x);
107 bool ServerConfig::DelIOHook(InspSocket* is)
109 std::map<InspSocket*,Module*>::iterator x = SocketIOHookModule.find(is);
110 if (x != SocketIOHookModule.end())
112 SocketIOHookModule.erase(x);
118 bool ServerConfig::CheckOnce(char* tag, bool bail, userrec* user)
120 int count = ConfValueEnum(this->config_data, tag);
126 printf("There were errors in your configuration:\nYou have more than one <%s> tag, this is not permitted.\n",tag);
127 InspIRCd::Exit(ERROR);
133 user->WriteServ("There were errors in your configuration:");
134 user->WriteServ("You have more than one <%s> tag, this is not permitted.\n",tag);
138 ServerInstance->WriteOpers("There were errors in the configuration file:");
139 ServerInstance->WriteOpers("You have more than one <%s> tag, this is not permitted.\n",tag);
148 printf("There were errors in your configuration:\nYou have not defined a <%s> tag, this is required.\n",tag);
149 InspIRCd::Exit(ERROR);
155 user->WriteServ("There were errors in your configuration:");
156 user->WriteServ("You have not defined a <%s> tag, this is required.",tag);
160 ServerInstance->WriteOpers("There were errors in the configuration file:");
161 ServerInstance->WriteOpers("You have not defined a <%s> tag, this is required.",tag);
169 bool NoValidation(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
171 conf->GetInstance()->Log(DEBUG,"No validation for <%s:%s>",tag,value);
175 bool ValidateMaxTargets(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
177 if ((data.GetInteger() < 0) || (data.GetInteger() > 31))
179 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
185 bool ValidateSoftLimit(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
187 if ((data.GetInteger() < 1) || (data.GetInteger() > MAXCLIENTS))
189 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
190 data.Set(MAXCLIENTS);
195 bool ValidateMaxConn(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
197 if (data.GetInteger() > SOMAXCONN)
198 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
199 if (!data.GetInteger())
204 bool ValidateDnsTimeout(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
206 if (!data.GetInteger())
211 bool InitializeDisabledCommands(const char* data, InspIRCd* ServerInstance)
213 std::stringstream dcmds(data);
216 /* Enable everything first */
217 for (nspace::hash_map<std::string,command_t*>::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
218 x->second->Disable(false);
220 /* Now disable all the ones which the user wants disabled */
221 while (dcmds >> thiscmd)
223 nspace::hash_map<std::string,command_t*>::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
224 if (cm != ServerInstance->Parser->cmdlist.end())
226 ServerInstance->Log(DEBUG,"Disabling command '%s'",cm->second->command.c_str());
227 cm->second->Disable(true);
233 bool ValidateDnsServer(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
235 if (!*(data.GetString()))
237 // attempt to look up their nameserver from /etc/resolv.conf
238 conf->GetInstance()->Log(DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
239 ifstream resolv("/etc/resolv.conf");
240 std::string nameserver;
241 bool found_server = false;
243 if (resolv.is_open())
245 while (resolv >> nameserver)
247 if ((nameserver == "nameserver") && (!found_server))
249 resolv >> nameserver;
250 data.Set(nameserver.c_str());
252 conf->GetInstance()->Log(DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
258 conf->GetInstance()->Log(DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
259 data.Set("127.0.0.1");
264 conf->GetInstance()->Log(DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
265 data.Set("127.0.0.1");
271 bool ValidateModPath(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
273 if (!*(data.GetString()))
279 bool ValidateServerName(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
281 if (!strchr(data.GetString(),'.'))
283 conf->GetInstance()->Log(DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s%c'",data.GetString(),data.GetString(),'.');
284 std::string moo = std::string(data.GetString()).append(".");
285 data.Set(moo.c_str());
290 bool ValidateNetBufferSize(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
292 if ((!data.GetInteger()) || (data.GetInteger() > 65535) || (data.GetInteger() < 1024))
294 conf->GetInstance()->Log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
300 bool ValidateMaxWho(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
302 if ((!data.GetInteger()) || (data.GetInteger() > 65535) || (data.GetInteger() < 1))
304 conf->GetInstance()->Log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
310 bool ValidateLogLevel(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
312 std::string dbg = data.GetString();
313 conf->LogLevel = DEFAULT;
316 conf->LogLevel = DEBUG;
317 else if (dbg == "verbose")
318 conf->LogLevel = VERBOSE;
319 else if (dbg == "default")
320 conf->LogLevel = DEFAULT;
321 else if (dbg == "sparse")
322 conf->LogLevel = SPARSE;
323 else if (dbg == "none")
324 conf->LogLevel = NONE;
326 conf->debugging = (conf->LogLevel == DEBUG);
331 bool ValidateMotd(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
333 conf->ReadFile(conf->MOTD, data.GetString());
337 bool ValidateRules(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
339 conf->ReadFile(conf->RULES, data.GetString());
343 bool ValidateWhoWas(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
345 conf->WhoWasMaxKeep = conf->GetInstance()->Duration(data.GetString());
347 if (conf->WhoWasGroupSize < 0)
348 conf->WhoWasGroupSize = 0;
350 if (conf->WhoWasMaxGroups < 0)
351 conf->WhoWasMaxGroups = 0;
353 if (conf->WhoWasMaxKeep < 3600)
355 conf->WhoWasMaxKeep = 3600;
356 conf->GetInstance()->Log(DEFAULT,"WARNING: <whowas:maxkeep> value less than 3600, setting to default 3600");
358 conf->GetInstance()->Log(DEBUG,"whowas:groupsize:%d maxgroups:%d maxkeep:%d",conf->WhoWasGroupSize,conf->WhoWasMaxGroups,conf->WhoWasMaxKeep);
359 irc::whowas::PruneWhoWas(conf->GetInstance(), conf->GetInstance()->Time());
363 /* Callback called before processing the first <connect> tag
365 bool InitConnect(ServerConfig* conf, const char* tag)
367 conf->GetInstance()->Log(DEFAULT,"Reading connect classes...");
368 conf->Classes.clear();
372 /* Callback called to process a single <connect> tag
374 bool DoConnect(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
377 const char* allow = values[0].GetString(); /* Yeah, there are a lot of values. Live with it. */
378 const char* deny = values[1].GetString();
379 const char* password = values[2].GetString();
380 int timeout = values[3].GetInteger();
381 int pingfreq = values[4].GetInteger();
382 int flood = values[5].GetInteger();
383 int threshold = values[6].GetInteger();
384 int sendq = values[7].GetInteger();
385 int recvq = values[8].GetInteger();
386 int localmax = values[9].GetInteger();
387 int globalmax = values[10].GetInteger();
394 c.registration_timeout = timeout;
395 c.pingtime = pingfreq;
397 c.threshold = threshold;
400 c.maxlocal = localmax;
401 c.maxglobal = globalmax;
406 if (c.maxglobal == 0)
408 if (c.threshold == 0)
412 conf->GetInstance()->Log(DEFAULT,"Warning: Connect allow line '%s' has no flood/threshold settings. Setting this tag to 999 lines in 1 second.",c.host.c_str());
418 if (c.registration_timeout == 0)
419 c.registration_timeout = 90;
422 conf->Classes.push_back(c);
428 conf->Classes.push_back(c);
429 conf->GetInstance()->Log(DEBUG,"Read connect class type DENY, host=%s",deny);
435 /* Callback called when there are no more <connect> tags
437 bool DoneConnect(ServerConfig* conf, const char* tag)
439 conf->GetInstance()->Log(DEBUG,"DoneConnect called for tag: %s",tag);
443 /* Callback called before processing the first <uline> tag
445 bool InitULine(ServerConfig* conf, const char* tag)
447 conf->ulines.clear();
451 /* Callback called to process a single <uline> tag
453 bool DoULine(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
455 const char* server = values[0].GetString();
456 conf->GetInstance()->Log(DEBUG,"Read ULINE '%s'",server);
457 conf->ulines.push_back(server);
461 /* Callback called when there are no more <uline> tags
463 bool DoneULine(ServerConfig* conf, const char* tag)
468 /* Callback called before processing the first <module> tag
470 bool InitModule(ServerConfig* conf, const char* tag)
472 old_module_names.clear();
473 new_module_names.clear();
474 added_modules.clear();
475 removed_modules.clear();
476 for (std::vector<std::string>::iterator t = conf->module_names.begin(); t != conf->module_names.end(); t++)
478 old_module_names.push_back(*t);
483 /* Callback called to process a single <module> tag
485 bool DoModule(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
487 const char* modname = values[0].GetString();
488 new_module_names.push_back(modname);
492 /* Callback called when there are no more <module> tags
494 bool DoneModule(ServerConfig* conf, const char* tag)
496 // now create a list of new modules that are due to be loaded
497 // and a seperate list of modules which are due to be unloaded
498 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
502 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
509 added_modules.push_back(*_new);
512 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
515 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
522 removed_modules.push_back(*oldm);
527 /* Callback called before processing the first <banlist> tag
529 bool InitMaxBans(ServerConfig* conf, const char* tag)
531 conf->maxbans.clear();
535 /* Callback called to process a single <banlist> tag
537 bool DoMaxBans(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
539 const char* channel = values[0].GetString();
540 int limit = values[1].GetInteger();
541 conf->maxbans[channel] = limit;
545 /* Callback called when there are no more <banlist> tags.
547 bool DoneMaxBans(ServerConfig* conf, const char* tag)
552 void ServerConfig::Read(bool bail, userrec* user)
554 static char debug[MAXBUF]; /* Temporary buffer for debugging value */
555 static char maxkeep[MAXBUF]; /* Temporary buffer for WhoWasMaxKeep value */
556 int rem = 0, add = 0; /* Number of modules added, number of modules removed */
557 std::ostringstream errstr; /* String stream containing the error output */
559 /* These tags MUST occur and must ONLY occur once in the config file */
560 static char* Once[] = { "server", "admin", "files", "power", "options", NULL };
562 /* These tags can occur ONCE or not at all */
563 InitialConfig Values[] = {
564 {"options", "softlimit", new ValueContainerUInt (&this->SoftLimit), DT_INTEGER, ValidateSoftLimit},
565 {"options", "somaxconn", new ValueContainerInt (&this->MaxConn), DT_INTEGER, ValidateMaxConn},
566 {"server", "name", new ValueContainerChar (this->ServerName), DT_CHARPTR, ValidateServerName},
567 {"server", "description", new ValueContainerChar (this->ServerDesc), DT_CHARPTR, NoValidation},
568 {"server", "network", new ValueContainerChar (this->Network), DT_CHARPTR, NoValidation},
569 {"admin", "name", new ValueContainerChar (this->AdminName), DT_CHARPTR, NoValidation},
570 {"admin", "email", new ValueContainerChar (this->AdminEmail), DT_CHARPTR, NoValidation},
571 {"admin", "nick", new ValueContainerChar (this->AdminNick), DT_CHARPTR, NoValidation},
572 {"files", "motd", new ValueContainerChar (this->motd), DT_CHARPTR, ValidateMotd},
573 {"files", "rules", new ValueContainerChar (this->rules), DT_CHARPTR, ValidateRules},
574 {"power", "diepass", new ValueContainerChar (this->diepass), DT_CHARPTR, NoValidation},
575 {"power", "pause", new ValueContainerInt (&this->DieDelay), DT_INTEGER, NoValidation},
576 {"power", "restartpass", new ValueContainerChar (this->restartpass), DT_CHARPTR, NoValidation},
577 {"options", "prefixquit", new ValueContainerChar (this->PrefixQuit), DT_CHARPTR, NoValidation},
578 {"options", "loglevel", new ValueContainerChar (debug), DT_CHARPTR, ValidateLogLevel},
579 {"options", "netbuffersize", new ValueContainerInt (&this->NetBufferSize), DT_INTEGER, ValidateNetBufferSize},
580 {"options", "maxwho", new ValueContainerInt (&this->MaxWhoResults), DT_INTEGER, ValidateMaxWho},
581 {"options", "allowhalfop", new ValueContainerBool (&this->AllowHalfop), DT_BOOLEAN, NoValidation},
582 {"dns", "server", new ValueContainerChar (this->DNSServer), DT_CHARPTR, ValidateDnsServer},
583 {"dns", "timeout", new ValueContainerInt (&this->dns_timeout), DT_INTEGER, ValidateDnsTimeout},
584 {"options", "moduledir", new ValueContainerChar (this->ModPath), DT_CHARPTR, ValidateModPath},
585 {"disabled", "commands", new ValueContainerChar (this->DisabledCommands), DT_CHARPTR, NoValidation},
586 {"options", "userstats", new ValueContainerChar (this->UserStats), DT_CHARPTR, NoValidation},
587 {"options", "customversion", new ValueContainerChar (this->CustomVersion), DT_CHARPTR, NoValidation},
588 {"options", "hidesplits", new ValueContainerBool (&this->HideSplits), DT_BOOLEAN, NoValidation},
589 {"options", "hidebans", new ValueContainerBool (&this->HideBans), DT_BOOLEAN, NoValidation},
590 {"options", "hidewhois", new ValueContainerChar (this->HideWhoisServer), DT_CHARPTR, NoValidation},
591 {"options", "operspywhois", new ValueContainerBool (&this->OperSpyWhois), DT_BOOLEAN, NoValidation},
592 {"options", "nouserdns", new ValueContainerBool (&this->NoUserDns), DT_BOOLEAN, NoValidation},
593 {"options", "syntaxhints", new ValueContainerBool (&this->SyntaxHints), DT_BOOLEAN, NoValidation},
594 {"options", "cyclehosts", new ValueContainerBool (&this->CycleHosts), DT_BOOLEAN, NoValidation},
595 {"pid", "file", new ValueContainerChar (this->PID), DT_CHARPTR, NoValidation},
596 {"whowas", "groupsize", new ValueContainerInt (&this->WhoWasGroupSize), DT_INTEGER, NoValidation},
597 {"whowas", "maxgroups", new ValueContainerInt (&this->WhoWasMaxGroups), DT_INTEGER, NoValidation},
598 {"whowas", "maxkeep", new ValueContainerChar (maxkeep), DT_CHARPTR, ValidateWhoWas},
599 {"die", "value", new ValueContainerChar (this->DieValue), DT_CHARPTR, NoValidation},
603 /* These tags can occur multiple times, and therefore they have special code to read them
604 * which is different to the code for reading the singular tags listed above.
606 MultiConfig MultiValues[] = {
609 {"allow", "deny", "password", "timeout", "pingfreq", "flood",
610 "threshold", "sendq", "recvq", "localmax", "globalmax", NULL},
611 {DT_CHARPTR, DT_CHARPTR, DT_CHARPTR, DT_INTEGER, DT_INTEGER, DT_INTEGER,
612 DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER},
613 InitConnect, DoConnect, DoneConnect},
618 InitULine,DoULine,DoneULine},
621 {"chan", "limit", NULL},
622 {DT_CHARPTR, DT_INTEGER},
623 InitMaxBans, DoMaxBans, DoneMaxBans},
628 InitModule, DoModule, DoneModule},
631 {"reason", "ipmask", NULL},
632 {DT_CHARPTR, DT_CHARPTR},
633 InitXLine, DoZLine, DoneXLine},
636 {"reason", "nick", NULL},
637 {DT_CHARPTR, DT_CHARPTR},
638 InitXLine, DoQLine, DoneXLine},
641 {"reason", "host", NULL},
642 {DT_CHARPTR, DT_CHARPTR},
643 InitXLine, DoKLine, DoneXLine},
646 {"reason", "host", NULL},
647 {DT_CHARPTR, DT_CHARPTR},
648 InitXLine, DoELine, DoneXLine},
651 {"name", "classes", NULL},
652 {DT_CHARPTR, DT_CHARPTR},
653 InitTypes, DoType, DoneClassesAndTypes},
656 {"name", "commands", NULL},
657 {DT_CHARPTR, DT_CHARPTR},
658 InitClasses, DoClass, DoneClassesAndTypes},
663 include_stack.clear();
665 /* Load and parse the config file, if there are any errors then explode */
667 /* Make a copy here so if it fails then we can carry on running with an unaffected config */
668 ConfigDataHash newconfig;
670 if (this->LoadConf(newconfig, CONFIG_FILE, errstr))
672 /* If we succeeded, set the ircd config to the new one */
673 this->config_data = newconfig;
677 ServerInstance->Log(DEFAULT, "There were errors in your configuration:\n%s", errstr.str().c_str());
681 /* Unneeded because of the ServerInstance->Log() aboive? */
682 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
683 InspIRCd::Exit(ERROR);
687 std::string errors = errstr.str();
688 std::string::size_type start;
689 unsigned int prefixlen;
692 /* ":ServerInstance->Config->ServerName NOTICE user->nick :" */
693 prefixlen = strlen(this->ServerName) + strlen(user->nick) + 11;
697 user->WriteServ("NOTICE %s :There were errors in the configuration file:",user->nick);
699 while(start < errors.length())
701 user->WriteServ("NOTICE %s :%s",user->nick, errors.substr(start, 510 - prefixlen).c_str());
702 start += 510 - prefixlen;
707 ServerInstance->WriteOpers("There were errors in the configuration file:");
709 while(start < errors.length())
711 ServerInstance->WriteOpers(errors.substr(start, 360).c_str());
720 /* Check we dont have more than one of singular tags, or any of them missing
722 for (int Index = 0; Once[Index]; Index++)
723 if (!CheckOnce(Once[Index], bail, user))
726 /* Read the values of all the tags which occur once or not at all, and call their callbacks.
728 for (int Index = 0; Values[Index].tag; Index++)
731 ConfValue(this->config_data, Values[Index].tag, Values[Index].value, 0, item, MAXBUF);
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 switch (MultiValues[Index].datatype[valuenum])
787 ConfValue(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], tagnum, item, MAXBUF);
788 vl.push_back(ValueItem(item));
794 ConfValueInteger(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], tagnum, item);
795 vl.push_back(ValueItem(item));
800 bool item = ConfValueBool(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], tagnum);
801 vl.push_back(ValueItem(item));
805 /* Someone was smoking craq if we got here, and we're all gonna die. */
810 MultiValues[Index].validation_function(this, MultiValues[Index].tag, (char**)MultiValues[Index].items, vl, MultiValues[Index].datatype);
813 MultiValues[Index].finish_function(this, MultiValues[Index].tag);
816 // write once here, to try it out and make sure its ok
817 ServerInstance->WritePID(this->PID);
819 ServerInstance->Log(DEFAULT,"Done reading configuration file.");
821 /* If we're rehashing, let's load any new modules, and unload old ones
827 ServerInstance->stats->BoundPortCount = ServerInstance->BindPorts(false, found_ports, pl);
831 user->WriteServ("NOTICE %s :*** Not all your client ports could be bound.", user->nick);
832 user->WriteServ("NOTICE %s :*** The following port%s failed to bind:", user->nick, found_ports - ServerInstance->stats->BoundPortCount != 1 ? "s" : "");
834 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
836 user->WriteServ("NOTICE %s :*** %d. IP: %s Port: %lu", user->nick, j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
840 if (!removed_modules.empty())
842 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
844 if (ServerInstance->UnloadModule(removing->c_str()))
846 ServerInstance->WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
849 user->WriteServ("973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
856 user->WriteServ("972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
861 if (!added_modules.empty())
863 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
865 if (ServerInstance->LoadModule(adding->c_str()))
867 ServerInstance->WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
870 user->WriteServ("975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
877 user->WriteServ("974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
882 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());
886 bool ServerConfig::LoadConf(ConfigDataHash &target, const char* filename, std::ostringstream &errorstream)
888 std::ifstream conf(filename);
901 /* Check if the file open failed first */
904 errorstream << "LoadConf: Couldn't open config file: " << filename << std::endl;
908 /* Fix the chmod of the file to restrict it to the current user and group */
909 chmod(filename,0600);
911 for (unsigned int t = 0; t < include_stack.size(); t++)
913 if (std::string(filename) == include_stack[t])
915 errorstream << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
920 /* It's not already included, add it to the list of files we've loaded */
921 include_stack.push_back(filename);
923 /* Start reading characters... */
927 * Here we try and get individual tags on separate lines,
928 * this would be so easy if we just made people format
929 * their config files like that, but they don't so...
930 * We check for a '<' and then know the line is over when
931 * we get a '>' not inside quotes. If we find two '<' and
932 * no '>' then die with an error.
935 if((ch == '#') && !in_quote)
938 if(((ch == '\n') || (ch == '\r')) && in_quote)
940 errorstream << "Got a newline within a quoted section, this is probably a typo: " << filename << ":" << linenumber << std::endl;
959 /* XXX: Added by Brain, May 1st 2006 - Escaping of characters.
960 * Note that this WILL NOT usually allow insertion of newlines,
961 * because a newline is two characters long. Use it primarily to
962 * insert the " symbol.
964 * Note that this also involves a further check when parsing the line,
965 * which can be found below.
967 if ((ch == '\\') && (in_quote) && (in_tag))
970 ServerInstance->Log(DEBUG,"Escape sequence in config line.");
972 if (conf.get(real_character))
974 ServerInstance->Log(DEBUG,"Escaping %c", real_character);
975 if (real_character == 'n')
976 real_character = '\n';
977 line += real_character;
982 errorstream << "End of file after a \\, what did you want to escape?: " << filename << ":" << linenumber << std::endl;
995 errorstream << "Got another opening < when the first one wasn't closed: " << filename << ":" << linenumber << std::endl;
1003 errorstream << "We're in a quote but outside a tag, interesting. " << filename << ":" << linenumber << std::endl;
1008 // errorstream << "Opening new config tag on line " << linenumber << std::endl;
1019 // errorstream << "Closing quote in config tag on line " << linenumber << std::endl;
1024 // errorstream << "Opening quote in config tag on line " << linenumber << std::endl;
1032 errorstream << "Found a (closing) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1036 errorstream << "Found a (opening) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1046 // errorstream << "Closing config tag on line " << linenumber << std::endl;
1050 * If this finds an <include> then ParseLine can simply call
1051 * LoadConf() and load the included config into the same ConfigDataHash
1054 if(!this->ParseLine(target, line, linenumber, errorstream))
1061 errorstream << "Got a closing > when we weren't inside a tag: " << filename << ":" << linenumber << std::endl;
1071 bool ServerConfig::LoadConf(ConfigDataHash &target, const std::string &filename, std::ostringstream &errorstream)
1073 return this->LoadConf(target, filename.c_str(), errorstream);
1076 bool ServerConfig::ParseLine(ConfigDataHash &target, std::string &line, long linenumber, std::ostringstream &errorstream)
1078 std::string tagname;
1079 std::string current_key;
1080 std::string current_value;
1086 got_name = got_key = in_quote = false;
1088 // std::cout << "ParseLine(data, '" << line << "', " << linenumber << ", stream)" << std::endl;
1090 for(std::string::iterator c = line.begin(); c != line.end(); c++)
1094 /* We don't know the tag name yet. */
1105 /* We got to a space, we should have the tagname now. */
1106 if(tagname.length())
1114 /* We have the tag name */
1117 /* We're still reading the key name */
1127 /* We got an '=', end of the key name. */
1133 /* We have the key name, now we're looking for quotes and the value */
1135 /* Correctly handle escaped characters here.
1136 * See the XXX'ed section above.
1138 if ((*c == '\\') && (in_quote))
1142 current_value += '\n';
1144 current_value += *c;
1151 /* We're not already in a quote. */
1156 /* Leaving quotes, we have the value */
1157 results.push_back(KeyVal(current_key, current_value));
1159 // std::cout << "<" << tagname << ":" << current_key << "> " << current_value << std::endl;
1164 if((tagname == "include") && (current_key == "file"))
1166 if(!this->DoInclude(target, current_value, errorstream))
1170 current_key.clear();
1171 current_value.clear();
1178 current_value += *c;
1185 /* Finished parsing the tag, add it to the config hash */
1186 target.insert(std::pair<std::string, KeyValList > (tagname, results));
1191 bool ServerConfig::DoInclude(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream)
1193 std::string confpath;
1194 std::string newfile;
1195 std::string::size_type pos;
1197 confpath = CONFIG_FILE;
1200 for (std::string::iterator c = newfile.begin(); c != newfile.end(); c++)
1210 if((pos = confpath.find("/inspircd.conf")) != std::string::npos)
1212 /* Leaves us with just the path */
1213 newfile = confpath.substr(0, pos) + std::string("/") + newfile;
1217 errorstream << "Couldn't get config path from: " << confpath << std::endl;
1222 return LoadConf(target, newfile, errorstream);
1225 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, int index, char* result, int length)
1228 bool r = ConfValue(target, std::string(tag), std::string(var), index, value);
1229 strlcpy(result, value.c_str(), length);
1233 bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, std::string &result)
1235 ConfigDataHash::size_type pos = index;
1236 if((pos >= 0) && (pos < target.count(tag)))
1238 ConfigDataHash::const_iterator iter = target.find(tag);
1240 for(int i = 0; i < index; i++)
1243 for(KeyValList::const_iterator j = iter->second.begin(); j != iter->second.end(); j++)
1254 ServerInstance->Log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1258 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());
1264 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, int index, int &result)
1266 return ConfValueInteger(target, std::string(tag), std::string(var), index, result);
1269 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, int &result)
1272 std::istringstream stream;
1273 bool r = ConfValue(target, tag, var, index, value);
1275 if(!(stream >> result))
1280 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, int index)
1282 return ConfValueBool(target, std::string(tag), std::string(var), index);
1285 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, int index)
1288 if(!ConfValue(target, tag, var, index, result))
1291 return ((result == "yes") || (result == "true") || (result == "1"));
1294 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const char* tag)
1296 return target.count(tag);
1299 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const std::string &tag)
1301 return target.count(tag);
1304 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const char* tag, int index)
1306 return ConfVarEnum(target, std::string(tag), index);
1309 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const std::string &tag, int index)
1311 ConfigDataHash::size_type pos = index;
1313 if((pos >= 0) && (pos < target.count(tag)))
1315 ConfigDataHash::const_iterator iter = target.find(tag);
1317 for(int i = 0; i < index; i++)
1320 return iter->second.size();
1324 ServerInstance->Log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1328 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());
1334 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1336 bool ServerConfig::ReadFile(file_cache &F, const char* fname)
1339 char linebuf[MAXBUF];
1345 std::string::size_type pos;
1346 std::string confpath = CONFIG_FILE;
1347 if((pos = confpath.find("/inspircd.conf")) != std::string::npos)
1349 /* Leaves us with just the path */
1350 std::string newfile = confpath.substr(0, pos) + std::string("/") + fname;
1351 file = fopen(newfile.c_str(), "r");
1356 file = fopen(fname, "r");
1362 if (fgets(linebuf, sizeof(linebuf), file))
1363 linebuf[strlen(linebuf)-1] = 0;
1369 F.push_back(*linebuf ? linebuf : " ");
1381 bool ServerConfig::FileExists(const char* file)
1384 if ((input = fopen (file, "r")) == NULL)
1395 char* ServerConfig::CleanFilename(char* name)
1397 char* p = name + strlen(name);
1398 while ((p != name) && (*p != '/')) p--;
1399 return (p != name ? ++p : p);
1403 bool ServerConfig::DirValid(const char* dirandfile)
1406 char buffer[MAXBUF];
1407 char otherdir[MAXBUF];
1410 strlcpy(work, dirandfile, MAXBUF);
1413 // we just want the dir
1425 // Get the current working directory
1426 if (getcwd(buffer, MAXBUF ) == NULL )
1429 if (chdir(work) == -1)
1432 if (getcwd(otherdir, MAXBUF ) == NULL )
1435 if (chdir(buffer) == -1)
1438 size_t t = strlen(work);
1440 if (strlen(otherdir) >= t)
1444 if (!strcmp(otherdir,work))
1457 std::string ServerConfig::GetFullProgDir(char** argv, int argc)
1460 char buffer[MAXBUF];
1461 char otherdir[MAXBUF];
1464 strlcpy(work,argv[0],MAXBUF);
1467 // we just want the dir
1479 // Get the current working directory
1480 if (getcwd(buffer, MAXBUF) == NULL)
1483 if (chdir(work) == -1)
1486 if (getcwd(otherdir, MAXBUF) == NULL)
1489 if (chdir(buffer) == -1)
1495 InspIRCd* ServerConfig::GetInstance()
1497 return ServerInstance;
1501 ValueItem::ValueItem(int value)
1503 std::stringstream n;
1508 ValueItem::ValueItem(bool value)
1510 std::stringstream n;
1515 ValueItem::ValueItem(char* value)
1520 void ValueItem::Set(char* value)
1525 void ValueItem::Set(const char* value)
1530 void ValueItem::Set(int value)
1532 std::stringstream n;
1537 int ValueItem::GetInteger()
1539 return atoi(v.c_str());
1542 char* ValueItem::GetString()
1544 return (char*)v.c_str();
1547 bool ValueItem::GetBool()
1549 return (GetInteger() || v == "yes" || v == "true");