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 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
33 ServerConfig::ServerConfig(InspIRCd* Instance) : ServerInstance(Instance)
36 *TempDir = *ServerName = *Network = *ServerDesc = *AdminName = '\0';
37 *HideWhoisServer = *AdminEmail = *AdminNick = *diepass = *restartpass = '\0';
38 *CustomVersion = *motd = *rules = *PrefixQuit = *DieValue = *DNSServer = '\0';
39 *OperOnlyStats = *ModPath = *MyExecutable = *DisabledCommands = *PID = '\0';
41 NoUserDns = forcedebug = OperSpyWhois = nofork = HideBans = HideSplits = false;
42 writelog = AllowHalfop = true;
43 dns_timeout = DieDelay = 5;
45 NetBufferSize = 10240;
46 SoftLimit = MAXCLIENTS;
54 void ServerConfig::ClearStack()
56 include_stack.clear();
59 Module* ServerConfig::GetIOHook(int port)
61 std::map<int,Module*>::iterator x = IOHookModule.find(port);
62 return (x != IOHookModule.end() ? x->second : NULL);
65 bool ServerConfig::AddIOHook(int port, Module* iomod)
69 IOHookModule[port] = iomod;
74 ModuleException err("Port already hooked by another module");
80 bool ServerConfig::DelIOHook(int port)
82 std::map<int,Module*>::iterator x = IOHookModule.find(port);
83 if (x != IOHookModule.end())
85 IOHookModule.erase(x);
91 bool ServerConfig::CheckOnce(char* tag, bool bail, userrec* user)
93 int count = ConfValueEnum(this->config_data, tag);
99 printf("There were errors in your configuration:\nYou have more than one <%s> tag, this is not permitted.\n",tag);
100 InspIRCd::Exit(ERROR);
106 user->WriteServ("There were errors in your configuration:");
107 user->WriteServ("You have more than one <%s> tag, this is not permitted.\n",tag);
111 ServerInstance->WriteOpers("There were errors in the configuration file:");
112 ServerInstance->WriteOpers("You have more than one <%s> tag, this is not permitted.\n",tag);
121 printf("There were errors in your configuration:\nYou have not defined a <%s> tag, this is required.\n",tag);
122 InspIRCd::Exit(ERROR);
128 user->WriteServ("There were errors in your configuration:");
129 user->WriteServ("You have not defined a <%s> tag, this is required.",tag);
133 ServerInstance->WriteOpers("There were errors in the configuration file:");
134 ServerInstance->WriteOpers("You have not defined a <%s> tag, this is required.",tag);
142 bool NoValidation(ServerConfig* conf, const char* tag, const char* value, void* data)
144 log(DEBUG,"No validation for <%s:%s>",tag,value);
148 bool ValidateTempDir(ServerConfig* conf, const char* tag, const char* value, void* data)
150 char* x = (char*)data;
152 strlcpy(x,"/tmp",1024);
156 bool ValidateMaxTargets(ServerConfig* conf, const char* tag, const char* value, void* data)
159 if ((*x < 0) || (*x > 31))
161 log(DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
167 bool ValidateSoftLimit(ServerConfig* conf, const char* tag, const char* value, void* data)
170 if ((*x < 1) || (*x > MAXCLIENTS))
172 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
178 bool ValidateMaxConn(ServerConfig* conf, const char* tag, const char* value, void* data)
182 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
188 bool ValidateDnsTimeout(ServerConfig* conf, const char* tag, const char* value, void* data)
196 bool InitializeDisabledCommands(const char* data, InspIRCd* ServerInstance)
198 std::stringstream dcmds(data);
201 /* Enable everything first */
202 for (nspace::hash_map<std::string,command_t*>::iterator x = ServerInstance->Parser->cmdlist.begin(); x != ServerInstance->Parser->cmdlist.end(); x++)
203 x->second->Disable(false);
205 /* Now disable all the ones which the user wants disabled */
206 while (dcmds >> thiscmd)
208 nspace::hash_map<std::string,command_t*>::iterator cm = ServerInstance->Parser->cmdlist.find(thiscmd);
209 if (cm != ServerInstance->Parser->cmdlist.end())
211 log(DEBUG,"Disabling command '%s'",cm->second->command.c_str());
212 cm->second->Disable(true);
218 bool ValidateDnsServer(ServerConfig* conf, const char* tag, const char* value, void* data)
220 char* x = (char*)data;
223 // attempt to look up their nameserver from /etc/resolv.conf
224 log(DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
225 ifstream resolv("/etc/resolv.conf");
226 std::string nameserver;
227 bool found_server = false;
229 if (resolv.is_open())
231 while (resolv >> nameserver)
233 if ((nameserver == "nameserver") && (!found_server))
235 resolv >> nameserver;
236 strlcpy(x,nameserver.c_str(),MAXBUF);
238 log(DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
244 log(DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
245 strlcpy(x,"127.0.0.1",MAXBUF);
250 log(DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
251 strlcpy(x,"127.0.0.1",MAXBUF);
257 bool ValidateModPath(ServerConfig* conf, const char* tag, const char* value, void* data)
259 char* x = (char*)data;
261 strlcpy(x,MOD_PATH,MAXBUF);
266 bool ValidateServerName(ServerConfig* conf, const char* tag, const char* value, void* data)
268 char* x = (char*)data;
271 log(DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s%c'",x,x,'.');
272 charlcat(x,'.',MAXBUF);
278 bool ValidateNetBufferSize(ServerConfig* conf, const char* tag, const char* value, void* data)
280 if ((!conf->NetBufferSize) || (conf->NetBufferSize > 65535) || (conf->NetBufferSize < 1024))
282 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
283 conf->NetBufferSize = 10240;
288 bool ValidateMaxWho(ServerConfig* conf, const char* tag, const char* value, void* data)
290 if ((!conf->MaxWhoResults) || (conf->MaxWhoResults > 65535) || (conf->MaxWhoResults < 1))
292 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
293 conf->MaxWhoResults = 128;
298 bool ValidateLogLevel(ServerConfig* conf, const char* tag, const char* value, void* data)
300 const char* dbg = (const char*)data;
301 conf->LogLevel = DEFAULT;
302 if (!strcmp(dbg,"debug"))
304 conf->LogLevel = DEBUG;
307 else if (!strcmp(dbg,"verbose"))
308 conf->LogLevel = VERBOSE;
309 else if (!strcmp(dbg,"default"))
310 conf->LogLevel = DEFAULT;
311 else if (!strcmp(dbg,"sparse"))
312 conf->LogLevel = SPARSE;
313 else if (!strcmp(dbg,"none"))
314 conf->LogLevel = NONE;
318 bool ValidateMotd(ServerConfig* conf, const char* tag, const char* value, void* data)
320 conf->ReadFile(conf->MOTD,conf->motd);
324 bool ValidateRules(ServerConfig* conf, const char* tag, const char* value, void* data)
326 conf->ReadFile(conf->RULES,conf->rules);
330 /* Callback called before processing the first <connect> tag
332 bool InitConnect(ServerConfig* conf, const char* tag)
334 log(DEFAULT,"Reading connect classes...");
335 conf->Classes.clear();
339 /* Callback called to process a single <connect> tag
341 bool DoConnect(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
344 char* allow = (char*)values[0]; /* Yeah, there are a lot of values. Live with it. */
345 char* deny = (char*)values[1];
346 char* password = (char*)values[2];
347 int* timeout = (int*)values[3];
348 int* pingfreq = (int*)values[4];
349 int* flood = (int*)values[5];
350 int* threshold = (int*)values[6];
351 int* sendq = (int*)values[7];
352 int* recvq = (int*)values[8];
353 int* localmax = (int*)values[9];
354 int* globalmax = (int*)values[10];
361 c.registration_timeout = *timeout;
362 c.pingtime = *pingfreq;
364 c.threshold = *threshold;
367 c.maxlocal = *localmax;
368 c.maxglobal = *globalmax;
373 if (c.maxglobal == 0)
375 if (c.threshold == 0)
379 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());
385 if (c.registration_timeout == 0)
386 c.registration_timeout = 90;
389 conf->Classes.push_back(c);
395 conf->Classes.push_back(c);
396 log(DEBUG,"Read connect class type DENY, host=%s",deny);
402 /* Callback called when there are no more <connect> tags
404 bool DoneConnect(ServerConfig* conf, const char* tag)
406 log(DEBUG,"DoneConnect called for tag: %s",tag);
410 /* Callback called before processing the first <uline> tag
412 bool InitULine(ServerConfig* conf, const char* tag)
414 conf->ulines.clear();
418 /* Callback called to process a single <uline> tag
420 bool DoULine(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
422 char* server = (char*)values[0];
423 log(DEBUG,"Read ULINE '%s'",server);
424 conf->ulines.push_back(server);
428 /* Callback called when there are no more <uline> tags
430 bool DoneULine(ServerConfig* conf, const char* tag)
435 /* Callback called before processing the first <module> tag
437 bool InitModule(ServerConfig* conf, const char* tag)
439 old_module_names.clear();
440 new_module_names.clear();
441 added_modules.clear();
442 removed_modules.clear();
443 for (std::vector<std::string>::iterator t = conf->module_names.begin(); t != conf->module_names.end(); t++)
445 old_module_names.push_back(*t);
450 /* Callback called to process a single <module> tag
452 bool DoModule(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
454 char* modname = (char*)values[0];
455 new_module_names.push_back(modname);
459 /* Callback called when there are no more <module> tags
461 bool DoneModule(ServerConfig* conf, const char* tag)
463 // now create a list of new modules that are due to be loaded
464 // and a seperate list of modules which are due to be unloaded
465 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
469 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
476 added_modules.push_back(*_new);
479 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
482 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
489 removed_modules.push_back(*oldm);
494 /* Callback called before processing the first <banlist> tag
496 bool InitMaxBans(ServerConfig* conf, const char* tag)
498 conf->maxbans.clear();
502 /* Callback called to process a single <banlist> tag
504 bool DoMaxBans(ServerConfig* conf, const char* tag, char** entries, void** values, int* types)
506 char* channel = (char*)values[0];
507 int* limit = (int*)values[1];
508 conf->maxbans[channel] = *limit;
512 /* Callback called when there are no more <banlist> tags.
514 bool DoneMaxBans(ServerConfig* conf, const char* tag)
519 void ServerConfig::Read(bool bail, userrec* user)
521 char debug[MAXBUF]; /* Temporary buffer for debugging value */
522 char* data[12]; /* Temporary buffers for reading multiple occurance tags into */
523 void* ptr[12]; /* Temporary pointers for passing to callbacks */
524 int r_i[12]; /* Temporary array for casting */
525 int rem = 0, add = 0; /* Number of modules added, number of modules removed */
526 std::ostringstream errstr; /* String stream containing the error output */
528 /* These tags MUST occur and must ONLY occur once in the config file */
529 static char* Once[] = { "server", "admin", "files", "power", "options", "pid", NULL };
531 /* These tags can occur ONCE or not at all */
532 static InitialConfig Values[] = {
533 {"options", "softlimit", &this->SoftLimit, DT_INTEGER, ValidateSoftLimit},
534 {"options", "somaxconn", &this->MaxConn, DT_INTEGER, ValidateMaxConn},
535 {"server", "name", &this->ServerName, DT_CHARPTR, ValidateServerName},
536 {"server", "description", &this->ServerDesc, DT_CHARPTR, NoValidation},
537 {"server", "network", &this->Network, DT_CHARPTR, NoValidation},
538 {"admin", "name", &this->AdminName, DT_CHARPTR, NoValidation},
539 {"admin", "email", &this->AdminEmail, DT_CHARPTR, NoValidation},
540 {"admin", "nick", &this->AdminNick, DT_CHARPTR, NoValidation},
541 {"files", "motd", &this->motd, DT_CHARPTR, ValidateMotd},
542 {"files", "rules", &this->rules, DT_CHARPTR, ValidateRules},
543 {"power", "diepass", &this->diepass, DT_CHARPTR, NoValidation},
544 {"power", "pauseval", &this->DieDelay, DT_INTEGER, NoValidation},
545 {"power", "restartpass", &this->restartpass, DT_CHARPTR, NoValidation},
546 {"options", "prefixquit", &this->PrefixQuit, DT_CHARPTR, NoValidation},
547 {"die", "value", &this->DieValue, DT_CHARPTR, NoValidation},
548 {"options", "loglevel", &debug, DT_CHARPTR, ValidateLogLevel},
549 {"options", "netbuffersize", &this->NetBufferSize, DT_INTEGER, ValidateNetBufferSize},
550 {"options", "maxwho", &this->MaxWhoResults, DT_INTEGER, ValidateMaxWho},
551 {"options", "allowhalfop", &this->AllowHalfop, DT_BOOLEAN, NoValidation},
552 {"dns", "server", &this->DNSServer, DT_CHARPTR, ValidateDnsServer},
553 {"dns", "timeout", &this->dns_timeout, DT_INTEGER, ValidateDnsTimeout},
554 {"options", "moduledir", &this->ModPath, DT_CHARPTR, ValidateModPath},
555 {"disabled", "commands", &this->DisabledCommands, DT_CHARPTR, NoValidation},
556 {"options", "operonlystats", &this->OperOnlyStats, DT_CHARPTR, NoValidation},
557 {"options", "customversion", &this->CustomVersion, DT_CHARPTR, NoValidation},
558 {"options", "hidesplits", &this->HideSplits, DT_BOOLEAN, NoValidation},
559 {"options", "hidebans", &this->HideBans, DT_BOOLEAN, NoValidation},
560 {"options", "hidewhois", &this->HideWhoisServer, DT_CHARPTR, NoValidation},
561 {"options", "operspywhois", &this->OperSpyWhois, DT_BOOLEAN, NoValidation},
562 {"options", "tempdir", &this->TempDir, DT_CHARPTR, ValidateTempDir},
563 {"options", "nouserdns", &this->NoUserDns, DT_BOOLEAN, NoValidation},
564 {"options", "syntaxhints", &this->SyntaxHints, DT_BOOLEAN, NoValidation},
565 {"pid", "file", &this->PID, DT_CHARPTR, NoValidation},
569 /* These tags can occur multiple times, and therefore they have special code to read them
570 * which is different to the code for reading the singular tags listed above.
572 static MultiConfig MultiValues[] = {
575 {"allow", "deny", "password", "timeout", "pingfreq", "flood",
576 "threshold", "sendq", "recvq", "localmax", "globalmax", NULL},
577 {DT_CHARPTR, DT_CHARPTR, DT_CHARPTR, DT_INTEGER, DT_INTEGER, DT_INTEGER,
578 DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER},
579 InitConnect, DoConnect, DoneConnect},
584 InitULine,DoULine,DoneULine},
587 {"chan", "limit", NULL},
588 {DT_CHARPTR, DT_INTEGER},
589 InitMaxBans, DoMaxBans, DoneMaxBans},
594 InitModule, DoModule, DoneModule},
597 {"reason", "ipmask", NULL},
598 {DT_CHARPTR, DT_CHARPTR},
599 InitXLine, DoZLine, DoneXLine},
602 {"reason", "nick", NULL},
603 {DT_CHARPTR, DT_CHARPTR},
604 InitXLine, DoQLine, DoneXLine},
607 {"reason", "host", NULL},
608 {DT_CHARPTR, DT_CHARPTR},
609 InitXLine, DoKLine, DoneXLine},
612 {"reason", "host", NULL},
613 {DT_CHARPTR, DT_CHARPTR},
614 InitXLine, DoELine, DoneXLine},
617 {"name", "classes", NULL},
618 {DT_CHARPTR, DT_CHARPTR},
619 InitTypes, DoType, DoneClassesAndTypes},
622 {"name", "commands", NULL},
623 {DT_CHARPTR, DT_CHARPTR},
624 InitClasses, DoClass, DoneClassesAndTypes},
629 include_stack.clear();
631 /* Load and parse the config file, if there are any errors then explode */
633 /* Make a copy here so if it fails then we can carry on running with an unaffected config */
634 ConfigDataHash newconfig;
636 if (this->LoadConf(newconfig, CONFIG_FILE, errstr))
638 /* If we succeeded, set the ircd config to the new one */
639 this->config_data = newconfig;
644 for(ConfigDataHash::const_iterator i = this->config_data.begin(); i != this->config_data.end(); i++)
646 c = (i->first != last) ? 1 : c+1;
649 std::cout << "[" << i->first << " " << c << "/" << this->config_data.count(i->first) << "]" << std::endl;
651 for(KeyValList::const_iterator j = i->second.begin(); j != i->second.end(); j++)
652 std::cout << "\t" << j->first << " = " << j->second << std::endl;
654 std::cout << "[/" << i->first << " " << c << "/" << this->config_data.count(i->first) << "]" << std::endl;
659 log(DEFAULT, "There were errors in your configuration:\n%s", errstr.str().c_str());
663 /* Unneeded because of the log() aboive? */
664 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
665 InspIRCd::Exit(ERROR);
669 std::string errors = errstr.str();
670 std::string::size_type start;
671 unsigned int prefixlen;
674 /* ":ServerInstance->Config->ServerName NOTICE user->nick :" */
675 prefixlen = strlen(this->ServerName) + strlen(user->nick) + 11;
679 user->WriteServ("NOTICE %s :There were errors in the configuration file:",user->nick);
681 while(start < errors.length())
683 user->WriteServ("NOTICE %s :%s",user->nick, errors.substr(start, 510 - prefixlen).c_str());
684 start += 510 - prefixlen;
689 ServerInstance->WriteOpers("There were errors in the configuration file:");
691 while(start < errors.length())
693 ServerInstance->WriteOpers(errors.substr(start, 360).c_str());
702 /* Check we dont have more than one of singular tags, or any of them missing
704 for (int Index = 0; Once[Index]; Index++)
705 if (!CheckOnce(Once[Index],bail,user))
708 /* Read the values of all the tags which occur once or not at all, and call their callbacks.
710 for (int Index = 0; Values[Index].tag; Index++)
712 int* val_i = (int*) Values[Index].val;
713 char* val_c = (char*) Values[Index].val;
715 switch (Values[Index].datatype)
718 /* Assuming MAXBUF here, potentially unsafe */
719 ConfValue(this->config_data, Values[Index].tag, Values[Index].value, 0, val_c, MAXBUF);
723 ConfValueInteger(this->config_data, Values[Index].tag, Values[Index].value, 0, *val_i);
727 *val_i = ConfValueBool(this->config_data, Values[Index].tag, Values[Index].value, 0);
734 Values[Index].validation_function(this, Values[Index].tag, Values[Index].value, Values[Index].val);
737 /* Claim memory for use when reading multiple tags
739 for (int n = 0; n < 12; n++)
740 data[n] = new char[MAXBUF];
742 /* Read the multiple-tag items (class tags, connect tags, etc)
743 * and call the callbacks associated with them. We have three
744 * callbacks for these, a 'start', 'item' and 'end' callback.
747 /* XXX - Make this use ConfValueInteger and so on */
748 for (int Index = 0; MultiValues[Index].tag; Index++)
750 MultiValues[Index].init_function(this, MultiValues[Index].tag);
752 int number_of_tags = ConfValueEnum(this->config_data, MultiValues[Index].tag);
754 for (int tagnum = 0; tagnum < number_of_tags; tagnum++)
756 for (int valuenum = 0; MultiValues[Index].items[valuenum]; valuenum++)
758 ConfValue(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], tagnum, data[valuenum], MAXBUF);
760 switch (MultiValues[Index].datatype[valuenum])
763 ptr[valuenum] = data[valuenum];
766 r_i[valuenum] = atoi(data[valuenum]);
767 ptr[valuenum] = &r_i[valuenum];
770 r_i[valuenum] = ((*data[valuenum] == tolower('y')) || (*data[valuenum] == tolower('t')) || (*data[valuenum] == '1'));
771 ptr[valuenum] = &r_i[valuenum];
777 MultiValues[Index].validation_function(this, MultiValues[Index].tag, (char**)MultiValues[Index].items, ptr, MultiValues[Index].datatype);
780 MultiValues[Index].finish_function(this, MultiValues[Index].tag);
783 /* Free any memory we claimed
785 for (int n = 0; n < 12; n++)
788 // write once here, to try it out and make sure its ok
789 ServerInstance->WritePID(this->PID);
791 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
793 /* If we're rehashing, let's load any new modules, and unload old ones
797 ServerInstance->stats->BoundPortCount = ServerInstance->BindPorts(false);
799 if (!removed_modules.empty())
800 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
802 if (ServerInstance->UnloadModule(removing->c_str()))
804 ServerInstance->WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
807 user->WriteServ("973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
814 user->WriteServ("972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
818 if (!added_modules.empty())
819 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
821 if (ServerInstance->LoadModule(adding->c_str()))
823 ServerInstance->WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
826 user->WriteServ("975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
833 user->WriteServ("974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
837 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());
841 bool ServerConfig::LoadConf(ConfigDataHash &target, const char* filename, std::ostringstream &errorstream)
843 std::ifstream conf(filename);
856 /* Check if the file open failed first */
859 errorstream << "LoadConf: Couldn't open config file: " << filename << std::endl;
863 /* Fix the chmod of the file to restrict it to the current user and group */
864 chmod(filename,0600);
866 for (unsigned int t = 0; t < include_stack.size(); t++)
868 if (std::string(filename) == include_stack[t])
870 errorstream << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
875 /* It's not already included, add it to the list of files we've loaded */
876 include_stack.push_back(filename);
878 /* Start reading characters... */
882 * Here we try and get individual tags on separate lines,
883 * this would be so easy if we just made people format
884 * their config files like that, but they don't so...
885 * We check for a '<' and then know the line is over when
886 * we get a '>' not inside quotes. If we find two '<' and
887 * no '>' then die with an error.
890 if((ch == '#') && !in_quote)
893 if(((ch == '\n') || (ch == '\r')) && in_quote)
895 errorstream << "Got a newline within a quoted section, this is probably a typo: " << filename << ":" << linenumber << std::endl;
914 /* XXX: Added by Brain, May 1st 2006 - Escaping of characters.
915 * Note that this WILL NOT usually allow insertion of newlines,
916 * because a newline is two characters long. Use it primarily to
917 * insert the " symbol.
919 * Note that this also involves a further check when parsing the line,
920 * which can be found below.
922 if ((ch == '\\') && (in_quote) && (in_tag))
925 log(DEBUG,"Escape sequence in config line.");
927 if (conf.get(real_character))
929 log(DEBUG,"Escaping %c", real_character);
930 line += real_character;
935 errorstream << "End of file after a \\, what did you want to escape?: " << filename << ":" << linenumber << std::endl;
948 errorstream << "Got another opening < when the first one wasn't closed: " << filename << ":" << linenumber << std::endl;
956 errorstream << "We're in a quote but outside a tag, interesting. " << filename << ":" << linenumber << std::endl;
961 // errorstream << "Opening new config tag on line " << linenumber << std::endl;
972 // errorstream << "Closing quote in config tag on line " << linenumber << std::endl;
977 // errorstream << "Opening quote in config tag on line " << linenumber << std::endl;
985 errorstream << "Found a (closing) \" outside a tag: " << filename << ":" << linenumber << std::endl;
989 errorstream << "Found a (opening) \" outside a tag: " << filename << ":" << linenumber << std::endl;
999 // errorstream << "Closing config tag on line " << linenumber << std::endl;
1003 * If this finds an <include> then ParseLine can simply call
1004 * LoadConf() and load the included config into the same ConfigDataHash
1007 if(!this->ParseLine(target, line, linenumber, errorstream))
1014 errorstream << "Got a closing > when we weren't inside a tag: " << filename << ":" << linenumber << std::endl;
1024 bool ServerConfig::LoadConf(ConfigDataHash &target, const std::string &filename, std::ostringstream &errorstream)
1026 return this->LoadConf(target, filename.c_str(), errorstream);
1029 bool ServerConfig::ParseLine(ConfigDataHash &target, std::string &line, long linenumber, std::ostringstream &errorstream)
1031 std::string tagname;
1032 std::string current_key;
1033 std::string current_value;
1039 got_name = got_key = in_quote = false;
1041 // std::cout << "ParseLine(data, '" << line << "', " << linenumber << ", stream)" << std::endl;
1043 for(std::string::iterator c = line.begin(); c != line.end(); c++)
1047 /* We don't know the tag name yet. */
1058 /* We got to a space, we should have the tagname now. */
1059 if(tagname.length())
1067 /* We have the tag name */
1070 /* We're still reading the key name */
1080 /* We got an '=', end of the key name. */
1086 /* We have the key name, now we're looking for quotes and the value */
1088 /* Correctly handle escaped characters here.
1089 * See the XXX'ed section above.
1091 if ((*c == '\\') && (in_quote))
1094 current_value += *c;
1101 /* We're not already in a quote. */
1106 /* Leaving quotes, we have the value */
1107 results.push_back(KeyVal(current_key, current_value));
1109 // std::cout << "<" << tagname << ":" << current_key << "> " << current_value << std::endl;
1114 if((tagname == "include") && (current_key == "file"))
1116 if(!this->DoInclude(target, current_value, errorstream))
1120 current_key.clear();
1121 current_value.clear();
1128 current_value += *c;
1135 /* Finished parsing the tag, add it to the config hash */
1136 target.insert(std::pair<std::string, KeyValList > (tagname, results));
1141 bool ServerConfig::DoInclude(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream)
1143 std::string confpath;
1144 std::string newfile;
1145 std::string::size_type pos;
1147 confpath = CONFIG_FILE;
1150 for (std::string::iterator c = newfile.begin(); c != newfile.end(); c++)
1160 if((pos = confpath.find("/inspircd.conf")) != std::string::npos)
1162 /* Leaves us with just the path */
1163 newfile = confpath.substr(0, pos) + std::string("/") + newfile;
1167 errorstream << "Couldn't get config path from: " << confpath << std::endl;
1172 return LoadConf(target, newfile, errorstream);
1175 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, int index, char* result, int length)
1178 bool r = ConfValue(target, std::string(tag), std::string(var), index, value);
1179 strlcpy(result, value.c_str(), length);
1183 bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, std::string &result)
1185 ConfigDataHash::size_type pos = index;
1186 if((pos >= 0) && (pos < target.count(tag)))
1188 ConfigDataHash::const_iterator iter = target.find(tag);
1190 for(int i = 0; i < index; i++)
1193 for(KeyValList::const_iterator j = iter->second.begin(); j != iter->second.end(); j++)
1204 log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1208 log(DEBUG, "ConfValue got an out-of-range index %d, there are only %d occurences of %s", pos, target.count(tag), tag.c_str());
1214 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, int index, int &result)
1216 return ConfValueInteger(target, std::string(tag), std::string(var), index, result);
1219 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, int &result)
1222 std::istringstream stream;
1223 bool r = ConfValue(target, tag, var, index, value);
1225 if(!(stream >> result))
1230 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, int index)
1232 return ConfValueBool(target, std::string(tag), std::string(var), index);
1235 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, int index)
1238 if(!ConfValue(target, tag, var, index, result))
1241 return ((result == "yes") || (result == "true") || (result == "1"));
1244 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const char* tag)
1246 return target.count(tag);
1249 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const std::string &tag)
1251 return target.count(tag);
1254 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const char* tag, int index)
1256 return ConfVarEnum(target, std::string(tag), index);
1259 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const std::string &tag, int index)
1261 ConfigDataHash::size_type pos = index;
1263 if((pos >= 0) && (pos < target.count(tag)))
1265 ConfigDataHash::const_iterator iter = target.find(tag);
1267 for(int i = 0; i < index; i++)
1270 return iter->second.size();
1274 log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1278 log(DEBUG, "ConfVarEnum got an out-of-range index %d, there are only %d occurences of %s", pos, target.count(tag), tag.c_str());
1284 /** Read the contents of a file located by `fname' into a file_cache pointed at by `F'.
1286 bool ServerConfig::ReadFile(file_cache &F, const char* fname)
1289 char linebuf[MAXBUF];
1292 file = fopen(fname,"r");
1298 fgets(linebuf,sizeof(linebuf),file);
1299 linebuf[strlen(linebuf)-1]='\0';
1303 strcpy(linebuf," ");
1308 F.push_back(linebuf);
1320 bool ServerConfig::FileExists(const char* file)
1323 if ((input = fopen (file, "r")) == NULL)
1334 char* ServerConfig::CleanFilename(char* name)
1336 char* p = name + strlen(name);
1337 while ((p != name) && (*p != '/')) p--;
1338 return (p != name ? ++p : p);
1342 bool ServerConfig::DirValid(const char* dirandfile)
1345 char buffer[MAXBUF];
1346 char otherdir[MAXBUF];
1349 strlcpy(work, dirandfile, MAXBUF);
1352 // we just want the dir
1364 // Get the current working directory
1365 if (getcwd(buffer, MAXBUF ) == NULL )
1370 if (getcwd(otherdir, MAXBUF ) == NULL )
1375 size_t t = strlen(work);
1377 if (strlen(otherdir) >= t)
1381 if (!strcmp(otherdir,work))
1394 std::string ServerConfig::GetFullProgDir(char** argv, int argc)
1397 char buffer[MAXBUF];
1398 char otherdir[MAXBUF];
1401 strlcpy(work,argv[0],MAXBUF);
1404 // we just want the dir
1416 // Get the current working directory
1417 if (getcwd(buffer, MAXBUF) == NULL)
1422 if (getcwd(otherdir, MAXBUF) == NULL)