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 "inspircd_config.h"
18 #include "configreader.h"
24 #include "inspstring.h"
26 #include "userprocess.h"
29 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
31 ServerConfig::ServerConfig(InspIRCd* Instance) : ServerInstance(Instance)
34 *TempDir = *ServerName = *Network = *ServerDesc = *AdminName = '\0';
35 *HideWhoisServer = *AdminEmail = *AdminNick = *diepass = *restartpass = '\0';
36 *CustomVersion = *motd = *rules = *PrefixQuit = *DieValue = *DNSServer = '\0';
37 *OperOnlyStats = *ModPath = *MyExecutable = *DisabledCommands = *PID = '\0';
39 NoUserDns = forcedebug = OperSpyWhois = nofork = HideBans = HideSplits = false;
40 CycleHosts = writelog = AllowHalfop = true;
41 dns_timeout = DieDelay = 5;
43 NetBufferSize = 10240;
44 SoftLimit = MAXCLIENTS;
52 void ServerConfig::ClearStack()
54 include_stack.clear();
57 Module* ServerConfig::GetIOHook(int port)
59 std::map<int,Module*>::iterator x = IOHookModule.find(port);
60 return (x != IOHookModule.end() ? x->second : NULL);
63 bool ServerConfig::AddIOHook(int port, Module* iomod)
67 IOHookModule[port] = iomod;
72 ModuleException err("Port already hooked by another module");
78 bool ServerConfig::DelIOHook(int port)
80 std::map<int,Module*>::iterator x = IOHookModule.find(port);
81 if (x != IOHookModule.end())
83 IOHookModule.erase(x);
89 bool ServerConfig::CheckOnce(char* tag, bool bail, userrec* user)
91 int count = ConfValueEnum(this->config_data, tag);
97 printf("There were errors in your configuration:\nYou have more than one <%s> tag, this is not permitted.\n",tag);
98 InspIRCd::Exit(ERROR);
104 user->WriteServ("There were errors in your configuration:");
105 user->WriteServ("You have more than one <%s> tag, this is not permitted.\n",tag);
109 ServerInstance->WriteOpers("There were errors in the configuration file:");
110 ServerInstance->WriteOpers("You have more than one <%s> tag, this is not permitted.\n",tag);
119 printf("There were errors in your configuration:\nYou have not defined a <%s> tag, this is required.\n",tag);
120 InspIRCd::Exit(ERROR);
126 user->WriteServ("There were errors in your configuration:");
127 user->WriteServ("You have not defined a <%s> tag, this is required.",tag);
131 ServerInstance->WriteOpers("There were errors in the configuration file:");
132 ServerInstance->WriteOpers("You have not defined a <%s> tag, this is required.",tag);
140 bool NoValidation(ServerConfig* conf, const char* tag, const char* value, void* data)
142 conf->GetInstance()->Log(DEBUG,"No validation for <%s:%s>",tag,value);
146 bool ValidateTempDir(ServerConfig* conf, const char* tag, const char* value, void* data)
148 char* x = (char*)data;
150 strlcpy(x,"/tmp",1024);
154 bool ValidateMaxTargets(ServerConfig* conf, const char* tag, const char* value, void* data)
157 if ((*x < 0) || (*x > 31))
159 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
165 bool ValidateSoftLimit(ServerConfig* conf, const char* tag, const char* value, void* data)
168 if ((*x < 1) || (*x > MAXCLIENTS))
170 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
176 bool ValidateMaxConn(ServerConfig* conf, const char* tag, const char* value, void* data)
180 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
186 bool ValidateDnsTimeout(ServerConfig* conf, const char* tag, const char* value, void* data)
194 bool InitializeDisabledCommands(const char* data, InspIRCd* ServerInstance)
196 std::stringstream dcmds(data);
199 /* Enable everything first */
200 for (nspace::hash_map<std::string,command_t*>::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
201 x->second->Disable(false);
203 /* Now disable all the ones which the user wants disabled */
204 while (dcmds >> thiscmd)
206 nspace::hash_map<std::string,command_t*>::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
207 if (cm != ServerInstance->Parser->cmdlist.end())
209 ServerInstance->Log(DEBUG,"Disabling command '%s'",cm->second->command.c_str());
210 cm->second->Disable(true);
216 bool ValidateDnsServer(ServerConfig* conf, const char* tag, const char* value, void* data)
218 char* x = (char*)data;
221 // attempt to look up their nameserver from /etc/resolv.conf
222 conf->GetInstance()->Log(DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
223 ifstream resolv("/etc/resolv.conf");
224 std::string nameserver;
225 bool found_server = false;
227 if (resolv.is_open())
229 while (resolv >> nameserver)
231 if ((nameserver == "nameserver") && (!found_server))
233 resolv >> nameserver;
234 strlcpy(x,nameserver.c_str(),MAXBUF);
236 conf->GetInstance()->Log(DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
242 conf->GetInstance()->Log(DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
243 strlcpy(x,"127.0.0.1",MAXBUF);
248 conf->GetInstance()->Log(DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
249 strlcpy(x,"127.0.0.1",MAXBUF);
255 bool ValidateModPath(ServerConfig* conf, const char* tag, const char* value, void* data)
257 char* x = (char*)data;
259 strlcpy(x,MOD_PATH,MAXBUF);
264 bool ValidateServerName(ServerConfig* conf, const char* tag, const char* value, void* data)
266 char* x = (char*)data;
269 conf->GetInstance()->Log(DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s%c'",x,x,'.');
270 charlcat(x,'.',MAXBUF);
276 bool ValidateNetBufferSize(ServerConfig* conf, const char* tag, const char* value, void* data)
278 if ((!conf->NetBufferSize) || (conf->NetBufferSize > 65535) || (conf->NetBufferSize < 1024))
280 conf->GetInstance()->Log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
281 conf->NetBufferSize = 10240;
286 bool ValidateMaxWho(ServerConfig* conf, const char* tag, const char* value, void* data)
288 if ((!conf->MaxWhoResults) || (conf->MaxWhoResults > 65535) || (conf->MaxWhoResults < 1))
290 conf->GetInstance()->Log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
291 conf->MaxWhoResults = 128;
296 bool ValidateLogLevel(ServerConfig* conf, const char* tag, const char* value, void* data)
298 const char* dbg = (const char*)data;
299 conf->LogLevel = DEFAULT;
300 if (!strcmp(dbg,"debug"))
302 conf->LogLevel = DEBUG;
305 else if (!strcmp(dbg,"verbose"))
306 conf->LogLevel = VERBOSE;
307 else if (!strcmp(dbg,"default"))
308 conf->LogLevel = DEFAULT;
309 else if (!strcmp(dbg,"sparse"))
310 conf->LogLevel = SPARSE;
311 else if (!strcmp(dbg,"none"))
312 conf->LogLevel = NONE;
316 bool ValidateMotd(ServerConfig* conf, const char* tag, const char* value, void* data)
318 conf->ReadFile(conf->MOTD,conf->motd);
322 bool ValidateRules(ServerConfig* conf, const char* tag, const char* value, void* data)
324 conf->ReadFile(conf->RULES,conf->rules);
328 /* Callback called before processing the first <connect> tag
330 bool InitConnect(ServerConfig* conf, const char* tag)
332 conf->GetInstance()->Log(DEFAULT,"Reading connect classes...");
333 conf->Classes.clear();
337 /* Callback called to process a single <connect> tag
339 bool DoConnect(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
342 char* allow = (char*)values[0]; /* Yeah, there are a lot of values. Live with it. */
343 char* deny = (char*)values[1];
344 char* password = (char*)values[2];
345 int* timeout = (int*)values[3];
346 int* pingfreq = (int*)values[4];
347 int* flood = (int*)values[5];
348 int* threshold = (int*)values[6];
349 int* sendq = (int*)values[7];
350 int* recvq = (int*)values[8];
351 int* localmax = (int*)values[9];
352 int* globalmax = (int*)values[10];
359 c.registration_timeout = *timeout;
360 c.pingtime = *pingfreq;
362 c.threshold = *threshold;
365 c.maxlocal = *localmax;
366 c.maxglobal = *globalmax;
371 if (c.maxglobal == 0)
373 if (c.threshold == 0)
377 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());
383 if (c.registration_timeout == 0)
384 c.registration_timeout = 90;
387 conf->Classes.push_back(c);
393 conf->Classes.push_back(c);
394 conf->GetInstance()->Log(DEBUG,"Read connect class type DENY, host=%s",deny);
400 /* Callback called when there are no more <connect> tags
402 bool DoneConnect(ServerConfig* conf, const char* tag)
404 conf->GetInstance()->Log(DEBUG,"DoneConnect called for tag: %s",tag);
408 /* Callback called before processing the first <uline> tag
410 bool InitULine(ServerConfig* conf, const char* tag)
412 conf->ulines.clear();
416 /* Callback called to process a single <uline> tag
418 bool DoULine(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
420 char* server = (char*)values[0];
421 conf->GetInstance()->Log(DEBUG,"Read ULINE '%s'",server);
422 conf->ulines.push_back(server);
426 /* Callback called when there are no more <uline> tags
428 bool DoneULine(ServerConfig* conf, const char* tag)
433 /* Callback called before processing the first <module> tag
435 bool InitModule(ServerConfig* conf, const char* tag)
437 old_module_names.clear();
438 new_module_names.clear();
439 added_modules.clear();
440 removed_modules.clear();
441 for (std::vector<std::string>::iterator t = conf->module_names.begin(); t != conf->module_names.end(); t++)
443 old_module_names.push_back(*t);
448 /* Callback called to process a single <module> tag
450 bool DoModule(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
452 char* modname = (char*)values[0];
453 new_module_names.push_back(modname);
457 /* Callback called when there are no more <module> tags
459 bool DoneModule(ServerConfig* conf, const char* tag)
461 // now create a list of new modules that are due to be loaded
462 // and a seperate list of modules which are due to be unloaded
463 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
467 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
474 added_modules.push_back(*_new);
477 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
480 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
487 removed_modules.push_back(*oldm);
492 /* Callback called before processing the first <banlist> tag
494 bool InitMaxBans(ServerConfig* conf, const char* tag)
496 conf->maxbans.clear();
500 /* Callback called to process a single <banlist> tag
502 bool DoMaxBans(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
504 char* channel = (char*)values[0];
505 int* limit = (int*)values[1];
506 conf->maxbans[channel] = *limit;
510 /* Callback called when there are no more <banlist> tags.
512 bool DoneMaxBans(ServerConfig* conf, const char* tag)
517 void ServerConfig::Read(bool bail, userrec* user)
519 char debug[MAXBUF]; /* Temporary buffer for debugging value */
520 char* data[12]; /* Temporary buffers for reading multiple occurance tags into */
521 void* ptr[12]; /* Temporary pointers for passing to callbacks */
522 int r_i[12]; /* Temporary array for casting */
523 int rem = 0, add = 0; /* Number of modules added, number of modules removed */
524 std::ostringstream errstr; /* String stream containing the error output */
526 /* These tags MUST occur and must ONLY occur once in the config file */
527 static char* Once[] = { "server", "admin", "files", "power", "options", "pid", NULL };
529 /* These tags can occur ONCE or not at all */
530 static InitialConfig Values[] = {
531 {"options", "softlimit", &this->SoftLimit, DT_INTEGER, ValidateSoftLimit},
532 {"options", "somaxconn", &this->MaxConn, DT_INTEGER, ValidateMaxConn},
533 {"server", "name", &this->ServerName, DT_CHARPTR, ValidateServerName},
534 {"server", "description", &this->ServerDesc, DT_CHARPTR, NoValidation},
535 {"server", "network", &this->Network, DT_CHARPTR, NoValidation},
536 {"admin", "name", &this->AdminName, DT_CHARPTR, NoValidation},
537 {"admin", "email", &this->AdminEmail, DT_CHARPTR, NoValidation},
538 {"admin", "nick", &this->AdminNick, DT_CHARPTR, NoValidation},
539 {"files", "motd", &this->motd, DT_CHARPTR, ValidateMotd},
540 {"files", "rules", &this->rules, DT_CHARPTR, ValidateRules},
541 {"power", "diepass", &this->diepass, DT_CHARPTR, NoValidation},
542 {"power", "pauseval", &this->DieDelay, DT_INTEGER, NoValidation},
543 {"power", "restartpass", &this->restartpass, DT_CHARPTR, NoValidation},
544 {"options", "prefixquit", &this->PrefixQuit, DT_CHARPTR, NoValidation},
545 {"die", "value", &this->DieValue, DT_CHARPTR, NoValidation},
546 {"options", "loglevel", &debug, DT_CHARPTR, ValidateLogLevel},
547 {"options", "netbuffersize", &this->NetBufferSize, DT_INTEGER, ValidateNetBufferSize},
548 {"options", "maxwho", &this->MaxWhoResults, DT_INTEGER, ValidateMaxWho},
549 {"options", "allowhalfop", &this->AllowHalfop, DT_BOOLEAN, NoValidation},
550 {"dns", "server", &this->DNSServer, DT_CHARPTR, ValidateDnsServer},
551 {"dns", "timeout", &this->dns_timeout, DT_INTEGER, ValidateDnsTimeout},
552 {"options", "moduledir", &this->ModPath, DT_CHARPTR, ValidateModPath},
553 {"disabled", "commands", &this->DisabledCommands, DT_CHARPTR, NoValidation},
554 {"options", "operonlystats", &this->OperOnlyStats, DT_CHARPTR, NoValidation},
555 {"options", "customversion", &this->CustomVersion, DT_CHARPTR, NoValidation},
556 {"options", "hidesplits", &this->HideSplits, DT_BOOLEAN, NoValidation},
557 {"options", "hidebans", &this->HideBans, DT_BOOLEAN, NoValidation},
558 {"options", "hidewhois", &this->HideWhoisServer, DT_CHARPTR, NoValidation},
559 {"options", "operspywhois", &this->OperSpyWhois, DT_BOOLEAN, NoValidation},
560 {"options", "tempdir", &this->TempDir, DT_CHARPTR, ValidateTempDir},
561 {"options", "nouserdns", &this->NoUserDns, DT_BOOLEAN, NoValidation},
562 {"options", "syntaxhints", &this->SyntaxHints, DT_BOOLEAN, NoValidation},
563 {"options", "cyclehosts", &this->CycleHosts, DT_BOOLEAN, NoValidation},
564 {"pid", "file", &this->PID, DT_CHARPTR, NoValidation},
568 /* These tags can occur multiple times, and therefore they have special code to read them
569 * which is different to the code for reading the singular tags listed above.
571 static MultiConfig MultiValues[] = {
574 {"allow", "deny", "password", "timeout", "pingfreq", "flood",
575 "threshold", "sendq", "recvq", "localmax", "globalmax", NULL},
576 {DT_CHARPTR, DT_CHARPTR, DT_CHARPTR, DT_INTEGER, DT_INTEGER, DT_INTEGER,
577 DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER},
578 InitConnect, DoConnect, DoneConnect},
583 InitULine,DoULine,DoneULine},
586 {"chan", "limit", NULL},
587 {DT_CHARPTR, DT_INTEGER},
588 InitMaxBans, DoMaxBans, DoneMaxBans},
593 InitModule, DoModule, DoneModule},
596 {"reason", "ipmask", NULL},
597 {DT_CHARPTR, DT_CHARPTR},
598 InitXLine, DoZLine, DoneXLine},
601 {"reason", "nick", NULL},
602 {DT_CHARPTR, DT_CHARPTR},
603 InitXLine, DoQLine, DoneXLine},
606 {"reason", "host", NULL},
607 {DT_CHARPTR, DT_CHARPTR},
608 InitXLine, DoKLine, DoneXLine},
611 {"reason", "host", NULL},
612 {DT_CHARPTR, DT_CHARPTR},
613 InitXLine, DoELine, DoneXLine},
616 {"name", "classes", NULL},
617 {DT_CHARPTR, DT_CHARPTR},
618 InitTypes, DoType, DoneClassesAndTypes},
621 {"name", "commands", NULL},
622 {DT_CHARPTR, DT_CHARPTR},
623 InitClasses, DoClass, DoneClassesAndTypes},
628 include_stack.clear();
630 /* Load and parse the config file, if there are any errors then explode */
632 /* Make a copy here so if it fails then we can carry on running with an unaffected config */
633 ConfigDataHash newconfig;
635 if (this->LoadConf(newconfig, CONFIG_FILE, errstr))
637 /* If we succeeded, set the ircd config to the new one */
638 this->config_data = newconfig;
643 for(ConfigDataHash::const_iterator i = this->config_data.begin(); i != this->config_data.end(); i++)
645 c = (i->first != last) ? 1 : c+1;
648 std::cout << "[" << i->first << " " << c << "/" << this->config_data.count(i->first) << "]" << std::endl;
650 for(KeyValList::const_iterator j = i->second.begin(); j != i->second.end(); j++)
651 std::cout << "\t" << j->first << " = " << j->second << std::endl;
653 std::cout << "[/" << i->first << " " << c << "/" << this->config_data.count(i->first) << "]" << std::endl;
658 ServerInstance->Log(DEFAULT, "There were errors in your configuration:\n%s", errstr.str().c_str());
662 /* Unneeded because of the ServerInstance->Log() aboive? */
663 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
664 InspIRCd::Exit(ERROR);
668 std::string errors = errstr.str();
669 std::string::size_type start;
670 unsigned int prefixlen;
673 /* ":ServerInstance->Config->ServerName NOTICE user->nick :" */
674 prefixlen = strlen(this->ServerName) + strlen(user->nick) + 11;
678 user->WriteServ("NOTICE %s :There were errors in the configuration file:",user->nick);
680 while(start < errors.length())
682 user->WriteServ("NOTICE %s :%s",user->nick, errors.substr(start, 510 - prefixlen).c_str());
683 start += 510 - prefixlen;
688 ServerInstance->WriteOpers("There were errors in the configuration file:");
690 while(start < errors.length())
692 ServerInstance->WriteOpers(errors.substr(start, 360).c_str());
701 /* Check we dont have more than one of singular tags, or any of them missing
703 for (int Index = 0; Once[Index]; Index++)
704 if (!CheckOnce(Once[Index],bail,user))
707 /* Read the values of all the tags which occur once or not at all, and call their callbacks.
709 for (int Index = 0; Values[Index].tag; Index++)
711 int* val_i = (int*) Values[Index].val;
712 char* val_c = (char*) Values[Index].val;
714 switch (Values[Index].datatype)
717 /* Assuming MAXBUF here, potentially unsafe */
718 ConfValue(this->config_data, Values[Index].tag, Values[Index].value, 0, val_c, MAXBUF);
722 ConfValueInteger(this->config_data, Values[Index].tag, Values[Index].value, 0, *val_i);
726 *val_i = ConfValueBool(this->config_data, Values[Index].tag, Values[Index].value, 0);
733 Values[Index].validation_function(this, Values[Index].tag, Values[Index].value, Values[Index].val);
736 /* Claim memory for use when reading multiple tags
738 for (int n = 0; n < 12; n++)
739 data[n] = new char[MAXBUF];
741 /* Read the multiple-tag items (class tags, connect tags, etc)
742 * and call the callbacks associated with them. We have three
743 * callbacks for these, a 'start', 'item' and 'end' callback.
746 /* XXX - Make this use ConfValueInteger and so on */
747 for (int Index = 0; MultiValues[Index].tag; Index++)
749 MultiValues[Index].init_function(this, MultiValues[Index].tag);
751 int number_of_tags = ConfValueEnum(this->config_data, MultiValues[Index].tag);
753 for (int tagnum = 0; tagnum < number_of_tags; tagnum++)
755 for (int valuenum = 0; MultiValues[Index].items[valuenum]; valuenum++)
757 ConfValue(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], tagnum, data[valuenum], MAXBUF);
759 switch (MultiValues[Index].datatype[valuenum])
762 ptr[valuenum] = data[valuenum];
765 r_i[valuenum] = atoi(data[valuenum]);
766 ptr[valuenum] = &r_i[valuenum];
769 r_i[valuenum] = ((*data[valuenum] == tolower('y')) || (*data[valuenum] == tolower('t')) || (*data[valuenum] == '1'));
770 ptr[valuenum] = &r_i[valuenum];
776 MultiValues[Index].validation_function(this, MultiValues[Index].tag, (char**)MultiValues[Index].items, ptr, MultiValues[Index].datatype);
779 MultiValues[Index].finish_function(this, MultiValues[Index].tag);
782 /* Free any memory we claimed
784 for (int n = 0; n < 12; n++)
787 // write once here, to try it out and make sure its ok
788 ServerInstance->WritePID(this->PID);
790 ServerInstance->Log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
792 /* If we're rehashing, let's load any new modules, and unload old ones
796 ServerInstance->stats->BoundPortCount = ServerInstance->BindPorts(false);
798 if (!removed_modules.empty())
799 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
801 if (ServerInstance->UnloadModule(removing->c_str()))
803 ServerInstance->WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
806 user->WriteServ("973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
813 user->WriteServ("972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
817 if (!added_modules.empty())
818 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
820 if (ServerInstance->LoadModule(adding->c_str()))
822 ServerInstance->WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
825 user->WriteServ("975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
832 user->WriteServ("974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
836 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());
840 bool ServerConfig::LoadConf(ConfigDataHash &target, const char* filename, std::ostringstream &errorstream)
842 std::ifstream conf(filename);
855 /* Check if the file open failed first */
858 errorstream << "LoadConf: Couldn't open config file: " << filename << std::endl;
862 /* Fix the chmod of the file to restrict it to the current user and group */
863 chmod(filename,0600);
865 for (unsigned int t = 0; t < include_stack.size(); t++)
867 if (std::string(filename) == include_stack[t])
869 errorstream << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
874 /* It's not already included, add it to the list of files we've loaded */
875 include_stack.push_back(filename);
877 /* Start reading characters... */
881 * Here we try and get individual tags on separate lines,
882 * this would be so easy if we just made people format
883 * their config files like that, but they don't so...
884 * We check for a '<' and then know the line is over when
885 * we get a '>' not inside quotes. If we find two '<' and
886 * no '>' then die with an error.
889 if((ch == '#') && !in_quote)
892 if(((ch == '\n') || (ch == '\r')) && in_quote)
894 errorstream << "Got a newline within a quoted section, this is probably a typo: " << filename << ":" << linenumber << std::endl;
913 /* XXX: Added by Brain, May 1st 2006 - Escaping of characters.
914 * Note that this WILL NOT usually allow insertion of newlines,
915 * because a newline is two characters long. Use it primarily to
916 * insert the " symbol.
918 * Note that this also involves a further check when parsing the line,
919 * which can be found below.
921 if ((ch == '\\') && (in_quote) && (in_tag))
924 ServerInstance->Log(DEBUG,"Escape sequence in config line.");
926 if (conf.get(real_character))
928 ServerInstance->Log(DEBUG,"Escaping %c", real_character);
929 line += real_character;
934 errorstream << "End of file after a \\, what did you want to escape?: " << filename << ":" << linenumber << std::endl;
947 errorstream << "Got another opening < when the first one wasn't closed: " << filename << ":" << linenumber << std::endl;
955 errorstream << "We're in a quote but outside a tag, interesting. " << filename << ":" << linenumber << std::endl;
960 // errorstream << "Opening new config tag on line " << linenumber << std::endl;
971 // errorstream << "Closing quote in config tag on line " << linenumber << std::endl;
976 // errorstream << "Opening quote in config tag on line " << linenumber << std::endl;
984 errorstream << "Found a (closing) \" outside a tag: " << filename << ":" << linenumber << std::endl;
988 errorstream << "Found a (opening) \" outside a tag: " << filename << ":" << linenumber << std::endl;
998 // errorstream << "Closing config tag on line " << linenumber << std::endl;
1002 * If this finds an <include> then ParseLine can simply call
1003 * LoadConf() and load the included config into the same ConfigDataHash
1006 if(!this->ParseLine(target, line, linenumber, errorstream))
1013 errorstream << "Got a closing > when we weren't inside a tag: " << filename << ":" << linenumber << std::endl;
1023 bool ServerConfig::LoadConf(ConfigDataHash &target, const std::string &filename, std::ostringstream &errorstream)
1025 return this->LoadConf(target, filename.c_str(), errorstream);
1028 bool ServerConfig::ParseLine(ConfigDataHash &target, std::string &line, long linenumber, std::ostringstream &errorstream)
1030 std::string tagname;
1031 std::string current_key;
1032 std::string current_value;
1038 got_name = got_key = in_quote = false;
1040 // std::cout << "ParseLine(data, '" << line << "', " << linenumber << ", stream)" << std::endl;
1042 for(std::string::iterator c = line.begin(); c != line.end(); c++)
1046 /* We don't know the tag name yet. */
1057 /* We got to a space, we should have the tagname now. */
1058 if(tagname.length())
1066 /* We have the tag name */
1069 /* We're still reading the key name */
1079 /* We got an '=', end of the key name. */
1085 /* We have the key name, now we're looking for quotes and the value */
1087 /* Correctly handle escaped characters here.
1088 * See the XXX'ed section above.
1090 if ((*c == '\\') && (in_quote))
1093 current_value += *c;
1100 /* We're not already in a quote. */
1105 /* Leaving quotes, we have the value */
1106 results.push_back(KeyVal(current_key, current_value));
1108 // std::cout << "<" << tagname << ":" << current_key << "> " << current_value << std::endl;
1113 if((tagname == "include") && (current_key == "file"))
1115 if(!this->DoInclude(target, current_value, errorstream))
1119 current_key.clear();
1120 current_value.clear();
1127 current_value += *c;
1134 /* Finished parsing the tag, add it to the config hash */
1135 target.insert(std::pair<std::string, KeyValList > (tagname, results));
1140 bool ServerConfig::DoInclude(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream)
1142 std::string confpath;
1143 std::string newfile;
1144 std::string::size_type pos;
1146 confpath = CONFIG_FILE;
1149 for (std::string::iterator c = newfile.begin(); c != newfile.end(); c++)
1159 if((pos = confpath.find("/inspircd.conf")) != std::string::npos)
1161 /* Leaves us with just the path */
1162 newfile = confpath.substr(0, pos) + std::string("/") + newfile;
1166 errorstream << "Couldn't get config path from: " << confpath << std::endl;
1171 return LoadConf(target, newfile, errorstream);
1174 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, int index, char* result, int length)
1177 bool r = ConfValue(target, std::string(tag), std::string(var), index, value);
1178 strlcpy(result, value.c_str(), length);
1182 bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, std::string &result)
1184 ConfigDataHash::size_type pos = index;
1185 if((pos >= 0) && (pos < target.count(tag)))
1187 ConfigDataHash::const_iterator iter = target.find(tag);
1189 for(int i = 0; i < index; i++)
1192 for(KeyValList::const_iterator j = iter->second.begin(); j != iter->second.end(); j++)
1203 ServerInstance->Log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1207 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());
1213 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, int index, int &result)
1215 return ConfValueInteger(target, std::string(tag), std::string(var), index, result);
1218 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, int &result)
1221 std::istringstream stream;
1222 bool r = ConfValue(target, tag, var, index, value);
1224 if(!(stream >> result))
1229 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, int index)
1231 return ConfValueBool(target, std::string(tag), std::string(var), index);
1234 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, int index)
1237 if(!ConfValue(target, tag, var, index, result))
1240 return ((result == "yes") || (result == "true") || (result == "1"));
1243 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const char* tag)
1245 return target.count(tag);
1248 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const std::string &tag)
1250 return target.count(tag);
1253 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const char* tag, int index)
1255 return ConfVarEnum(target, std::string(tag), index);
1258 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const std::string &tag, int index)
1260 ConfigDataHash::size_type pos = index;
1262 if((pos >= 0) && (pos < target.count(tag)))
1264 ConfigDataHash::const_iterator iter = target.find(tag);
1266 for(int i = 0; i < index; i++)
1269 return iter->second.size();
1273 ServerInstance->Log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1277 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());
1283 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1285 bool ServerConfig::ReadFile(file_cache &F, const char* fname)
1288 char linebuf[MAXBUF];
1291 file = fopen(fname,"r");
1297 fgets(linebuf,sizeof(linebuf),file);
1298 linebuf[strlen(linebuf)-1]='\0';
1302 strcpy(linebuf," ");
1307 F.push_back(linebuf);
1319 bool ServerConfig::FileExists(const char* file)
1322 if ((input = fopen (file, "r")) == NULL)
1333 char* ServerConfig::CleanFilename(char* name)
1335 char* p = name + strlen(name);
1336 while ((p != name) && (*p != '/')) p--;
1337 return (p != name ? ++p : p);
1341 bool ServerConfig::DirValid(const char* dirandfile)
1344 char buffer[MAXBUF];
1345 char otherdir[MAXBUF];
1348 strlcpy(work, dirandfile, MAXBUF);
1351 // we just want the dir
1363 // Get the current working directory
1364 if (getcwd(buffer, MAXBUF ) == NULL )
1369 if (getcwd(otherdir, MAXBUF ) == NULL )
1374 size_t t = strlen(work);
1376 if (strlen(otherdir) >= t)
1380 if (!strcmp(otherdir,work))
1393 std::string ServerConfig::GetFullProgDir(char** argv, int argc)
1396 char buffer[MAXBUF];
1397 char otherdir[MAXBUF];
1400 strlcpy(work,argv[0],MAXBUF);
1403 // we just want the dir
1415 // Get the current working directory
1416 if (getcwd(buffer, MAXBUF) == NULL)
1421 if (getcwd(otherdir, MAXBUF) == NULL)
1428 InspIRCd* ServerConfig::GetInstance()
1430 return ServerInstance;