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"
25 #include "inspstring.h"
26 #include "helperfuncs.h"
27 #include "userprocess.h"
30 extern InspIRCd* ServerInstance;
34 extern std::vector<Module*> modules;
35 extern std::vector<ircd_module*> factory;
37 using irc::sockets::BindPorts;
39 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
41 ServerConfig::ServerConfig()
44 *TempDir = *ServerName = *Network = *ServerDesc = *AdminName = '\0';
45 *HideWhoisServer = *AdminEmail = *AdminNick = *diepass = *restartpass = '\0';
46 *CustomVersion = *motd = *rules = *PrefixQuit = *DieValue = *DNSServer = '\0';
47 *OperOnlyStats = *ModPath = *MyExecutable = *DisabledCommands = *PID = '\0';
49 NoUserDns = forcedebug = OperSpyWhois = nofork = HideBans = HideSplits = false;
50 writelog = AllowHalfop = true;
51 dns_timeout = DieDelay = 5;
53 NetBufferSize = 10240;
54 SoftLimit = MAXCLIENTS;
62 void ServerConfig::ClearStack()
64 include_stack.clear();
67 Module* ServerConfig::GetIOHook(int port)
69 std::map<int,Module*>::iterator x = IOHookModule.find(port);
70 return (x != IOHookModule.end() ? x->second : NULL);
73 bool ServerConfig::AddIOHook(int port, Module* iomod)
77 IOHookModule[port] = iomod;
82 ModuleException err("Port already hooked by another module");
88 bool ServerConfig::DelIOHook(int port)
90 std::map<int,Module*>::iterator x = IOHookModule.find(port);
91 if (x != IOHookModule.end())
93 IOHookModule.erase(x);
99 bool ServerConfig::CheckOnce(char* tag, bool bail, userrec* user)
101 int count = ConfValueEnum(this->config_data, tag);
107 printf("There were errors in your configuration:\nYou have more than one <%s> tag, this is not permitted.\n",tag);
114 user->WriteServ("There were errors in your configuration:");
115 user->WriteServ("You have more than one <%s> tag, this is not permitted.\n",tag);
119 WriteOpers("There were errors in the configuration file:");
120 WriteOpers("You have more than one <%s> tag, this is not permitted.\n",tag);
129 printf("There were errors in your configuration:\nYou have not defined a <%s> tag, this is required.\n",tag);
136 user->WriteServ("There were errors in your configuration:");
137 user->WriteServ("You have not defined a <%s> tag, this is required.",tag);
141 WriteOpers("There were errors in the configuration file:");
142 WriteOpers("You have not defined a <%s> tag, this is required.",tag);
150 bool NoValidation(ServerConfig* conf, const char* tag, const char* value, void* data)
152 log(DEBUG,"No validation for <%s:%s>",tag,value);
156 bool ValidateTempDir(ServerConfig* conf, const char* tag, const char* value, void* data)
158 char* x = (char*)data;
160 strlcpy(x,"/tmp",1024);
164 bool ValidateMaxTargets(ServerConfig* conf, const char* tag, const char* value, void* data)
167 if ((*x < 0) || (*x > 31))
169 log(DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
175 bool ValidateSoftLimit(ServerConfig* conf, const char* tag, const char* value, void* data)
178 if ((*x < 1) || (*x > MAXCLIENTS))
180 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
186 bool ValidateMaxConn(ServerConfig* conf, const char* tag, const char* value, void* data)
190 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
196 bool ValidateDnsTimeout(ServerConfig* conf, const char* tag, const char* value, void* data)
204 bool InitializeDisabledCommands(const char* data, InspIRCd* ServerInstance)
206 std::stringstream dcmds(data);
209 /* Enable everything first */
210 for (nspace::hash_map<std::string,command_t*>::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
211 x->second->Disable(false);
213 /* Now disable all the ones which the user wants disabled */
214 while (dcmds >> thiscmd)
216 nspace::hash_map<std::string,command_t*>::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
217 if (cm != ServerInstance->Parser->cmdlist.end())
219 log(DEBUG,"Disabling command '%s'",cm->second->command.c_str());
220 cm->second->Disable(true);
226 bool ValidateDnsServer(ServerConfig* conf, const char* tag, const char* value, void* data)
228 char* x = (char*)data;
231 // attempt to look up their nameserver from /etc/resolv.conf
232 log(DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
233 ifstream resolv("/etc/resolv.conf");
234 std::string nameserver;
235 bool found_server = false;
237 if (resolv.is_open())
239 while (resolv >> nameserver)
241 if ((nameserver == "nameserver") && (!found_server))
243 resolv >> nameserver;
244 strlcpy(x,nameserver.c_str(),MAXBUF);
246 log(DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
252 log(DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
253 strlcpy(x,"127.0.0.1",MAXBUF);
258 log(DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
259 strlcpy(x,"127.0.0.1",MAXBUF);
265 bool ValidateModPath(ServerConfig* conf, const char* tag, const char* value, void* data)
267 char* x = (char*)data;
269 strlcpy(x,MOD_PATH,MAXBUF);
274 bool ValidateServerName(ServerConfig* conf, const char* tag, const char* value, void* data)
276 char* x = (char*)data;
279 log(DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s%c'",x,x,'.');
280 charlcat(x,'.',MAXBUF);
286 bool ValidateNetBufferSize(ServerConfig* conf, const char* tag, const char* value, void* data)
288 if ((!ServerInstance->Config->NetBufferSize) || (ServerInstance->Config->NetBufferSize > 65535) || (ServerInstance->Config->NetBufferSize < 1024))
290 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
291 ServerInstance->Config->NetBufferSize = 10240;
296 bool ValidateMaxWho(ServerConfig* conf, const char* tag, const char* value, void* data)
298 if ((!ServerInstance->Config->MaxWhoResults) || (ServerInstance->Config->MaxWhoResults > 65535) || (ServerInstance->Config->MaxWhoResults < 1))
300 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
301 ServerInstance->Config->MaxWhoResults = 128;
306 bool ValidateLogLevel(ServerConfig* conf, const char* tag, const char* value, void* data)
308 const char* dbg = (const char*)data;
309 ServerInstance->Config->LogLevel = DEFAULT;
310 if (!strcmp(dbg,"debug"))
312 ServerInstance->Config->LogLevel = DEBUG;
313 ServerInstance->Config->debugging = 1;
315 else if (!strcmp(dbg,"verbose"))
316 ServerInstance->Config->LogLevel = VERBOSE;
317 else if (!strcmp(dbg,"default"))
318 ServerInstance->Config->LogLevel = DEFAULT;
319 else if (!strcmp(dbg,"sparse"))
320 ServerInstance->Config->LogLevel = SPARSE;
321 else if (!strcmp(dbg,"none"))
322 ServerInstance->Config->LogLevel = NONE;
326 bool ValidateMotd(ServerConfig* conf, const char* tag, const char* value, void* data)
328 conf->ReadFile(ServerInstance->Config->MOTD,ServerInstance->Config->motd);
332 bool ValidateRules(ServerConfig* conf, const char* tag, const char* value, void* data)
334 conf->ReadFile(ServerInstance->Config->RULES,ServerInstance->Config->rules);
338 /* Callback called before processing the first <connect> tag
340 bool InitConnect(ServerConfig* conf, const char* tag)
342 log(DEFAULT,"Reading connect classes...");
343 ServerInstance->Config->Classes.clear();
347 /* Callback called to process a single <connect> tag
349 bool DoConnect(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
352 char* allow = (char*)values[0]; /* Yeah, there are a lot of values. Live with it. */
353 char* deny = (char*)values[1];
354 char* password = (char*)values[2];
355 int* timeout = (int*)values[3];
356 int* pingfreq = (int*)values[4];
357 int* flood = (int*)values[5];
358 int* threshold = (int*)values[6];
359 int* sendq = (int*)values[7];
360 int* recvq = (int*)values[8];
361 int* localmax = (int*)values[9];
362 int* globalmax = (int*)values[10];
369 c.registration_timeout = *timeout;
370 c.pingtime = *pingfreq;
372 c.threshold = *threshold;
375 c.maxlocal = *localmax;
376 c.maxglobal = *globalmax;
381 if (c.maxglobal == 0)
383 if (c.threshold == 0)
387 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());
393 if (c.registration_timeout == 0)
394 c.registration_timeout = 90;
397 ServerInstance->Config->Classes.push_back(c);
403 ServerInstance->Config->Classes.push_back(c);
404 log(DEBUG,"Read connect class type DENY, host=%s",deny);
410 /* Callback called when there are no more <connect> tags
412 bool DoneConnect(ServerConfig* conf, const char* tag)
414 log(DEBUG,"DoneConnect called for tag: %s",tag);
418 /* Callback called before processing the first <uline> tag
420 bool InitULine(ServerConfig* conf, const char* tag)
422 ServerInstance->Config->ulines.clear();
426 /* Callback called to process a single <uline> tag
428 bool DoULine(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
430 char* server = (char*)values[0];
431 log(DEBUG,"Read ULINE '%s'",server);
432 ServerInstance->Config->ulines.push_back(server);
436 /* Callback called when there are no more <uline> tags
438 bool DoneULine(ServerConfig* conf, const char* tag)
443 /* Callback called before processing the first <module> tag
445 bool InitModule(ServerConfig* conf, const char* tag)
447 old_module_names.clear();
448 new_module_names.clear();
449 added_modules.clear();
450 removed_modules.clear();
451 for (std::vector<std::string>::iterator t = ServerInstance->Config->module_names.begin(); t != ServerInstance->Config->module_names.end(); t++)
453 old_module_names.push_back(*t);
458 /* Callback called to process a single <module> tag
460 bool DoModule(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
462 char* modname = (char*)values[0];
463 new_module_names.push_back(modname);
467 /* Callback called when there are no more <module> tags
469 bool DoneModule(ServerConfig* conf, const char* tag)
471 // now create a list of new modules that are due to be loaded
472 // and a seperate list of modules which are due to be unloaded
473 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
477 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
484 added_modules.push_back(*_new);
487 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
490 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
497 removed_modules.push_back(*oldm);
502 /* Callback called before processing the first <banlist> tag
504 bool InitMaxBans(ServerConfig* conf, const char* tag)
506 ServerInstance->Config->maxbans.clear();
510 /* Callback called to process a single <banlist> tag
512 bool DoMaxBans(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
514 char* channel = (char*)values[0];
515 int* limit = (int*)values[1];
516 ServerInstance->Config->maxbans[channel] = *limit;
520 /* Callback called when there are no more <banlist> tags.
522 bool DoneMaxBans(ServerConfig* conf, const char* tag)
527 void ServerConfig::Read(bool bail, userrec* user)
529 char debug[MAXBUF]; /* Temporary buffer for debugging value */
530 char* data[12]; /* Temporary buffers for reading multiple occurance tags into */
531 void* ptr[12]; /* Temporary pointers for passing to callbacks */
532 int r_i[12]; /* Temporary array for casting */
533 int rem = 0, add = 0; /* Number of modules added, number of modules removed */
534 std::ostringstream errstr; /* String stream containing the error output */
536 /* These tags MUST occur and must ONLY occur once in the config file */
537 static char* Once[] = { "server", "admin", "files", "power", "options", "pid", NULL };
539 /* These tags can occur ONCE or not at all */
540 static InitialConfig Values[] = {
541 {"options", "softlimit", &this->SoftLimit, DT_INTEGER, ValidateSoftLimit},
542 {"options", "somaxconn", &this->MaxConn, DT_INTEGER, ValidateMaxConn},
543 {"server", "name", &this->ServerName, DT_CHARPTR, ValidateServerName},
544 {"server", "description", &this->ServerDesc, DT_CHARPTR, NoValidation},
545 {"server", "network", &this->Network, DT_CHARPTR, NoValidation},
546 {"admin", "name", &this->AdminName, DT_CHARPTR, NoValidation},
547 {"admin", "email", &this->AdminEmail, DT_CHARPTR, NoValidation},
548 {"admin", "nick", &this->AdminNick, DT_CHARPTR, NoValidation},
549 {"files", "motd", &this->motd, DT_CHARPTR, ValidateMotd},
550 {"files", "rules", &this->rules, DT_CHARPTR, ValidateRules},
551 {"power", "diepass", &this->diepass, DT_CHARPTR, NoValidation},
552 {"power", "pauseval", &this->DieDelay, DT_INTEGER, NoValidation},
553 {"power", "restartpass", &this->restartpass, DT_CHARPTR, NoValidation},
554 {"options", "prefixquit", &this->PrefixQuit, DT_CHARPTR, NoValidation},
555 {"die", "value", &this->DieValue, DT_CHARPTR, NoValidation},
556 {"options", "loglevel", &debug, DT_CHARPTR, ValidateLogLevel},
557 {"options", "netbuffersize", &this->NetBufferSize, DT_INTEGER, ValidateNetBufferSize},
558 {"options", "maxwho", &this->MaxWhoResults, DT_INTEGER, ValidateMaxWho},
559 {"options", "allowhalfop", &this->AllowHalfop, DT_BOOLEAN, NoValidation},
560 {"dns", "server", &this->DNSServer, DT_CHARPTR, ValidateDnsServer},
561 {"dns", "timeout", &this->dns_timeout, DT_INTEGER, ValidateDnsTimeout},
562 {"options", "moduledir", &this->ModPath, DT_CHARPTR, ValidateModPath},
563 {"disabled", "commands", &this->DisabledCommands, DT_CHARPTR, NoValidation},
564 {"options", "operonlystats", &this->OperOnlyStats, DT_CHARPTR, NoValidation},
565 {"options", "customversion", &this->CustomVersion, DT_CHARPTR, NoValidation},
566 {"options", "hidesplits", &this->HideSplits, DT_BOOLEAN, NoValidation},
567 {"options", "hidebans", &this->HideBans, DT_BOOLEAN, NoValidation},
568 {"options", "hidewhois", &this->HideWhoisServer, DT_CHARPTR, NoValidation},
569 {"options", "operspywhois", &this->OperSpyWhois, DT_BOOLEAN, NoValidation},
570 {"options", "tempdir", &this->TempDir, DT_CHARPTR, ValidateTempDir},
571 {"options", "nouserdns", &this->NoUserDns, DT_BOOLEAN, NoValidation},
572 {"options", "syntaxhints", &this->SyntaxHints, DT_BOOLEAN, NoValidation},
573 {"pid", "file", &this->PID, DT_CHARPTR, NoValidation},
577 /* These tags can occur multiple times, and therefore they have special code to read them
578 * which is different to the code for reading the singular tags listed above.
580 static MultiConfig MultiValues[] = {
583 {"allow", "deny", "password", "timeout", "pingfreq", "flood",
584 "threshold", "sendq", "recvq", "localmax", "globalmax", NULL},
585 {DT_CHARPTR, DT_CHARPTR, DT_CHARPTR, DT_INTEGER, DT_INTEGER, DT_INTEGER,
586 DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER},
587 InitConnect, DoConnect, DoneConnect},
592 InitULine,DoULine,DoneULine},
595 {"chan", "limit", NULL},
596 {DT_CHARPTR, DT_INTEGER},
597 InitMaxBans, DoMaxBans, DoneMaxBans},
602 InitModule, DoModule, DoneModule},
605 {"reason", "ipmask", NULL},
606 {DT_CHARPTR, DT_CHARPTR},
607 InitXLine, DoZLine, DoneXLine},
610 {"reason", "nick", NULL},
611 {DT_CHARPTR, DT_CHARPTR},
612 InitXLine, DoQLine, DoneXLine},
615 {"reason", "host", NULL},
616 {DT_CHARPTR, DT_CHARPTR},
617 InitXLine, DoKLine, DoneXLine},
620 {"reason", "host", NULL},
621 {DT_CHARPTR, DT_CHARPTR},
622 InitXLine, DoELine, DoneXLine},
625 {"name", "classes", NULL},
626 {DT_CHARPTR, DT_CHARPTR},
627 InitTypes, DoType, DoneClassesAndTypes},
630 {"name", "commands", NULL},
631 {DT_CHARPTR, DT_CHARPTR},
632 InitClasses, DoClass, DoneClassesAndTypes},
637 include_stack.clear();
639 /* Load and parse the config file, if there are any errors then explode */
641 /* Make a copy here so if it fails then we can carry on running with an unaffected config */
642 ConfigDataHash newconfig;
644 if (this->LoadConf(newconfig, CONFIG_FILE, errstr))
646 /* If we succeeded, set the ircd config to the new one */
647 this->config_data = newconfig;
652 for(ConfigDataHash::const_iterator i = this->config_data.begin(); i != this->config_data.end(); i++)
654 c = (i->first != last) ? 1 : c+1;
657 std::cout << "[" << i->first << " " << c << "/" << this->config_data.count(i->first) << "]" << std::endl;
659 for(KeyValList::const_iterator j = i->second.begin(); j != i->second.end(); j++)
660 std::cout << "\t" << j->first << " = " << j->second << std::endl;
662 std::cout << "[/" << i->first << " " << c << "/" << this->config_data.count(i->first) << "]" << std::endl;
667 log(DEFAULT, "There were errors in your configuration:\n%s", errstr.str().c_str());
671 /* Unneeded because of the log() aboive? */
672 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
677 std::string errors = errstr.str();
678 std::string::size_type start;
679 unsigned int prefixlen;
682 /* ":ServerInstance->Config->ServerName NOTICE user->nick :" */
683 prefixlen = strlen(this->ServerName) + strlen(user->nick) + 11;
687 user->WriteServ("NOTICE %s :There were errors in the configuration file:",user->nick);
689 while(start < errors.length())
691 user->WriteServ("NOTICE %s :%s",user->nick, errors.substr(start, 510 - prefixlen).c_str());
692 start += 510 - prefixlen;
697 WriteOpers("There were errors in the configuration file:");
699 while(start < errors.length())
701 WriteOpers(errors.substr(start, 360).c_str());
710 /* Check we dont have more than one of singular tags, or any of them missing
712 for (int Index = 0; Once[Index]; Index++)
713 if (!CheckOnce(Once[Index],bail,user))
716 /* Read the values of all the tags which occur once or not at all, and call their callbacks.
718 for (int Index = 0; Values[Index].tag; Index++)
720 int* val_i = (int*) Values[Index].val;
721 char* val_c = (char*) Values[Index].val;
723 switch (Values[Index].datatype)
726 /* Assuming MAXBUF here, potentially unsafe */
727 ConfValue(this->config_data, Values[Index].tag, Values[Index].value, 0, val_c, MAXBUF);
731 ConfValueInteger(this->config_data, Values[Index].tag, Values[Index].value, 0, *val_i);
735 *val_i = ConfValueBool(this->config_data, Values[Index].tag, Values[Index].value, 0);
742 Values[Index].validation_function(this, Values[Index].tag, Values[Index].value, Values[Index].val);
745 /* Claim memory for use when reading multiple tags
747 for (int n = 0; n < 12; n++)
748 data[n] = new char[MAXBUF];
750 /* Read the multiple-tag items (class tags, connect tags, etc)
751 * and call the callbacks associated with them. We have three
752 * callbacks for these, a 'start', 'item' and 'end' callback.
755 /* XXX - Make this use ConfValueInteger and so on */
756 for (int Index = 0; MultiValues[Index].tag; Index++)
758 MultiValues[Index].init_function(this, MultiValues[Index].tag);
760 int number_of_tags = ConfValueEnum(this->config_data, MultiValues[Index].tag);
762 for (int tagnum = 0; tagnum < number_of_tags; tagnum++)
764 for (int valuenum = 0; MultiValues[Index].items[valuenum]; valuenum++)
766 ConfValue(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], tagnum, data[valuenum], MAXBUF);
768 switch (MultiValues[Index].datatype[valuenum])
771 ptr[valuenum] = data[valuenum];
774 r_i[valuenum] = atoi(data[valuenum]);
775 ptr[valuenum] = &r_i[valuenum];
778 r_i[valuenum] = ((*data[valuenum] == tolower('y')) || (*data[valuenum] == tolower('t')) || (*data[valuenum] == '1'));
779 ptr[valuenum] = &r_i[valuenum];
785 MultiValues[Index].validation_function(this, MultiValues[Index].tag, (char**)MultiValues[Index].items, ptr, MultiValues[Index].datatype);
788 MultiValues[Index].finish_function(this, MultiValues[Index].tag);
791 /* Free any memory we claimed
793 for (int n = 0; n < 12; n++)
796 // write once here, to try it out and make sure its ok
797 ServerInstance->WritePID(this->PID);
799 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
801 /* If we're rehashing, let's load any new modules, and unload old ones
805 ServerInstance->stats->BoundPortCount = BindPorts(false);
807 if (!removed_modules.empty())
808 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
810 if (ServerInstance->UnloadModule(removing->c_str()))
812 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
815 user->WriteServ("973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
822 user->WriteServ("972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
826 if (!added_modules.empty())
827 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
829 if (ServerInstance->LoadModule(adding->c_str()))
831 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
834 user->WriteServ("975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
841 user->WriteServ("974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
845 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());
849 bool ServerConfig::LoadConf(ConfigDataHash &target, const char* filename, std::ostringstream &errorstream)
851 std::ifstream conf(filename);
864 /* Check if the file open failed first */
867 errorstream << "LoadConf: Couldn't open config file: " << filename << std::endl;
871 /* Fix the chmod of the file to restrict it to the current user and group */
872 chmod(filename,0600);
874 for (unsigned int t = 0; t < include_stack.size(); t++)
876 if (std::string(filename) == include_stack[t])
878 errorstream << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
883 /* It's not already included, add it to the list of files we've loaded */
884 include_stack.push_back(filename);
886 /* Start reading characters... */
890 * Here we try and get individual tags on separate lines,
891 * this would be so easy if we just made people format
892 * their config files like that, but they don't so...
893 * We check for a '<' and then know the line is over when
894 * we get a '>' not inside quotes. If we find two '<' and
895 * no '>' then die with an error.
898 if((ch == '#') && !in_quote)
901 if(((ch == '\n') || (ch == '\r')) && in_quote)
903 errorstream << "Got a newline within a quoted section, this is probably a typo: " << filename << ":" << linenumber << std::endl;
922 /* XXX: Added by Brain, May 1st 2006 - Escaping of characters.
923 * Note that this WILL NOT usually allow insertion of newlines,
924 * because a newline is two characters long. Use it primarily to
925 * insert the " symbol.
927 * Note that this also involves a further check when parsing the line,
928 * which can be found below.
930 if ((ch == '\\') && (in_quote) && (in_tag))
933 log(DEBUG,"Escape sequence in config line.");
935 if (conf.get(real_character))
937 log(DEBUG,"Escaping %c", real_character);
938 line += real_character;
943 errorstream << "End of file after a \\, what did you want to escape?: " << filename << ":" << linenumber << std::endl;
956 errorstream << "Got another opening < when the first one wasn't closed: " << filename << ":" << linenumber << std::endl;
964 errorstream << "We're in a quote but outside a tag, interesting. " << filename << ":" << linenumber << std::endl;
969 // errorstream << "Opening new config tag on line " << linenumber << std::endl;
980 // errorstream << "Closing quote in config tag on line " << linenumber << std::endl;
985 // errorstream << "Opening quote in config tag on line " << linenumber << std::endl;
993 errorstream << "Found a (closing) \" outside a tag: " << filename << ":" << linenumber << std::endl;
997 errorstream << "Found a (opening) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1007 // errorstream << "Closing config tag on line " << linenumber << std::endl;
1011 * If this finds an <include> then ParseLine can simply call
1012 * LoadConf() and load the included config into the same ConfigDataHash
1015 if(!this->ParseLine(target, line, linenumber, errorstream))
1022 errorstream << "Got a closing > when we weren't inside a tag: " << filename << ":" << linenumber << std::endl;
1032 bool ServerConfig::LoadConf(ConfigDataHash &target, const std::string &filename, std::ostringstream &errorstream)
1034 return this->LoadConf(target, filename.c_str(), errorstream);
1037 bool ServerConfig::ParseLine(ConfigDataHash &target, std::string &line, long linenumber, std::ostringstream &errorstream)
1039 std::string tagname;
1040 std::string current_key;
1041 std::string current_value;
1047 got_name = got_key = in_quote = false;
1049 // std::cout << "ParseLine(data, '" << line << "', " << linenumber << ", stream)" << std::endl;
1051 for(std::string::iterator c = line.begin(); c != line.end(); c++)
1055 /* We don't know the tag name yet. */
1066 /* We got to a space, we should have the tagname now. */
1067 if(tagname.length())
1075 /* We have the tag name */
1078 /* We're still reading the key name */
1088 /* We got an '=', end of the key name. */
1094 /* We have the key name, now we're looking for quotes and the value */
1096 /* Correctly handle escaped characters here.
1097 * See the XXX'ed section above.
1099 if ((*c == '\\') && (in_quote))
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 log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1216 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 log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1286 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];
1300 file = fopen(fname,"r");
1306 fgets(linebuf,sizeof(linebuf),file);
1307 linebuf[strlen(linebuf)-1]='\0';
1311 strcpy(linebuf," ");
1316 F.push_back(linebuf);