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, ValueItem &data)
139 conf->GetInstance()->Log(DEBUG,"No validation for <%s:%s>",tag,value);
143 bool ValidateTempDir(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
145 if (!*(data.GetString()))
150 bool ValidateMaxTargets(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
152 if ((data.GetInteger() < 0) || (data.GetInteger() > 31))
154 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
160 bool ValidateSoftLimit(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
162 if ((data.GetInteger() < 1) || (data.GetInteger() > MAXCLIENTS))
164 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
165 data.Set(MAXCLIENTS);
170 bool ValidateMaxConn(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
172 if (data.GetInteger() > SOMAXCONN)
173 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
174 if (!data.GetInteger())
179 bool ValidateDnsTimeout(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
181 if (!data.GetInteger())
186 bool InitializeDisabledCommands(const char* data, InspIRCd* ServerInstance)
188 std::stringstream dcmds(data);
191 /* Enable everything first */
192 for (nspace::hash_map<std::string,command_t*>::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
193 x->second->Disable(false);
195 /* Now disable all the ones which the user wants disabled */
196 while (dcmds >> thiscmd)
198 nspace::hash_map<std::string,command_t*>::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
199 if (cm != ServerInstance->Parser->cmdlist.end())
201 ServerInstance->Log(DEBUG,"Disabling command '%s'",cm->second->command.c_str());
202 cm->second->Disable(true);
208 bool ValidateDnsServer(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
210 if (!*(data.GetString()))
212 // attempt to look up their nameserver from /etc/resolv.conf
213 conf->GetInstance()->Log(DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
214 ifstream resolv("/etc/resolv.conf");
215 std::string nameserver;
216 bool found_server = false;
218 if (resolv.is_open())
220 while (resolv >> nameserver)
222 if ((nameserver == "nameserver") && (!found_server))
224 resolv >> nameserver;
225 data.Set(nameserver);
227 conf->GetInstance()->Log(DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
233 conf->GetInstance()->Log(DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
234 data.Set("127.0.0.1");
239 conf->GetInstance()->Log(DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
240 data.Set("127.0.0.1");
246 bool ValidateModPath(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
248 if (!*(data.GetString()))
254 bool ValidateServerName(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
256 if (!strchr(data.GetString(),'.'))
258 conf->GetInstance()->Log(DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s%c'",data.GetString(),data.GetString(),'.');
259 data.Set(std::string(data.GetString()) + ".");
264 bool ValidateNetBufferSize(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
266 if ((!data.GetInteger()) || (data.GetInteger() > 65535) || (data.GetInteger() < 1024))
268 conf->GetInstance()->Log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
274 bool ValidateMaxWho(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
276 if ((!data.GetInteger()) || (data.GetInteger() > 65535) || (data.GetInteger() < 1))
278 conf->GetInstance()->Log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
284 bool ValidateLogLevel(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
286 std::string dbg = data.GetString();
287 conf->LogLevel = DEFAULT;
290 conf->LogLevel = DEBUG;
291 else if (dbg == "verbose")
292 conf->LogLevel = VERBOSE;
293 else if (dbg == "default")
294 conf->LogLevel = DEFAULT;
295 else if (dbg == "sparse")
296 conf->LogLevel = SPARSE;
297 else if (dbg == "none")
298 conf->LogLevel = NONE;
300 conf->debugging = (conf->LogLevel == DEBUG);
305 bool ValidateMotd(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
307 conf->ReadFile(conf->MOTD, data.GetString());
311 bool ValidateRules(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
313 conf->ReadFile(conf->RULES, data.GetString());
317 bool ValidateWhoWas(ServerConfig* conf, const char* tag, const char* value, ValueItem &data)
319 conf->WhoWasMaxKeep = conf->GetInstance()->Duration(data.GetString());
321 if (conf->WhoWasGroupSize < 0)
322 conf->WhoWasGroupSize = 0;
324 if (conf->WhoWasMaxGroups < 0)
325 conf->WhoWasMaxGroups = 0;
327 if (conf->WhoWasMaxKeep < 3600)
329 conf->WhoWasMaxKeep = 3600;
330 conf->GetInstance()->Log(DEFAULT,"WARNING: <whowas:maxkeep> value less than 3600, setting to default 3600");
332 conf->GetInstance()->Log(DEBUG,"whowas:groupsize:%d maxgroups:%d maxkeep:%d",conf->WhoWasGroupSize,conf->WhoWasMaxGroups,conf->WhoWasMaxKeep);
333 irc::whowas::PruneWhoWas(conf->GetInstance(), conf->GetInstance()->Time());
337 /* Callback called before processing the first <connect> tag
339 bool InitConnect(ServerConfig* conf, const char* tag)
341 conf->GetInstance()->Log(DEFAULT,"Reading connect classes...");
342 conf->Classes.clear();
346 /* Callback called to process a single <connect> tag
348 bool DoConnect(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
351 const char* allow = values[0].GetString(); /* Yeah, there are a lot of values. Live with it. */
352 const char* deny = values[1].GetString();
353 const char* password = values[2].GetString();
354 int timeout = values[3].GetInteger();
355 int pingfreq = values[4].GetInteger();
356 int flood = values[5].GetInteger();
357 int threshold = values[6].GetInteger();
358 int sendq = values[7].GetInteger();
359 int recvq = values[8].GetInteger();
360 int localmax = values[9].GetInteger();
361 int globalmax = values[10].GetInteger();
368 c.registration_timeout = timeout;
369 c.pingtime = pingfreq;
371 c.threshold = threshold;
374 c.maxlocal = localmax;
375 c.maxglobal = globalmax;
380 if (c.maxglobal == 0)
382 if (c.threshold == 0)
386 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());
392 if (c.registration_timeout == 0)
393 c.registration_timeout = 90;
396 conf->Classes.push_back(c);
402 conf->Classes.push_back(c);
403 conf->GetInstance()->Log(DEBUG,"Read connect class type DENY, host=%s",deny);
409 /* Callback called when there are no more <connect> tags
411 bool DoneConnect(ServerConfig* conf, const char* tag)
413 conf->GetInstance()->Log(DEBUG,"DoneConnect called for tag: %s",tag);
417 /* Callback called before processing the first <uline> tag
419 bool InitULine(ServerConfig* conf, const char* tag)
421 conf->ulines.clear();
425 /* Callback called to process a single <uline> tag
427 bool DoULine(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
429 const char* server = values[0].GetString();
430 conf->GetInstance()->Log(DEBUG,"Read ULINE '%s'",server);
431 conf->ulines.push_back(server);
435 /* Callback called when there are no more <uline> tags
437 bool DoneULine(ServerConfig* conf, const char* tag)
442 /* Callback called before processing the first <module> tag
444 bool InitModule(ServerConfig* conf, const char* tag)
446 old_module_names.clear();
447 new_module_names.clear();
448 added_modules.clear();
449 removed_modules.clear();
450 for (std::vector<std::string>::iterator t = conf->module_names.begin(); t != conf->module_names.end(); t++)
452 old_module_names.push_back(*t);
457 /* Callback called to process a single <module> tag
459 bool DoModule(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
461 const char* modname = values[0].GetString();
462 new_module_names.push_back(modname);
466 /* Callback called when there are no more <module> tags
468 bool DoneModule(ServerConfig* conf, const char* tag)
470 // now create a list of new modules that are due to be loaded
471 // and a seperate list of modules which are due to be unloaded
472 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
476 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
483 added_modules.push_back(*_new);
486 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
489 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
496 removed_modules.push_back(*oldm);
501 /* Callback called before processing the first <banlist> tag
503 bool InitMaxBans(ServerConfig* conf, const char* tag)
505 conf->maxbans.clear();
509 /* Callback called to process a single <banlist> tag
511 bool DoMaxBans(ServerConfig* conf, const char* tag, char** entries, ValueList &values, int* types)
513 const char* channel = values[0].GetString();
514 int limit = values[1].GetInteger();
515 conf->maxbans[channel] = limit;
519 /* Callback called when there are no more <banlist> tags.
521 bool DoneMaxBans(ServerConfig* conf, const char* tag)
526 void ServerConfig::Read(bool bail, userrec* user)
528 static char debug[MAXBUF]; /* Temporary buffer for debugging value */
529 static char maxkeep[MAXBUF]; /* Temporary buffer for WhoWasMaxKeep value */
530 int rem = 0, add = 0; /* Number of modules added, number of modules removed */
531 std::ostringstream errstr; /* String stream containing the error output */
533 /* These tags MUST occur and must ONLY occur once in the config file */
534 static char* Once[] = { "server", "admin", "files", "power", "options", NULL };
536 /* These tags can occur ONCE or not at all */
537 static InitialConfig Values[] = {
538 {"options", "softlimit", &this->SoftLimit, DT_INTEGER, ValidateSoftLimit},
539 {"options", "somaxconn", &this->MaxConn, DT_INTEGER, ValidateMaxConn},
540 {"server", "name", &this->ServerName, DT_CHARPTR, ValidateServerName},
541 {"server", "description", &this->ServerDesc, DT_CHARPTR, NoValidation},
542 {"server", "network", &this->Network, DT_CHARPTR, NoValidation},
543 {"admin", "name", &this->AdminName, DT_CHARPTR, NoValidation},
544 {"admin", "email", &this->AdminEmail, DT_CHARPTR, NoValidation},
545 {"admin", "nick", &this->AdminNick, DT_CHARPTR, NoValidation},
546 {"files", "motd", &this->motd, DT_CHARPTR, ValidateMotd},
547 {"files", "rules", &this->rules, DT_CHARPTR, ValidateRules},
548 {"power", "diepass", &this->diepass, DT_CHARPTR, NoValidation},
549 {"power", "pause", &this->DieDelay, DT_INTEGER, NoValidation},
550 {"power", "restartpass", &this->restartpass, DT_CHARPTR, NoValidation},
551 {"options", "prefixquit", &this->PrefixQuit, DT_CHARPTR, NoValidation},
552 {"die", "value", &this->DieValue, DT_CHARPTR, NoValidation},
553 {"options", "loglevel", &debug, DT_CHARPTR, ValidateLogLevel},
554 {"options", "netbuffersize", &this->NetBufferSize, DT_INTEGER, ValidateNetBufferSize},
555 {"options", "maxwho", &this->MaxWhoResults, DT_INTEGER, ValidateMaxWho},
556 {"options", "allowhalfop", &this->AllowHalfop, DT_BOOLEAN, NoValidation},
557 {"dns", "server", &this->DNSServer, DT_CHARPTR, ValidateDnsServer},
558 {"dns", "timeout", &this->dns_timeout, DT_INTEGER, ValidateDnsTimeout},
559 {"options", "moduledir", &this->ModPath, DT_CHARPTR, ValidateModPath},
560 {"disabled", "commands", &this->DisabledCommands, DT_CHARPTR, NoValidation},
561 {"options", "userstats", &this->UserStats, DT_CHARPTR, NoValidation},
562 {"options", "customversion", &this->CustomVersion, DT_CHARPTR, NoValidation},
563 {"options", "hidesplits", &this->HideSplits, DT_BOOLEAN, NoValidation},
564 {"options", "hidebans", &this->HideBans, DT_BOOLEAN, NoValidation},
565 {"options", "hidewhois", &this->HideWhoisServer, DT_CHARPTR, NoValidation},
566 {"options", "operspywhois", &this->OperSpyWhois, DT_BOOLEAN, NoValidation},
567 {"options", "tempdir", &this->TempDir, DT_CHARPTR, ValidateTempDir},
568 {"options", "nouserdns", &this->NoUserDns, DT_BOOLEAN, NoValidation},
569 {"options", "syntaxhints", &this->SyntaxHints, DT_BOOLEAN, NoValidation},
570 {"options", "cyclehosts", &this->CycleHosts, DT_BOOLEAN, NoValidation},
571 {"pid", "file", &this->PID, DT_CHARPTR, NoValidation},
572 {"whowas", "groupsize", &this->WhoWasGroupSize, DT_INTEGER, NoValidation},
573 {"whowas", "maxgroups", &this->WhoWasMaxGroups, DT_INTEGER, NoValidation},
574 {"whowas", "maxkeep", &maxkeep, DT_CHARPTR, ValidateWhoWas},
578 /* These tags can occur multiple times, and therefore they have special code to read them
579 * which is different to the code for reading the singular tags listed above.
581 static MultiConfig MultiValues[] = {
584 {"allow", "deny", "password", "timeout", "pingfreq", "flood",
585 "threshold", "sendq", "recvq", "localmax", "globalmax", NULL},
586 {DT_CHARPTR, DT_CHARPTR, DT_CHARPTR, DT_INTEGER, DT_INTEGER, DT_INTEGER,
587 DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER},
588 InitConnect, DoConnect, DoneConnect},
593 InitULine,DoULine,DoneULine},
596 {"chan", "limit", NULL},
597 {DT_CHARPTR, DT_INTEGER},
598 InitMaxBans, DoMaxBans, DoneMaxBans},
603 InitModule, DoModule, DoneModule},
606 {"reason", "ipmask", NULL},
607 {DT_CHARPTR, DT_CHARPTR},
608 InitXLine, DoZLine, DoneXLine},
611 {"reason", "nick", NULL},
612 {DT_CHARPTR, DT_CHARPTR},
613 InitXLine, DoQLine, DoneXLine},
616 {"reason", "host", NULL},
617 {DT_CHARPTR, DT_CHARPTR},
618 InitXLine, DoKLine, DoneXLine},
621 {"reason", "host", NULL},
622 {DT_CHARPTR, DT_CHARPTR},
623 InitXLine, DoELine, DoneXLine},
626 {"name", "classes", NULL},
627 {DT_CHARPTR, DT_CHARPTR},
628 InitTypes, DoType, DoneClassesAndTypes},
631 {"name", "commands", NULL},
632 {DT_CHARPTR, DT_CHARPTR},
633 InitClasses, DoClass, DoneClassesAndTypes},
638 include_stack.clear();
640 /* Load and parse the config file, if there are any errors then explode */
642 /* Make a copy here so if it fails then we can carry on running with an unaffected config */
643 ConfigDataHash newconfig;
645 if (this->LoadConf(newconfig, CONFIG_FILE, errstr))
647 /* If we succeeded, set the ircd config to the new one */
648 this->config_data = newconfig;
652 ServerInstance->Log(DEFAULT, "There were errors in your configuration:\n%s", errstr.str().c_str());
656 /* Unneeded because of the ServerInstance->Log() aboive? */
657 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
658 InspIRCd::Exit(ERROR);
662 std::string errors = errstr.str();
663 std::string::size_type start;
664 unsigned int prefixlen;
667 /* ":ServerInstance->Config->ServerName NOTICE user->nick :" */
668 prefixlen = strlen(this->ServerName) + strlen(user->nick) + 11;
672 user->WriteServ("NOTICE %s :There were errors in the configuration file:",user->nick);
674 while(start < errors.length())
676 user->WriteServ("NOTICE %s :%s",user->nick, errors.substr(start, 510 - prefixlen).c_str());
677 start += 510 - prefixlen;
682 ServerInstance->WriteOpers("There were errors in the configuration file:");
684 while(start < errors.length())
686 ServerInstance->WriteOpers(errors.substr(start, 360).c_str());
695 /* Check we dont have more than one of singular tags, or any of them missing
697 for (int Index = 0; Once[Index]; Index++)
698 if (!CheckOnce(Once[Index],bail,user))
701 /* Read the values of all the tags which occur once or not at all, and call their callbacks.
703 for (int Index = 0; Values[Index].tag; Index++)
706 ConfValue(this->config_data, Values[Index].tag, Values[Index].value, 0, item, MAXBUF);
709 Values[Index].validation_function(this, Values[Index].tag, Values[Index].value, vi);
711 switch (Values[Index].datatype)
714 strlcpy((char*)Values[Index].val, vi.GetString(), MAXBUF);
717 *((int*)Values[Index].val) = vi.GetInteger();
720 *((bool*)(Values[Index].val)) = vi.GetBool();
727 /* Read the multiple-tag items (class tags, connect tags, etc)
728 * and call the callbacks associated with them. We have three
729 * callbacks for these, a 'start', 'item' and 'end' callback.
731 for (int Index = 0; MultiValues[Index].tag; Index++)
733 MultiValues[Index].init_function(this, MultiValues[Index].tag);
735 int number_of_tags = ConfValueEnum(this->config_data, MultiValues[Index].tag);
737 for (int tagnum = 0; tagnum < number_of_tags; tagnum++)
740 for (int valuenum = 0; MultiValues[Index].items[valuenum]; valuenum++)
742 switch (MultiValues[Index].datatype[valuenum])
747 ConfValue(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], tagnum, item, MAXBUF);
748 ServerInstance->Log(DEBUG,"Data type DT_CHARPTR multi-item <%s:%s>[%d] = '%s'", MultiValues[Index].tag, MultiValues[Index].items[valuenum],tagnum, item);
749 vl.push_back(ValueItem(item));
755 ConfValueInteger(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], tagnum, item);
756 ServerInstance->Log(DEBUG,"Data type DT_INTEGER multi-item <%s:%s>[%d] = '%d'", MultiValues[Index].tag, MultiValues[Index].items[valuenum],tagnum, item);
757 vl.push_back(ValueItem(item));
762 bool item = ConfValueBool(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], tagnum);
763 ServerInstance->Log(DEBUG,"Data type DT_BOOLEAN multi-item <%s:%s>[%d] = '%d'", MultiValues[Index].tag, MultiValues[Index].items[valuenum],tagnum, item);
764 vl.push_back(ValueItem(item));
771 ServerInstance->Log(DEBUG,"Call validation function for multi-value <%s>", MultiValues[Index].tag);
772 MultiValues[Index].validation_function(this, MultiValues[Index].tag, (char**)MultiValues[Index].items, vl, MultiValues[Index].datatype);
775 MultiValues[Index].finish_function(this, MultiValues[Index].tag);
778 // write once here, to try it out and make sure its ok
779 ServerInstance->WritePID(this->PID);
781 ServerInstance->Log(DEFAULT,"Done reading configuration file.");
783 /* If we're rehashing, let's load any new modules, and unload old ones
789 ServerInstance->stats->BoundPortCount = ServerInstance->BindPorts(false, found_ports, pl);
793 user->WriteServ("NOTICE %s :*** Not all your client ports could be bound.", user->nick);
794 user->WriteServ("NOTICE %s :*** The following port%s failed to bind:", user->nick, found_ports - ServerInstance->stats->BoundPortCount != 1 ? "s" : "");
796 for (FailedPortList::iterator i = pl.begin(); i != pl.end(); i++, j++)
798 user->WriteServ("NOTICE %s :*** %d. IP: %s Port: %lu", user->nick, j, i->first.empty() ? "<all>" : i->first.c_str(), (unsigned long)i->second);
802 if (!removed_modules.empty())
803 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
805 if (ServerInstance->UnloadModule(removing->c_str()))
807 ServerInstance->WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
810 user->WriteServ("973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
817 user->WriteServ("972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
821 if (!added_modules.empty())
822 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
824 if (ServerInstance->LoadModule(adding->c_str()))
826 ServerInstance->WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
829 user->WriteServ("975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
836 user->WriteServ("974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
840 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());
844 bool ServerConfig::LoadConf(ConfigDataHash &target, const char* filename, std::ostringstream &errorstream)
846 std::ifstream conf(filename);
859 /* Check if the file open failed first */
862 errorstream << "LoadConf: Couldn't open config file: " << filename << std::endl;
866 /* Fix the chmod of the file to restrict it to the current user and group */
867 chmod(filename,0600);
869 for (unsigned int t = 0; t < include_stack.size(); t++)
871 if (std::string(filename) == include_stack[t])
873 errorstream << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
878 /* It's not already included, add it to the list of files we've loaded */
879 include_stack.push_back(filename);
881 /* Start reading characters... */
885 * Here we try and get individual tags on separate lines,
886 * this would be so easy if we just made people format
887 * their config files like that, but they don't so...
888 * We check for a '<' and then know the line is over when
889 * we get a '>' not inside quotes. If we find two '<' and
890 * no '>' then die with an error.
893 if((ch == '#') && !in_quote)
896 if(((ch == '\n') || (ch == '\r')) && in_quote)
898 errorstream << "Got a newline within a quoted section, this is probably a typo: " << filename << ":" << linenumber << std::endl;
917 /* XXX: Added by Brain, May 1st 2006 - Escaping of characters.
918 * Note that this WILL NOT usually allow insertion of newlines,
919 * because a newline is two characters long. Use it primarily to
920 * insert the " symbol.
922 * Note that this also involves a further check when parsing the line,
923 * which can be found below.
925 if ((ch == '\\') && (in_quote) && (in_tag))
928 ServerInstance->Log(DEBUG,"Escape sequence in config line.");
930 if (conf.get(real_character))
932 ServerInstance->Log(DEBUG,"Escaping %c", real_character);
933 if (real_character == 'n')
934 real_character = '\n';
935 line += real_character;
940 errorstream << "End of file after a \\, what did you want to escape?: " << filename << ":" << linenumber << std::endl;
953 errorstream << "Got another opening < when the first one wasn't closed: " << filename << ":" << linenumber << std::endl;
961 errorstream << "We're in a quote but outside a tag, interesting. " << filename << ":" << linenumber << std::endl;
966 // errorstream << "Opening new config tag on line " << linenumber << std::endl;
977 // errorstream << "Closing quote in config tag on line " << linenumber << std::endl;
982 // errorstream << "Opening quote in config tag on line " << linenumber << std::endl;
990 errorstream << "Found a (closing) \" outside a tag: " << filename << ":" << linenumber << std::endl;
994 errorstream << "Found a (opening) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1004 // errorstream << "Closing config tag on line " << linenumber << std::endl;
1008 * If this finds an <include> then ParseLine can simply call
1009 * LoadConf() and load the included config into the same ConfigDataHash
1012 if(!this->ParseLine(target, line, linenumber, errorstream))
1019 errorstream << "Got a closing > when we weren't inside a tag: " << filename << ":" << linenumber << std::endl;
1029 bool ServerConfig::LoadConf(ConfigDataHash &target, const std::string &filename, std::ostringstream &errorstream)
1031 return this->LoadConf(target, filename.c_str(), errorstream);
1034 bool ServerConfig::ParseLine(ConfigDataHash &target, std::string &line, long linenumber, std::ostringstream &errorstream)
1036 std::string tagname;
1037 std::string current_key;
1038 std::string current_value;
1044 got_name = got_key = in_quote = false;
1046 // std::cout << "ParseLine(data, '" << line << "', " << linenumber << ", stream)" << std::endl;
1048 for(std::string::iterator c = line.begin(); c != line.end(); c++)
1052 /* We don't know the tag name yet. */
1063 /* We got to a space, we should have the tagname now. */
1064 if(tagname.length())
1072 /* We have the tag name */
1075 /* We're still reading the key name */
1085 /* We got an '=', end of the key name. */
1091 /* We have the key name, now we're looking for quotes and the value */
1093 /* Correctly handle escaped characters here.
1094 * See the XXX'ed section above.
1096 if ((*c == '\\') && (in_quote))
1100 current_value += '\n';
1102 current_value += *c;
1109 /* We're not already in a quote. */
1114 /* Leaving quotes, we have the value */
1115 results.push_back(KeyVal(current_key, current_value));
1117 // std::cout << "<" << tagname << ":" << current_key << "> " << current_value << std::endl;
1122 if((tagname == "include") && (current_key == "file"))
1124 if(!this->DoInclude(target, current_value, errorstream))
1128 current_key.clear();
1129 current_value.clear();
1136 current_value += *c;
1143 /* Finished parsing the tag, add it to the config hash */
1144 target.insert(std::pair<std::string, KeyValList > (tagname, results));
1149 bool ServerConfig::DoInclude(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream)
1151 std::string confpath;
1152 std::string newfile;
1153 std::string::size_type pos;
1155 confpath = CONFIG_FILE;
1158 for (std::string::iterator c = newfile.begin(); c != newfile.end(); c++)
1168 if((pos = confpath.find("/inspircd.conf")) != std::string::npos)
1170 /* Leaves us with just the path */
1171 newfile = confpath.substr(0, pos) + std::string("/") + newfile;
1175 errorstream << "Couldn't get config path from: " << confpath << std::endl;
1180 return LoadConf(target, newfile, errorstream);
1183 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, int index, char* result, int length)
1186 bool r = ConfValue(target, std::string(tag), std::string(var), index, value);
1187 strlcpy(result, value.c_str(), length);
1191 bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, std::string &result)
1193 ConfigDataHash::size_type pos = index;
1194 if((pos >= 0) && (pos < target.count(tag)))
1196 ConfigDataHash::const_iterator iter = target.find(tag);
1198 for(int i = 0; i < index; i++)
1201 for(KeyValList::const_iterator j = iter->second.begin(); j != iter->second.end(); j++)
1212 ServerInstance->Log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1216 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());
1222 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, int index, int &result)
1224 return ConfValueInteger(target, std::string(tag), std::string(var), index, result);
1227 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, int &result)
1230 std::istringstream stream;
1231 bool r = ConfValue(target, tag, var, index, value);
1233 if(!(stream >> result))
1238 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, int index)
1240 return ConfValueBool(target, std::string(tag), std::string(var), index);
1243 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, int index)
1246 if(!ConfValue(target, tag, var, index, result))
1249 return ((result == "yes") || (result == "true") || (result == "1"));
1252 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const char* tag)
1254 return target.count(tag);
1257 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const std::string &tag)
1259 return target.count(tag);
1262 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const char* tag, int index)
1264 return ConfVarEnum(target, std::string(tag), index);
1267 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const std::string &tag, int index)
1269 ConfigDataHash::size_type pos = index;
1271 if((pos >= 0) && (pos < target.count(tag)))
1273 ConfigDataHash::const_iterator iter = target.find(tag);
1275 for(int i = 0; i < index; i++)
1278 return iter->second.size();
1282 ServerInstance->Log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1286 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());
1292 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1294 bool ServerConfig::ReadFile(file_cache &F, const char* fname)
1297 char linebuf[MAXBUF];
1303 std::string::size_type pos;
1304 std::string confpath = CONFIG_FILE;
1305 if((pos = confpath.find("/inspircd.conf")) != std::string::npos)
1307 /* Leaves us with just the path */
1308 std::string newfile = confpath.substr(0, pos) + std::string("/") + fname;
1309 file = fopen(newfile.c_str(), "r");
1314 file = fopen(fname, "r");
1320 fgets(linebuf, sizeof(linebuf), file);
1321 linebuf[strlen(linebuf)-1] = 0;
1325 F.push_back(*linebuf ? linebuf : " ");
1337 bool ServerConfig::FileExists(const char* file)
1340 if ((input = fopen (file, "r")) == NULL)
1351 char* ServerConfig::CleanFilename(char* name)
1353 char* p = name + strlen(name);
1354 while ((p != name) && (*p != '/')) p--;
1355 return (p != name ? ++p : p);
1359 bool ServerConfig::DirValid(const char* dirandfile)
1362 char buffer[MAXBUF];
1363 char otherdir[MAXBUF];
1366 strlcpy(work, dirandfile, MAXBUF);
1369 // we just want the dir
1381 // Get the current working directory
1382 if (getcwd(buffer, MAXBUF ) == NULL )
1387 if (getcwd(otherdir, MAXBUF ) == NULL )
1392 size_t t = strlen(work);
1394 if (strlen(otherdir) >= t)
1398 if (!strcmp(otherdir,work))
1411 std::string ServerConfig::GetFullProgDir(char** argv, int argc)
1414 char buffer[MAXBUF];
1415 char otherdir[MAXBUF];
1418 strlcpy(work,argv[0],MAXBUF);
1421 // we just want the dir
1433 // Get the current working directory
1434 if (getcwd(buffer, MAXBUF) == NULL)
1439 if (getcwd(otherdir, MAXBUF) == NULL)
1446 InspIRCd* ServerConfig::GetInstance()
1448 return ServerInstance;