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 *TempDir = *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 bool ServerConfig::AddIOHook(int port, Module* iomod)
64 IOHookModule[port] = iomod;
69 ModuleException err("Port already hooked by another module");
75 bool ServerConfig::DelIOHook(int port)
77 std::map<int,Module*>::iterator x = IOHookModule.find(port);
78 if (x != IOHookModule.end())
80 IOHookModule.erase(x);
86 bool ServerConfig::CheckOnce(char* tag, bool bail, userrec* user)
88 int count = ConfValueEnum(this->config_data, tag);
94 printf("There were errors in your configuration:\nYou have more than one <%s> tag, this is not permitted.\n",tag);
95 InspIRCd::Exit(ERROR);
101 user->WriteServ("There were errors in your configuration:");
102 user->WriteServ("You have more than one <%s> tag, this is not permitted.\n",tag);
106 ServerInstance->WriteOpers("There were errors in the configuration file:");
107 ServerInstance->WriteOpers("You have more than one <%s> tag, this is not permitted.\n",tag);
116 printf("There were errors in your configuration:\nYou have not defined a <%s> tag, this is required.\n",tag);
117 InspIRCd::Exit(ERROR);
123 user->WriteServ("There were errors in your configuration:");
124 user->WriteServ("You have not defined a <%s> tag, this is required.",tag);
128 ServerInstance->WriteOpers("There were errors in the configuration file:");
129 ServerInstance->WriteOpers("You have not defined a <%s> tag, this is required.",tag);
137 bool NoValidation(ServerConfig* conf, const char* tag, const char* value, void* data)
139 conf->GetInstance()->Log(DEBUG,"No validation for <%s:%s>",tag,value);
143 bool ValidateTempDir(ServerConfig* conf, const char* tag, const char* value, void* data)
145 char* x = (char*)data;
147 strlcpy(x,"/tmp",1024);
151 bool ValidateMaxTargets(ServerConfig* conf, const char* tag, const char* value, void* data)
154 if ((*x < 0) || (*x > 31))
156 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
162 bool ValidateSoftLimit(ServerConfig* conf, const char* tag, const char* value, void* data)
165 if ((*x < 1) || (*x > MAXCLIENTS))
167 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
173 bool ValidateMaxConn(ServerConfig* conf, const char* tag, const char* value, void* data)
177 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
183 bool ValidateDnsTimeout(ServerConfig* conf, const char* tag, const char* value, void* data)
191 bool InitializeDisabledCommands(const char* data, InspIRCd* ServerInstance)
193 std::stringstream dcmds(data);
196 /* Enable everything first */
197 for (nspace::hash_map<std::string,command_t*>::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
198 x->second->Disable(false);
200 /* Now disable all the ones which the user wants disabled */
201 while (dcmds >> thiscmd)
203 nspace::hash_map<std::string,command_t*>::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
204 if (cm != ServerInstance->Parser->cmdlist.end())
206 ServerInstance->Log(DEBUG,"Disabling command '%s'",cm->second->command.c_str());
207 cm->second->Disable(true);
213 bool ValidateDnsServer(ServerConfig* conf, const char* tag, const char* value, void* data)
215 char* x = (char*)data;
218 // attempt to look up their nameserver from /etc/resolv.conf
219 conf->GetInstance()->Log(DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
220 ifstream resolv("/etc/resolv.conf");
221 std::string nameserver;
222 bool found_server = false;
224 if (resolv.is_open())
226 while (resolv >> nameserver)
228 if ((nameserver == "nameserver") && (!found_server))
230 resolv >> nameserver;
231 strlcpy(x,nameserver.c_str(),MAXBUF);
233 conf->GetInstance()->Log(DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
239 conf->GetInstance()->Log(DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
240 strlcpy(x,"127.0.0.1",MAXBUF);
245 conf->GetInstance()->Log(DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
246 strlcpy(x,"127.0.0.1",MAXBUF);
252 bool ValidateModPath(ServerConfig* conf, const char* tag, const char* value, void* data)
254 char* x = (char*)data;
256 strlcpy(x,MOD_PATH,MAXBUF);
261 bool ValidateServerName(ServerConfig* conf, const char* tag, const char* value, void* data)
263 char* x = (char*)data;
266 conf->GetInstance()->Log(DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s%c'",x,x,'.');
267 charlcat(x,'.',MAXBUF);
273 bool ValidateNetBufferSize(ServerConfig* conf, const char* tag, const char* value, void* data)
275 if ((!conf->NetBufferSize) || (conf->NetBufferSize > 65535) || (conf->NetBufferSize < 1024))
277 conf->GetInstance()->Log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
278 conf->NetBufferSize = 10240;
283 bool ValidateMaxWho(ServerConfig* conf, const char* tag, const char* value, void* data)
285 if ((!conf->MaxWhoResults) || (conf->MaxWhoResults > 65535) || (conf->MaxWhoResults < 1))
287 conf->GetInstance()->Log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
288 conf->MaxWhoResults = 128;
293 bool ValidateLogLevel(ServerConfig* conf, const char* tag, const char* value, void* data)
295 const char* dbg = (const char*)data;
296 conf->LogLevel = DEFAULT;
297 if (!strcmp(dbg,"debug"))
299 conf->LogLevel = DEBUG;
302 else if (!strcmp(dbg,"verbose"))
303 conf->LogLevel = VERBOSE;
304 else if (!strcmp(dbg,"default"))
305 conf->LogLevel = DEFAULT;
306 else if (!strcmp(dbg,"sparse"))
307 conf->LogLevel = SPARSE;
308 else if (!strcmp(dbg,"none"))
309 conf->LogLevel = NONE;
313 bool ValidateMotd(ServerConfig* conf, const char* tag, const char* value, void* data)
315 conf->ReadFile(conf->MOTD,conf->motd);
319 bool ValidateRules(ServerConfig* conf, const char* tag, const char* value, void* data)
321 conf->ReadFile(conf->RULES,conf->rules);
325 bool ValidateWhoWas(ServerConfig* conf, const char* tag, const char* value, void* data)
327 char* max = (char*)data;
328 conf->WhoWasMaxKeep = conf->GetInstance()->Duration(max);
330 if (conf->WhoWasGroupSize < 0)
331 conf->WhoWasGroupSize = 0;
333 if (conf->WhoWasMaxGroups < 0)
334 conf->WhoWasMaxGroups = 0;
336 if (conf->WhoWasMaxKeep < 3600)
338 conf->WhoWasMaxKeep = 3600;
339 conf->GetInstance()->Log(DEFAULT,"WARNING: <whowas:maxkeep> value less than 3600, setting to default 3600");
341 conf->GetInstance()->Log(DEBUG,"whowas:groupsize:%d maxgroups:%d maxkeep:%d",conf->WhoWasGroupSize,conf->WhoWasMaxGroups,conf->WhoWasMaxKeep);
342 irc::whowas::PruneWhoWas(conf->GetInstance(), conf->GetInstance()->Time());
346 /* Callback called before processing the first <connect> tag
348 bool InitConnect(ServerConfig* conf, const char* tag)
350 conf->GetInstance()->Log(DEFAULT,"Reading connect classes...");
351 conf->Classes.clear();
355 /* Callback called to process a single <connect> tag
357 bool DoConnect(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
360 const char* allow = values[0].GetString(); /* Yeah, there are a lot of values. Live with it. */
361 const char* deny = values[1].GetString();
362 const char* password = values[2].GetString();
363 int timeout = values[3].GetInteger();
364 int pingfreq = values[4].GetInteger();
365 int flood = values[5].GetInteger();
366 int threshold = values[6].GetInteger();
367 int sendq = values[7].GetInteger();
368 int recvq = values[8].GetInteger();
369 int localmax = values[9].GetInteger();
370 int globalmax = values[10].GetInteger();
377 c.registration_timeout = timeout;
378 c.pingtime = pingfreq;
380 c.threshold = threshold;
383 c.maxlocal = localmax;
384 c.maxglobal = globalmax;
389 if (c.maxglobal == 0)
391 if (c.threshold == 0)
395 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());
401 if (c.registration_timeout == 0)
402 c.registration_timeout = 90;
405 conf->Classes.push_back(c);
411 conf->Classes.push_back(c);
412 conf->GetInstance()->Log(DEBUG,"Read connect class type DENY, host=%s",deny);
418 /* Callback called when there are no more <connect> tags
420 bool DoneConnect(ServerConfig* conf, const char* tag)
422 conf->GetInstance()->Log(DEBUG,"DoneConnect called for tag: %s",tag);
426 /* Callback called before processing the first <uline> tag
428 bool InitULine(ServerConfig* conf, const char* tag)
430 conf->ulines.clear();
434 /* Callback called to process a single <uline> tag
436 bool DoULine(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
438 const char* server = values[0].GetString();
439 conf->GetInstance()->Log(DEBUG,"Read ULINE '%s'",server);
440 conf->ulines.push_back(server);
444 /* Callback called when there are no more <uline> tags
446 bool DoneULine(ServerConfig* conf, const char* tag)
451 /* Callback called before processing the first <module> tag
453 bool InitModule(ServerConfig* conf, const char* tag)
455 old_module_names.clear();
456 new_module_names.clear();
457 added_modules.clear();
458 removed_modules.clear();
459 for (std::vector<std::string>::iterator t = conf->module_names.begin(); t != conf->module_names.end(); t++)
461 old_module_names.push_back(*t);
466 /* Callback called to process a single <module> tag
468 bool DoModule(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
470 const char* modname = values[0].GetString();
471 new_module_names.push_back(modname);
475 /* Callback called when there are no more <module> tags
477 bool DoneModule(ServerConfig* conf, const char* tag)
479 // now create a list of new modules that are due to be loaded
480 // and a seperate list of modules which are due to be unloaded
481 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
485 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
492 added_modules.push_back(*_new);
495 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
498 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
505 removed_modules.push_back(*oldm);
510 /* Callback called before processing the first <banlist> tag
512 bool InitMaxBans(ServerConfig* conf, const char* tag)
514 conf->maxbans.clear();
518 /* Callback called to process a single <banlist> tag
520 bool DoMaxBans(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
522 const char* channel = values[0].GetString();
523 int limit = values[1].GetInteger();
524 conf->maxbans[channel] = limit;
528 /* Callback called when there are no more <banlist> tags.
530 bool DoneMaxBans(ServerConfig* conf, const char* tag)
535 void ServerConfig::Read(bool bail, userrec* user)
537 static char debug[MAXBUF]; /* Temporary buffer for debugging value */
538 static char maxkeep[MAXBUF]; /* Temporary buffer for WhoWasMaxKeep value */
539 int rem = 0, add = 0; /* Number of modules added, number of modules removed */
540 std::ostringstream errstr; /* String stream containing the error output */
542 /* These tags MUST occur and must ONLY occur once in the config file */
543 static char* Once[] = { "server", "admin", "files", "power", "options", NULL };
545 /* These tags can occur ONCE or not at all */
546 static InitialConfig Values[] = {
547 {"options", "softlimit", &this->SoftLimit, DT_INTEGER, ValidateSoftLimit},
548 {"options", "somaxconn", &this->MaxConn, DT_INTEGER, ValidateMaxConn},
549 {"server", "name", &this->ServerName, DT_CHARPTR, ValidateServerName},
550 {"server", "description", &this->ServerDesc, DT_CHARPTR, NoValidation},
551 {"server", "network", &this->Network, DT_CHARPTR, NoValidation},
552 {"admin", "name", &this->AdminName, DT_CHARPTR, NoValidation},
553 {"admin", "email", &this->AdminEmail, DT_CHARPTR, NoValidation},
554 {"admin", "nick", &this->AdminNick, DT_CHARPTR, NoValidation},
555 {"files", "motd", &this->motd, DT_CHARPTR, ValidateMotd},
556 {"files", "rules", &this->rules, DT_CHARPTR, ValidateRules},
557 {"power", "diepass", &this->diepass, DT_CHARPTR, NoValidation},
558 {"power", "pause", &this->DieDelay, DT_INTEGER, NoValidation},
559 {"power", "restartpass", &this->restartpass, DT_CHARPTR, NoValidation},
560 {"options", "prefixquit", &this->PrefixQuit, DT_CHARPTR, NoValidation},
561 {"die", "value", &this->DieValue, DT_CHARPTR, NoValidation},
562 {"options", "loglevel", &debug, DT_CHARPTR, ValidateLogLevel},
563 {"options", "netbuffersize", &this->NetBufferSize, DT_INTEGER, ValidateNetBufferSize},
564 {"options", "maxwho", &this->MaxWhoResults, DT_INTEGER, ValidateMaxWho},
565 {"options", "allowhalfop", &this->AllowHalfop, DT_BOOLEAN, NoValidation},
566 {"dns", "server", &this->DNSServer, DT_CHARPTR, ValidateDnsServer},
567 {"dns", "timeout", &this->dns_timeout, DT_INTEGER, ValidateDnsTimeout},
568 {"options", "moduledir", &this->ModPath, DT_CHARPTR, ValidateModPath},
569 {"disabled", "commands", &this->DisabledCommands, DT_CHARPTR, NoValidation},
570 {"options", "userstats", &this->UserStats, DT_CHARPTR, NoValidation},
571 {"options", "customversion", &this->CustomVersion, DT_CHARPTR, NoValidation},
572 {"options", "hidesplits", &this->HideSplits, DT_BOOLEAN, NoValidation},
573 {"options", "hidebans", &this->HideBans, DT_BOOLEAN, NoValidation},
574 {"options", "hidewhois", &this->HideWhoisServer, DT_CHARPTR, NoValidation},
575 {"options", "operspywhois", &this->OperSpyWhois, DT_BOOLEAN, NoValidation},
576 {"options", "tempdir", &this->TempDir, DT_CHARPTR, ValidateTempDir},
577 {"options", "nouserdns", &this->NoUserDns, DT_BOOLEAN, NoValidation},
578 {"options", "syntaxhints", &this->SyntaxHints, DT_BOOLEAN, NoValidation},
579 {"options", "cyclehosts", &this->CycleHosts, DT_BOOLEAN, NoValidation},
580 {"pid", "file", &this->PID, DT_CHARPTR, NoValidation},
581 {"whowas", "groupsize", &this->WhoWasGroupSize, DT_INTEGER, NoValidation},
582 {"whowas", "maxgroups", &this->WhoWasMaxGroups, DT_INTEGER, NoValidation},
583 {"whowas", "maxkeep", &maxkeep, DT_CHARPTR, ValidateWhoWas},
587 /* These tags can occur multiple times, and therefore they have special code to read them
588 * which is different to the code for reading the singular tags listed above.
590 static MultiConfig MultiValues[] = {
593 {"allow", "deny", "password", "timeout", "pingfreq", "flood",
594 "threshold", "sendq", "recvq", "localmax", "globalmax", NULL},
595 {DT_CHARPTR, DT_CHARPTR, DT_CHARPTR, DT_INTEGER, DT_INTEGER, DT_INTEGER,
596 DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER},
597 InitConnect, DoConnect, DoneConnect},
602 InitULine,DoULine,DoneULine},
605 {"chan", "limit", NULL},
606 {DT_CHARPTR, DT_INTEGER},
607 InitMaxBans, DoMaxBans, DoneMaxBans},
612 InitModule, DoModule, DoneModule},
615 {"reason", "ipmask", NULL},
616 {DT_CHARPTR, DT_CHARPTR},
617 InitXLine, DoZLine, DoneXLine},
620 {"reason", "nick", NULL},
621 {DT_CHARPTR, DT_CHARPTR},
622 InitXLine, DoQLine, DoneXLine},
625 {"reason", "host", NULL},
626 {DT_CHARPTR, DT_CHARPTR},
627 InitXLine, DoKLine, DoneXLine},
630 {"reason", "host", NULL},
631 {DT_CHARPTR, DT_CHARPTR},
632 InitXLine, DoELine, DoneXLine},
635 {"name", "classes", NULL},
636 {DT_CHARPTR, DT_CHARPTR},
637 InitTypes, DoType, DoneClassesAndTypes},
640 {"name", "commands", NULL},
641 {DT_CHARPTR, DT_CHARPTR},
642 InitClasses, DoClass, DoneClassesAndTypes},
647 include_stack.clear();
649 /* Load and parse the config file, if there are any errors then explode */
651 /* Make a copy here so if it fails then we can carry on running with an unaffected config */
652 ConfigDataHash newconfig;
654 if (this->LoadConf(newconfig, CONFIG_FILE, errstr))
656 /* If we succeeded, set the ircd config to the new one */
657 this->config_data = newconfig;
661 ServerInstance->Log(DEFAULT, "There were errors in your configuration:\n%s", errstr.str().c_str());
665 /* Unneeded because of the ServerInstance->Log() aboive? */
666 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
667 InspIRCd::Exit(ERROR);
671 std::string errors = errstr.str();
672 std::string::size_type start;
673 unsigned int prefixlen;
676 /* ":ServerInstance->Config->ServerName NOTICE user->nick :" */
677 prefixlen = strlen(this->ServerName) + strlen(user->nick) + 11;
681 user->WriteServ("NOTICE %s :There were errors in the configuration file:",user->nick);
683 while(start < errors.length())
685 user->WriteServ("NOTICE %s :%s",user->nick, errors.substr(start, 510 - prefixlen).c_str());
686 start += 510 - prefixlen;
691 ServerInstance->WriteOpers("There were errors in the configuration file:");
693 while(start < errors.length())
695 ServerInstance->WriteOpers(errors.substr(start, 360).c_str());
704 /* Check we dont have more than one of singular tags, or any of them missing
706 for (int Index = 0; Once[Index]; Index++)
707 if (!CheckOnce(Once[Index],bail,user))
710 /* Read the values of all the tags which occur once or not at all, and call their callbacks.
712 for (int Index = 0; Values[Index].tag; Index++)
714 switch (Values[Index].datatype)
717 /* Assuming MAXBUF here, potentially unsafe */
718 ConfValue(this->config_data, Values[Index].tag, Values[Index].value, 0, ((char*)Values[Index].val), MAXBUF);
719 ServerInstance->Log(DEBUG,"Data type DT_CHARPTR item <%s:%s> = '%s'", Values[Index].tag, Values[Index].value, ((char*)Values[Index].val));
723 ConfValueInteger(this->config_data, Values[Index].tag, Values[Index].value, 0, *((int*)Values[Index].val));
724 ServerInstance->Log(DEBUG,"Data type DT_INTEGER item <%s:%s> = '%d'", Values[Index].tag, Values[Index].value, *((int*)Values[Index].val));
728 *((bool*)(Values[Index].val)) = (ConfValueBool(this->config_data, Values[Index].tag, Values[Index].value, 0));
729 ServerInstance->Log(DEBUG,"Data type DT_BOOLEAN item <%s:%s> = '%d'", Values[Index].tag, Values[Index].value, *((bool*)(Values[Index].val)));
736 Values[Index].validation_function(this, Values[Index].tag, Values[Index].value, Values[Index].val);
739 /* Read the multiple-tag items (class tags, connect tags, etc)
740 * and call the callbacks associated with them. We have three
741 * callbacks for these, a 'start', 'item' and 'end' callback.
744 /* XXX - Make this use ConfValueInteger and so on */
745 for (int Index = 0; MultiValues[Index].tag; Index++)
747 MultiValues[Index].init_function(this, MultiValues[Index].tag);
749 int number_of_tags = ConfValueEnum(this->config_data, MultiValues[Index].tag);
751 for (int tagnum = 0; tagnum < number_of_tags; tagnum++)
754 for (int valuenum = 0; MultiValues[Index].items[valuenum]; valuenum++)
756 switch (MultiValues[Index].datatype[valuenum])
761 ConfValue(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], tagnum, item, MAXBUF);
762 ServerInstance->Log(DEBUG,"Data type DT_CHARPTR multi-item <%s:%s>[%d] = '%s'", MultiValues[Index].tag, MultiValues[Index].items[valuenum],tagnum, item);
763 vl.push_back(ValueItem(item));
769 ConfValueInteger(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], tagnum, item);
770 ServerInstance->Log(DEBUG,"Data type DT_INTEGER multi-item <%s:%s>[%d] = '%d'", MultiValues[Index].tag, MultiValues[Index].items[valuenum],tagnum, item);
771 vl.push_back(ValueItem(item));
776 bool item = ConfValueBool(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], tagnum);
777 ServerInstance->Log(DEBUG,"Data type DT_BOOLEAN multi-item <%s:%s>[%d] = '%d'", MultiValues[Index].tag, MultiValues[Index].items[valuenum],tagnum, item);
778 vl.push_back(ValueItem(item));
785 ServerInstance->Log(DEBUG,"Call validation function for multi-value <%s>", MultiValues[Index].tag);
786 MultiValues[Index].validation_function(this, MultiValues[Index].tag, (char**)MultiValues[Index].items, vl, MultiValues[Index].datatype);
789 MultiValues[Index].finish_function(this, MultiValues[Index].tag);
792 // write once here, to try it out and make sure its ok
793 ServerInstance->WritePID(this->PID);
795 ServerInstance->Log(DEFAULT,"Done reading configuration file.");
797 /* If we're rehashing, let's load any new modules, and unload old ones
803 ServerInstance->stats->BoundPortCount = ServerInstance->BindPorts(false, found_ports, pl);
807 user->WriteServ("NOTICE %s :*** Not all your client ports could be bound.", user->nick);
808 user->WriteServ("NOTICE %s :*** The following port%s failed to bind:", user->nick, found_ports - ServerInstance->stats->BoundPortCount != 1 ? "s" : "");
810 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
812 user->WriteServ("NOTICE %s :*** %d. IP: %s Port: %lu", user->nick, j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
816 if (!removed_modules.empty())
817 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
819 if (ServerInstance->UnloadModule(removing->c_str()))
821 ServerInstance->WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
824 user->WriteServ("973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
831 user->WriteServ("972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
835 if (!added_modules.empty())
836 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
838 if (ServerInstance->LoadModule(adding->c_str()))
840 ServerInstance->WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
843 user->WriteServ("975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
850 user->WriteServ("974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
854 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());
858 bool ServerConfig::LoadConf(ConfigDataHash &target, const char* filename, std::ostringstream &errorstream)
860 std::ifstream conf(filename);
873 /* Check if the file open failed first */
876 errorstream << "LoadConf: Couldn't open config file: " << filename << std::endl;
880 /* Fix the chmod of the file to restrict it to the current user and group */
881 chmod(filename,0600);
883 for (unsigned int t = 0; t < include_stack.size(); t++)
885 if (std::string(filename) == include_stack[t])
887 errorstream << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
892 /* It's not already included, add it to the list of files we've loaded */
893 include_stack.push_back(filename);
895 /* Start reading characters... */
899 * Here we try and get individual tags on separate lines,
900 * this would be so easy if we just made people format
901 * their config files like that, but they don't so...
902 * We check for a '<' and then know the line is over when
903 * we get a '>' not inside quotes. If we find two '<' and
904 * no '>' then die with an error.
907 if((ch == '#') && !in_quote)
910 if(((ch == '\n') || (ch == '\r')) && in_quote)
912 errorstream << "Got a newline within a quoted section, this is probably a typo: " << filename << ":" << linenumber << std::endl;
931 /* XXX: Added by Brain, May 1st 2006 - Escaping of characters.
932 * Note that this WILL NOT usually allow insertion of newlines,
933 * because a newline is two characters long. Use it primarily to
934 * insert the " symbol.
936 * Note that this also involves a further check when parsing the line,
937 * which can be found below.
939 if ((ch == '\\') && (in_quote) && (in_tag))
942 ServerInstance->Log(DEBUG,"Escape sequence in config line.");
944 if (conf.get(real_character))
946 ServerInstance->Log(DEBUG,"Escaping %c", real_character);
947 if (real_character == 'n')
948 real_character = '\n';
949 line += real_character;
954 errorstream << "End of file after a \\, what did you want to escape?: " << filename << ":" << linenumber << std::endl;
967 errorstream << "Got another opening < when the first one wasn't closed: " << filename << ":" << linenumber << std::endl;
975 errorstream << "We're in a quote but outside a tag, interesting. " << filename << ":" << linenumber << std::endl;
980 // errorstream << "Opening new config tag on line " << linenumber << std::endl;
991 // errorstream << "Closing quote in config tag on line " << linenumber << std::endl;
996 // errorstream << "Opening quote in config tag on line " << linenumber << std::endl;
1004 errorstream << "Found a (closing) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1008 errorstream << "Found a (opening) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1018 // errorstream << "Closing config tag on line " << linenumber << std::endl;
1022 * If this finds an <include> then ParseLine can simply call
1023 * LoadConf() and load the included config into the same ConfigDataHash
1026 if(!this->ParseLine(target, line, linenumber, errorstream))
1033 errorstream << "Got a closing > when we weren't inside a tag: " << filename << ":" << linenumber << std::endl;
1043 bool ServerConfig::LoadConf(ConfigDataHash &target, const std::string &filename, std::ostringstream &errorstream)
1045 return this->LoadConf(target, filename.c_str(), errorstream);
1048 bool ServerConfig::ParseLine(ConfigDataHash &target, std::string &line, long linenumber, std::ostringstream &errorstream)
1050 std::string tagname;
1051 std::string current_key;
1052 std::string current_value;
1058 got_name = got_key = in_quote = false;
1060 // std::cout << "ParseLine(data, '" << line << "', " << linenumber << ", stream)" << std::endl;
1062 for(std::string::iterator c = line.begin(); c != line.end(); c++)
1066 /* We don't know the tag name yet. */
1077 /* We got to a space, we should have the tagname now. */
1078 if(tagname.length())
1086 /* We have the tag name */
1089 /* We're still reading the key name */
1099 /* We got an '=', end of the key name. */
1105 /* We have the key name, now we're looking for quotes and the value */
1107 /* Correctly handle escaped characters here.
1108 * See the XXX'ed section above.
1110 if ((*c == '\\') && (in_quote))
1114 current_value += '\n';
1116 current_value += *c;
1123 /* We're not already in a quote. */
1128 /* Leaving quotes, we have the value */
1129 results.push_back(KeyVal(current_key, current_value));
1131 // std::cout << "<" << tagname << ":" << current_key << "> " << current_value << std::endl;
1136 if((tagname == "include") && (current_key == "file"))
1138 if(!this->DoInclude(target, current_value, errorstream))
1142 current_key.clear();
1143 current_value.clear();
1150 current_value += *c;
1157 /* Finished parsing the tag, add it to the config hash */
1158 target.insert(std::pair<std::string, KeyValList > (tagname, results));
1163 bool ServerConfig::DoInclude(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream)
1165 std::string confpath;
1166 std::string newfile;
1167 std::string::size_type pos;
1169 confpath = CONFIG_FILE;
1172 for (std::string::iterator c = newfile.begin(); c != newfile.end(); c++)
1182 if((pos = confpath.find("/inspircd.conf")) != std::string::npos)
1184 /* Leaves us with just the path */
1185 newfile = confpath.substr(0, pos) + std::string("/") + newfile;
1189 errorstream << "Couldn't get config path from: " << confpath << std::endl;
1194 return LoadConf(target, newfile, errorstream);
1197 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, int index, char* result, int length)
1200 bool r = ConfValue(target, std::string(tag), std::string(var), index, value);
1201 strlcpy(result, value.c_str(), length);
1205 bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, std::string &result)
1207 ConfigDataHash::size_type pos = index;
1208 if((pos >= 0) && (pos < target.count(tag)))
1210 ConfigDataHash::const_iterator iter = target.find(tag);
1212 for(int i = 0; i < index; i++)
1215 for(KeyValList::const_iterator j = iter->second.begin(); j != iter->second.end(); j++)
1226 ServerInstance->Log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1230 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());
1236 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, int index, int &result)
1238 return ConfValueInteger(target, std::string(tag), std::string(var), index, result);
1241 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, int &result)
1244 std::istringstream stream;
1245 bool r = ConfValue(target, tag, var, index, value);
1247 if(!(stream >> result))
1252 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, int index)
1254 return ConfValueBool(target, std::string(tag), std::string(var), index);
1257 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, int index)
1260 if(!ConfValue(target, tag, var, index, result))
1263 return ((result == "yes") || (result == "true") || (result == "1"));
1266 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const char* tag)
1268 return target.count(tag);
1271 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const std::string &tag)
1273 return target.count(tag);
1276 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const char* tag, int index)
1278 return ConfVarEnum(target, std::string(tag), index);
1281 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const std::string &tag, int index)
1283 ConfigDataHash::size_type pos = index;
1285 if((pos >= 0) && (pos < target.count(tag)))
1287 ConfigDataHash::const_iterator iter = target.find(tag);
1289 for(int i = 0; i < index; i++)
1292 return iter->second.size();
1296 ServerInstance->Log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1300 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());
1306 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1308 bool ServerConfig::ReadFile(file_cache &F, const char* fname)
1311 char linebuf[MAXBUF];
1317 std::string::size_type pos;
1318 std::string confpath = CONFIG_FILE;
1319 if((pos = confpath.find("/inspircd.conf")) != std::string::npos)
1321 /* Leaves us with just the path */
1322 std::string newfile = confpath.substr(0, pos) + std::string("/") + fname;
1323 file = fopen(newfile.c_str(), "r");
1328 file = fopen(fname, "r");
1334 fgets(linebuf, sizeof(linebuf), file);
1335 linebuf[strlen(linebuf)-1] = 0;
1339 F.push_back(*linebuf ? linebuf : " ");
1351 bool ServerConfig::FileExists(const char* file)
1354 if ((input = fopen (file, "r")) == NULL)
1365 char* ServerConfig::CleanFilename(char* name)
1367 char* p = name + strlen(name);
1368 while ((p != name) && (*p != '/')) p--;
1369 return (p != name ? ++p : p);
1373 bool ServerConfig::DirValid(const char* dirandfile)
1376 char buffer[MAXBUF];
1377 char otherdir[MAXBUF];
1380 strlcpy(work, dirandfile, MAXBUF);
1383 // we just want the dir
1395 // Get the current working directory
1396 if (getcwd(buffer, MAXBUF ) == NULL )
1401 if (getcwd(otherdir, MAXBUF ) == NULL )
1406 size_t t = strlen(work);
1408 if (strlen(otherdir) >= t)
1412 if (!strcmp(otherdir,work))
1425 std::string ServerConfig::GetFullProgDir(char** argv, int argc)
1428 char buffer[MAXBUF];
1429 char otherdir[MAXBUF];
1432 strlcpy(work,argv[0],MAXBUF);
1435 // we just want the dir
1447 // Get the current working directory
1448 if (getcwd(buffer, MAXBUF) == NULL)
1453 if (getcwd(otherdir, MAXBUF) == NULL)
1460 InspIRCd* ServerConfig::GetInstance()
1462 return ServerInstance;