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 void ServerConfig::Read(bool bail, userrec* user)
154 /* XXX - this needs a rework someday, BAD. */
155 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF],MCON[MAXBUF],MT[MAXBUF];
156 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF],SLIMT[MAXBUF];
157 char localmax[MAXBUF],globalmax[MAXBUF],HS[MAXBUF],HB[MAXBUF],ServName[MAXBUF];
159 std::stringstream errstr;
161 include_stack.clear();
163 if (!LoadConf(CONFIG_FILE,&Config->config_f,&errstr))
166 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
170 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);
200 /* Check we dont have more than one of singular tags
202 if (!CheckOnce("server",bail,user) || !CheckOnce("admin",bail,user) || !CheckOnce("files",bail,user)
203 || !CheckOnce("power",bail,user) || !CheckOnce("options",bail,user) || !CheckOnce("pid",bail,user))
208 ConfValue("server","name",0,Config->ServerName,&Config->config_f);
209 ConfValue("server","description",0,Config->ServerDesc,&Config->config_f);
210 ConfValue("server","network",0,Config->Network,&Config->config_f);
211 ConfValue("admin","name",0,Config->AdminName,&Config->config_f);
212 ConfValue("admin","email",0,Config->AdminEmail,&Config->config_f);
213 ConfValue("admin","nick",0,Config->AdminNick,&Config->config_f);
214 ConfValue("files","motd",0,Config->motd,&Config->config_f);
215 ConfValue("files","rules",0,Config->rules,&Config->config_f);
216 ConfValue("power","diepass",0,Config->diepass,&Config->config_f);
217 ConfValue("power","pause",0,pauseval,&Config->config_f);
218 ConfValue("power","restartpass",0,Config->restartpass,&Config->config_f);
219 ConfValue("options","prefixquit",0,Config->PrefixQuit,&Config->config_f);
220 ConfValue("die","value",0,Config->DieValue,&Config->config_f);
221 ConfValue("options","loglevel",0,dbg,&Config->config_f);
222 ConfValue("options","netbuffersize",0,NB,&Config->config_f);
223 ConfValue("options","maxwho",0,MW,&Config->config_f);
224 ConfValue("options","allowhalfop",0,AH,&Config->config_f);
225 ConfValue("options","allowprotect",0,AP,&Config->config_f);
226 ConfValue("options","allowfounder",0,AF,&Config->config_f);
227 ConfValue("dns","server",0,Config->DNSServer,&Config->config_f);
228 ConfValue("dns","timeout",0,DNT,&Config->config_f);
229 ConfValue("options","moduledir",0,Config->ModPath,&Config->config_f);
230 ConfValue("disabled","commands",0,Config->DisabledCommands,&Config->config_f);
231 ConfValue("options","somaxconn",0,MCON,&Config->config_f);
232 ConfValue("options","softlimit",0,SLIMT,&Config->config_f);
233 ConfValue("options","operonlystats",0,Config->OperOnlyStats,&Config->config_f);
234 ConfValue("options","customversion",0,Config->CustomVersion,&Config->config_f);
235 ConfValue("options","maxtargets",0,MT,&Config->config_f);
236 ConfValue("options","hidesplits",0,HS,&Config->config_f);
237 ConfValue("options","hidebans",0,HB,&Config->config_f);
238 ConfValue("options","hidewhois",0,Config->HideWhoisServer,&Config->config_f);
239 ConfValue("options","tempdir",0,Config->TempDir,&Config->config_f);
241 strlower(Config->ServerName);
243 if (!*Config->TempDir)
244 strlcpy(Config->TempDir,"/tmp",1024);
246 Config->HideSplits = ((*HS == 'y') || (*HS == 'Y') || (*HS == '1') || (*HS == 't') || (*HS == 'T'));
247 Config->HideBans = ((*HB == 'y') || (*HB == 'Y') || (*HB == '1') || (*HB == 't') || (*HB == 'T'));
248 Config->SoftLimit = atoi(SLIMT);
251 Config->MaxTargets = atoi(MT);
253 if ((Config->MaxTargets < 0) || (Config->MaxTargets > 31))
255 log(DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
256 Config->MaxTargets = 20;
259 if ((Config->SoftLimit < 1) || (Config->SoftLimit > MAXCLIENTS))
261 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
262 Config->SoftLimit = MAXCLIENTS;
265 Config->MaxConn = atoi(MCON);
267 if (Config->MaxConn > SOMAXCONN)
268 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
270 Config->NetBufferSize = atoi(NB);
271 Config->MaxWhoResults = atoi(MW);
272 Config->dns_timeout = atoi(DNT);
274 if (!strchr(Config->ServerName,'.'))
276 log(DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s%c'",Config->ServerName,Config->ServerName,'.');
277 charlcat(Config->ServerName,'.',MAXBUF);
280 if (!Config->dns_timeout)
281 Config->dns_timeout = 5;
283 if (!Config->MaxConn)
284 Config->MaxConn = SOMAXCONN;
286 if (!*Config->DNSServer)
288 // attempt to look up their nameserver from /etc/resolv.conf
289 log(DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
290 ifstream resolv("/etc/resolv.conf");
291 std::string nameserver;
292 bool found_server = false;
294 if (resolv.is_open())
296 while (resolv >> nameserver)
298 if ((nameserver == "nameserver") && (!found_server))
300 resolv >> nameserver;
301 strlcpy(Config->DNSServer,nameserver.c_str(),MAXBUF);
303 log(DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
309 log(DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
310 strlcpy(Config->DNSServer,"127.0.0.1",MAXBUF);
315 log(DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
316 strlcpy(Config->DNSServer,"127.0.0.1",MAXBUF);
320 if (!*Config->ModPath)
321 strlcpy(Config->ModPath,MOD_PATH,MAXBUF);
323 Config->AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
325 if ((!Config->NetBufferSize) || (Config->NetBufferSize > 65535) || (Config->NetBufferSize < 1024))
327 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
328 Config->NetBufferSize = 10240;
331 if ((!Config->MaxWhoResults) || (Config->MaxWhoResults > 65535) || (Config->MaxWhoResults < 1))
333 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
334 Config->MaxWhoResults = 128;
337 Config->LogLevel = DEFAULT;
339 if (!strcmp(dbg,"debug"))
341 Config->LogLevel = DEBUG;
342 Config->debugging = 1;
344 else if (!strcmp(dbg,"verbose"))
345 Config->LogLevel = VERBOSE;
346 else if (!strcmp(dbg,"default"))
347 Config->LogLevel = DEFAULT;
348 else if (!strcmp(dbg,"sparse"))
349 Config->LogLevel = SPARSE;
350 else if (!strcmp(dbg,"none"))
351 Config->LogLevel = NONE;
353 readfile(Config->MOTD,Config->motd);
354 log(DEFAULT,"Reading message of the day...");
355 readfile(Config->RULES,Config->rules);
356 log(DEFAULT,"Reading connect classes...");
359 for (int i = 0; i < ConfValueEnum("connect",&Config->config_f); i++)
362 ConfValue("connect","allow",i,Value,&Config->config_f);
363 ConfValue("connect","timeout",i,timeout,&Config->config_f);
364 ConfValue("connect","flood",i,flood,&Config->config_f);
365 ConfValue("connect","pingfreq",i,pfreq,&Config->config_f);
366 ConfValue("connect","threshold",i,thold,&Config->config_f);
367 ConfValue("connect","sendq",i,sqmax,&Config->config_f);
368 ConfValue("connect","recvq",i,rqmax,&Config->config_f);
369 ConfValue("connect","localmax",i,localmax,&Config->config_f);
370 ConfValue("connect","globalmax",i,globalmax,&Config->config_f);
376 strlcpy(Value,"",MAXBUF);
377 ConfValue("connect","password",i,Value,&Config->config_f);
379 c.registration_timeout = 90; // default is 2 minutes
381 c.flood = atoi(flood);
383 c.sendqmax = 262144; // 256k
384 c.recvqmax = 4096; // 4k
388 if (atoi(localmax)>0)
390 c.maxlocal = atoi(localmax);
393 if (atoi(globalmax)>0)
395 c.maxglobal = atoi(globalmax);
400 c.threshold = atoi(thold);
406 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());
411 c.sendqmax = atoi(sqmax);
415 c.recvqmax = atoi(rqmax);
419 c.registration_timeout = atoi(timeout);
423 c.pingtime = atoi(pfreq);
426 Classes.push_back(c);
430 ConfValue("connect","deny",i,Value,&Config->config_f);
433 Classes.push_back(c);
434 log(DEBUG,"Read connect class type DENY, host=%s",c.host.c_str());
438 Config->ulines.clear();
440 for (int i = 0; i < ConfValueEnum("uline",&Config->config_f); i++)
442 ConfValue("uline","server",i,ServName,&Config->config_f);
444 log(DEBUG,"Read ULINE '%s'",ServName);
445 Config->ulines.push_back(ServName);
450 char CM1[MAXBUF],CM2[MAXBUF];
452 for (int count = 0; count < Config->ConfValueEnum("banlist",&Config->config_f); count++)
454 Config->ConfValue("banlist","chan",count,CM1,&Config->config_f);
455 Config->ConfValue("banlist","limit",count,CM2,&Config->config_f);
456 maxbans[CM1] = atoi(CM2);
459 ReadClassesAndTypes();
460 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
461 read_xline_defaults();
462 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
463 apply_lines(APPLY_ALL);
465 ConfValue("pid","file",0,Config->PID,&Config->config_f);
466 // write once here, to try it out and make sure its ok
467 WritePID(Config->PID);
469 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
472 log(DEFAULT,"Adding and removing modules due to rehash...");
474 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
476 // store the old module names
477 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
479 old_module_names.push_back(*t);
482 // get the new module names
483 for (int count2 = 0; count2 < ConfValueEnum("module",&Config->config_f); count2++)
485 ConfValue("module","name",count2,Value,&Config->config_f);
486 new_module_names.push_back(Value);
489 // now create a list of new modules that are due to be loaded
490 // and a seperate list of modules which are due to be unloaded
491 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
495 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
502 added_modules.push_back(*_new);
505 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
508 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
515 removed_modules.push_back(*oldm);
519 * now we have added_modules, a vector of modules to be loaded,
520 * and removed_modules, a vector of modules
523 int rem = 0, add = 0;
524 if (!removed_modules.empty())
525 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
527 if (ServerInstance->UnloadModule(removing->c_str()))
529 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
532 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
539 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
543 if (!added_modules.empty())
544 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
546 if (ServerInstance->LoadModule(adding->c_str()))
548 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
551 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
558 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
562 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());
567 void Exit (int status)
569 if (Config->log_file)
570 fclose(Config->log_file);
571 send_error("Server shutdown.");
575 void Killed(int status)
577 if (Config->log_file)
578 fclose(Config->log_file);
579 send_error("Server terminated.");
583 char* CleanFilename(char* name)
585 char* p = name + strlen(name);
586 while ((p != name) && (*p != '/')) p--;
587 return (p != name ? ++p : p);
591 void Rehash(int status)
593 WriteOpers("Rehashing config file %s due to SIGHUP",CleanFilename(CONFIG_FILE));
594 fclose(Config->log_file);
596 Config->Read(false,NULL);
597 FOREACH_MOD(I_OnRehash,OnRehash(""));
604 printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
605 printf("(C) ChatSpike Development team.\033[0m\n\n");
606 printf("Developers:\033[1;32m Brain, FrostyCoolSlug, w00t, Om\033[0m\n");
607 printf("Others:\033[1;32m See /INFO Output\033[0m\n");
608 printf("Name concept:\033[1;32m Lord_Zathras\033[0m\n\n");
611 void WritePID(std::string filename)
613 ofstream outfile(filename.c_str());
614 if (outfile.is_open())
621 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
622 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
629 signal (SIGALRM, SIG_IGN);
630 signal (SIGHUP, Rehash);
631 signal (SIGPIPE, SIG_IGN);
632 signal (SIGTERM, Exit);
633 signal (SIGSEGV, Error);
637 int DaemonSeed (void)
640 if ((childpid = fork ()) < 0)
642 else if (childpid > 0)
644 /* We wait a few seconds here, so that the shell prompt doesnt come back over the output */
650 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
652 if (Config->unlimitcore)
655 if (getrlimit(RLIMIT_CORE, &rl) == -1)
657 log(DEFAULT,"Failed to getrlimit()!");
662 rl.rlim_cur = rl.rlim_max;
663 if (setrlimit(RLIMIT_CORE, &rl) == -1)
664 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
672 /* Make Sure Modules Are Avaliable!
673 * (BugFix By Craig.. See? I do work! :p)
674 * Modified by brain, requires const char*
675 * to work with other API functions
678 bool FileExists (const char* file)
681 if ((input = fopen (file, "r")) == NULL)
692 /* ConfProcess does the following things to a config line in the following order:
694 * Processes the line for syntax errors as shown below
695 * (1) Line void of quotes or equals (a malformed, illegal tag format)
696 * (2) Odd number of quotes on the line indicating a missing quote
697 * (3) number of equals signs not equal to number of quotes / 2 (missing an equals sign)
698 * (4) Spaces between the opening bracket (<) and the keyword
699 * (5) Spaces between a keyword and an equals sign
700 * (6) Spaces between an equals sign and a quote
701 * Removes trailing spaces
702 * Removes leading spaces
703 * Converts tabs to spaces
704 * Turns multiple spaces that are outside of quotes into single spaces
707 std::string ServerConfig::ConfProcess(char* buffer, long linenumber, std::stringstream* errorstream, bool &error, std::string filename)
709 long number_of_quotes = 0;
710 long number_of_equals = 0;
711 bool has_open_bracket = false;
712 bool in_quotes = false;
718 // firstly clean up the line by stripping spaces from the start and end and converting tabs to spaces
719 for (char* d = buffer; *d; d++)
722 while (*buffer == ' ') buffer++;
723 while ((buffer[strlen(buffer)-1] == ' ') && (*buffer)) buffer[strlen(buffer)-1] = '\0';
725 // empty lines are syntactically valid, as are comments
726 if (!(*buffer) || buffer[0] == '#')
729 for (unsigned int c = 0; c < strlen(buffer); c++)
731 // convert all spaces that are OUTSIDE quotes into hardspace (0xA0) as this will make them easier to
732 // search and replace later :)
733 if ((!in_quotes) && (buffer[c] == ' '))
735 if ((buffer[c] == '<') && (!in_quotes))
737 has_open_bracket = true;
738 if (strlen(buffer) == 1)
740 *errorstream << "Tag without identifier at " << filename << ":" << linenumber << endl;
744 else if ((tolower(buffer[c+1]) < 'a') || (tolower(buffer[c+1]) > 'z'))
746 *errorstream << "Invalid characters in identifier at " << filename << ":" << linenumber << endl;
751 if (buffer[c] == '"')
754 in_quotes = (!in_quotes);
756 if ((buffer[c] == '=') && (!in_quotes))
759 if (strlen(buffer) == c)
761 *errorstream << "Variable without a value at " << filename << ":" << linenumber << endl;
765 else if (buffer[c+1] != '"')
767 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
773 *errorstream << "Value without a variable (line starts with '=') at " << filename << ":" << linenumber << endl;
777 else if (buffer[c-1] == '\xA0')
779 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
785 // no quotes, and no equals. something freaky.
786 if ((!number_of_quotes) || (!number_of_equals) && (strlen(buffer)>2) && (buffer[0]=='<'))
788 *errorstream << "Malformed tag at " << filename << ":" << linenumber << endl;
792 // odd number of quotes. thats just wrong.
793 if ((number_of_quotes % 2) != 0)
795 *errorstream << "Missing \" at " << filename << ":" << linenumber << endl;
799 if (number_of_equals < (number_of_quotes/2))
801 *errorstream << "Missing '=' at " << filename << ":" << linenumber << endl;
803 if (number_of_equals > (number_of_quotes/2))
805 *errorstream << "Too many '=' at " << filename << ":" << linenumber << endl;
808 std::string parsedata = buffer;
809 // turn multispace into single space
810 while (parsedata.find("\xA0\xA0") != std::string::npos)
812 parsedata.erase(parsedata.find("\xA0\xA0"),1);
815 // turn our hardspace back into softspace
816 for (unsigned int d = 0; d < parsedata.length(); d++)
818 if (parsedata[d] == '\xA0')
822 // and we're done, the line is fine!
826 int ServerConfig::fgets_safe(char* buffer, size_t maxsize, FILE* &file)
829 unsigned int bufptr = 0;
830 while ((!feof(file)) && (c_read != '\n') && (c_read != '\r') && (bufptr < maxsize))
832 c_read = fgetc(file);
833 if ((c_read != '\n') && (c_read != '\r'))
834 buffer[bufptr++] = c_read;
836 buffer[bufptr] = '\0';
840 bool ServerConfig::LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream)
843 errorstream->str("");
845 // first, check that the file exists before we try to do anything with it
846 if (!FileExists(filename))
848 *errorstream << "File " << filename << " not found." << endl;
851 // Fix the chmod of the file to restrict it to the current user and group
852 chmod(filename,0600);
853 for (unsigned int t = 0; t < include_stack.size(); t++)
855 if (std::string(filename) == include_stack[t])
857 *errorstream << "File " << filename << " is included recursively (looped inclusion)." << endl;
861 include_stack.push_back(filename);
863 FILE* conf = fopen(filename,"r");
869 if (fgets_safe(buffer, MAXBUF, conf))
871 if ((!feof(conf)) && (buffer) && (strlen(buffer)))
873 if ((buffer[0] != '#') && (buffer[0] != '\r') && (buffer[0] != '\n'))
875 if (!strncmp(buffer,"<include file=\"",15))
878 char confpath[10240],newconf[10240];
879 // include file directive
880 buf += 15; // advance to filename
881 for (unsigned int j = 0; j < strlen(buf); j++)
891 log(DEBUG,"Opening included file '%s'",buf);
894 strlcpy(confpath,CONFIG_FILE,10240);
895 if (strstr(confpath,"/inspircd.conf"))
897 // leaves us with just the path
898 *(strstr(confpath,"/inspircd.conf")) = '\0';
900 snprintf(newconf,10240,"%s/%s",confpath,buf);
902 else strlcpy(newconf,buf,10240);
903 std::stringstream merge(stringstream::in | stringstream::out);
904 // recursively call LoadConf and get the new data, use the same errorstream
905 if (LoadConf(newconf, &merge, errorstream))
907 // append to the end of the file
908 std::string newstuff = merge.str();
913 // the error propogates up to its parent recursively
914 // causing the config reader to bail at the top level.
922 std::string data = this->ConfProcess(buffer,linenumber++,errorstream,error,filename);
940 /* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */
942 int ServerConfig::EnumConf(std::stringstream *config, const char* tag)
945 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
946 int in_token, in_quotes, tptr, idx = 0;
948 std::string x = config->str();
949 const char* buf = x.c_str();
951 long len = config->str().length();
961 if ((c == '#') && (lastc == '\n'))
963 while ((c != '\n') && (bptr<len))
969 if ((c == '<') && (!in_quotes))
984 in_quotes = (!in_quotes);
986 if ((c == '>') && (!in_quotes))
989 if (!strcmp(c_tag,tag))
991 /* correct tag, but wrong index */
1001 if ((in_token) && (c != '\n') && (c != '\r'))
1011 /* Counts the number of values within a certain tag */
1013 int ServerConfig::EnumValues(std::stringstream *config, const char* tag, int index)
1016 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
1017 int in_token, in_quotes, tptr, idx = 0;
1019 bool correct_tag = false;
1022 const char* buf = config->str().c_str();
1024 long len = strlen(buf);
1034 if ((c == '#') && (lastc == '\n'))
1036 while ((c != '\n') && (bptr<len))
1042 if ((c == '<') && (!in_quotes))
1053 if ((!strcmp(c_tag,tag)) && (idx == index))
1062 in_quotes = (!in_quotes);
1065 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
1069 if ((c == '>') && (!in_quotes))
1073 correct_tag = false;
1074 if (!strcmp(c_tag,tag))
1076 /* correct tag, but wrong index */
1086 if ((in_token) && (c != '\n') && (c != '\r'))
1098 int ServerConfig::ConfValueEnum(char* tag, std::stringstream* config)
1100 return EnumConf(config,tag);
1105 /* Retrieves a value from the config file. If there is more than one value of the specified
1106 * key and section (e.g. for opers etc) then the index value specifies which to retreive, e.g.
1108 * ConfValue("oper","name",2,result);
1111 int ServerConfig::ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
1114 char buffer[65535], c_tag[MAXBUF], c, lastc;
1115 int in_token, in_quotes, tptr, idx = 0;
1118 std::string x = config->str();
1119 const char* buf = x.c_str();
1121 long len = config->str().length();
1133 // FIX: Treat tabs as spaces
1136 if ((c == '<') && (!in_quotes))
1147 // FIX: Tab can follow a tagname as well as space.
1148 } while ((c != ' ') && (c != 9));
1152 in_quotes = (!in_quotes);
1154 if ((c == '>') && (!in_quotes))
1159 if (!strcmp(c_tag,tag))
1161 if ((buffer) && (c_tag) && (var))
1163 key = strstr(buffer,var);
1166 /* value not found in tag */
1184 for (unsigned j = 0; j < strlen(key); j++)
1191 strlcpy(result,key,MAXBUF);
1197 if (!strcmp(c_tag,tag))
1199 /* correct tag, but wrong index */
1209 if ((in_token) && (c != '\n') && (c != '\r'))
1216 *result = 0; // value or its tag not found at all
1222 int ServerConfig::ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
1224 ReadConf(config, tag, var, index, result);
1230 // This will bind a socket to a port. It works for UDP/TCP
1231 int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
1233 memset((char *)&server,0,sizeof(server));
1234 struct in_addr addy;
1235 inet_aton(addr,&addy);
1236 server.sin_family = AF_INET;
1239 server.sin_addr.s_addr = htonl(INADDR_ANY);
1243 server.sin_addr = addy;
1245 server.sin_port = htons(port);
1246 if (bind(sockfd,(struct sockaddr*)&server,sizeof(server))<0)
1252 listen(sockfd, Config->MaxConn);
1258 // Open a TCP Socket
1259 int OpenTCPSocket (void)
1263 struct linger linger = { 0 };
1265 if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
1269 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
1270 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
1272 linger.l_linger = 1;
1273 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));
1280 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
1281 sockaddr_in client,server;
1282 int clientportcount = 0;
1283 int BoundPortCount = 0;
1285 for (int count = 0; count < Config->ConfValueEnum("bind",&Config->config_f); count++)
1287 Config->ConfValue("bind","port",count,configToken,&Config->config_f);
1288 Config->ConfValue("bind","address",count,Addr,&Config->config_f);
1289 Config->ConfValue("bind","type",count,Type,&Config->config_f);
1291 if ((!*Type) || (!strcmp(Type,"clients")))
1293 // modules handle server bind types now
1294 Config->ports[clientportcount] = atoi(configToken);
1296 // If the client put bind "*", this is an unrealism.
1297 // We don't actually support this as documented, but
1298 // i got fed up of people trying it, so now it converts
1299 // it to an empty string meaning the same 'bind to all'.
1303 strlcpy(Config->addrs[clientportcount],Addr,256);
1305 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
1309 int PortCount = clientportcount;
1311 for (int count = 0; count < PortCount; count++)
1313 if ((openSockfd[BoundPortCount] = OpenTCPSocket()) == ERROR)
1315 log(DEBUG,"InspIRCd: startup: bad fd %lu binding port [%s:%d]",(unsigned long)openSockfd[BoundPortCount],Config->addrs[count],(unsigned long)Config->ports[count]);
1319 if (BindSocket(openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]) == ERROR)
1321 log(DEFAULT,"InspIRCd: startup: failed to bind port [%s:%lu]: %s",Config->addrs[count],(unsigned long)Config->ports[count],strerror(errno));
1325 /* well we at least bound to one socket so we'll continue */
1330 /* if we didn't bind to anything then abort */
1331 if (!BoundPortCount)
1333 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
1334 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)PortCount);
1338 return BoundPortCount;