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;
64 void ServerConfig::ClearStack()
66 include_stack.clear();
69 Module* ServerConfig::GetIOHook(int port)
71 std::map<int,Module*>::iterator x = IOHookModule.find(port);
72 return (x != IOHookModule.end() ? x->second : NULL);
75 bool ServerConfig::AddIOHook(int port, Module* iomod)
79 IOHookModule[port] = iomod;
84 ModuleException err("Port already hooked by another module");
90 bool ServerConfig::DelIOHook(int port)
92 std::map<int,Module*>::iterator x = IOHookModule.find(port);
93 if (x != IOHookModule.end())
95 IOHookModule.erase(x);
101 bool ServerConfig::CheckOnce(char* tag, bool bail, userrec* user)
103 int count = ConfValueEnum(tag,&Config->config_f);
108 printf("There were errors in your configuration:\nYou have more than one <%s> tag, this is not permitted.\n",tag);
115 WriteServ(user->fd,"There were errors in your configuration:");
116 WriteServ(user->fd,"You have more than one <%s> tag, this is not permitted.\n",tag);
120 WriteOpers("There were errors in the configuration file:");
121 WriteOpers("You have more than one <%s> tag, this is not permitted.\n",tag);
130 printf("There were errors in your configuration:\nYou have not defined a <%s> tag, this is required.\n",tag);
137 WriteServ(user->fd,"There were errors in your configuration:");
138 WriteServ(user->fd,"You have not defined a <%s> tag, this is required.",tag);
142 WriteOpers("There were errors in the configuration file:");
143 WriteOpers("You have not defined a <%s> tag, this is required.",tag);
151 void ServerConfig::Read(bool bail, userrec* user)
153 /** Yes yes, i know, this function is craq worthy of
154 * sirv. Its a mess, and some day i will tidy it.
155 * ...But that day will not be today. or probaby not
156 * tomorrow even, because it works fine.
158 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF],MCON[MAXBUF],MT[MAXBUF];
159 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF],SLIMT[MAXBUF];
160 char localmax[MAXBUF],globalmax[MAXBUF],HS[MAXBUF],HB[MAXBUF],ServName[MAXBUF];
162 std::stringstream errstr;
163 include_stack.clear();
165 if (!LoadConf(CONFIG_FILE,&Config->config_f,&errstr))
168 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
171 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
179 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
180 while (!errstr.eof())
182 errstr.getline(dataline,1024);
183 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
188 WriteOpers("There were errors in the configuration file:");
189 while (!errstr.eof())
191 errstr.getline(dataline,1024);
192 WriteOpers(dataline);
199 /* Check we dont have more than one of singular tags
201 if (!CheckOnce("server",bail,user) || !CheckOnce("admin",bail,user) || !CheckOnce("files",bail,user)
202 || !CheckOnce("power",bail,user) || !CheckOnce("options",bail,user) || !CheckOnce("pid",bail,user))
207 ConfValue("server","name",0,Config->ServerName,&Config->config_f);
208 ConfValue("server","description",0,Config->ServerDesc,&Config->config_f);
209 ConfValue("server","network",0,Config->Network,&Config->config_f);
210 ConfValue("admin","name",0,Config->AdminName,&Config->config_f);
211 ConfValue("admin","email",0,Config->AdminEmail,&Config->config_f);
212 ConfValue("admin","nick",0,Config->AdminNick,&Config->config_f);
213 ConfValue("files","motd",0,Config->motd,&Config->config_f);
214 ConfValue("files","rules",0,Config->rules,&Config->config_f);
215 ConfValue("power","diepass",0,Config->diepass,&Config->config_f);
216 ConfValue("power","pause",0,pauseval,&Config->config_f);
217 ConfValue("power","restartpass",0,Config->restartpass,&Config->config_f);
218 ConfValue("options","prefixquit",0,Config->PrefixQuit,&Config->config_f);
219 ConfValue("die","value",0,Config->DieValue,&Config->config_f);
220 ConfValue("options","loglevel",0,dbg,&Config->config_f);
221 ConfValue("options","netbuffersize",0,NB,&Config->config_f);
222 ConfValue("options","maxwho",0,MW,&Config->config_f);
223 ConfValue("options","allowhalfop",0,AH,&Config->config_f);
224 ConfValue("options","allowprotect",0,AP,&Config->config_f);
225 ConfValue("options","allowfounder",0,AF,&Config->config_f);
226 ConfValue("dns","server",0,Config->DNSServer,&Config->config_f);
227 ConfValue("dns","timeout",0,DNT,&Config->config_f);
228 ConfValue("options","moduledir",0,Config->ModPath,&Config->config_f);
229 ConfValue("disabled","commands",0,Config->DisabledCommands,&Config->config_f);
230 ConfValue("options","somaxconn",0,MCON,&Config->config_f);
231 ConfValue("options","softlimit",0,SLIMT,&Config->config_f);
232 ConfValue("options","operonlystats",0,Config->OperOnlyStats,&Config->config_f);
233 ConfValue("options","customversion",0,Config->CustomVersion,&Config->config_f);
234 ConfValue("options","maxtargets",0,MT,&Config->config_f);
235 ConfValue("options","hidesplits",0,HS,&Config->config_f);
236 ConfValue("options","hidebans",0,HB,&Config->config_f);
237 ConfValue("options","hidewhois",0,Config->HideWhoisServer,&Config->config_f);
238 ConfValue("options","tempdir",0,Config->TempDir,&Config->config_f);
240 strlower(Config->ServerName);
242 if (!*Config->TempDir)
243 strlcpy(Config->TempDir,"/tmp",1024);
244 Config->HideSplits = ((*HS == 'y') || (*HS == 'Y') || (*HS == '1') || (*HS == 't') || (*HS == 'T'));
245 Config->HideBans = ((*HB == 'y') || (*HB == 'Y') || (*HB == '1') || (*HB == 't') || (*HB == 'T'));
246 Config->SoftLimit = atoi(SLIMT);
248 Config->MaxTargets = atoi(MT);
249 if ((Config->MaxTargets < 0) || (Config->MaxTargets > 31))
251 log(DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
252 Config->MaxTargets = 20;
254 if ((Config->SoftLimit < 1) || (Config->SoftLimit > MAXCLIENTS))
256 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
257 Config->SoftLimit = MAXCLIENTS;
259 Config->MaxConn = atoi(MCON);
260 if (Config->MaxConn > SOMAXCONN)
261 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
262 Config->NetBufferSize = atoi(NB);
263 Config->MaxWhoResults = atoi(MW);
264 Config->dns_timeout = atoi(DNT);
265 if (!strchr(Config->ServerName,'.'))
267 log(DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s%c'",Config->ServerName,Config->ServerName,'.');
268 charlcat(Config->ServerName,'.',MAXBUF);
270 if (!Config->dns_timeout)
271 Config->dns_timeout = 5;
272 if (!Config->MaxConn)
273 Config->MaxConn = SOMAXCONN;
274 if (!*Config->DNSServer)
276 // attempt to look up their nameserver from /etc/resolv.conf
277 log(DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
278 ifstream resolv("/etc/resolv.conf");
279 std::string nameserver;
280 bool found_server = false;
281 if (resolv.is_open())
283 while (resolv >> nameserver)
285 if ((nameserver == "nameserver") && (!found_server))
287 resolv >> nameserver;
288 strlcpy(Config->DNSServer,nameserver.c_str(),MAXBUF);
290 log(DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
295 log(DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
296 strlcpy(Config->DNSServer,"127.0.0.1",MAXBUF);
301 log(DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
302 strlcpy(Config->DNSServer,"127.0.0.1",MAXBUF);
305 if (!*Config->ModPath)
306 strlcpy(Config->ModPath,MOD_PATH,MAXBUF);
307 Config->AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
308 if ((!Config->NetBufferSize) || (Config->NetBufferSize > 65535) || (Config->NetBufferSize < 1024))
310 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
311 Config->NetBufferSize = 10240;
313 if ((!Config->MaxWhoResults) || (Config->MaxWhoResults > 65535) || (Config->MaxWhoResults < 1))
315 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
316 Config->MaxWhoResults = 128;
318 Config->LogLevel = DEFAULT;
319 if (!strcmp(dbg,"debug"))
321 Config->LogLevel = DEBUG;
322 Config->debugging = 1;
324 if (!strcmp(dbg,"verbose"))
325 Config->LogLevel = VERBOSE;
326 if (!strcmp(dbg,"default"))
327 Config->LogLevel = DEFAULT;
328 if (!strcmp(dbg,"sparse"))
329 Config->LogLevel = SPARSE;
330 if (!strcmp(dbg,"none"))
331 Config->LogLevel = NONE;
333 readfile(Config->MOTD,Config->motd);
334 log(DEFAULT,"Reading message of the day...");
335 readfile(Config->RULES,Config->rules);
336 log(DEFAULT,"Reading connect classes...");
338 for (int i = 0; i < ConfValueEnum("connect",&Config->config_f); i++)
341 ConfValue("connect","allow",i,Value,&Config->config_f);
342 ConfValue("connect","timeout",i,timeout,&Config->config_f);
343 ConfValue("connect","flood",i,flood,&Config->config_f);
344 ConfValue("connect","pingfreq",i,pfreq,&Config->config_f);
345 ConfValue("connect","threshold",i,thold,&Config->config_f);
346 ConfValue("connect","sendq",i,sqmax,&Config->config_f);
347 ConfValue("connect","recvq",i,rqmax,&Config->config_f);
348 ConfValue("connect","localmax",i,localmax,&Config->config_f);
349 ConfValue("connect","globalmax",i,globalmax,&Config->config_f);
354 strlcpy(Value,"",MAXBUF);
355 ConfValue("connect","password",i,Value,&Config->config_f);
357 c.registration_timeout = 90; // default is 2 minutes
359 c.flood = atoi(flood);
361 c.sendqmax = 262144; // 256k
362 c.recvqmax = 4096; // 4k
365 if (atoi(localmax)>0)
367 c.maxlocal = atoi(localmax);
369 if (atoi(globalmax)>0)
371 c.maxglobal = atoi(globalmax);
375 c.threshold = atoi(thold);
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());
385 c.sendqmax = atoi(sqmax);
389 c.recvqmax = atoi(rqmax);
393 c.registration_timeout = atoi(timeout);
397 c.pingtime = atoi(pfreq);
399 Classes.push_back(c);
403 ConfValue("connect","deny",i,Value,&Config->config_f);
406 Classes.push_back(c);
407 log(DEBUG,"Read connect class type DENY, host=%s",c.host.c_str());
411 Config->ulines.clear();
412 for (int i = 0; i < ConfValueEnum("uline",&Config->config_f); i++)
414 ConfValue("uline","server",i,ServName,&Config->config_f);
416 log(DEBUG,"Read ULINE '%s'",ServName);
417 Config->ulines.push_back(ServName);
420 ReadClassesAndTypes();
421 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
422 read_xline_defaults();
423 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
424 apply_lines(APPLY_ALL);
426 ConfValue("pid","file",0,Config->PID,&Config->config_f);
427 // write once here, to try it out and make sure its ok
428 WritePID(Config->PID);
430 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
433 log(DEFAULT,"Adding and removing modules due to rehash...");
435 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
437 // store the old module names
438 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
440 old_module_names.push_back(*t);
443 // get the new module names
444 for (int count2 = 0; count2 < ConfValueEnum("module",&Config->config_f); count2++)
446 ConfValue("module","name",count2,Value,&Config->config_f);
447 new_module_names.push_back(Value);
450 // now create a list of new modules that are due to be loaded
451 // and a seperate list of modules which are due to be unloaded
452 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
455 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
461 added_modules.push_back(*_new);
463 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
466 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
472 removed_modules.push_back(*oldm);
474 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
476 int rem = 0, add = 0;
477 if (!removed_modules.empty())
478 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
480 if (ServerInstance->UnloadModule(removing->c_str()))
482 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
484 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
490 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
493 if (!added_modules.empty())
494 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
496 if (ServerInstance->LoadModule(adding->c_str()))
498 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
500 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
506 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
509 log(DEFAULT,"Successfully unloaded %lu of %lu modules and loaded %lu of %lu modules.",(unsigned long)rem,(unsigned long)removed_modules.size(),
510 (unsigned long)add,(unsigned long)added_modules.size());
515 void Exit (int status)
517 if (Config->log_file)
518 fclose(Config->log_file);
519 send_error("Server shutdown.");
523 void Killed(int status)
525 if (Config->log_file)
526 fclose(Config->log_file);
527 send_error("Server terminated.");
531 char* CleanFilename(char* name)
533 char* p = name + strlen(name);
534 while ((p != name) && (*p != '/')) p--;
535 return (p != name ? ++p : p);
539 void Rehash(int status)
541 WriteOpers("Rehashing config file %s due to SIGHUP",CleanFilename(CONFIG_FILE));
542 fclose(Config->log_file);
544 Config->Read(false,NULL);
545 FOREACH_MOD(I_OnRehash,OnRehash(""));
552 printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
553 printf("(C) ChatSpike Development team.\033[0m\n\n");
554 printf("Developers:\033[1;32m Brain, FrostyCoolSlug\033[0m\n");
555 printf("Documentation:\033[1;32m FrostyCoolSlug, w00t\033[0m\n");
556 printf("Testers:\033[1;32m typobox43, piggles, Lord_Zathras, CC\033[0m\n");
557 printf("Name concept:\033[1;32m Lord_Zathras\033[0m\n\n");
560 void WritePID(std::string filename)
562 ofstream outfile(filename.c_str());
563 if (outfile.is_open())
570 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
571 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
578 signal (SIGALRM, SIG_IGN);
579 signal (SIGHUP, Rehash);
580 signal (SIGPIPE, SIG_IGN);
581 signal (SIGTERM, Exit);
582 signal (SIGSEGV, Error);
586 int DaemonSeed (void)
589 if ((childpid = fork ()) < 0)
591 else if (childpid > 0)
593 /* We wait a few seconds here, so that the shell prompt doesnt come back over the output */
599 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
601 if (Config->unlimitcore)
604 if (getrlimit(RLIMIT_CORE, &rl) == -1)
606 log(DEFAULT,"Failed to getrlimit()!");
611 rl.rlim_cur = rl.rlim_max;
612 if (setrlimit(RLIMIT_CORE, &rl) == -1)
613 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
621 /* Make Sure Modules Are Avaliable!
622 * (BugFix By Craig.. See? I do work! :p)
623 * Modified by brain, requires const char*
624 * to work with other API functions
627 bool FileExists (const char* file)
630 if ((input = fopen (file, "r")) == NULL)
641 /* ConfProcess does the following things to a config line in the following order:
643 * Processes the line for syntax errors as shown below
644 * (1) Line void of quotes or equals (a malformed, illegal tag format)
645 * (2) Odd number of quotes on the line indicating a missing quote
646 * (3) number of equals signs not equal to number of quotes / 2 (missing an equals sign)
647 * (4) Spaces between the opening bracket (<) and the keyword
648 * (5) Spaces between a keyword and an equals sign
649 * (6) Spaces between an equals sign and a quote
650 * Removes trailing spaces
651 * Removes leading spaces
652 * Converts tabs to spaces
653 * Turns multiple spaces that are outside of quotes into single spaces
656 std::string ServerConfig::ConfProcess(char* buffer, long linenumber, std::stringstream* errorstream, bool &error, std::string filename)
658 long number_of_quotes = 0;
659 long number_of_equals = 0;
660 bool has_open_bracket = false;
661 bool in_quotes = false;
667 // firstly clean up the line by stripping spaces from the start and end and converting tabs to spaces
668 for (char* d = buffer; *d; d++)
671 while (*buffer == ' ') buffer++;
672 while ((buffer[strlen(buffer)-1] == ' ') && (*buffer)) buffer[strlen(buffer)-1] = '\0';
674 // empty lines are syntactically valid, as are comments
675 if (!(*buffer) || buffer[0] == '#')
678 for (unsigned int c = 0; c < strlen(buffer); c++)
680 // convert all spaces that are OUTSIDE quotes into hardspace (0xA0) as this will make them easier to
681 // search and replace later :)
682 if ((!in_quotes) && (buffer[c] == ' '))
684 if ((buffer[c] == '<') && (!in_quotes))
686 has_open_bracket = true;
687 if (strlen(buffer) == 1)
689 *errorstream << "Tag without identifier at " << filename << ":" << linenumber << endl;
693 else if ((tolower(buffer[c+1]) < 'a') || (tolower(buffer[c+1]) > 'z'))
695 *errorstream << "Invalid characters in identifier at " << filename << ":" << linenumber << endl;
700 if (buffer[c] == '"')
703 in_quotes = (!in_quotes);
705 if ((buffer[c] == '=') && (!in_quotes))
708 if (strlen(buffer) == c)
710 *errorstream << "Variable without a value at " << filename << ":" << linenumber << endl;
714 else if (buffer[c+1] != '"')
716 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
722 *errorstream << "Value without a variable (line starts with '=') at " << filename << ":" << linenumber << endl;
726 else if (buffer[c-1] == '\xA0')
728 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
734 // no quotes, and no equals. something freaky.
735 if ((!number_of_quotes) || (!number_of_equals) && (strlen(buffer)>2) && (buffer[0]=='<'))
737 *errorstream << "Malformed tag at " << filename << ":" << linenumber << endl;
741 // odd number of quotes. thats just wrong.
742 if ((number_of_quotes % 2) != 0)
744 *errorstream << "Missing \" at " << filename << ":" << linenumber << endl;
748 if (number_of_equals < (number_of_quotes/2))
750 *errorstream << "Missing '=' at " << filename << ":" << linenumber << endl;
752 if (number_of_equals > (number_of_quotes/2))
754 *errorstream << "Too many '=' at " << filename << ":" << linenumber << endl;
757 std::string parsedata = buffer;
758 // turn multispace into single space
759 while (parsedata.find("\xA0\xA0") != std::string::npos)
761 parsedata.erase(parsedata.find("\xA0\xA0"),1);
764 // turn our hardspace back into softspace
765 for (unsigned int d = 0; d < parsedata.length(); d++)
767 if (parsedata[d] == '\xA0')
771 // and we're done, the line is fine!
775 int ServerConfig::fgets_safe(char* buffer, size_t maxsize, FILE* &file)
778 unsigned int bufptr = 0;
779 while ((!feof(file)) && (c_read != '\n') && (c_read != '\r') && (bufptr < maxsize))
781 c_read = fgetc(file);
782 if ((c_read != '\n') && (c_read != '\r'))
783 buffer[bufptr++] = c_read;
785 buffer[bufptr] = '\0';
789 bool ServerConfig::LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream)
792 errorstream->str("");
794 // first, check that the file exists before we try to do anything with it
795 if (!FileExists(filename))
797 *errorstream << "File " << filename << " not found." << endl;
800 // Fix the chmod of the file to restrict it to the current user and group
801 chmod(filename,0600);
802 for (unsigned int t = 0; t < include_stack.size(); t++)
804 if (std::string(filename) == include_stack[t])
806 *errorstream << "File " << filename << " is included recursively (looped inclusion)." << endl;
810 include_stack.push_back(filename);
812 FILE* conf = fopen(filename,"r");
818 if (fgets_safe(buffer, MAXBUF, conf))
820 if ((!feof(conf)) && (buffer) && (strlen(buffer)))
822 if ((buffer[0] != '#') && (buffer[0] != '\r') && (buffer[0] != '\n'))
824 if (!strncmp(buffer,"<include file=\"",15))
827 char confpath[10240],newconf[10240];
828 // include file directive
829 buf += 15; // advance to filename
830 for (unsigned int j = 0; j < strlen(buf); j++)
840 log(DEBUG,"Opening included file '%s'",buf);
843 strlcpy(confpath,CONFIG_FILE,10240);
844 if (strstr(confpath,"/inspircd.conf"))
846 // leaves us with just the path
847 *(strstr(confpath,"/inspircd.conf")) = '\0';
849 snprintf(newconf,10240,"%s/%s",confpath,buf);
851 else strlcpy(newconf,buf,10240);
852 std::stringstream merge(stringstream::in | stringstream::out);
853 // recursively call LoadConf and get the new data, use the same errorstream
854 if (LoadConf(newconf, &merge, errorstream))
856 // append to the end of the file
857 std::string newstuff = merge.str();
862 // the error propogates up to its parent recursively
863 // causing the config reader to bail at the top level.
871 std::string data = this->ConfProcess(buffer,linenumber++,errorstream,error,filename);
889 /* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */
891 int ServerConfig::EnumConf(std::stringstream *config, const char* tag)
894 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
895 int in_token, in_quotes, tptr, idx = 0;
897 std::string x = config->str();
898 const char* buf = x.c_str();
900 long len = config->str().length();
910 if ((c == '#') && (lastc == '\n'))
912 while ((c != '\n') && (bptr<len))
918 if ((c == '<') && (!in_quotes))
933 in_quotes = (!in_quotes);
935 if ((c == '>') && (!in_quotes))
938 if (!strcmp(c_tag,tag))
940 /* correct tag, but wrong index */
950 if ((in_token) && (c != '\n') && (c != '\r'))
960 /* Counts the number of values within a certain tag */
962 int ServerConfig::EnumValues(std::stringstream *config, const char* tag, int index)
965 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
966 int in_token, in_quotes, tptr, idx = 0;
968 bool correct_tag = false;
971 const char* buf = config->str().c_str();
973 long len = strlen(buf);
983 if ((c == '#') && (lastc == '\n'))
985 while ((c != '\n') && (bptr<len))
991 if ((c == '<') && (!in_quotes))
1002 if ((!strcmp(c_tag,tag)) && (idx == index))
1011 in_quotes = (!in_quotes);
1014 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
1018 if ((c == '>') && (!in_quotes))
1022 correct_tag = false;
1023 if (!strcmp(c_tag,tag))
1025 /* correct tag, but wrong index */
1035 if ((in_token) && (c != '\n') && (c != '\r'))
1047 int ServerConfig::ConfValueEnum(char* tag, std::stringstream* config)
1049 return EnumConf(config,tag);
1054 /* Retrieves a value from the config file. If there is more than one value of the specified
1055 * key and section (e.g. for opers etc) then the index value specifies which to retreive, e.g.
1057 * ConfValue("oper","name",2,result);
1060 int ServerConfig::ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
1063 char buffer[65535], c_tag[MAXBUF], c, lastc;
1064 int in_token, in_quotes, tptr, idx = 0;
1067 std::string x = config->str();
1068 const char* buf = x.c_str();
1070 long len = config->str().length();
1082 // FIX: Treat tabs as spaces
1085 if ((c == '<') && (!in_quotes))
1096 // FIX: Tab can follow a tagname as well as space.
1097 } while ((c != ' ') && (c != 9));
1101 in_quotes = (!in_quotes);
1103 if ((c == '>') && (!in_quotes))
1108 if (!strcmp(c_tag,tag))
1110 if ((buffer) && (c_tag) && (var))
1112 key = strstr(buffer,var);
1115 /* value not found in tag */
1133 for (unsigned j = 0; j < strlen(key); j++)
1140 strlcpy(result,key,MAXBUF);
1146 if (!strcmp(c_tag,tag))
1148 /* correct tag, but wrong index */
1158 if ((in_token) && (c != '\n') && (c != '\r'))
1165 *result = 0; // value or its tag not found at all
1171 int ServerConfig::ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
1173 ReadConf(config, tag, var, index, result);
1179 // This will bind a socket to a port. It works for UDP/TCP
1180 int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
1182 memset((char *)&server,0,sizeof(server));
1183 struct in_addr addy;
1184 inet_aton(addr,&addy);
1185 server.sin_family = AF_INET;
1188 server.sin_addr.s_addr = htonl(INADDR_ANY);
1192 server.sin_addr = addy;
1194 server.sin_port = htons(port);
1195 if (bind(sockfd,(struct sockaddr*)&server,sizeof(server))<0)
1201 listen(sockfd, Config->MaxConn);
1207 // Open a TCP Socket
1208 int OpenTCPSocket (void)
1212 struct linger linger = { 0 };
1214 if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
1218 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
1219 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
1221 linger.l_linger = 1;
1222 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));
1229 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
1230 sockaddr_in client,server;
1231 int clientportcount = 0;
1232 int BoundPortCount = 0;
1233 for (int count = 0; count < Config->ConfValueEnum("bind",&Config->config_f); count++)
1235 Config->ConfValue("bind","port",count,configToken,&Config->config_f);
1236 Config->ConfValue("bind","address",count,Addr,&Config->config_f);
1237 Config->ConfValue("bind","type",count,Type,&Config->config_f);
1238 if ((!*Type) || (!strcmp(Type,"clients")))
1240 // modules handle server bind types now
1241 Config->ports[clientportcount] = atoi(configToken);
1243 // If the client put bind "*", this is an unrealism.
1244 // We don't actually support this as documented, but
1245 // i got fed up of people trying it, so now it converts
1246 // it to an empty string meaning the same 'bind to all'.
1250 strlcpy(Config->addrs[clientportcount],Addr,256);
1252 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
1255 int PortCount = clientportcount;
1257 for (int count = 0; count < PortCount; count++)
1259 if ((openSockfd[BoundPortCount] = OpenTCPSocket()) == ERROR)
1261 log(DEBUG,"InspIRCd: startup: bad fd %lu binding port [%s:%d]",(unsigned long)openSockfd[BoundPortCount],Config->addrs[count],(unsigned long)Config->ports[count]);
1264 if (BindSocket(openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]) == ERROR)
1266 log(DEFAULT,"InspIRCd: startup: failed to bind port [%s:%lu]: %s",Config->addrs[count],(unsigned long)Config->ports[count],strerror(errno));
1268 else /* well we at least bound to one socket so we'll continue */
1274 /* if we didn't bind to anything then abort */
1275 if (!BoundPortCount)
1277 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
1278 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)PortCount);
1282 return BoundPortCount;