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 /** Yes yes, i know, this function is craq worthy of
155 * sirv. Its a mess, and some day i will tidy it.
156 * ...But that day will not be today. or probaby not
157 * tomorrow even, because it works fine.
159 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF],MCON[MAXBUF],MT[MAXBUF];
160 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF],SLIMT[MAXBUF];
161 char localmax[MAXBUF],globalmax[MAXBUF],HS[MAXBUF],HB[MAXBUF],ServName[MAXBUF];
163 std::stringstream errstr;
164 include_stack.clear();
166 if (!LoadConf(CONFIG_FILE,&Config->config_f,&errstr))
169 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
172 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
180 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
181 while (!errstr.eof())
183 errstr.getline(dataline,1024);
184 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
189 WriteOpers("There were errors in the configuration file:");
190 while (!errstr.eof())
192 errstr.getline(dataline,1024);
193 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);
245 Config->HideSplits = ((*HS == 'y') || (*HS == 'Y') || (*HS == '1') || (*HS == 't') || (*HS == 'T'));
246 Config->HideBans = ((*HB == 'y') || (*HB == 'Y') || (*HB == '1') || (*HB == 't') || (*HB == 'T'));
247 Config->SoftLimit = atoi(SLIMT);
249 Config->MaxTargets = atoi(MT);
250 if ((Config->MaxTargets < 0) || (Config->MaxTargets > 31))
252 log(DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
253 Config->MaxTargets = 20;
255 if ((Config->SoftLimit < 1) || (Config->SoftLimit > MAXCLIENTS))
257 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
258 Config->SoftLimit = MAXCLIENTS;
260 Config->MaxConn = atoi(MCON);
261 if (Config->MaxConn > SOMAXCONN)
262 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
263 Config->NetBufferSize = atoi(NB);
264 Config->MaxWhoResults = atoi(MW);
265 Config->dns_timeout = atoi(DNT);
266 if (!strchr(Config->ServerName,'.'))
268 log(DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s%c'",Config->ServerName,Config->ServerName,'.');
269 charlcat(Config->ServerName,'.',MAXBUF);
271 if (!Config->dns_timeout)
272 Config->dns_timeout = 5;
273 if (!Config->MaxConn)
274 Config->MaxConn = SOMAXCONN;
275 if (!*Config->DNSServer)
277 // attempt to look up their nameserver from /etc/resolv.conf
278 log(DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
279 ifstream resolv("/etc/resolv.conf");
280 std::string nameserver;
281 bool found_server = false;
282 if (resolv.is_open())
284 while (resolv >> nameserver)
286 if ((nameserver == "nameserver") && (!found_server))
288 resolv >> nameserver;
289 strlcpy(Config->DNSServer,nameserver.c_str(),MAXBUF);
291 log(DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
296 log(DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
297 strlcpy(Config->DNSServer,"127.0.0.1",MAXBUF);
302 log(DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
303 strlcpy(Config->DNSServer,"127.0.0.1",MAXBUF);
306 if (!*Config->ModPath)
307 strlcpy(Config->ModPath,MOD_PATH,MAXBUF);
308 Config->AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
309 if ((!Config->NetBufferSize) || (Config->NetBufferSize > 65535) || (Config->NetBufferSize < 1024))
311 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
312 Config->NetBufferSize = 10240;
314 if ((!Config->MaxWhoResults) || (Config->MaxWhoResults > 65535) || (Config->MaxWhoResults < 1))
316 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
317 Config->MaxWhoResults = 128;
319 Config->LogLevel = DEFAULT;
320 if (!strcmp(dbg,"debug"))
322 Config->LogLevel = DEBUG;
323 Config->debugging = 1;
325 if (!strcmp(dbg,"verbose"))
326 Config->LogLevel = VERBOSE;
327 if (!strcmp(dbg,"default"))
328 Config->LogLevel = DEFAULT;
329 if (!strcmp(dbg,"sparse"))
330 Config->LogLevel = SPARSE;
331 if (!strcmp(dbg,"none"))
332 Config->LogLevel = NONE;
334 readfile(Config->MOTD,Config->motd);
335 log(DEFAULT,"Reading message of the day...");
336 readfile(Config->RULES,Config->rules);
337 log(DEFAULT,"Reading connect classes...");
339 for (int i = 0; i < ConfValueEnum("connect",&Config->config_f); i++)
342 ConfValue("connect","allow",i,Value,&Config->config_f);
343 ConfValue("connect","timeout",i,timeout,&Config->config_f);
344 ConfValue("connect","flood",i,flood,&Config->config_f);
345 ConfValue("connect","pingfreq",i,pfreq,&Config->config_f);
346 ConfValue("connect","threshold",i,thold,&Config->config_f);
347 ConfValue("connect","sendq",i,sqmax,&Config->config_f);
348 ConfValue("connect","recvq",i,rqmax,&Config->config_f);
349 ConfValue("connect","localmax",i,localmax,&Config->config_f);
350 ConfValue("connect","globalmax",i,globalmax,&Config->config_f);
355 strlcpy(Value,"",MAXBUF);
356 ConfValue("connect","password",i,Value,&Config->config_f);
358 c.registration_timeout = 90; // default is 2 minutes
360 c.flood = atoi(flood);
362 c.sendqmax = 262144; // 256k
363 c.recvqmax = 4096; // 4k
366 if (atoi(localmax)>0)
368 c.maxlocal = atoi(localmax);
370 if (atoi(globalmax)>0)
372 c.maxglobal = atoi(globalmax);
376 c.threshold = atoi(thold);
382 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());
386 c.sendqmax = atoi(sqmax);
390 c.recvqmax = atoi(rqmax);
394 c.registration_timeout = atoi(timeout);
398 c.pingtime = atoi(pfreq);
400 Classes.push_back(c);
404 ConfValue("connect","deny",i,Value,&Config->config_f);
407 Classes.push_back(c);
408 log(DEBUG,"Read connect class type DENY, host=%s",c.host.c_str());
412 Config->ulines.clear();
413 for (int i = 0; i < ConfValueEnum("uline",&Config->config_f); i++)
415 ConfValue("uline","server",i,ServName,&Config->config_f);
417 log(DEBUG,"Read ULINE '%s'",ServName);
418 Config->ulines.push_back(ServName);
422 char CM1[MAXBUF],CM2[MAXBUF];
423 for (int count = 0; count < Config->ConfValueEnum("banlist",&Config->config_f); count++)
425 Config->ConfValue("banlist","chan",count,CM1,&Config->config_f);
426 Config->ConfValue("banlist","limit",count,CM2,&Config->config_f);
427 maxbans[CM1] = atoi(CM2);
429 ReadClassesAndTypes();
430 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
431 read_xline_defaults();
432 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
433 apply_lines(APPLY_ALL);
435 ConfValue("pid","file",0,Config->PID,&Config->config_f);
436 // write once here, to try it out and make sure its ok
437 WritePID(Config->PID);
439 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
442 log(DEFAULT,"Adding and removing modules due to rehash...");
444 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
446 // store the old module names
447 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
449 old_module_names.push_back(*t);
452 // get the new module names
453 for (int count2 = 0; count2 < ConfValueEnum("module",&Config->config_f); count2++)
455 ConfValue("module","name",count2,Value,&Config->config_f);
456 new_module_names.push_back(Value);
459 // now create a list of new modules that are due to be loaded
460 // and a seperate list of modules which are due to be unloaded
461 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
464 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
470 added_modules.push_back(*_new);
472 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
475 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
481 removed_modules.push_back(*oldm);
483 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
485 int rem = 0, add = 0;
486 if (!removed_modules.empty())
487 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
489 if (ServerInstance->UnloadModule(removing->c_str()))
491 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
493 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
499 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
502 if (!added_modules.empty())
503 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
505 if (ServerInstance->LoadModule(adding->c_str()))
507 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
509 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
515 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
518 log(DEFAULT,"Successfully unloaded %lu of %lu modules and loaded %lu of %lu modules.",(unsigned long)rem,(unsigned long)removed_modules.size(),
519 (unsigned long)add,(unsigned long)added_modules.size());
524 void Exit (int status)
526 if (Config->log_file)
527 fclose(Config->log_file);
528 send_error("Server shutdown.");
532 void Killed(int status)
534 if (Config->log_file)
535 fclose(Config->log_file);
536 send_error("Server terminated.");
540 char* CleanFilename(char* name)
542 char* p = name + strlen(name);
543 while ((p != name) && (*p != '/')) p--;
544 return (p != name ? ++p : p);
548 void Rehash(int status)
550 WriteOpers("Rehashing config file %s due to SIGHUP",CleanFilename(CONFIG_FILE));
551 fclose(Config->log_file);
553 Config->Read(false,NULL);
554 FOREACH_MOD(I_OnRehash,OnRehash(""));
561 printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
562 printf("(C) ChatSpike Development team.\033[0m\n\n");
563 printf("Developers:\033[1;32m Brain, FrostyCoolSlug\033[0m\n");
564 printf("Documentation:\033[1;32m FrostyCoolSlug, w00t\033[0m\n");
565 printf("Testers:\033[1;32m typobox43, piggles, Lord_Zathras, CC\033[0m\n");
566 printf("Name concept:\033[1;32m Lord_Zathras\033[0m\n\n");
569 void WritePID(std::string filename)
571 ofstream outfile(filename.c_str());
572 if (outfile.is_open())
579 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
580 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
587 signal (SIGALRM, SIG_IGN);
588 signal (SIGHUP, Rehash);
589 signal (SIGPIPE, SIG_IGN);
590 signal (SIGTERM, Exit);
591 signal (SIGSEGV, Error);
595 int DaemonSeed (void)
598 if ((childpid = fork ()) < 0)
600 else if (childpid > 0)
602 /* We wait a few seconds here, so that the shell prompt doesnt come back over the output */
608 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
610 if (Config->unlimitcore)
613 if (getrlimit(RLIMIT_CORE, &rl) == -1)
615 log(DEFAULT,"Failed to getrlimit()!");
620 rl.rlim_cur = rl.rlim_max;
621 if (setrlimit(RLIMIT_CORE, &rl) == -1)
622 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
630 /* Make Sure Modules Are Avaliable!
631 * (BugFix By Craig.. See? I do work! :p)
632 * Modified by brain, requires const char*
633 * to work with other API functions
636 bool FileExists (const char* file)
639 if ((input = fopen (file, "r")) == NULL)
650 /* ConfProcess does the following things to a config line in the following order:
652 * Processes the line for syntax errors as shown below
653 * (1) Line void of quotes or equals (a malformed, illegal tag format)
654 * (2) Odd number of quotes on the line indicating a missing quote
655 * (3) number of equals signs not equal to number of quotes / 2 (missing an equals sign)
656 * (4) Spaces between the opening bracket (<) and the keyword
657 * (5) Spaces between a keyword and an equals sign
658 * (6) Spaces between an equals sign and a quote
659 * Removes trailing spaces
660 * Removes leading spaces
661 * Converts tabs to spaces
662 * Turns multiple spaces that are outside of quotes into single spaces
665 std::string ServerConfig::ConfProcess(char* buffer, long linenumber, std::stringstream* errorstream, bool &error, std::string filename)
667 long number_of_quotes = 0;
668 long number_of_equals = 0;
669 bool has_open_bracket = false;
670 bool in_quotes = false;
676 // firstly clean up the line by stripping spaces from the start and end and converting tabs to spaces
677 for (char* d = buffer; *d; d++)
680 while (*buffer == ' ') buffer++;
681 while ((buffer[strlen(buffer)-1] == ' ') && (*buffer)) buffer[strlen(buffer)-1] = '\0';
683 // empty lines are syntactically valid, as are comments
684 if (!(*buffer) || buffer[0] == '#')
687 for (unsigned int c = 0; c < strlen(buffer); c++)
689 // convert all spaces that are OUTSIDE quotes into hardspace (0xA0) as this will make them easier to
690 // search and replace later :)
691 if ((!in_quotes) && (buffer[c] == ' '))
693 if ((buffer[c] == '<') && (!in_quotes))
695 has_open_bracket = true;
696 if (strlen(buffer) == 1)
698 *errorstream << "Tag without identifier at " << filename << ":" << linenumber << endl;
702 else if ((tolower(buffer[c+1]) < 'a') || (tolower(buffer[c+1]) > 'z'))
704 *errorstream << "Invalid characters in identifier at " << filename << ":" << linenumber << endl;
709 if (buffer[c] == '"')
712 in_quotes = (!in_quotes);
714 if ((buffer[c] == '=') && (!in_quotes))
717 if (strlen(buffer) == c)
719 *errorstream << "Variable without a value at " << filename << ":" << linenumber << endl;
723 else if (buffer[c+1] != '"')
725 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
731 *errorstream << "Value without a variable (line starts with '=') at " << filename << ":" << linenumber << endl;
735 else if (buffer[c-1] == '\xA0')
737 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
743 // no quotes, and no equals. something freaky.
744 if ((!number_of_quotes) || (!number_of_equals) && (strlen(buffer)>2) && (buffer[0]=='<'))
746 *errorstream << "Malformed tag at " << filename << ":" << linenumber << endl;
750 // odd number of quotes. thats just wrong.
751 if ((number_of_quotes % 2) != 0)
753 *errorstream << "Missing \" at " << filename << ":" << linenumber << endl;
757 if (number_of_equals < (number_of_quotes/2))
759 *errorstream << "Missing '=' at " << filename << ":" << linenumber << endl;
761 if (number_of_equals > (number_of_quotes/2))
763 *errorstream << "Too many '=' at " << filename << ":" << linenumber << endl;
766 std::string parsedata = buffer;
767 // turn multispace into single space
768 while (parsedata.find("\xA0\xA0") != std::string::npos)
770 parsedata.erase(parsedata.find("\xA0\xA0"),1);
773 // turn our hardspace back into softspace
774 for (unsigned int d = 0; d < parsedata.length(); d++)
776 if (parsedata[d] == '\xA0')
780 // and we're done, the line is fine!
784 int ServerConfig::fgets_safe(char* buffer, size_t maxsize, FILE* &file)
787 unsigned int bufptr = 0;
788 while ((!feof(file)) && (c_read != '\n') && (c_read != '\r') && (bufptr < maxsize))
790 c_read = fgetc(file);
791 if ((c_read != '\n') && (c_read != '\r'))
792 buffer[bufptr++] = c_read;
794 buffer[bufptr] = '\0';
798 bool ServerConfig::LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream)
801 errorstream->str("");
803 // first, check that the file exists before we try to do anything with it
804 if (!FileExists(filename))
806 *errorstream << "File " << filename << " not found." << endl;
809 // Fix the chmod of the file to restrict it to the current user and group
810 chmod(filename,0600);
811 for (unsigned int t = 0; t < include_stack.size(); t++)
813 if (std::string(filename) == include_stack[t])
815 *errorstream << "File " << filename << " is included recursively (looped inclusion)." << endl;
819 include_stack.push_back(filename);
821 FILE* conf = fopen(filename,"r");
827 if (fgets_safe(buffer, MAXBUF, conf))
829 if ((!feof(conf)) && (buffer) && (strlen(buffer)))
831 if ((buffer[0] != '#') && (buffer[0] != '\r') && (buffer[0] != '\n'))
833 if (!strncmp(buffer,"<include file=\"",15))
836 char confpath[10240],newconf[10240];
837 // include file directive
838 buf += 15; // advance to filename
839 for (unsigned int j = 0; j < strlen(buf); j++)
849 log(DEBUG,"Opening included file '%s'",buf);
852 strlcpy(confpath,CONFIG_FILE,10240);
853 if (strstr(confpath,"/inspircd.conf"))
855 // leaves us with just the path
856 *(strstr(confpath,"/inspircd.conf")) = '\0';
858 snprintf(newconf,10240,"%s/%s",confpath,buf);
860 else strlcpy(newconf,buf,10240);
861 std::stringstream merge(stringstream::in | stringstream::out);
862 // recursively call LoadConf and get the new data, use the same errorstream
863 if (LoadConf(newconf, &merge, errorstream))
865 // append to the end of the file
866 std::string newstuff = merge.str();
871 // the error propogates up to its parent recursively
872 // causing the config reader to bail at the top level.
880 std::string data = this->ConfProcess(buffer,linenumber++,errorstream,error,filename);
898 /* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */
900 int ServerConfig::EnumConf(std::stringstream *config, const char* tag)
903 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
904 int in_token, in_quotes, tptr, idx = 0;
906 std::string x = config->str();
907 const char* buf = x.c_str();
909 long len = config->str().length();
919 if ((c == '#') && (lastc == '\n'))
921 while ((c != '\n') && (bptr<len))
927 if ((c == '<') && (!in_quotes))
942 in_quotes = (!in_quotes);
944 if ((c == '>') && (!in_quotes))
947 if (!strcmp(c_tag,tag))
949 /* correct tag, but wrong index */
959 if ((in_token) && (c != '\n') && (c != '\r'))
969 /* Counts the number of values within a certain tag */
971 int ServerConfig::EnumValues(std::stringstream *config, const char* tag, int index)
974 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
975 int in_token, in_quotes, tptr, idx = 0;
977 bool correct_tag = false;
980 const char* buf = config->str().c_str();
982 long len = strlen(buf);
992 if ((c == '#') && (lastc == '\n'))
994 while ((c != '\n') && (bptr<len))
1000 if ((c == '<') && (!in_quotes))
1011 if ((!strcmp(c_tag,tag)) && (idx == index))
1020 in_quotes = (!in_quotes);
1023 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
1027 if ((c == '>') && (!in_quotes))
1031 correct_tag = false;
1032 if (!strcmp(c_tag,tag))
1034 /* correct tag, but wrong index */
1044 if ((in_token) && (c != '\n') && (c != '\r'))
1056 int ServerConfig::ConfValueEnum(char* tag, std::stringstream* config)
1058 return EnumConf(config,tag);
1063 /* Retrieves a value from the config file. If there is more than one value of the specified
1064 * key and section (e.g. for opers etc) then the index value specifies which to retreive, e.g.
1066 * ConfValue("oper","name",2,result);
1069 int ServerConfig::ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
1072 char buffer[65535], c_tag[MAXBUF], c, lastc;
1073 int in_token, in_quotes, tptr, idx = 0;
1076 std::string x = config->str();
1077 const char* buf = x.c_str();
1079 long len = config->str().length();
1091 // FIX: Treat tabs as spaces
1094 if ((c == '<') && (!in_quotes))
1105 // FIX: Tab can follow a tagname as well as space.
1106 } while ((c != ' ') && (c != 9));
1110 in_quotes = (!in_quotes);
1112 if ((c == '>') && (!in_quotes))
1117 if (!strcmp(c_tag,tag))
1119 if ((buffer) && (c_tag) && (var))
1121 key = strstr(buffer,var);
1124 /* value not found in tag */
1142 for (unsigned j = 0; j < strlen(key); j++)
1149 strlcpy(result,key,MAXBUF);
1155 if (!strcmp(c_tag,tag))
1157 /* correct tag, but wrong index */
1167 if ((in_token) && (c != '\n') && (c != '\r'))
1174 *result = 0; // value or its tag not found at all
1180 int ServerConfig::ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
1182 ReadConf(config, tag, var, index, result);
1188 // This will bind a socket to a port. It works for UDP/TCP
1189 int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
1191 memset((char *)&server,0,sizeof(server));
1192 struct in_addr addy;
1193 inet_aton(addr,&addy);
1194 server.sin_family = AF_INET;
1197 server.sin_addr.s_addr = htonl(INADDR_ANY);
1201 server.sin_addr = addy;
1203 server.sin_port = htons(port);
1204 if (bind(sockfd,(struct sockaddr*)&server,sizeof(server))<0)
1210 listen(sockfd, Config->MaxConn);
1216 // Open a TCP Socket
1217 int OpenTCPSocket (void)
1221 struct linger linger = { 0 };
1223 if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
1227 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
1228 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
1230 linger.l_linger = 1;
1231 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));
1238 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
1239 sockaddr_in client,server;
1240 int clientportcount = 0;
1241 int BoundPortCount = 0;
1242 for (int count = 0; count < Config->ConfValueEnum("bind",&Config->config_f); count++)
1244 Config->ConfValue("bind","port",count,configToken,&Config->config_f);
1245 Config->ConfValue("bind","address",count,Addr,&Config->config_f);
1246 Config->ConfValue("bind","type",count,Type,&Config->config_f);
1247 if ((!*Type) || (!strcmp(Type,"clients")))
1249 // modules handle server bind types now
1250 Config->ports[clientportcount] = atoi(configToken);
1252 // If the client put bind "*", this is an unrealism.
1253 // We don't actually support this as documented, but
1254 // i got fed up of people trying it, so now it converts
1255 // it to an empty string meaning the same 'bind to all'.
1259 strlcpy(Config->addrs[clientportcount],Addr,256);
1261 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
1264 int PortCount = clientportcount;
1266 for (int count = 0; count < PortCount; count++)
1268 if ((openSockfd[BoundPortCount] = OpenTCPSocket()) == ERROR)
1270 log(DEBUG,"InspIRCd: startup: bad fd %lu binding port [%s:%d]",(unsigned long)openSockfd[BoundPortCount],Config->addrs[count],(unsigned long)Config->ports[count]);
1273 if (BindSocket(openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]) == ERROR)
1275 log(DEFAULT,"InspIRCd: startup: failed to bind port [%s:%lu]: %s",Config->addrs[count],(unsigned long)Config->ports[count],strerror(errno));
1277 else /* well we at least bound to one socket so we'll continue */
1283 /* if we didn't bind to anything then abort */
1284 if (!BoundPortCount)
1286 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
1287 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)PortCount);
1291 return BoundPortCount;