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"
25 #include "helperfuncs.h"
26 #include "userprocess.h"
32 extern std::vector<Module*> modules;
33 extern std::vector<ircd_module*> factory;
35 using irc::sockets::BindPorts;
37 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
39 ServerConfig::ServerConfig(InspIRCd* Instance) : ServerInstance(Instance)
42 *TempDir = *ServerName = *Network = *ServerDesc = *AdminName = '\0';
43 *HideWhoisServer = *AdminEmail = *AdminNick = *diepass = *restartpass = '\0';
44 *CustomVersion = *motd = *rules = *PrefixQuit = *DieValue = *DNSServer = '\0';
45 *OperOnlyStats = *ModPath = *MyExecutable = *DisabledCommands = *PID = '\0';
47 NoUserDns = forcedebug = OperSpyWhois = nofork = HideBans = HideSplits = false;
48 writelog = AllowHalfop = true;
49 dns_timeout = DieDelay = 5;
51 NetBufferSize = 10240;
52 SoftLimit = MAXCLIENTS;
60 void ServerConfig::ClearStack()
62 include_stack.clear();
65 Module* ServerConfig::GetIOHook(int port)
67 std::map<int,Module*>::iterator x = IOHookModule.find(port);
68 return (x != IOHookModule.end() ? x->second : NULL);
71 bool ServerConfig::AddIOHook(int port, Module* iomod)
75 IOHookModule[port] = iomod;
80 ModuleException err("Port already hooked by another module");
86 bool ServerConfig::DelIOHook(int port)
88 std::map<int,Module*>::iterator x = IOHookModule.find(port);
89 if (x != IOHookModule.end())
91 IOHookModule.erase(x);
97 bool ServerConfig::CheckOnce(char* tag, bool bail, userrec* user)
99 int count = ConfValueEnum(this->config_data, tag);
105 printf("There were errors in your configuration:\nYou have more than one <%s> tag, this is not permitted.\n",tag);
112 user->WriteServ("There were errors in your configuration:");
113 user->WriteServ("You have more than one <%s> tag, this is not permitted.\n",tag);
117 ServerInstance->WriteOpers("There were errors in the configuration file:");
118 ServerInstance->WriteOpers("You have more than one <%s> tag, this is not permitted.\n",tag);
127 printf("There were errors in your configuration:\nYou have not defined a <%s> tag, this is required.\n",tag);
134 user->WriteServ("There were errors in your configuration:");
135 user->WriteServ("You have not defined a <%s> tag, this is required.",tag);
139 ServerInstance->WriteOpers("There were errors in the configuration file:");
140 ServerInstance->WriteOpers("You have not defined a <%s> tag, this is required.",tag);
148 bool NoValidation(ServerConfig* conf, const char* tag, const char* value, void* data)
150 log(DEBUG,"No validation for <%s:%s>",tag,value);
154 bool ValidateTempDir(ServerConfig* conf, const char* tag, const char* value, void* data)
156 char* x = (char*)data;
158 strlcpy(x,"/tmp",1024);
162 bool ValidateMaxTargets(ServerConfig* conf, const char* tag, const char* value, void* data)
165 if ((*x < 0) || (*x > 31))
167 log(DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
173 bool ValidateSoftLimit(ServerConfig* conf, const char* tag, const char* value, void* data)
176 if ((*x < 1) || (*x > MAXCLIENTS))
178 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
184 bool ValidateMaxConn(ServerConfig* conf, const char* tag, const char* value, void* data)
188 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
194 bool ValidateDnsTimeout(ServerConfig* conf, const char* tag, const char* value, void* data)
202 bool InitializeDisabledCommands(const char* data, InspIRCd* ServerInstance)
204 std::stringstream dcmds(data);
207 /* Enable everything first */
208 for (nspace::hash_map<std::string,command_t*>::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
209 x->second->Disable(false);
211 /* Now disable all the ones which the user wants disabled */
212 while (dcmds >> thiscmd)
214 nspace::hash_map<std::string,command_t*>::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
215 if (cm != ServerInstance->Parser->cmdlist.end())
217 log(DEBUG,"Disabling command '%s'",cm->second->command.c_str());
218 cm->second->Disable(true);
224 bool ValidateDnsServer(ServerConfig* conf, const char* tag, const char* value, void* data)
226 char* x = (char*)data;
229 // attempt to look up their nameserver from /etc/resolv.conf
230 log(DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
231 ifstream resolv("/etc/resolv.conf");
232 std::string nameserver;
233 bool found_server = false;
235 if (resolv.is_open())
237 while (resolv >> nameserver)
239 if ((nameserver == "nameserver") && (!found_server))
241 resolv >> nameserver;
242 strlcpy(x,nameserver.c_str(),MAXBUF);
244 log(DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
250 log(DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
251 strlcpy(x,"127.0.0.1",MAXBUF);
256 log(DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
257 strlcpy(x,"127.0.0.1",MAXBUF);
263 bool ValidateModPath(ServerConfig* conf, const char* tag, const char* value, void* data)
265 char* x = (char*)data;
267 strlcpy(x,MOD_PATH,MAXBUF);
272 bool ValidateServerName(ServerConfig* conf, const char* tag, const char* value, void* data)
274 char* x = (char*)data;
277 log(DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s%c'",x,x,'.');
278 charlcat(x,'.',MAXBUF);
284 bool ValidateNetBufferSize(ServerConfig* conf, const char* tag, const char* value, void* data)
286 if ((!conf->NetBufferSize) || (conf->NetBufferSize > 65535) || (conf->NetBufferSize < 1024))
288 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
289 conf->NetBufferSize = 10240;
294 bool ValidateMaxWho(ServerConfig* conf, const char* tag, const char* value, void* data)
296 if ((!conf->MaxWhoResults) || (conf->MaxWhoResults > 65535) || (conf->MaxWhoResults < 1))
298 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
299 conf->MaxWhoResults = 128;
304 bool ValidateLogLevel(ServerConfig* conf, const char* tag, const char* value, void* data)
306 const char* dbg = (const char*)data;
307 conf->LogLevel = DEFAULT;
308 if (!strcmp(dbg,"debug"))
310 conf->LogLevel = DEBUG;
313 else if (!strcmp(dbg,"verbose"))
314 conf->LogLevel = VERBOSE;
315 else if (!strcmp(dbg,"default"))
316 conf->LogLevel = DEFAULT;
317 else if (!strcmp(dbg,"sparse"))
318 conf->LogLevel = SPARSE;
319 else if (!strcmp(dbg,"none"))
320 conf->LogLevel = NONE;
324 bool ValidateMotd(ServerConfig* conf, const char* tag, const char* value, void* data)
326 conf->ReadFile(conf->MOTD,conf->motd);
330 bool ValidateRules(ServerConfig* conf, const char* tag, const char* value, void* data)
332 conf->ReadFile(conf->RULES,conf->rules);
336 /* Callback called before processing the first <connect> tag
338 bool InitConnect(ServerConfig* conf, const char* tag)
340 log(DEFAULT,"Reading connect classes...");
341 conf->Classes.clear();
345 /* Callback called to process a single <connect> tag
347 bool DoConnect(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
350 char* allow = (char*)values[0]; /* Yeah, there are a lot of values. Live with it. */
351 char* deny = (char*)values[1];
352 char* password = (char*)values[2];
353 int* timeout = (int*)values[3];
354 int* pingfreq = (int*)values[4];
355 int* flood = (int*)values[5];
356 int* threshold = (int*)values[6];
357 int* sendq = (int*)values[7];
358 int* recvq = (int*)values[8];
359 int* localmax = (int*)values[9];
360 int* globalmax = (int*)values[10];
367 c.registration_timeout = *timeout;
368 c.pingtime = *pingfreq;
370 c.threshold = *threshold;
373 c.maxlocal = *localmax;
374 c.maxglobal = *globalmax;
379 if (c.maxglobal == 0)
381 if (c.threshold == 0)
385 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());
391 if (c.registration_timeout == 0)
392 c.registration_timeout = 90;
395 conf->Classes.push_back(c);
401 conf->Classes.push_back(c);
402 log(DEBUG,"Read connect class type DENY, host=%s",deny);
408 /* Callback called when there are no more <connect> tags
410 bool DoneConnect(ServerConfig* conf, const char* tag)
412 log(DEBUG,"DoneConnect called for tag: %s",tag);
416 /* Callback called before processing the first <uline> tag
418 bool InitULine(ServerConfig* conf, const char* tag)
420 conf->ulines.clear();
424 /* Callback called to process a single <uline> tag
426 bool DoULine(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
428 char* server = (char*)values[0];
429 log(DEBUG,"Read ULINE '%s'",server);
430 conf->ulines.push_back(server);
434 /* Callback called when there are no more <uline> tags
436 bool DoneULine(ServerConfig* conf, const char* tag)
441 /* Callback called before processing the first <module> tag
443 bool InitModule(ServerConfig* conf, const char* tag)
445 old_module_names.clear();
446 new_module_names.clear();
447 added_modules.clear();
448 removed_modules.clear();
449 for (std::vector<std::string>::iterator t = conf->module_names.begin(); t != conf->module_names.end(); t++)
451 old_module_names.push_back(*t);
456 /* Callback called to process a single <module> tag
458 bool DoModule(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
460 char* modname = (char*)values[0];
461 new_module_names.push_back(modname);
465 /* Callback called when there are no more <module> tags
467 bool DoneModule(ServerConfig* conf, const char* tag)
469 // now create a list of new modules that are due to be loaded
470 // and a seperate list of modules which are due to be unloaded
471 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
475 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
482 added_modules.push_back(*_new);
485 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
488 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
495 removed_modules.push_back(*oldm);
500 /* Callback called before processing the first <banlist> tag
502 bool InitMaxBans(ServerConfig* conf, const char* tag)
504 conf->maxbans.clear();
508 /* Callback called to process a single <banlist> tag
510 bool DoMaxBans(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
512 char* channel = (char*)values[0];
513 int* limit = (int*)values[1];
514 conf->maxbans[channel] = *limit;
518 /* Callback called when there are no more <banlist> tags.
520 bool DoneMaxBans(ServerConfig* conf, const char* tag)
525 void ServerConfig::Read(bool bail, userrec* user)
527 char debug[MAXBUF]; /* Temporary buffer for debugging value */
528 char* data[12]; /* Temporary buffers for reading multiple occurance tags into */
529 void* ptr[12]; /* Temporary pointers for passing to callbacks */
530 int r_i[12]; /* Temporary array for casting */
531 int rem = 0, add = 0; /* Number of modules added, number of modules removed */
532 std::ostringstream errstr; /* String stream containing the error output */
534 /* These tags MUST occur and must ONLY occur once in the config file */
535 static char* Once[] = { "server", "admin", "files", "power", "options", "pid", NULL };
537 /* These tags can occur ONCE or not at all */
538 static InitialConfig Values[] = {
539 {"options", "softlimit", &this->SoftLimit, DT_INTEGER, ValidateSoftLimit},
540 {"options", "somaxconn", &this->MaxConn, DT_INTEGER, ValidateMaxConn},
541 {"server", "name", &this->ServerName, DT_CHARPTR, ValidateServerName},
542 {"server", "description", &this->ServerDesc, DT_CHARPTR, NoValidation},
543 {"server", "network", &this->Network, DT_CHARPTR, NoValidation},
544 {"admin", "name", &this->AdminName, DT_CHARPTR, NoValidation},
545 {"admin", "email", &this->AdminEmail, DT_CHARPTR, NoValidation},
546 {"admin", "nick", &this->AdminNick, DT_CHARPTR, NoValidation},
547 {"files", "motd", &this->motd, DT_CHARPTR, ValidateMotd},
548 {"files", "rules", &this->rules, DT_CHARPTR, ValidateRules},
549 {"power", "diepass", &this->diepass, DT_CHARPTR, NoValidation},
550 {"power", "pauseval", &this->DieDelay, DT_INTEGER, NoValidation},
551 {"power", "restartpass", &this->restartpass, DT_CHARPTR, NoValidation},
552 {"options", "prefixquit", &this->PrefixQuit, DT_CHARPTR, NoValidation},
553 {"die", "value", &this->DieValue, DT_CHARPTR, NoValidation},
554 {"options", "loglevel", &debug, DT_CHARPTR, ValidateLogLevel},
555 {"options", "netbuffersize", &this->NetBufferSize, DT_INTEGER, ValidateNetBufferSize},
556 {"options", "maxwho", &this->MaxWhoResults, DT_INTEGER, ValidateMaxWho},
557 {"options", "allowhalfop", &this->AllowHalfop, DT_BOOLEAN, NoValidation},
558 {"dns", "server", &this->DNSServer, DT_CHARPTR, ValidateDnsServer},
559 {"dns", "timeout", &this->dns_timeout, DT_INTEGER, ValidateDnsTimeout},
560 {"options", "moduledir", &this->ModPath, DT_CHARPTR, ValidateModPath},
561 {"disabled", "commands", &this->DisabledCommands, DT_CHARPTR, NoValidation},
562 {"options", "operonlystats", &this->OperOnlyStats, DT_CHARPTR, NoValidation},
563 {"options", "customversion", &this->CustomVersion, DT_CHARPTR, NoValidation},
564 {"options", "hidesplits", &this->HideSplits, DT_BOOLEAN, NoValidation},
565 {"options", "hidebans", &this->HideBans, DT_BOOLEAN, NoValidation},
566 {"options", "hidewhois", &this->HideWhoisServer, DT_CHARPTR, NoValidation},
567 {"options", "operspywhois", &this->OperSpyWhois, DT_BOOLEAN, NoValidation},
568 {"options", "tempdir", &this->TempDir, DT_CHARPTR, ValidateTempDir},
569 {"options", "nouserdns", &this->NoUserDns, DT_BOOLEAN, NoValidation},
570 {"options", "syntaxhints", &this->SyntaxHints, DT_BOOLEAN, NoValidation},
571 {"pid", "file", &this->PID, DT_CHARPTR, NoValidation},
575 /* These tags can occur multiple times, and therefore they have special code to read them
576 * which is different to the code for reading the singular tags listed above.
578 static MultiConfig MultiValues[] = {
581 {"allow", "deny", "password", "timeout", "pingfreq", "flood",
582 "threshold", "sendq", "recvq", "localmax", "globalmax", NULL},
583 {DT_CHARPTR, DT_CHARPTR, DT_CHARPTR, DT_INTEGER, DT_INTEGER, DT_INTEGER,
584 DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER},
585 InitConnect, DoConnect, DoneConnect},
590 InitULine,DoULine,DoneULine},
593 {"chan", "limit", NULL},
594 {DT_CHARPTR, DT_INTEGER},
595 InitMaxBans, DoMaxBans, DoneMaxBans},
600 InitModule, DoModule, DoneModule},
603 {"reason", "ipmask", NULL},
604 {DT_CHARPTR, DT_CHARPTR},
605 InitXLine, DoZLine, DoneXLine},
608 {"reason", "nick", NULL},
609 {DT_CHARPTR, DT_CHARPTR},
610 InitXLine, DoQLine, DoneXLine},
613 {"reason", "host", NULL},
614 {DT_CHARPTR, DT_CHARPTR},
615 InitXLine, DoKLine, DoneXLine},
618 {"reason", "host", NULL},
619 {DT_CHARPTR, DT_CHARPTR},
620 InitXLine, DoELine, DoneXLine},
623 {"name", "classes", NULL},
624 {DT_CHARPTR, DT_CHARPTR},
625 InitTypes, DoType, DoneClassesAndTypes},
628 {"name", "commands", NULL},
629 {DT_CHARPTR, DT_CHARPTR},
630 InitClasses, DoClass, DoneClassesAndTypes},
635 include_stack.clear();
637 /* Load and parse the config file, if there are any errors then explode */
639 /* Make a copy here so if it fails then we can carry on running with an unaffected config */
640 ConfigDataHash newconfig;
642 if (this->LoadConf(newconfig, CONFIG_FILE, errstr))
644 /* If we succeeded, set the ircd config to the new one */
645 this->config_data = newconfig;
650 for(ConfigDataHash::const_iterator i = this->config_data.begin(); i != this->config_data.end(); i++)
652 c = (i->first != last) ? 1 : c+1;
655 std::cout << "[" << i->first << " " << c << "/" << this->config_data.count(i->first) << "]" << std::endl;
657 for(KeyValList::const_iterator j = i->second.begin(); j != i->second.end(); j++)
658 std::cout << "\t" << j->first << " = " << j->second << std::endl;
660 std::cout << "[/" << i->first << " " << c << "/" << this->config_data.count(i->first) << "]" << std::endl;
665 log(DEFAULT, "There were errors in your configuration:\n%s", errstr.str().c_str());
669 /* Unneeded because of the log() aboive? */
670 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
675 std::string errors = errstr.str();
676 std::string::size_type start;
677 unsigned int prefixlen;
680 /* ":ServerInstance->Config->ServerName NOTICE user->nick :" */
681 prefixlen = strlen(this->ServerName) + strlen(user->nick) + 11;
685 user->WriteServ("NOTICE %s :There were errors in the configuration file:",user->nick);
687 while(start < errors.length())
689 user->WriteServ("NOTICE %s :%s",user->nick, errors.substr(start, 510 - prefixlen).c_str());
690 start += 510 - prefixlen;
695 ServerInstance->WriteOpers("There were errors in the configuration file:");
697 while(start < errors.length())
699 ServerInstance->WriteOpers(errors.substr(start, 360).c_str());
708 /* Check we dont have more than one of singular tags, or any of them missing
710 for (int Index = 0; Once[Index]; Index++)
711 if (!CheckOnce(Once[Index],bail,user))
714 /* Read the values of all the tags which occur once or not at all, and call their callbacks.
716 for (int Index = 0; Values[Index].tag; Index++)
718 int* val_i = (int*) Values[Index].val;
719 char* val_c = (char*) Values[Index].val;
721 switch (Values[Index].datatype)
724 /* Assuming MAXBUF here, potentially unsafe */
725 ConfValue(this->config_data, Values[Index].tag, Values[Index].value, 0, val_c, MAXBUF);
729 ConfValueInteger(this->config_data, Values[Index].tag, Values[Index].value, 0, *val_i);
733 *val_i = ConfValueBool(this->config_data, Values[Index].tag, Values[Index].value, 0);
740 Values[Index].validation_function(this, Values[Index].tag, Values[Index].value, Values[Index].val);
743 /* Claim memory for use when reading multiple tags
745 for (int n = 0; n < 12; n++)
746 data[n] = new char[MAXBUF];
748 /* Read the multiple-tag items (class tags, connect tags, etc)
749 * and call the callbacks associated with them. We have three
750 * callbacks for these, a 'start', 'item' and 'end' callback.
753 /* XXX - Make this use ConfValueInteger and so on */
754 for (int Index = 0; MultiValues[Index].tag; Index++)
756 MultiValues[Index].init_function(this, MultiValues[Index].tag);
758 int number_of_tags = ConfValueEnum(this->config_data, MultiValues[Index].tag);
760 for (int tagnum = 0; tagnum < number_of_tags; tagnum++)
762 for (int valuenum = 0; MultiValues[Index].items[valuenum]; valuenum++)
764 ConfValue(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], tagnum, data[valuenum], MAXBUF);
766 switch (MultiValues[Index].datatype[valuenum])
769 ptr[valuenum] = data[valuenum];
772 r_i[valuenum] = atoi(data[valuenum]);
773 ptr[valuenum] = &r_i[valuenum];
776 r_i[valuenum] = ((*data[valuenum] == tolower('y')) || (*data[valuenum] == tolower('t')) || (*data[valuenum] == '1'));
777 ptr[valuenum] = &r_i[valuenum];
783 MultiValues[Index].validation_function(this, MultiValues[Index].tag, (char**)MultiValues[Index].items, ptr, MultiValues[Index].datatype);
786 MultiValues[Index].finish_function(this, MultiValues[Index].tag);
789 /* Free any memory we claimed
791 for (int n = 0; n < 12; n++)
794 // write once here, to try it out and make sure its ok
795 ServerInstance->WritePID(this->PID);
797 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
799 /* If we're rehashing, let's load any new modules, and unload old ones
803 ServerInstance->stats->BoundPortCount = BindPorts(false);
805 if (!removed_modules.empty())
806 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
808 if (ServerInstance->UnloadModule(removing->c_str()))
810 ServerInstance->WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
813 user->WriteServ("973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
820 user->WriteServ("972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
824 if (!added_modules.empty())
825 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
827 if (ServerInstance->LoadModule(adding->c_str()))
829 ServerInstance->WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
832 user->WriteServ("975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
839 user->WriteServ("974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
843 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());
847 bool ServerConfig::LoadConf(ConfigDataHash &target, const char* filename, std::ostringstream &errorstream)
849 std::ifstream conf(filename);
862 /* Check if the file open failed first */
865 errorstream << "LoadConf: Couldn't open config file: " << filename << std::endl;
869 /* Fix the chmod of the file to restrict it to the current user and group */
870 chmod(filename,0600);
872 for (unsigned int t = 0; t < include_stack.size(); t++)
874 if (std::string(filename) == include_stack[t])
876 errorstream << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
881 /* It's not already included, add it to the list of files we've loaded */
882 include_stack.push_back(filename);
884 /* Start reading characters... */
888 * Here we try and get individual tags on separate lines,
889 * this would be so easy if we just made people format
890 * their config files like that, but they don't so...
891 * We check for a '<' and then know the line is over when
892 * we get a '>' not inside quotes. If we find two '<' and
893 * no '>' then die with an error.
896 if((ch == '#') && !in_quote)
899 if(((ch == '\n') || (ch == '\r')) && in_quote)
901 errorstream << "Got a newline within a quoted section, this is probably a typo: " << filename << ":" << linenumber << std::endl;
920 /* XXX: Added by Brain, May 1st 2006 - Escaping of characters.
921 * Note that this WILL NOT usually allow insertion of newlines,
922 * because a newline is two characters long. Use it primarily to
923 * insert the " symbol.
925 * Note that this also involves a further check when parsing the line,
926 * which can be found below.
928 if ((ch == '\\') && (in_quote) && (in_tag))
931 log(DEBUG,"Escape sequence in config line.");
933 if (conf.get(real_character))
935 log(DEBUG,"Escaping %c", real_character);
936 line += real_character;
941 errorstream << "End of file after a \\, what did you want to escape?: " << filename << ":" << linenumber << std::endl;
954 errorstream << "Got another opening < when the first one wasn't closed: " << filename << ":" << linenumber << std::endl;
962 errorstream << "We're in a quote but outside a tag, interesting. " << filename << ":" << linenumber << std::endl;
967 // errorstream << "Opening new config tag on line " << linenumber << std::endl;
978 // errorstream << "Closing quote in config tag on line " << linenumber << std::endl;
983 // errorstream << "Opening quote in config tag on line " << linenumber << std::endl;
991 errorstream << "Found a (closing) \" outside a tag: " << filename << ":" << linenumber << std::endl;
995 errorstream << "Found a (opening) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1005 // errorstream << "Closing config tag on line " << linenumber << std::endl;
1009 * If this finds an <include> then ParseLine can simply call
1010 * LoadConf() and load the included config into the same ConfigDataHash
1013 if(!this->ParseLine(target, line, linenumber, errorstream))
1020 errorstream << "Got a closing > when we weren't inside a tag: " << filename << ":" << linenumber << std::endl;
1030 bool ServerConfig::LoadConf(ConfigDataHash &target, const std::string &filename, std::ostringstream &errorstream)
1032 return this->LoadConf(target, filename.c_str(), errorstream);
1035 bool ServerConfig::ParseLine(ConfigDataHash &target, std::string &line, long linenumber, std::ostringstream &errorstream)
1037 std::string tagname;
1038 std::string current_key;
1039 std::string current_value;
1045 got_name = got_key = in_quote = false;
1047 // std::cout << "ParseLine(data, '" << line << "', " << linenumber << ", stream)" << std::endl;
1049 for(std::string::iterator c = line.begin(); c != line.end(); c++)
1053 /* We don't know the tag name yet. */
1064 /* We got to a space, we should have the tagname now. */
1065 if(tagname.length())
1073 /* We have the tag name */
1076 /* We're still reading the key name */
1086 /* We got an '=', end of the key name. */
1092 /* We have the key name, now we're looking for quotes and the value */
1094 /* Correctly handle escaped characters here.
1095 * See the XXX'ed section above.
1097 if ((*c == '\\') && (in_quote))
1100 current_value += *c;
1107 /* We're not already in a quote. */
1112 /* Leaving quotes, we have the value */
1113 results.push_back(KeyVal(current_key, current_value));
1115 // std::cout << "<" << tagname << ":" << current_key << "> " << current_value << std::endl;
1120 if((tagname == "include") && (current_key == "file"))
1122 if(!this->DoInclude(target, current_value, errorstream))
1126 current_key.clear();
1127 current_value.clear();
1134 current_value += *c;
1141 /* Finished parsing the tag, add it to the config hash */
1142 target.insert(std::pair<std::string, KeyValList > (tagname, results));
1147 bool ServerConfig::DoInclude(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream)
1149 std::string confpath;
1150 std::string newfile;
1151 std::string::size_type pos;
1153 confpath = CONFIG_FILE;
1156 for (std::string::iterator c = newfile.begin(); c != newfile.end(); c++)
1166 if((pos = confpath.find("/inspircd.conf")) != std::string::npos)
1168 /* Leaves us with just the path */
1169 newfile = confpath.substr(0, pos) + std::string("/") + newfile;
1173 errorstream << "Couldn't get config path from: " << confpath << std::endl;
1178 return LoadConf(target, newfile, errorstream);
1181 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, int index, char* result, int length)
1184 bool r = ConfValue(target, std::string(tag), std::string(var), index, value);
1185 strlcpy(result, value.c_str(), length);
1189 bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, std::string &result)
1191 ConfigDataHash::size_type pos = index;
1192 if((pos >= 0) && (pos < target.count(tag)))
1194 ConfigDataHash::const_iterator iter = target.find(tag);
1196 for(int i = 0; i < index; i++)
1199 for(KeyValList::const_iterator j = iter->second.begin(); j != iter->second.end(); j++)
1210 log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1214 log(DEBUG, "ConfValue got an out-of-range index %d, there are only %d occurences of %s", pos, target.count(tag), tag.c_str());
1220 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, int index, int &result)
1222 return ConfValueInteger(target, std::string(tag), std::string(var), index, result);
1225 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, int &result)
1228 std::istringstream stream;
1229 bool r = ConfValue(target, tag, var, index, value);
1231 if(!(stream >> result))
1236 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, int index)
1238 return ConfValueBool(target, std::string(tag), std::string(var), index);
1241 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, int index)
1244 if(!ConfValue(target, tag, var, index, result))
1247 return ((result == "yes") || (result == "true") || (result == "1"));
1250 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const char* tag)
1252 return target.count(tag);
1255 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const std::string &tag)
1257 return target.count(tag);
1260 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const char* tag, int index)
1262 return ConfVarEnum(target, std::string(tag), index);
1265 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const std::string &tag, int index)
1267 ConfigDataHash::size_type pos = index;
1269 if((pos >= 0) && (pos < target.count(tag)))
1271 ConfigDataHash::const_iterator iter = target.find(tag);
1273 for(int i = 0; i < index; i++)
1276 return iter->second.size();
1280 log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1284 log(DEBUG, "ConfVarEnum got an out-of-range index %d, there are only %d occurences of %s", pos, target.count(tag), tag.c_str());
1290 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1292 bool ServerConfig::ReadFile(file_cache &F, const char* fname)
1295 char linebuf[MAXBUF];
1298 file = fopen(fname,"r");
1304 fgets(linebuf,sizeof(linebuf),file);
1305 linebuf[strlen(linebuf)-1]='\0';
1309 strcpy(linebuf," ");
1314 F.push_back(linebuf);