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"
31 using irc::sockets::BindPorts;
33 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
35 ServerConfig::ServerConfig(InspIRCd* Instance) : ServerInstance(Instance)
38 *TempDir = *ServerName = *Network = *ServerDesc = *AdminName = '\0';
39 *HideWhoisServer = *AdminEmail = *AdminNick = *diepass = *restartpass = '\0';
40 *CustomVersion = *motd = *rules = *PrefixQuit = *DieValue = *DNSServer = '\0';
41 *OperOnlyStats = *ModPath = *MyExecutable = *DisabledCommands = *PID = '\0';
43 NoUserDns = forcedebug = OperSpyWhois = nofork = HideBans = HideSplits = false;
44 writelog = AllowHalfop = true;
45 dns_timeout = DieDelay = 5;
47 NetBufferSize = 10240;
48 SoftLimit = MAXCLIENTS;
56 void ServerConfig::ClearStack()
58 include_stack.clear();
61 Module* ServerConfig::GetIOHook(int port)
63 std::map<int,Module*>::iterator x = IOHookModule.find(port);
64 return (x != IOHookModule.end() ? x->second : NULL);
67 bool ServerConfig::AddIOHook(int port, Module* iomod)
71 IOHookModule[port] = iomod;
76 ModuleException err("Port already hooked by another module");
82 bool ServerConfig::DelIOHook(int port)
84 std::map<int,Module*>::iterator x = IOHookModule.find(port);
85 if (x != IOHookModule.end())
87 IOHookModule.erase(x);
93 bool ServerConfig::CheckOnce(char* tag, bool bail, userrec* user)
95 int count = ConfValueEnum(this->config_data, tag);
101 printf("There were errors in your configuration:\nYou have more than one <%s> tag, this is not permitted.\n",tag);
102 InspIRCd::Exit(ERROR);
108 user->WriteServ("There were errors in your configuration:");
109 user->WriteServ("You have more than one <%s> tag, this is not permitted.\n",tag);
113 ServerInstance->WriteOpers("There were errors in the configuration file:");
114 ServerInstance->WriteOpers("You have more than one <%s> tag, this is not permitted.\n",tag);
123 printf("There were errors in your configuration:\nYou have not defined a <%s> tag, this is required.\n",tag);
124 InspIRCd::Exit(ERROR);
130 user->WriteServ("There were errors in your configuration:");
131 user->WriteServ("You have not defined a <%s> tag, this is required.",tag);
135 ServerInstance->WriteOpers("There were errors in the configuration file:");
136 ServerInstance->WriteOpers("You have not defined a <%s> tag, this is required.",tag);
144 bool NoValidation(ServerConfig* conf, const char* tag, const char* value, void* data)
146 log(DEBUG,"No validation for <%s:%s>",tag,value);
150 bool ValidateTempDir(ServerConfig* conf, const char* tag, const char* value, void* data)
152 char* x = (char*)data;
154 strlcpy(x,"/tmp",1024);
158 bool ValidateMaxTargets(ServerConfig* conf, const char* tag, const char* value, void* data)
161 if ((*x < 0) || (*x > 31))
163 log(DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
169 bool ValidateSoftLimit(ServerConfig* conf, const char* tag, const char* value, void* data)
172 if ((*x < 1) || (*x > MAXCLIENTS))
174 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
180 bool ValidateMaxConn(ServerConfig* conf, const char* tag, const char* value, void* data)
184 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
190 bool ValidateDnsTimeout(ServerConfig* conf, const char* tag, const char* value, void* data)
198 bool InitializeDisabledCommands(const char* data, InspIRCd* ServerInstance)
200 std::stringstream dcmds(data);
203 /* Enable everything first */
204 for (nspace::hash_map<std::string,command_t*>::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
205 x->second->Disable(false);
207 /* Now disable all the ones which the user wants disabled */
208 while (dcmds >> thiscmd)
210 nspace::hash_map<std::string,command_t*>::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
211 if (cm != ServerInstance->Parser->cmdlist.end())
213 log(DEBUG,"Disabling command '%s'",cm->second->command.c_str());
214 cm->second->Disable(true);
220 bool ValidateDnsServer(ServerConfig* conf, const char* tag, const char* value, void* data)
222 char* x = (char*)data;
225 // attempt to look up their nameserver from /etc/resolv.conf
226 log(DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
227 ifstream resolv("/etc/resolv.conf");
228 std::string nameserver;
229 bool found_server = false;
231 if (resolv.is_open())
233 while (resolv >> nameserver)
235 if ((nameserver == "nameserver") && (!found_server))
237 resolv >> nameserver;
238 strlcpy(x,nameserver.c_str(),MAXBUF);
240 log(DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
246 log(DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
247 strlcpy(x,"127.0.0.1",MAXBUF);
252 log(DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
253 strlcpy(x,"127.0.0.1",MAXBUF);
259 bool ValidateModPath(ServerConfig* conf, const char* tag, const char* value, void* data)
261 char* x = (char*)data;
263 strlcpy(x,MOD_PATH,MAXBUF);
268 bool ValidateServerName(ServerConfig* conf, const char* tag, const char* value, void* data)
270 char* x = (char*)data;
273 log(DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s%c'",x,x,'.');
274 charlcat(x,'.',MAXBUF);
280 bool ValidateNetBufferSize(ServerConfig* conf, const char* tag, const char* value, void* data)
282 if ((!conf->NetBufferSize) || (conf->NetBufferSize > 65535) || (conf->NetBufferSize < 1024))
284 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
285 conf->NetBufferSize = 10240;
290 bool ValidateMaxWho(ServerConfig* conf, const char* tag, const char* value, void* data)
292 if ((!conf->MaxWhoResults) || (conf->MaxWhoResults > 65535) || (conf->MaxWhoResults < 1))
294 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
295 conf->MaxWhoResults = 128;
300 bool ValidateLogLevel(ServerConfig* conf, const char* tag, const char* value, void* data)
302 const char* dbg = (const char*)data;
303 conf->LogLevel = DEFAULT;
304 if (!strcmp(dbg,"debug"))
306 conf->LogLevel = DEBUG;
309 else if (!strcmp(dbg,"verbose"))
310 conf->LogLevel = VERBOSE;
311 else if (!strcmp(dbg,"default"))
312 conf->LogLevel = DEFAULT;
313 else if (!strcmp(dbg,"sparse"))
314 conf->LogLevel = SPARSE;
315 else if (!strcmp(dbg,"none"))
316 conf->LogLevel = NONE;
320 bool ValidateMotd(ServerConfig* conf, const char* tag, const char* value, void* data)
322 conf->ReadFile(conf->MOTD,conf->motd);
326 bool ValidateRules(ServerConfig* conf, const char* tag, const char* value, void* data)
328 conf->ReadFile(conf->RULES,conf->rules);
332 /* Callback called before processing the first <connect> tag
334 bool InitConnect(ServerConfig* conf, const char* tag)
336 log(DEFAULT,"Reading connect classes...");
337 conf->Classes.clear();
341 /* Callback called to process a single <connect> tag
343 bool DoConnect(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
346 char* allow = (char*)values[0]; /* Yeah, there are a lot of values. Live with it. */
347 char* deny = (char*)values[1];
348 char* password = (char*)values[2];
349 int* timeout = (int*)values[3];
350 int* pingfreq = (int*)values[4];
351 int* flood = (int*)values[5];
352 int* threshold = (int*)values[6];
353 int* sendq = (int*)values[7];
354 int* recvq = (int*)values[8];
355 int* localmax = (int*)values[9];
356 int* globalmax = (int*)values[10];
363 c.registration_timeout = *timeout;
364 c.pingtime = *pingfreq;
366 c.threshold = *threshold;
369 c.maxlocal = *localmax;
370 c.maxglobal = *globalmax;
375 if (c.maxglobal == 0)
377 if (c.threshold == 0)
381 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());
387 if (c.registration_timeout == 0)
388 c.registration_timeout = 90;
391 conf->Classes.push_back(c);
397 conf->Classes.push_back(c);
398 log(DEBUG,"Read connect class type DENY, host=%s",deny);
404 /* Callback called when there are no more <connect> tags
406 bool DoneConnect(ServerConfig* conf, const char* tag)
408 log(DEBUG,"DoneConnect called for tag: %s",tag);
412 /* Callback called before processing the first <uline> tag
414 bool InitULine(ServerConfig* conf, const char* tag)
416 conf->ulines.clear();
420 /* Callback called to process a single <uline> tag
422 bool DoULine(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
424 char* server = (char*)values[0];
425 log(DEBUG,"Read ULINE '%s'",server);
426 conf->ulines.push_back(server);
430 /* Callback called when there are no more <uline> tags
432 bool DoneULine(ServerConfig* conf, const char* tag)
437 /* Callback called before processing the first <module> tag
439 bool InitModule(ServerConfig* conf, const char* tag)
441 old_module_names.clear();
442 new_module_names.clear();
443 added_modules.clear();
444 removed_modules.clear();
445 for (std::vector<std::string>::iterator t = conf->module_names.begin(); t != conf->module_names.end(); t++)
447 old_module_names.push_back(*t);
452 /* Callback called to process a single <module> tag
454 bool DoModule(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
456 char* modname = (char*)values[0];
457 new_module_names.push_back(modname);
461 /* Callback called when there are no more <module> tags
463 bool DoneModule(ServerConfig* conf, const char* tag)
465 // now create a list of new modules that are due to be loaded
466 // and a seperate list of modules which are due to be unloaded
467 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
471 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
478 added_modules.push_back(*_new);
481 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
484 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
491 removed_modules.push_back(*oldm);
496 /* Callback called before processing the first <banlist> tag
498 bool InitMaxBans(ServerConfig* conf, const char* tag)
500 conf->maxbans.clear();
504 /* Callback called to process a single <banlist> tag
506 bool DoMaxBans(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
508 char* channel = (char*)values[0];
509 int* limit = (int*)values[1];
510 conf->maxbans[channel] = *limit;
514 /* Callback called when there are no more <banlist> tags.
516 bool DoneMaxBans(ServerConfig* conf, const char* tag)
521 void ServerConfig::Read(bool bail, userrec* user)
523 char debug[MAXBUF]; /* Temporary buffer for debugging value */
524 char* data[12]; /* Temporary buffers for reading multiple occurance tags into */
525 void* ptr[12]; /* Temporary pointers for passing to callbacks */
526 int r_i[12]; /* Temporary array for casting */
527 int rem = 0, add = 0; /* Number of modules added, number of modules removed */
528 std::ostringstream errstr; /* String stream containing the error output */
530 /* These tags MUST occur and must ONLY occur once in the config file */
531 static char* Once[] = { "server", "admin", "files", "power", "options", "pid", NULL };
533 /* These tags can occur ONCE or not at all */
534 static InitialConfig Values[] = {
535 {"options", "softlimit", &this->SoftLimit, DT_INTEGER, ValidateSoftLimit},
536 {"options", "somaxconn", &this->MaxConn, DT_INTEGER, ValidateMaxConn},
537 {"server", "name", &this->ServerName, DT_CHARPTR, ValidateServerName},
538 {"server", "description", &this->ServerDesc, DT_CHARPTR, NoValidation},
539 {"server", "network", &this->Network, DT_CHARPTR, NoValidation},
540 {"admin", "name", &this->AdminName, DT_CHARPTR, NoValidation},
541 {"admin", "email", &this->AdminEmail, DT_CHARPTR, NoValidation},
542 {"admin", "nick", &this->AdminNick, DT_CHARPTR, NoValidation},
543 {"files", "motd", &this->motd, DT_CHARPTR, ValidateMotd},
544 {"files", "rules", &this->rules, DT_CHARPTR, ValidateRules},
545 {"power", "diepass", &this->diepass, DT_CHARPTR, NoValidation},
546 {"power", "pauseval", &this->DieDelay, DT_INTEGER, NoValidation},
547 {"power", "restartpass", &this->restartpass, DT_CHARPTR, NoValidation},
548 {"options", "prefixquit", &this->PrefixQuit, DT_CHARPTR, NoValidation},
549 {"die", "value", &this->DieValue, DT_CHARPTR, NoValidation},
550 {"options", "loglevel", &debug, DT_CHARPTR, ValidateLogLevel},
551 {"options", "netbuffersize", &this->NetBufferSize, DT_INTEGER, ValidateNetBufferSize},
552 {"options", "maxwho", &this->MaxWhoResults, DT_INTEGER, ValidateMaxWho},
553 {"options", "allowhalfop", &this->AllowHalfop, DT_BOOLEAN, NoValidation},
554 {"dns", "server", &this->DNSServer, DT_CHARPTR, ValidateDnsServer},
555 {"dns", "timeout", &this->dns_timeout, DT_INTEGER, ValidateDnsTimeout},
556 {"options", "moduledir", &this->ModPath, DT_CHARPTR, ValidateModPath},
557 {"disabled", "commands", &this->DisabledCommands, DT_CHARPTR, NoValidation},
558 {"options", "operonlystats", &this->OperOnlyStats, DT_CHARPTR, NoValidation},
559 {"options", "customversion", &this->CustomVersion, DT_CHARPTR, NoValidation},
560 {"options", "hidesplits", &this->HideSplits, DT_BOOLEAN, NoValidation},
561 {"options", "hidebans", &this->HideBans, DT_BOOLEAN, NoValidation},
562 {"options", "hidewhois", &this->HideWhoisServer, DT_CHARPTR, NoValidation},
563 {"options", "operspywhois", &this->OperSpyWhois, DT_BOOLEAN, NoValidation},
564 {"options", "tempdir", &this->TempDir, DT_CHARPTR, ValidateTempDir},
565 {"options", "nouserdns", &this->NoUserDns, DT_BOOLEAN, NoValidation},
566 {"options", "syntaxhints", &this->SyntaxHints, DT_BOOLEAN, NoValidation},
567 {"pid", "file", &this->PID, DT_CHARPTR, NoValidation},
571 /* These tags can occur multiple times, and therefore they have special code to read them
572 * which is different to the code for reading the singular tags listed above.
574 static MultiConfig MultiValues[] = {
577 {"allow", "deny", "password", "timeout", "pingfreq", "flood",
578 "threshold", "sendq", "recvq", "localmax", "globalmax", NULL},
579 {DT_CHARPTR, DT_CHARPTR, DT_CHARPTR, DT_INTEGER, DT_INTEGER, DT_INTEGER,
580 DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER},
581 InitConnect, DoConnect, DoneConnect},
586 InitULine,DoULine,DoneULine},
589 {"chan", "limit", NULL},
590 {DT_CHARPTR, DT_INTEGER},
591 InitMaxBans, DoMaxBans, DoneMaxBans},
596 InitModule, DoModule, DoneModule},
599 {"reason", "ipmask", NULL},
600 {DT_CHARPTR, DT_CHARPTR},
601 InitXLine, DoZLine, DoneXLine},
604 {"reason", "nick", NULL},
605 {DT_CHARPTR, DT_CHARPTR},
606 InitXLine, DoQLine, DoneXLine},
609 {"reason", "host", NULL},
610 {DT_CHARPTR, DT_CHARPTR},
611 InitXLine, DoKLine, DoneXLine},
614 {"reason", "host", NULL},
615 {DT_CHARPTR, DT_CHARPTR},
616 InitXLine, DoELine, DoneXLine},
619 {"name", "classes", NULL},
620 {DT_CHARPTR, DT_CHARPTR},
621 InitTypes, DoType, DoneClassesAndTypes},
624 {"name", "commands", NULL},
625 {DT_CHARPTR, DT_CHARPTR},
626 InitClasses, DoClass, DoneClassesAndTypes},
631 include_stack.clear();
633 /* Load and parse the config file, if there are any errors then explode */
635 /* Make a copy here so if it fails then we can carry on running with an unaffected config */
636 ConfigDataHash newconfig;
638 if (this->LoadConf(newconfig, CONFIG_FILE, errstr))
640 /* If we succeeded, set the ircd config to the new one */
641 this->config_data = newconfig;
646 for(ConfigDataHash::const_iterator i = this->config_data.begin(); i != this->config_data.end(); i++)
648 c = (i->first != last) ? 1 : c+1;
651 std::cout << "[" << i->first << " " << c << "/" << this->config_data.count(i->first) << "]" << std::endl;
653 for(KeyValList::const_iterator j = i->second.begin(); j != i->second.end(); j++)
654 std::cout << "\t" << j->first << " = " << j->second << std::endl;
656 std::cout << "[/" << i->first << " " << c << "/" << this->config_data.count(i->first) << "]" << std::endl;
661 log(DEFAULT, "There were errors in your configuration:\n%s", errstr.str().c_str());
665 /* Unneeded because of the log() aboive? */
666 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
667 InspIRCd::Exit(ERROR);
671 std::string errors = errstr.str();
672 std::string::size_type start;
673 unsigned int prefixlen;
676 /* ":ServerInstance->Config->ServerName NOTICE user->nick :" */
677 prefixlen = strlen(this->ServerName) + strlen(user->nick) + 11;
681 user->WriteServ("NOTICE %s :There were errors in the configuration file:",user->nick);
683 while(start < errors.length())
685 user->WriteServ("NOTICE %s :%s",user->nick, errors.substr(start, 510 - prefixlen).c_str());
686 start += 510 - prefixlen;
691 ServerInstance->WriteOpers("There were errors in the configuration file:");
693 while(start < errors.length())
695 ServerInstance->WriteOpers(errors.substr(start, 360).c_str());
704 /* Check we dont have more than one of singular tags, or any of them missing
706 for (int Index = 0; Once[Index]; Index++)
707 if (!CheckOnce(Once[Index],bail,user))
710 /* Read the values of all the tags which occur once or not at all, and call their callbacks.
712 for (int Index = 0; Values[Index].tag; Index++)
714 int* val_i = (int*) Values[Index].val;
715 char* val_c = (char*) Values[Index].val;
717 switch (Values[Index].datatype)
720 /* Assuming MAXBUF here, potentially unsafe */
721 ConfValue(this->config_data, Values[Index].tag, Values[Index].value, 0, val_c, MAXBUF);
725 ConfValueInteger(this->config_data, Values[Index].tag, Values[Index].value, 0, *val_i);
729 *val_i = ConfValueBool(this->config_data, Values[Index].tag, Values[Index].value, 0);
736 Values[Index].validation_function(this, Values[Index].tag, Values[Index].value, Values[Index].val);
739 /* Claim memory for use when reading multiple tags
741 for (int n = 0; n < 12; n++)
742 data[n] = new char[MAXBUF];
744 /* Read the multiple-tag items (class tags, connect tags, etc)
745 * and call the callbacks associated with them. We have three
746 * callbacks for these, a 'start', 'item' and 'end' callback.
749 /* XXX - Make this use ConfValueInteger and so on */
750 for (int Index = 0; MultiValues[Index].tag; Index++)
752 MultiValues[Index].init_function(this, MultiValues[Index].tag);
754 int number_of_tags = ConfValueEnum(this->config_data, MultiValues[Index].tag);
756 for (int tagnum = 0; tagnum < number_of_tags; tagnum++)
758 for (int valuenum = 0; MultiValues[Index].items[valuenum]; valuenum++)
760 ConfValue(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], tagnum, data[valuenum], MAXBUF);
762 switch (MultiValues[Index].datatype[valuenum])
765 ptr[valuenum] = data[valuenum];
768 r_i[valuenum] = atoi(data[valuenum]);
769 ptr[valuenum] = &r_i[valuenum];
772 r_i[valuenum] = ((*data[valuenum] == tolower('y')) || (*data[valuenum] == tolower('t')) || (*data[valuenum] == '1'));
773 ptr[valuenum] = &r_i[valuenum];
779 MultiValues[Index].validation_function(this, MultiValues[Index].tag, (char**)MultiValues[Index].items, ptr, MultiValues[Index].datatype);
782 MultiValues[Index].finish_function(this, MultiValues[Index].tag);
785 /* Free any memory we claimed
787 for (int n = 0; n < 12; n++)
790 // write once here, to try it out and make sure its ok
791 ServerInstance->WritePID(this->PID);
793 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
795 /* If we're rehashing, let's load any new modules, and unload old ones
799 ServerInstance->stats->BoundPortCount = BindPorts(false);
801 if (!removed_modules.empty())
802 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
804 if (ServerInstance->UnloadModule(removing->c_str()))
806 ServerInstance->WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
809 user->WriteServ("973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
816 user->WriteServ("972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
820 if (!added_modules.empty())
821 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
823 if (ServerInstance->LoadModule(adding->c_str()))
825 ServerInstance->WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
828 user->WriteServ("975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
835 user->WriteServ("974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
839 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());
843 bool ServerConfig::LoadConf(ConfigDataHash &target, const char* filename, std::ostringstream &errorstream)
845 std::ifstream conf(filename);
858 /* Check if the file open failed first */
861 errorstream << "LoadConf: Couldn't open config file: " << filename << std::endl;
865 /* Fix the chmod of the file to restrict it to the current user and group */
866 chmod(filename,0600);
868 for (unsigned int t = 0; t < include_stack.size(); t++)
870 if (std::string(filename) == include_stack[t])
872 errorstream << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
877 /* It's not already included, add it to the list of files we've loaded */
878 include_stack.push_back(filename);
880 /* Start reading characters... */
884 * Here we try and get individual tags on separate lines,
885 * this would be so easy if we just made people format
886 * their config files like that, but they don't so...
887 * We check for a '<' and then know the line is over when
888 * we get a '>' not inside quotes. If we find two '<' and
889 * no '>' then die with an error.
892 if((ch == '#') && !in_quote)
895 if(((ch == '\n') || (ch == '\r')) && in_quote)
897 errorstream << "Got a newline within a quoted section, this is probably a typo: " << filename << ":" << linenumber << std::endl;
916 /* XXX: Added by Brain, May 1st 2006 - Escaping of characters.
917 * Note that this WILL NOT usually allow insertion of newlines,
918 * because a newline is two characters long. Use it primarily to
919 * insert the " symbol.
921 * Note that this also involves a further check when parsing the line,
922 * which can be found below.
924 if ((ch == '\\') && (in_quote) && (in_tag))
927 log(DEBUG,"Escape sequence in config line.");
929 if (conf.get(real_character))
931 log(DEBUG,"Escaping %c", real_character);
932 line += real_character;
937 errorstream << "End of file after a \\, what did you want to escape?: " << filename << ":" << linenumber << std::endl;
950 errorstream << "Got another opening < when the first one wasn't closed: " << filename << ":" << linenumber << std::endl;
958 errorstream << "We're in a quote but outside a tag, interesting. " << filename << ":" << linenumber << std::endl;
963 // errorstream << "Opening new config tag on line " << linenumber << std::endl;
974 // errorstream << "Closing quote in config tag on line " << linenumber << std::endl;
979 // errorstream << "Opening quote in config tag on line " << linenumber << std::endl;
987 errorstream << "Found a (closing) \" outside a tag: " << filename << ":" << linenumber << std::endl;
991 errorstream << "Found a (opening) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1001 // errorstream << "Closing config tag on line " << linenumber << std::endl;
1005 * If this finds an <include> then ParseLine can simply call
1006 * LoadConf() and load the included config into the same ConfigDataHash
1009 if(!this->ParseLine(target, line, linenumber, errorstream))
1016 errorstream << "Got a closing > when we weren't inside a tag: " << filename << ":" << linenumber << std::endl;
1026 bool ServerConfig::LoadConf(ConfigDataHash &target, const std::string &filename, std::ostringstream &errorstream)
1028 return this->LoadConf(target, filename.c_str(), errorstream);
1031 bool ServerConfig::ParseLine(ConfigDataHash &target, std::string &line, long linenumber, std::ostringstream &errorstream)
1033 std::string tagname;
1034 std::string current_key;
1035 std::string current_value;
1041 got_name = got_key = in_quote = false;
1043 // std::cout << "ParseLine(data, '" << line << "', " << linenumber << ", stream)" << std::endl;
1045 for(std::string::iterator c = line.begin(); c != line.end(); c++)
1049 /* We don't know the tag name yet. */
1060 /* We got to a space, we should have the tagname now. */
1061 if(tagname.length())
1069 /* We have the tag name */
1072 /* We're still reading the key name */
1082 /* We got an '=', end of the key name. */
1088 /* We have the key name, now we're looking for quotes and the value */
1090 /* Correctly handle escaped characters here.
1091 * See the XXX'ed section above.
1093 if ((*c == '\\') && (in_quote))
1096 current_value += *c;
1103 /* We're not already in a quote. */
1108 /* Leaving quotes, we have the value */
1109 results.push_back(KeyVal(current_key, current_value));
1111 // std::cout << "<" << tagname << ":" << current_key << "> " << current_value << std::endl;
1116 if((tagname == "include") && (current_key == "file"))
1118 if(!this->DoInclude(target, current_value, errorstream))
1122 current_key.clear();
1123 current_value.clear();
1130 current_value += *c;
1137 /* Finished parsing the tag, add it to the config hash */
1138 target.insert(std::pair<std::string, KeyValList > (tagname, results));
1143 bool ServerConfig::DoInclude(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream)
1145 std::string confpath;
1146 std::string newfile;
1147 std::string::size_type pos;
1149 confpath = CONFIG_FILE;
1152 for (std::string::iterator c = newfile.begin(); c != newfile.end(); c++)
1162 if((pos = confpath.find("/inspircd.conf")) != std::string::npos)
1164 /* Leaves us with just the path */
1165 newfile = confpath.substr(0, pos) + std::string("/") + newfile;
1169 errorstream << "Couldn't get config path from: " << confpath << std::endl;
1174 return LoadConf(target, newfile, errorstream);
1177 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, int index, char* result, int length)
1180 bool r = ConfValue(target, std::string(tag), std::string(var), index, value);
1181 strlcpy(result, value.c_str(), length);
1185 bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, std::string &result)
1187 ConfigDataHash::size_type pos = index;
1188 if((pos >= 0) && (pos < target.count(tag)))
1190 ConfigDataHash::const_iterator iter = target.find(tag);
1192 for(int i = 0; i < index; i++)
1195 for(KeyValList::const_iterator j = iter->second.begin(); j != iter->second.end(); j++)
1206 log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1210 log(DEBUG, "ConfValue got an out-of-range index %d, there are only %d occurences of %s", pos, target.count(tag), tag.c_str());
1216 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, int index, int &result)
1218 return ConfValueInteger(target, std::string(tag), std::string(var), index, result);
1221 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, int &result)
1224 std::istringstream stream;
1225 bool r = ConfValue(target, tag, var, index, value);
1227 if(!(stream >> result))
1232 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, int index)
1234 return ConfValueBool(target, std::string(tag), std::string(var), index);
1237 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, int index)
1240 if(!ConfValue(target, tag, var, index, result))
1243 return ((result == "yes") || (result == "true") || (result == "1"));
1246 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const char* tag)
1248 return target.count(tag);
1251 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const std::string &tag)
1253 return target.count(tag);
1256 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const char* tag, int index)
1258 return ConfVarEnum(target, std::string(tag), index);
1261 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const std::string &tag, int index)
1263 ConfigDataHash::size_type pos = index;
1265 if((pos >= 0) && (pos < target.count(tag)))
1267 ConfigDataHash::const_iterator iter = target.find(tag);
1269 for(int i = 0; i < index; i++)
1272 return iter->second.size();
1276 log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1280 log(DEBUG, "ConfVarEnum got an out-of-range index %d, there are only %d occurences of %s", pos, target.count(tag), tag.c_str());
1286 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1288 bool ServerConfig::ReadFile(file_cache &F, const char* fname)
1291 char linebuf[MAXBUF];
1294 file = fopen(fname,"r");
1300 fgets(linebuf,sizeof(linebuf),file);
1301 linebuf[strlen(linebuf)-1]='\0';
1305 strcpy(linebuf," ");
1310 F.push_back(linebuf);
1322 bool ServerConfig::FileExists(const char* file)
1325 if ((input = fopen (file, "r")) == NULL)
1336 char* ServerConfig::CleanFilename(char* name)
1338 char* p = name + strlen(name);
1339 while ((p != name) && (*p != '/')) p--;
1340 return (p != name ? ++p : p);
1344 bool ServerConfig::DirValid(const char* dirandfile)
1347 char buffer[MAXBUF];
1348 char otherdir[MAXBUF];
1351 strlcpy(work, dirandfile, MAXBUF);
1354 // we just want the dir
1366 // Get the current working directory
1367 if (getcwd(buffer, MAXBUF ) == NULL )
1372 if (getcwd(otherdir, MAXBUF ) == NULL )
1377 size_t t = strlen(work);
1379 if (strlen(otherdir) >= t)
1383 if (!strcmp(otherdir,work))
1396 std::string ServerConfig::GetFullProgDir(char** argv, int argc)
1399 char buffer[MAXBUF];
1400 char otherdir[MAXBUF];
1403 strlcpy(work,argv[0],MAXBUF);
1406 // we just want the dir
1418 // Get the current working directory
1419 if (getcwd(buffer, MAXBUF) == NULL)
1424 if (getcwd(otherdir, MAXBUF) == NULL)