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 *OperOnlyStats = *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;
46 void ServerConfig::ClearStack()
48 include_stack.clear();
51 Module* ServerConfig::GetIOHook(int port)
53 std::map<int,Module*>::iterator x = IOHookModule.find(port);
54 return (x != IOHookModule.end() ? x->second : NULL);
57 bool ServerConfig::AddIOHook(int port, Module* iomod)
61 IOHookModule[port] = iomod;
66 ModuleException err("Port already hooked by another module");
72 bool ServerConfig::DelIOHook(int port)
74 std::map<int,Module*>::iterator x = IOHookModule.find(port);
75 if (x != IOHookModule.end())
77 IOHookModule.erase(x);
83 bool ServerConfig::CheckOnce(char* tag, bool bail, userrec* user)
85 int count = ConfValueEnum(this->config_data, tag);
91 printf("There were errors in your configuration:\nYou have more than one <%s> tag, this is not permitted.\n",tag);
92 InspIRCd::Exit(ERROR);
98 user->WriteServ("There were errors in your configuration:");
99 user->WriteServ("You have more than one <%s> tag, this is not permitted.\n",tag);
103 ServerInstance->WriteOpers("There were errors in the configuration file:");
104 ServerInstance->WriteOpers("You have more than one <%s> tag, this is not permitted.\n",tag);
113 printf("There were errors in your configuration:\nYou have not defined a <%s> tag, this is required.\n",tag);
114 InspIRCd::Exit(ERROR);
120 user->WriteServ("There were errors in your configuration:");
121 user->WriteServ("You have not defined a <%s> tag, this is required.",tag);
125 ServerInstance->WriteOpers("There were errors in the configuration file:");
126 ServerInstance->WriteOpers("You have not defined a <%s> tag, this is required.",tag);
134 bool NoValidation(ServerConfig* conf, const char* tag, const char* value, void* data)
136 conf->GetInstance()->Log(DEBUG,"No validation for <%s:%s>",tag,value);
140 bool ValidateTempDir(ServerConfig* conf, const char* tag, const char* value, void* data)
142 char* x = (char*)data;
144 strlcpy(x,"/tmp",1024);
148 bool ValidateMaxTargets(ServerConfig* conf, const char* tag, const char* value, void* data)
151 if ((*x < 0) || (*x > 31))
153 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
159 bool ValidateSoftLimit(ServerConfig* conf, const char* tag, const char* value, void* data)
162 if ((*x < 1) || (*x > MAXCLIENTS))
164 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
170 bool ValidateMaxConn(ServerConfig* conf, const char* tag, const char* value, void* data)
174 conf->GetInstance()->Log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
180 bool ValidateDnsTimeout(ServerConfig* conf, const char* tag, const char* value, void* data)
188 bool InitializeDisabledCommands(const char* data, InspIRCd* ServerInstance)
190 std::stringstream dcmds(data);
193 /* Enable everything first */
194 for (nspace::hash_map<std::string,command_t*>::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
195 x->second->Disable(false);
197 /* Now disable all the ones which the user wants disabled */
198 while (dcmds >> thiscmd)
200 nspace::hash_map<std::string,command_t*>::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
201 if (cm != ServerInstance->Parser->cmdlist.end())
203 ServerInstance->Log(DEBUG,"Disabling command '%s'",cm->second->command.c_str());
204 cm->second->Disable(true);
210 bool ValidateDnsServer(ServerConfig* conf, const char* tag, const char* value, void* data)
212 char* x = (char*)data;
215 // attempt to look up their nameserver from /etc/resolv.conf
216 conf->GetInstance()->Log(DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
217 ifstream resolv("/etc/resolv.conf");
218 std::string nameserver;
219 bool found_server = false;
221 if (resolv.is_open())
223 while (resolv >> nameserver)
225 if ((nameserver == "nameserver") && (!found_server))
227 resolv >> nameserver;
228 strlcpy(x,nameserver.c_str(),MAXBUF);
230 conf->GetInstance()->Log(DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
236 conf->GetInstance()->Log(DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
237 strlcpy(x,"127.0.0.1",MAXBUF);
242 conf->GetInstance()->Log(DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
243 strlcpy(x,"127.0.0.1",MAXBUF);
249 bool ValidateModPath(ServerConfig* conf, const char* tag, const char* value, void* data)
251 char* x = (char*)data;
253 strlcpy(x,MOD_PATH,MAXBUF);
258 bool ValidateServerName(ServerConfig* conf, const char* tag, const char* value, void* data)
260 char* x = (char*)data;
263 conf->GetInstance()->Log(DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s%c'",x,x,'.');
264 charlcat(x,'.',MAXBUF);
270 bool ValidateNetBufferSize(ServerConfig* conf, const char* tag, const char* value, void* data)
272 if ((!conf->NetBufferSize) || (conf->NetBufferSize > 65535) || (conf->NetBufferSize < 1024))
274 conf->GetInstance()->Log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
275 conf->NetBufferSize = 10240;
280 bool ValidateMaxWho(ServerConfig* conf, const char* tag, const char* value, void* data)
282 if ((!conf->MaxWhoResults) || (conf->MaxWhoResults > 65535) || (conf->MaxWhoResults < 1))
284 conf->GetInstance()->Log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
285 conf->MaxWhoResults = 128;
290 bool ValidateLogLevel(ServerConfig* conf, const char* tag, const char* value, void* data)
292 const char* dbg = (const char*)data;
293 conf->LogLevel = DEFAULT;
294 if (!strcmp(dbg,"debug"))
296 conf->LogLevel = DEBUG;
299 else if (!strcmp(dbg,"verbose"))
300 conf->LogLevel = VERBOSE;
301 else if (!strcmp(dbg,"default"))
302 conf->LogLevel = DEFAULT;
303 else if (!strcmp(dbg,"sparse"))
304 conf->LogLevel = SPARSE;
305 else if (!strcmp(dbg,"none"))
306 conf->LogLevel = NONE;
310 bool ValidateMotd(ServerConfig* conf, const char* tag, const char* value, void* data)
312 conf->ReadFile(conf->MOTD,conf->motd);
316 bool ValidateRules(ServerConfig* conf, const char* tag, const char* value, void* data)
318 conf->ReadFile(conf->RULES,conf->rules);
322 /* Callback called before processing the first <connect> tag
324 bool InitConnect(ServerConfig* conf, const char* tag)
326 conf->GetInstance()->Log(DEFAULT,"Reading connect classes...");
327 conf->Classes.clear();
331 /* Callback called to process a single <connect> tag
333 bool DoConnect(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
336 char* allow = (char*)values[0]; /* Yeah, there are a lot of values. Live with it. */
337 char* deny = (char*)values[1];
338 char* password = (char*)values[2];
339 int* timeout = (int*)values[3];
340 int* pingfreq = (int*)values[4];
341 int* flood = (int*)values[5];
342 int* threshold = (int*)values[6];
343 int* sendq = (int*)values[7];
344 int* recvq = (int*)values[8];
345 int* localmax = (int*)values[9];
346 int* globalmax = (int*)values[10];
353 c.registration_timeout = *timeout;
354 c.pingtime = *pingfreq;
356 c.threshold = *threshold;
359 c.maxlocal = *localmax;
360 c.maxglobal = *globalmax;
365 if (c.maxglobal == 0)
367 if (c.threshold == 0)
371 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());
377 if (c.registration_timeout == 0)
378 c.registration_timeout = 90;
381 conf->Classes.push_back(c);
387 conf->Classes.push_back(c);
388 conf->GetInstance()->Log(DEBUG,"Read connect class type DENY, host=%s",deny);
394 /* Callback called when there are no more <connect> tags
396 bool DoneConnect(ServerConfig* conf, const char* tag)
398 conf->GetInstance()->Log(DEBUG,"DoneConnect called for tag: %s",tag);
402 /* Callback called before processing the first <uline> tag
404 bool InitULine(ServerConfig* conf, const char* tag)
406 conf->ulines.clear();
410 /* Callback called to process a single <uline> tag
412 bool DoULine(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
414 char* server = (char*)values[0];
415 conf->GetInstance()->Log(DEBUG,"Read ULINE '%s'",server);
416 conf->ulines.push_back(server);
420 /* Callback called when there are no more <uline> tags
422 bool DoneULine(ServerConfig* conf, const char* tag)
427 /* Callback called before processing the first <module> tag
429 bool InitModule(ServerConfig* conf, const char* tag)
431 old_module_names.clear();
432 new_module_names.clear();
433 added_modules.clear();
434 removed_modules.clear();
435 for (std::vector<std::string>::iterator t = conf->module_names.begin(); t != conf->module_names.end(); t++)
437 old_module_names.push_back(*t);
442 /* Callback called to process a single <module> tag
444 bool DoModule(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
446 char* modname = (char*)values[0];
447 new_module_names.push_back(modname);
451 /* Callback called when there are no more <module> tags
453 bool DoneModule(ServerConfig* conf, const char* tag)
455 // now create a list of new modules that are due to be loaded
456 // and a seperate list of modules which are due to be unloaded
457 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
461 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
468 added_modules.push_back(*_new);
471 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
474 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
481 removed_modules.push_back(*oldm);
486 /* Callback called before processing the first <banlist> tag
488 bool InitMaxBans(ServerConfig* conf, const char* tag)
490 conf->maxbans.clear();
494 /* Callback called to process a single <banlist> tag
496 bool DoMaxBans(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
498 char* channel = (char*)values[0];
499 int* limit = (int*)values[1];
500 conf->maxbans[channel] = *limit;
504 /* Callback called when there are no more <banlist> tags.
506 bool DoneMaxBans(ServerConfig* conf, const char* tag)
511 void ServerConfig::Read(bool bail, userrec* user)
513 char debug[MAXBUF]; /* Temporary buffer for debugging value */
514 char* data[12]; /* Temporary buffers for reading multiple occurance tags into */
515 void* ptr[12]; /* Temporary pointers for passing to callbacks */
516 int r_i[12]; /* Temporary array for casting */
517 int rem = 0, add = 0; /* Number of modules added, number of modules removed */
518 std::ostringstream errstr; /* String stream containing the error output */
520 /* These tags MUST occur and must ONLY occur once in the config file */
521 static char* Once[] = { "server", "admin", "files", "power", "options", "pid", NULL };
523 /* These tags can occur ONCE or not at all */
524 static InitialConfig Values[] = {
525 {"options", "softlimit", &this->SoftLimit, DT_INTEGER, ValidateSoftLimit},
526 {"options", "somaxconn", &this->MaxConn, DT_INTEGER, ValidateMaxConn},
527 {"server", "name", &this->ServerName, DT_CHARPTR, ValidateServerName},
528 {"server", "description", &this->ServerDesc, DT_CHARPTR, NoValidation},
529 {"server", "network", &this->Network, DT_CHARPTR, NoValidation},
530 {"admin", "name", &this->AdminName, DT_CHARPTR, NoValidation},
531 {"admin", "email", &this->AdminEmail, DT_CHARPTR, NoValidation},
532 {"admin", "nick", &this->AdminNick, DT_CHARPTR, NoValidation},
533 {"files", "motd", &this->motd, DT_CHARPTR, ValidateMotd},
534 {"files", "rules", &this->rules, DT_CHARPTR, ValidateRules},
535 {"power", "diepass", &this->diepass, DT_CHARPTR, NoValidation},
536 {"power", "pauseval", &this->DieDelay, DT_INTEGER, NoValidation},
537 {"power", "restartpass", &this->restartpass, DT_CHARPTR, NoValidation},
538 {"options", "prefixquit", &this->PrefixQuit, DT_CHARPTR, NoValidation},
539 {"die", "value", &this->DieValue, DT_CHARPTR, NoValidation},
540 {"options", "loglevel", &debug, DT_CHARPTR, ValidateLogLevel},
541 {"options", "netbuffersize", &this->NetBufferSize, DT_INTEGER, ValidateNetBufferSize},
542 {"options", "maxwho", &this->MaxWhoResults, DT_INTEGER, ValidateMaxWho},
543 {"options", "allowhalfop", &this->AllowHalfop, DT_BOOLEAN, NoValidation},
544 {"dns", "server", &this->DNSServer, DT_CHARPTR, ValidateDnsServer},
545 {"dns", "timeout", &this->dns_timeout, DT_INTEGER, ValidateDnsTimeout},
546 {"options", "moduledir", &this->ModPath, DT_CHARPTR, ValidateModPath},
547 {"disabled", "commands", &this->DisabledCommands, DT_CHARPTR, NoValidation},
548 {"options", "operonlystats", &this->OperOnlyStats, DT_CHARPTR, NoValidation},
549 {"options", "customversion", &this->CustomVersion, DT_CHARPTR, NoValidation},
550 {"options", "hidesplits", &this->HideSplits, DT_BOOLEAN, NoValidation},
551 {"options", "hidebans", &this->HideBans, DT_BOOLEAN, NoValidation},
552 {"options", "hidewhois", &this->HideWhoisServer, DT_CHARPTR, NoValidation},
553 {"options", "operspywhois", &this->OperSpyWhois, DT_BOOLEAN, NoValidation},
554 {"options", "tempdir", &this->TempDir, DT_CHARPTR, ValidateTempDir},
555 {"options", "nouserdns", &this->NoUserDns, DT_BOOLEAN, NoValidation},
556 {"options", "syntaxhints", &this->SyntaxHints, DT_BOOLEAN, NoValidation},
557 {"options", "cyclehosts", &this->CycleHosts, DT_BOOLEAN, NoValidation},
558 {"pid", "file", &this->PID, DT_CHARPTR, NoValidation},
562 /* These tags can occur multiple times, and therefore they have special code to read them
563 * which is different to the code for reading the singular tags listed above.
565 static MultiConfig MultiValues[] = {
568 {"allow", "deny", "password", "timeout", "pingfreq", "flood",
569 "threshold", "sendq", "recvq", "localmax", "globalmax", NULL},
570 {DT_CHARPTR, DT_CHARPTR, DT_CHARPTR, DT_INTEGER, DT_INTEGER, DT_INTEGER,
571 DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER},
572 InitConnect, DoConnect, DoneConnect},
577 InitULine,DoULine,DoneULine},
580 {"chan", "limit", NULL},
581 {DT_CHARPTR, DT_INTEGER},
582 InitMaxBans, DoMaxBans, DoneMaxBans},
587 InitModule, DoModule, DoneModule},
590 {"reason", "ipmask", NULL},
591 {DT_CHARPTR, DT_CHARPTR},
592 InitXLine, DoZLine, DoneXLine},
595 {"reason", "nick", NULL},
596 {DT_CHARPTR, DT_CHARPTR},
597 InitXLine, DoQLine, DoneXLine},
600 {"reason", "host", NULL},
601 {DT_CHARPTR, DT_CHARPTR},
602 InitXLine, DoKLine, DoneXLine},
605 {"reason", "host", NULL},
606 {DT_CHARPTR, DT_CHARPTR},
607 InitXLine, DoELine, DoneXLine},
610 {"name", "classes", NULL},
611 {DT_CHARPTR, DT_CHARPTR},
612 InitTypes, DoType, DoneClassesAndTypes},
615 {"name", "commands", NULL},
616 {DT_CHARPTR, DT_CHARPTR},
617 InitClasses, DoClass, DoneClassesAndTypes},
622 include_stack.clear();
624 /* Load and parse the config file, if there are any errors then explode */
626 /* Make a copy here so if it fails then we can carry on running with an unaffected config */
627 ConfigDataHash newconfig;
629 if (this->LoadConf(newconfig, CONFIG_FILE, errstr))
631 /* If we succeeded, set the ircd config to the new one */
632 this->config_data = newconfig;
637 for(ConfigDataHash::const_iterator i = this->config_data.begin(); i != this->config_data.end(); i++)
639 c = (i->first != last) ? 1 : c+1;
642 std::cout << "[" << i->first << " " << c << "/" << this->config_data.count(i->first) << "]" << std::endl;
644 for(KeyValList::const_iterator j = i->second.begin(); j != i->second.end(); j++)
645 std::cout << "\t" << j->first << " = " << j->second << std::endl;
647 std::cout << "[/" << i->first << " " << c << "/" << this->config_data.count(i->first) << "]" << std::endl;
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++)
705 int* val_i = (int*) Values[Index].val;
706 char* val_c = (char*) Values[Index].val;
708 switch (Values[Index].datatype)
711 /* Assuming MAXBUF here, potentially unsafe */
712 ConfValue(this->config_data, Values[Index].tag, Values[Index].value, 0, val_c, MAXBUF);
716 ConfValueInteger(this->config_data, Values[Index].tag, Values[Index].value, 0, *val_i);
720 *val_i = ConfValueBool(this->config_data, Values[Index].tag, Values[Index].value, 0);
727 Values[Index].validation_function(this, Values[Index].tag, Values[Index].value, Values[Index].val);
730 /* Claim memory for use when reading multiple tags
732 for (int n = 0; n < 12; n++)
733 data[n] = new char[MAXBUF];
735 /* Read the multiple-tag items (class tags, connect tags, etc)
736 * and call the callbacks associated with them. We have three
737 * callbacks for these, a 'start', 'item' and 'end' callback.
740 /* XXX - Make this use ConfValueInteger and so on */
741 for (int Index = 0; MultiValues[Index].tag; Index++)
743 MultiValues[Index].init_function(this, MultiValues[Index].tag);
745 int number_of_tags = ConfValueEnum(this->config_data, MultiValues[Index].tag);
747 for (int tagnum = 0; tagnum < number_of_tags; tagnum++)
749 for (int valuenum = 0; MultiValues[Index].items[valuenum]; valuenum++)
751 ConfValue(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], tagnum, data[valuenum], MAXBUF);
753 switch (MultiValues[Index].datatype[valuenum])
756 ptr[valuenum] = data[valuenum];
759 r_i[valuenum] = atoi(data[valuenum]);
760 ptr[valuenum] = &r_i[valuenum];
763 r_i[valuenum] = ((*data[valuenum] == tolower('y')) || (*data[valuenum] == tolower('t')) || (*data[valuenum] == '1'));
764 ptr[valuenum] = &r_i[valuenum];
770 MultiValues[Index].validation_function(this, MultiValues[Index].tag, (char**)MultiValues[Index].items, ptr, MultiValues[Index].datatype);
773 MultiValues[Index].finish_function(this, MultiValues[Index].tag);
776 /* Free any memory we claimed
778 for (int n = 0; n < 12; n++)
781 // write once here, to try it out and make sure its ok
782 ServerInstance->WritePID(this->PID);
784 ServerInstance->Log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
786 /* If we're rehashing, let's load any new modules, and unload old ones
790 ServerInstance->stats->BoundPortCount = ServerInstance->BindPorts(false);
792 if (!removed_modules.empty())
793 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
795 if (ServerInstance->UnloadModule(removing->c_str()))
797 ServerInstance->WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
800 user->WriteServ("973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
807 user->WriteServ("972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
811 if (!added_modules.empty())
812 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
814 if (ServerInstance->LoadModule(adding->c_str()))
816 ServerInstance->WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
819 user->WriteServ("975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
826 user->WriteServ("974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
830 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());
834 bool ServerConfig::LoadConf(ConfigDataHash &target, const char* filename, std::ostringstream &errorstream)
836 std::ifstream conf(filename);
849 /* Check if the file open failed first */
852 errorstream << "LoadConf: Couldn't open config file: " << filename << std::endl;
856 /* Fix the chmod of the file to restrict it to the current user and group */
857 chmod(filename,0600);
859 for (unsigned int t = 0; t < include_stack.size(); t++)
861 if (std::string(filename) == include_stack[t])
863 errorstream << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
868 /* It's not already included, add it to the list of files we've loaded */
869 include_stack.push_back(filename);
871 /* Start reading characters... */
875 * Here we try and get individual tags on separate lines,
876 * this would be so easy if we just made people format
877 * their config files like that, but they don't so...
878 * We check for a '<' and then know the line is over when
879 * we get a '>' not inside quotes. If we find two '<' and
880 * no '>' then die with an error.
883 if((ch == '#') && !in_quote)
886 if(((ch == '\n') || (ch == '\r')) && in_quote)
888 errorstream << "Got a newline within a quoted section, this is probably a typo: " << filename << ":" << linenumber << std::endl;
907 /* XXX: Added by Brain, May 1st 2006 - Escaping of characters.
908 * Note that this WILL NOT usually allow insertion of newlines,
909 * because a newline is two characters long. Use it primarily to
910 * insert the " symbol.
912 * Note that this also involves a further check when parsing the line,
913 * which can be found below.
915 if ((ch == '\\') && (in_quote) && (in_tag))
918 ServerInstance->Log(DEBUG,"Escape sequence in config line.");
920 if (conf.get(real_character))
922 ServerInstance->Log(DEBUG,"Escaping %c", real_character);
923 line += real_character;
928 errorstream << "End of file after a \\, what did you want to escape?: " << filename << ":" << linenumber << std::endl;
941 errorstream << "Got another opening < when the first one wasn't closed: " << filename << ":" << linenumber << std::endl;
949 errorstream << "We're in a quote but outside a tag, interesting. " << filename << ":" << linenumber << std::endl;
954 // errorstream << "Opening new config tag on line " << linenumber << std::endl;
965 // errorstream << "Closing quote in config tag on line " << linenumber << std::endl;
970 // errorstream << "Opening quote in config tag on line " << linenumber << std::endl;
978 errorstream << "Found a (closing) \" outside a tag: " << filename << ":" << linenumber << std::endl;
982 errorstream << "Found a (opening) \" outside a tag: " << filename << ":" << linenumber << std::endl;
992 // errorstream << "Closing config tag on line " << linenumber << std::endl;
996 * If this finds an <include> then ParseLine can simply call
997 * LoadConf() and load the included config into the same ConfigDataHash
1000 if(!this->ParseLine(target, line, linenumber, errorstream))
1007 errorstream << "Got a closing > when we weren't inside a tag: " << filename << ":" << linenumber << std::endl;
1017 bool ServerConfig::LoadConf(ConfigDataHash &target, const std::string &filename, std::ostringstream &errorstream)
1019 return this->LoadConf(target, filename.c_str(), errorstream);
1022 bool ServerConfig::ParseLine(ConfigDataHash &target, std::string &line, long linenumber, std::ostringstream &errorstream)
1024 std::string tagname;
1025 std::string current_key;
1026 std::string current_value;
1032 got_name = got_key = in_quote = false;
1034 // std::cout << "ParseLine(data, '" << line << "', " << linenumber << ", stream)" << std::endl;
1036 for(std::string::iterator c = line.begin(); c != line.end(); c++)
1040 /* We don't know the tag name yet. */
1051 /* We got to a space, we should have the tagname now. */
1052 if(tagname.length())
1060 /* We have the tag name */
1063 /* We're still reading the key name */
1073 /* We got an '=', end of the key name. */
1079 /* We have the key name, now we're looking for quotes and the value */
1081 /* Correctly handle escaped characters here.
1082 * See the XXX'ed section above.
1084 if ((*c == '\\') && (in_quote))
1087 current_value += *c;
1094 /* We're not already in a quote. */
1099 /* Leaving quotes, we have the value */
1100 results.push_back(KeyVal(current_key, current_value));
1102 // std::cout << "<" << tagname << ":" << current_key << "> " << current_value << std::endl;
1107 if((tagname == "include") && (current_key == "file"))
1109 if(!this->DoInclude(target, current_value, errorstream))
1113 current_key.clear();
1114 current_value.clear();
1121 current_value += *c;
1128 /* Finished parsing the tag, add it to the config hash */
1129 target.insert(std::pair<std::string, KeyValList > (tagname, results));
1134 bool ServerConfig::DoInclude(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream)
1136 std::string confpath;
1137 std::string newfile;
1138 std::string::size_type pos;
1140 confpath = CONFIG_FILE;
1143 for (std::string::iterator c = newfile.begin(); c != newfile.end(); c++)
1153 if((pos = confpath.find("/inspircd.conf")) != std::string::npos)
1155 /* Leaves us with just the path */
1156 newfile = confpath.substr(0, pos) + std::string("/") + newfile;
1160 errorstream << "Couldn't get config path from: " << confpath << std::endl;
1165 return LoadConf(target, newfile, errorstream);
1168 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, int index, char* result, int length)
1171 bool r = ConfValue(target, std::string(tag), std::string(var), index, value);
1172 strlcpy(result, value.c_str(), length);
1176 bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, std::string &result)
1178 ConfigDataHash::size_type pos = index;
1179 if((pos >= 0) && (pos < target.count(tag)))
1181 ConfigDataHash::const_iterator iter = target.find(tag);
1183 for(int i = 0; i < index; i++)
1186 for(KeyValList::const_iterator j = iter->second.begin(); j != iter->second.end(); j++)
1197 ServerInstance->Log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1201 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());
1207 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, int index, int &result)
1209 return ConfValueInteger(target, std::string(tag), std::string(var), index, result);
1212 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, int &result)
1215 std::istringstream stream;
1216 bool r = ConfValue(target, tag, var, index, value);
1218 if(!(stream >> result))
1223 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, int index)
1225 return ConfValueBool(target, std::string(tag), std::string(var), index);
1228 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, int index)
1231 if(!ConfValue(target, tag, var, index, result))
1234 return ((result == "yes") || (result == "true") || (result == "1"));
1237 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const char* tag)
1239 return target.count(tag);
1242 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const std::string &tag)
1244 return target.count(tag);
1247 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const char* tag, int index)
1249 return ConfVarEnum(target, std::string(tag), index);
1252 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const std::string &tag, int index)
1254 ConfigDataHash::size_type pos = index;
1256 if((pos >= 0) && (pos < target.count(tag)))
1258 ConfigDataHash::const_iterator iter = target.find(tag);
1260 for(int i = 0; i < index; i++)
1263 return iter->second.size();
1267 ServerInstance->Log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1271 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());
1277 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1279 bool ServerConfig::ReadFile(file_cache &F, const char* fname)
1282 char linebuf[MAXBUF];
1285 file = fopen(fname,"r");
1291 fgets(linebuf,sizeof(linebuf),file);
1292 linebuf[strlen(linebuf)-1]='\0';
1296 strcpy(linebuf," ");
1301 F.push_back(linebuf);
1313 bool ServerConfig::FileExists(const char* file)
1316 if ((input = fopen (file, "r")) == NULL)
1327 char* ServerConfig::CleanFilename(char* name)
1329 char* p = name + strlen(name);
1330 while ((p != name) && (*p != '/')) p--;
1331 return (p != name ? ++p : p);
1335 bool ServerConfig::DirValid(const char* dirandfile)
1338 char buffer[MAXBUF];
1339 char otherdir[MAXBUF];
1342 strlcpy(work, dirandfile, MAXBUF);
1345 // we just want the dir
1357 // Get the current working directory
1358 if (getcwd(buffer, MAXBUF ) == NULL )
1363 if (getcwd(otherdir, MAXBUF ) == NULL )
1368 size_t t = strlen(work);
1370 if (strlen(otherdir) >= t)
1374 if (!strcmp(otherdir,work))
1387 std::string ServerConfig::GetFullProgDir(char** argv, int argc)
1390 char buffer[MAXBUF];
1391 char otherdir[MAXBUF];
1394 strlcpy(work,argv[0],MAXBUF);
1397 // we just want the dir
1409 // Get the current working directory
1410 if (getcwd(buffer, MAXBUF) == NULL)
1415 if (getcwd(otherdir, MAXBUF) == NULL)
1422 InspIRCd* ServerConfig::GetInstance()
1424 return ServerInstance;