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 * ---------------------------------------------------
19 #include "inspircd_config.h"
21 #include <sys/resource.h>
22 #include <sys/types.h>
29 #include "inspircd_io.h"
30 #include "inspstring.h"
31 #include "helperfuncs.h"
32 #include "userprocess.h"
35 extern ServerConfig *Config;
36 extern InspIRCd* ServerInstance;
37 extern int openSockfd[MAXSOCKS];
41 extern std::vector<Module*> modules;
42 extern std::vector<ircd_module*> factory;
44 ServerConfig::ServerConfig()
47 *TempDir = *ServerName = *Network = *ServerDesc = *AdminName = '\0';
48 *HideWhoisServer = *AdminEmail = *AdminNick = *diepass = *restartpass = '\0';
49 *CustomVersion = *motd = *rules = *PrefixQuit = *DieValue = *DNSServer = '\0';
50 *OperOnlyStats = *ModPath = *MyExecutable = *DisabledCommands = *PID = '\0';
52 nofork = HideBans = HideSplits = unlimitcore = false;
54 dns_timeout = DieDelay = 5;
56 NetBufferSize = 10240;
57 SoftLimit = MAXCLIENTS;
65 void ServerConfig::ClearStack()
67 include_stack.clear();
70 Module* ServerConfig::GetIOHook(int port)
72 std::map<int,Module*>::iterator x = IOHookModule.find(port);
73 return (x != IOHookModule.end() ? x->second : NULL);
76 bool ServerConfig::AddIOHook(int port, Module* iomod)
80 IOHookModule[port] = iomod;
85 ModuleException err("Port already hooked by another module");
91 bool ServerConfig::DelIOHook(int port)
93 std::map<int,Module*>::iterator x = IOHookModule.find(port);
94 if (x != IOHookModule.end())
96 IOHookModule.erase(x);
102 bool ServerConfig::CheckOnce(char* tag, bool bail, userrec* user)
104 int count = ConfValueEnum(tag,&Config->config_f);
109 printf("There were errors in your configuration:\nYou have more than one <%s> tag, this is not permitted.\n",tag);
116 WriteServ(user->fd,"There were errors in your configuration:");
117 WriteServ(user->fd,"You have more than one <%s> tag, this is not permitted.\n",tag);
121 WriteOpers("There were errors in the configuration file:");
122 WriteOpers("You have more than one <%s> tag, this is not permitted.\n",tag);
131 printf("There were errors in your configuration:\nYou have not defined a <%s> tag, this is required.\n",tag);
138 WriteServ(user->fd,"There were errors in your configuration:");
139 WriteServ(user->fd,"You have not defined a <%s> tag, this is required.",tag);
143 WriteOpers("There were errors in the configuration file:");
144 WriteOpers("You have not defined a <%s> tag, this is required.",tag);
152 bool NoValidation(const char* tag, const char* value, void* data)
154 log(DEBUG,"No validation for <%s:%s>",tag,value);
158 bool ValidateTempDir(const char* tag, const char* value, void* data)
160 char* x = (char*)data;
162 strlcpy(x,"/tmp",1024);
166 bool ValidateMaxTargets(const char* tag, const char* value, void* data)
169 if ((*x < 0) || (*x > 31))
171 log(DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
177 bool ValidateSoftLimit(const char* tag, const char* value, void* data)
180 if ((*x < 1) || (*x > MAXCLIENTS))
182 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
188 bool ValidateMaxConn(const char* tag, const char* value, void* data)
192 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
198 bool ValidateDnsTimeout(const char* tag, const char* value, void* data)
206 bool ValidateDnsServer(const char* tag, const char* value, void* data)
208 char* x = (char*)data;
211 // attempt to look up their nameserver from /etc/resolv.conf
212 log(DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
213 ifstream resolv("/etc/resolv.conf");
214 std::string nameserver;
215 bool found_server = false;
217 if (resolv.is_open())
219 while (resolv >> nameserver)
221 if ((nameserver == "nameserver") && (!found_server))
223 resolv >> nameserver;
224 strlcpy(x,nameserver.c_str(),MAXBUF);
226 log(DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
232 log(DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
233 strlcpy(x,"127.0.0.1",MAXBUF);
238 log(DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
239 strlcpy(x,"127.0.0.1",MAXBUF);
245 bool ValidateModPath(const char* tag, const char* value, void* data)
247 char* x = (char*)data;
249 strlcpy(x,MOD_PATH,MAXBUF);
254 bool ValidateServerName(const char* tag, const char* value, void* data)
256 char* x = (char*)data;
259 log(DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s%c'",x,x,'.');
260 charlcat(x,'.',MAXBUF);
266 bool ValidateNetBufferSize(const char* tag, const char* value, void* data)
268 if ((!Config->NetBufferSize) || (Config->NetBufferSize > 65535) || (Config->NetBufferSize < 1024))
270 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
271 Config->NetBufferSize = 10240;
276 bool ValidateMaxWho(const char* tag, const char* value, void* data)
278 if ((!Config->MaxWhoResults) || (Config->MaxWhoResults > 65535) || (Config->MaxWhoResults < 1))
280 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
281 Config->MaxWhoResults = 128;
286 bool ValidateLogLevel(const char* tag, const char* value, void* data)
288 const char* dbg = (const char*)data;
289 Config->LogLevel = DEFAULT;
290 if (!strcmp(dbg,"debug"))
292 Config->LogLevel = DEBUG;
293 Config->debugging = 1;
295 else if (!strcmp(dbg,"verbose"))
296 Config->LogLevel = VERBOSE;
297 else if (!strcmp(dbg,"default"))
298 Config->LogLevel = DEFAULT;
299 else if (!strcmp(dbg,"sparse"))
300 Config->LogLevel = SPARSE;
301 else if (!strcmp(dbg,"none"))
302 Config->LogLevel = NONE;
306 bool ValidateMotd(const char* tag, const char* value, void* data)
308 readfile(Config->MOTD,Config->motd);
312 bool ValidateRules(const char* tag, const char* value, void* data)
314 readfile(Config->RULES,Config->rules);
319 void ServerConfig::Read(bool bail, userrec* user)
322 char CM1[MAXBUF],CM2[MAXBUF];
323 char ServName[MAXBUF],Value[MAXBUF];
326 std::stringstream errstr;
328 static InitialConfig Values[] = {
329 {"options", "softlimit", &this->SoftLimit, DT_INTEGER, ValidateSoftLimit},
330 {"options", "somaxconn", &this->MaxConn, DT_INTEGER, ValidateMaxConn},
331 {"server", "name", &this->ServerName, DT_CHARPTR, ValidateServerName},
332 {"server", "description", &this->ServerDesc, DT_CHARPTR, NoValidation},
333 {"server", "network", &this->Network, DT_CHARPTR, NoValidation},
334 {"admin", "name", &this->AdminName, DT_CHARPTR, NoValidation},
335 {"admin", "email", &this->AdminEmail, DT_CHARPTR, NoValidation},
336 {"admin", "nick", &this->AdminNick, DT_CHARPTR, NoValidation},
337 {"files", "motd", &this->motd, DT_CHARPTR, ValidateMotd},
338 {"files", "rules", &this->rules, DT_CHARPTR, ValidateRules},
339 {"power", "diepass", &this->diepass, DT_CHARPTR, NoValidation},
340 {"power", "pauseval", &this->DieDelay, DT_INTEGER, NoValidation},
341 {"power", "restartpass", &this->restartpass, DT_CHARPTR, NoValidation},
342 {"options", "prefixquit", &this->PrefixQuit, DT_CHARPTR, NoValidation},
343 {"die", "value", &this->DieValue, DT_CHARPTR, NoValidation},
344 {"options", "loglevel", &debug, DT_CHARPTR, ValidateLogLevel},
345 {"options", "netbuffersize", &this->NetBufferSize, DT_INTEGER, ValidateNetBufferSize},
346 {"options", "maxwho", &this->MaxWhoResults, DT_INTEGER, ValidateMaxWho},
347 {"options", "allowhalfop", &this->AllowHalfop, DT_BOOLEAN, NoValidation},
348 {"dns", "server", &this->DNSServer, DT_CHARPTR, ValidateDnsServer},
349 {"dns", "timeout", &this->dns_timeout, DT_INTEGER, ValidateDnsTimeout},
350 {"options", "moduledir", &this->ModPath, DT_CHARPTR, ValidateModPath},
351 {"disabled", "commands", &this->DisabledCommands, DT_CHARPTR, NoValidation},
352 {"options", "operonlystats", &this->OperOnlyStats, DT_CHARPTR, NoValidation},
353 {"options", "customversion", &this->CustomVersion, DT_CHARPTR, NoValidation},
354 {"options", "hidesplits", &this->HideSplits, DT_BOOLEAN, NoValidation},
355 {"options", "hidebans", &this->HideBans, DT_BOOLEAN, NoValidation},
356 {"options", "hidewhois", &this->HideWhoisServer, DT_CHARPTR, NoValidation},
357 {"options", "tempdir", &this->TempDir, DT_CHARPTR, ValidateTempDir},
361 include_stack.clear();
363 if (!LoadConf(CONFIG_FILE,&Config->config_f,&errstr))
366 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
370 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
377 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
378 while (!errstr.eof())
380 errstr.getline(dataline,1024);
381 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
386 WriteOpers("There were errors in the configuration file:");
387 while (!errstr.eof())
389 errstr.getline(dataline,1024);
390 WriteOpers(dataline);
398 /* Check we dont have more than one of singular tags
400 if (!CheckOnce("server",bail,user) || !CheckOnce("admin",bail,user) || !CheckOnce("files",bail,user)
401 || !CheckOnce("power",bail,user) || !CheckOnce("options",bail,user) || !CheckOnce("pid",bail,user))
407 for (int Index = 0; Values[Index].tag; Index++)
409 int* val_i = (int*) Values[Index].val;
410 char* val_c = (char*) Values[Index].val;
412 switch (Values[Index].datatype)
415 ConfValue(Values[Index].tag, Values[Index].value, 0, val_c, &this->config_f);
419 convert = new char[MAXBUF];
420 ConfValue(Values[Index].tag, Values[Index].value, 0, convert, &this->config_f);
421 *val_i = atoi(convert);
426 convert = new char[MAXBUF];
427 ConfValue(Values[Index].tag, Values[Index].value, 0, convert, &this->config_f);
428 *val_i = ((*convert == tolower('y')) || (*convert == tolower('t')) || (*convert == '1'));
436 Values[Index].validation_function(Values[Index].tag, Values[Index].value, Values[Index].val);
439 log(DEFAULT,"Reading connect classes...");
442 for (int i = 0; i < ConfValueEnum("connect",&Config->config_f); i++)
445 ConfValue("connect","allow",i,Value,&Config->config_f);
451 ConfValue("connect","password",i,Value,&Config->config_f);
453 c.registration_timeout = ConfValueInteger("connect","timeout",i,&Config->config_f); // default is 2 minutes
454 c.pingtime = ConfValueInteger("connect","pingfreq",i,&Config->config_f);
455 c.flood = ConfValueInteger("connect","flood",i,&Config->config_f);
456 c.threshold = ConfValueInteger("connect","threshold",i,&Config->config_f);
457 c.sendqmax = ConfValueInteger("connect","sendq",i,&Config->config_f);
458 c.recvqmax = ConfValueInteger("connect","recvq",i,&Config->config_f);
459 c.maxlocal = ConfValueInteger("connect","localmax",i,&Config->config_f);
460 c.maxglobal = ConfValueInteger("connect","globalmax",i,&Config->config_f);
468 if (c.maxglobal == 0)
473 if (c.threshold == 0)
477 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());
488 if (c.registration_timeout == 0)
490 c.registration_timeout = 90;
497 Classes.push_back(c);
501 ConfValue("connect","deny",i,Value,&Config->config_f);
504 Classes.push_back(c);
505 log(DEBUG,"Read connect class type DENY, host=%s",c.host.c_str());
509 Config->ulines.clear();
511 for (int i = 0; i < ConfValueEnum("uline",&Config->config_f); i++)
513 ConfValue("uline","server",i,ServName,&Config->config_f);
515 log(DEBUG,"Read ULINE '%s'",ServName);
516 Config->ulines.push_back(ServName);
522 for (int count = 0; count < Config->ConfValueEnum("banlist",&Config->config_f); count++)
524 Config->ConfValue("banlist","chan",count,CM1,&Config->config_f);
525 Config->ConfValue("banlist","limit",count,CM2,&Config->config_f);
526 maxbans[CM1] = atoi(CM2);
529 ReadClassesAndTypes();
530 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
531 read_xline_defaults();
532 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
533 apply_lines(APPLY_ALL);
535 ConfValue("pid","file",0,Config->PID,&Config->config_f);
536 // write once here, to try it out and make sure its ok
537 WritePID(Config->PID);
539 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
542 log(DEFAULT,"Adding and removing modules due to rehash...");
544 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
546 // store the old module names
547 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
549 old_module_names.push_back(*t);
552 // get the new module names
553 for (int count2 = 0; count2 < ConfValueEnum("module",&Config->config_f); count2++)
555 ConfValue("module","name",count2,Value,&Config->config_f);
556 new_module_names.push_back(Value);
559 // now create a list of new modules that are due to be loaded
560 // and a seperate list of modules which are due to be unloaded
561 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
565 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
572 added_modules.push_back(*_new);
575 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
578 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
585 removed_modules.push_back(*oldm);
589 * now we have added_modules, a vector of modules to be loaded,
590 * and removed_modules, a vector of modules
593 int rem = 0, add = 0;
594 if (!removed_modules.empty())
595 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
597 if (ServerInstance->UnloadModule(removing->c_str()))
599 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
602 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
609 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
613 if (!added_modules.empty())
614 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
616 if (ServerInstance->LoadModule(adding->c_str()))
618 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
621 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
628 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
632 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());
637 void Exit (int status)
639 if (Config->log_file)
640 fclose(Config->log_file);
641 send_error("Server shutdown.");
645 void Killed(int status)
647 if (Config->log_file)
648 fclose(Config->log_file);
649 send_error("Server terminated.");
653 char* CleanFilename(char* name)
655 char* p = name + strlen(name);
656 while ((p != name) && (*p != '/')) p--;
657 return (p != name ? ++p : p);
661 void Rehash(int status)
663 WriteOpers("Rehashing config file %s due to SIGHUP",CleanFilename(CONFIG_FILE));
664 fclose(Config->log_file);
666 Config->Read(false,NULL);
667 FOREACH_MOD(I_OnRehash,OnRehash(""));
674 printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
675 printf("(C) ChatSpike Development team.\033[0m\n\n");
676 printf("Developers:\033[1;32m Brain, FrostyCoolSlug, w00t, Om\033[0m\n");
677 printf("Others:\033[1;32m See /INFO Output\033[0m\n");
678 printf("Name concept:\033[1;32m Lord_Zathras\033[0m\n\n");
681 void WritePID(std::string filename)
683 ofstream outfile(filename.c_str());
684 if (outfile.is_open())
691 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
692 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
699 signal (SIGALRM, SIG_IGN);
700 signal (SIGHUP, Rehash);
701 signal (SIGPIPE, SIG_IGN);
702 signal (SIGTERM, Exit);
703 signal (SIGSEGV, Error);
707 int DaemonSeed (void)
710 if ((childpid = fork ()) < 0)
712 else if (childpid > 0)
714 /* We wait a few seconds here, so that the shell prompt doesnt come back over the output */
720 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
722 if (Config->unlimitcore)
725 if (getrlimit(RLIMIT_CORE, &rl) == -1)
727 log(DEFAULT,"Failed to getrlimit()!");
732 rl.rlim_cur = rl.rlim_max;
733 if (setrlimit(RLIMIT_CORE, &rl) == -1)
734 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
742 /* Make Sure Modules Are Avaliable!
743 * (BugFix By Craig.. See? I do work! :p)
744 * Modified by brain, requires const char*
745 * to work with other API functions
748 bool FileExists (const char* file)
751 if ((input = fopen (file, "r")) == NULL)
762 /* ConfProcess does the following things to a config line in the following order:
764 * Processes the line for syntax errors as shown below
765 * (1) Line void of quotes or equals (a malformed, illegal tag format)
766 * (2) Odd number of quotes on the line indicating a missing quote
767 * (3) number of equals signs not equal to number of quotes / 2 (missing an equals sign)
768 * (4) Spaces between the opening bracket (<) and the keyword
769 * (5) Spaces between a keyword and an equals sign
770 * (6) Spaces between an equals sign and a quote
771 * Removes trailing spaces
772 * Removes leading spaces
773 * Converts tabs to spaces
774 * Turns multiple spaces that are outside of quotes into single spaces
777 std::string ServerConfig::ConfProcess(char* buffer, long linenumber, std::stringstream* errorstream, bool &error, std::string filename)
779 long number_of_quotes = 0;
780 long number_of_equals = 0;
781 bool has_open_bracket = false;
782 bool in_quotes = false;
788 // firstly clean up the line by stripping spaces from the start and end and converting tabs to spaces
789 for (char* d = buffer; *d; d++)
792 while (*buffer == ' ') buffer++;
793 while ((buffer[strlen(buffer)-1] == ' ') && (*buffer)) buffer[strlen(buffer)-1] = '\0';
795 // empty lines are syntactically valid, as are comments
796 if (!(*buffer) || buffer[0] == '#')
799 for (unsigned int c = 0; c < strlen(buffer); c++)
801 // convert all spaces that are OUTSIDE quotes into hardspace (0xA0) as this will make them easier to
802 // search and replace later :)
803 if ((!in_quotes) && (buffer[c] == ' '))
805 if ((buffer[c] == '<') && (!in_quotes))
807 has_open_bracket = true;
808 if (strlen(buffer) == 1)
810 *errorstream << "Tag without identifier at " << filename << ":" << linenumber << endl;
814 else if ((tolower(buffer[c+1]) < 'a') || (tolower(buffer[c+1]) > 'z'))
816 *errorstream << "Invalid characters in identifier at " << filename << ":" << linenumber << endl;
821 if (buffer[c] == '"')
824 in_quotes = (!in_quotes);
826 if ((buffer[c] == '=') && (!in_quotes))
829 if (strlen(buffer) == c)
831 *errorstream << "Variable without a value at " << filename << ":" << linenumber << endl;
835 else if (buffer[c+1] != '"')
837 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
843 *errorstream << "Value without a variable (line starts with '=') at " << filename << ":" << linenumber << endl;
847 else if (buffer[c-1] == '\xA0')
849 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
855 // no quotes, and no equals. something freaky.
856 if ((!number_of_quotes) || (!number_of_equals) && (strlen(buffer)>2) && (buffer[0]=='<'))
858 *errorstream << "Malformed tag at " << filename << ":" << linenumber << endl;
862 // odd number of quotes. thats just wrong.
863 if ((number_of_quotes % 2) != 0)
865 *errorstream << "Missing \" at " << filename << ":" << linenumber << endl;
869 if (number_of_equals < (number_of_quotes/2))
871 *errorstream << "Missing '=' at " << filename << ":" << linenumber << endl;
873 if (number_of_equals > (number_of_quotes/2))
875 *errorstream << "Too many '=' at " << filename << ":" << linenumber << endl;
878 std::string parsedata = buffer;
879 // turn multispace into single space
880 while (parsedata.find("\xA0\xA0") != std::string::npos)
882 parsedata.erase(parsedata.find("\xA0\xA0"),1);
885 // turn our hardspace back into softspace
886 for (unsigned int d = 0; d < parsedata.length(); d++)
888 if (parsedata[d] == '\xA0')
892 // and we're done, the line is fine!
896 int ServerConfig::fgets_safe(char* buffer, size_t maxsize, FILE* &file)
899 unsigned int bufptr = 0;
900 while ((!feof(file)) && (c_read != '\n') && (c_read != '\r') && (bufptr < maxsize))
902 c_read = fgetc(file);
903 if ((c_read != '\n') && (c_read != '\r'))
904 buffer[bufptr++] = c_read;
906 buffer[bufptr] = '\0';
910 bool ServerConfig::LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream)
913 errorstream->str("");
915 // first, check that the file exists before we try to do anything with it
916 if (!FileExists(filename))
918 *errorstream << "File " << filename << " not found." << endl;
921 // Fix the chmod of the file to restrict it to the current user and group
922 chmod(filename,0600);
923 for (unsigned int t = 0; t < include_stack.size(); t++)
925 if (std::string(filename) == include_stack[t])
927 *errorstream << "File " << filename << " is included recursively (looped inclusion)." << endl;
931 include_stack.push_back(filename);
933 FILE* conf = fopen(filename,"r");
939 if (fgets_safe(buffer, MAXBUF, conf))
941 if ((!feof(conf)) && (buffer) && (strlen(buffer)))
943 if ((buffer[0] != '#') && (buffer[0] != '\r') && (buffer[0] != '\n'))
945 if (!strncmp(buffer,"<include file=\"",15))
948 char confpath[10240],newconf[10240];
949 // include file directive
950 buf += 15; // advance to filename
951 for (unsigned int j = 0; j < strlen(buf); j++)
961 log(DEBUG,"Opening included file '%s'",buf);
964 strlcpy(confpath,CONFIG_FILE,10240);
965 if (strstr(confpath,"/inspircd.conf"))
967 // leaves us with just the path
968 *(strstr(confpath,"/inspircd.conf")) = '\0';
970 snprintf(newconf,10240,"%s/%s",confpath,buf);
972 else strlcpy(newconf,buf,10240);
973 std::stringstream merge(stringstream::in | stringstream::out);
974 // recursively call LoadConf and get the new data, use the same errorstream
975 if (LoadConf(newconf, &merge, errorstream))
977 // append to the end of the file
978 std::string newstuff = merge.str();
983 // the error propogates up to its parent recursively
984 // causing the config reader to bail at the top level.
992 std::string data = this->ConfProcess(buffer,linenumber++,errorstream,error,filename);
1010 /* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */
1012 int ServerConfig::EnumConf(std::stringstream *config, const char* tag)
1015 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
1016 int in_token, in_quotes, tptr, idx = 0;
1018 std::string x = config->str();
1019 const char* buf = x.c_str();
1021 long len = config->str().length();
1031 if ((c == '#') && (lastc == '\n'))
1033 while ((c != '\n') && (bptr<len))
1039 if ((c == '<') && (!in_quotes))
1054 in_quotes = (!in_quotes);
1056 if ((c == '>') && (!in_quotes))
1059 if (!strcmp(c_tag,tag))
1061 /* correct tag, but wrong index */
1071 if ((in_token) && (c != '\n') && (c != '\r'))
1081 /* Counts the number of values within a certain tag */
1083 int ServerConfig::EnumValues(std::stringstream *config, const char* tag, int index)
1086 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
1087 int in_token, in_quotes, tptr, idx = 0;
1089 bool correct_tag = false;
1092 const char* buf = config->str().c_str();
1094 long len = strlen(buf);
1104 if ((c == '#') && (lastc == '\n'))
1106 while ((c != '\n') && (bptr<len))
1112 if ((c == '<') && (!in_quotes))
1123 if ((!strcmp(c_tag,tag)) && (idx == index))
1132 in_quotes = (!in_quotes);
1135 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
1139 if ((c == '>') && (!in_quotes))
1143 correct_tag = false;
1144 if (!strcmp(c_tag,tag))
1146 /* correct tag, but wrong index */
1156 if ((in_token) && (c != '\n') && (c != '\r'))
1168 int ServerConfig::ConfValueEnum(char* tag, std::stringstream* config)
1170 return EnumConf(config,tag);
1175 /* Retrieves a value from the config file. If there is more than one value of the specified
1176 * key and section (e.g. for opers etc) then the index value specifies which to retreive, e.g.
1178 * ConfValue("oper","name",2,result);
1181 int ServerConfig::ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
1184 char buffer[65535], c_tag[MAXBUF], c, lastc;
1185 int in_token, in_quotes, tptr, idx = 0;
1188 std::string x = config->str();
1189 const char* buf = x.c_str();
1191 long len = config->str().length();
1203 // FIX: Treat tabs as spaces
1206 if ((c == '<') && (!in_quotes))
1217 // FIX: Tab can follow a tagname as well as space.
1218 } while ((c != ' ') && (c != 9));
1222 in_quotes = (!in_quotes);
1224 if ((c == '>') && (!in_quotes))
1229 if (!strcmp(c_tag,tag))
1231 if ((buffer) && (c_tag) && (var))
1233 key = strstr(buffer,var);
1236 /* value not found in tag */
1254 for (unsigned j = 0; j < strlen(key); j++)
1261 strlcpy(result,key,MAXBUF);
1267 if (!strcmp(c_tag,tag))
1269 /* correct tag, but wrong index */
1279 if ((in_token) && (c != '\n') && (c != '\r'))
1286 *result = 0; // value or its tag not found at all
1292 int ServerConfig::ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
1294 ReadConf(config, tag, var, index, result);
1298 int ServerConfig::ConfValueInteger(char* tag, char* var, int index, std::stringstream *config)
1300 char result[MAXBUF];
1301 ReadConf(config, tag, var, index, result);
1302 return atoi(result);
1305 // This will bind a socket to a port. It works for UDP/TCP
1306 int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
1308 memset((char *)&server,0,sizeof(server));
1309 struct in_addr addy;
1310 inet_aton(addr,&addy);
1311 server.sin_family = AF_INET;
1314 server.sin_addr.s_addr = htonl(INADDR_ANY);
1318 server.sin_addr = addy;
1320 server.sin_port = htons(port);
1321 if (bind(sockfd,(struct sockaddr*)&server,sizeof(server))<0)
1327 listen(sockfd, Config->MaxConn);
1333 // Open a TCP Socket
1334 int OpenTCPSocket (void)
1338 struct linger linger = { 0 };
1340 if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
1344 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
1345 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
1347 linger.l_linger = 1;
1348 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));
1355 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
1356 sockaddr_in client,server;
1357 int clientportcount = 0;
1358 int BoundPortCount = 0;
1360 for (int count = 0; count < Config->ConfValueEnum("bind",&Config->config_f); count++)
1362 Config->ConfValue("bind","port",count,configToken,&Config->config_f);
1363 Config->ConfValue("bind","address",count,Addr,&Config->config_f);
1364 Config->ConfValue("bind","type",count,Type,&Config->config_f);
1366 if ((!*Type) || (!strcmp(Type,"clients")))
1368 // modules handle server bind types now
1369 Config->ports[clientportcount] = atoi(configToken);
1371 // If the client put bind "*", this is an unrealism.
1372 // We don't actually support this as documented, but
1373 // i got fed up of people trying it, so now it converts
1374 // it to an empty string meaning the same 'bind to all'.
1378 strlcpy(Config->addrs[clientportcount],Addr,256);
1380 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
1384 int PortCount = clientportcount;
1386 for (int count = 0; count < PortCount; count++)
1388 if ((openSockfd[BoundPortCount] = OpenTCPSocket()) == ERROR)
1390 log(DEBUG,"InspIRCd: startup: bad fd %lu binding port [%s:%d]",(unsigned long)openSockfd[BoundPortCount],Config->addrs[count],(unsigned long)Config->ports[count]);
1394 if (BindSocket(openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]) == ERROR)
1396 log(DEFAULT,"InspIRCd: startup: failed to bind port [%s:%lu]: %s",Config->addrs[count],(unsigned long)Config->ports[count],strerror(errno));
1400 /* well we at least bound to one socket so we'll continue */
1405 /* if we didn't bind to anything then abort */
1406 if (!BoundPortCount)
1408 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
1409 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)PortCount);
1413 return BoundPortCount;