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 typedef bool (*Validator)(const char*, const char*, void*);
154 enum ConfigDataType { DT_NOTHING, DT_INTEGER, DT_CHARPTR, DT_BOOLEAN };
156 struct InitialConfig {
160 ConfigDataType datatype;
161 Validator validate_function;
164 bool NoValidation(const char* tag, const char* value, void* data)
166 log(DEBUG,"No validation for <%s:%s>",tag,value);
170 void ServerConfig::Read(bool bail, userrec* user)
174 InitialConfig Values[] = {
175 {"options", "softlimit", &this->SoftLimit, DT_INTEGER, NoValidation},
176 {"options", "somaxconn", &this->MaxConn, DT_INTEGER, NoValidation},
177 {"server", "name", &this->ServerName, DT_CHARPTR, NoValidation},
178 {"server", "description", &this->ServerDesc, DT_CHARPTR, NoValidation},
179 {"server", "network", &this->Network, DT_CHARPTR, NoValidation},
180 {"admin" "name", &this->AdminName, DT_CHARPTR, NoValidation},
181 {"admin", "email", &this->AdminEmail, DT_CHARPTR, NoValidation},
182 {"admin", "nick", &this->AdminNick, DT_CHARPTR, NoValidation},
183 {"files", "motd", &this->motd, DT_CHARPTR, NoValidation},
184 {"files", "rules", &this->rules, DT_CHARPTR, NoValidation},
185 {"power", "diepass", &this->diepass, DT_CHARPTR, NoValidation},
186 {"power", "pauseval", &this->DieDelay, DT_INTEGER, NoValidation},
187 {"power", "restartpass", &this->restartpass, DT_CHARPTR, NoValidation},
188 {"options", "prefixquit", &this->PrefixQuit, DT_CHARPTR, NoValidation},
189 {"die", "value", &this->DieValue, DT_CHARPTR, NoValidation},
190 {"options", "loglevel", &debug, DT_CHARPTR, NoValidation},
191 {"options", "netbuffersize", &this->NetBufferSize, DT_INTEGER, NoValidation},
192 {"options", "maxwho", &this->MaxWhoResults, DT_INTEGER, NoValidation},
193 {"options", "allowhalfop", &this->AllowHalfop, DT_BOOLEAN, NoValidation},
194 {"dns", "server", &this->DNSServer, DT_CHARPTR, NoValidation},
195 {"dns", "timeout", &this->dns_timeout, DT_INTEGER, NoValidation},
196 {"options", "moduledir", &this->ModPath, DT_CHARPTR, NoValidation},
197 {"disabled", "commands", &this->DisabledCommands, DT_CHARPTR, NoValidation},
198 {"options", "operonlystats", &this->OperOnlyStats, DT_CHARPTR, NoValidation},
199 {"options", "customversion", &this->CustomVersion, DT_CHARPTR, NoValidation},
200 {"options", "hidesplits", &this->HideSplits, DT_BOOLEAN, NoValidation},
201 {"options", "hidebans", &this->HideBans, DT_BOOLEAN, NoValidation},
202 {"options", "hidewhois", &this->HideWhoisServer, DT_CHARPTR, NoValidation},
203 {"options", "tempdir", &this->TempDir, DT_CHARPTR, NoValidation},
207 /* XXX - this needs a rework someday, BAD. */
208 char timeout[MAXBUF],flood[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF],SLIMT[MAXBUF];
209 char localmax[MAXBUF],globalmax[MAXBUF],ServName[MAXBUF];
212 std::stringstream errstr;
214 include_stack.clear();
216 if (!LoadConf(CONFIG_FILE,&Config->config_f,&errstr))
219 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
223 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
232 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
233 while (!errstr.eof())
235 errstr.getline(dataline,1024);
236 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
241 WriteOpers("There were errors in the configuration file:");
242 while (!errstr.eof())
244 errstr.getline(dataline,1024);
245 WriteOpers(dataline);
253 /* Check we dont have more than one of singular tags
255 if (!CheckOnce("server",bail,user) || !CheckOnce("admin",bail,user) || !CheckOnce("files",bail,user)
256 || !CheckOnce("power",bail,user) || !CheckOnce("options",bail,user) || !CheckOnce("pid",bail,user))
262 for (int Index = 0; Values[Index].datatype != DT_NOTHING; Index++)
264 void* val = Values[Index].val;
266 switch (Values[Index].datatype)
269 ConfValue((char*)Values[Index].tag,(char*)Values[Index].value,(char*) val,this->config_f);
273 convert = new char[MAXBUF];
274 ConfValue(Values[Index].tag,Values[Index].value,convert,this->config_f);
275 *val = atoi(convert);
280 convert = new char[MAXBUF];
281 ConfValue(Values[Index].tag,Values[Index].value,convert,this->config_f);
282 *val = ((*convert == tolower('y')) || (*convert == tolower('t')) || (*convert == '1'));
290 Values[Index].validation_function(Values[Index].tag, Values[Index].value, Values[Index].val);
293 strlower(this->ServerName);
295 if (!*Config->TempDir)
296 strlcpy(Config->TempDir,"/tmp",1024);
298 if ((Config->MaxTargets < 0) || (Config->MaxTargets > 31))
300 log(DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
301 Config->MaxTargets = 20;
304 if ((Config->SoftLimit < 1) || (Config->SoftLimit > MAXCLIENTS))
306 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
307 Config->SoftLimit = MAXCLIENTS;
310 Config->MaxConn = atoi(MCON);
312 if (Config->MaxConn > SOMAXCONN)
313 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
315 Config->NetBufferSize = atoi(NB);
316 Config->MaxWhoResults = atoi(MW);
317 Config->dns_timeout = atoi(DNT);
319 if (!strchr(Config->ServerName,'.'))
321 log(DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s%c'",Config->ServerName,Config->ServerName,'.');
322 charlcat(Config->ServerName,'.',MAXBUF);
325 if (!Config->dns_timeout)
326 Config->dns_timeout = 5;
328 if (!Config->MaxConn)
329 Config->MaxConn = SOMAXCONN;
331 if (!*Config->DNSServer)
333 // attempt to look up their nameserver from /etc/resolv.conf
334 log(DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
335 ifstream resolv("/etc/resolv.conf");
336 std::string nameserver;
337 bool found_server = false;
339 if (resolv.is_open())
341 while (resolv >> nameserver)
343 if ((nameserver == "nameserver") && (!found_server))
345 resolv >> nameserver;
346 strlcpy(Config->DNSServer,nameserver.c_str(),MAXBUF);
348 log(DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
354 log(DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
355 strlcpy(Config->DNSServer,"127.0.0.1",MAXBUF);
360 log(DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
361 strlcpy(Config->DNSServer,"127.0.0.1",MAXBUF);
365 if (!*Config->ModPath)
366 strlcpy(Config->ModPath,MOD_PATH,MAXBUF);
368 Config->AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
370 if ((!Config->NetBufferSize) || (Config->NetBufferSize > 65535) || (Config->NetBufferSize < 1024))
372 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
373 Config->NetBufferSize = 10240;
376 if ((!Config->MaxWhoResults) || (Config->MaxWhoResults > 65535) || (Config->MaxWhoResults < 1))
378 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
379 Config->MaxWhoResults = 128;
382 Config->LogLevel = DEFAULT;
384 if (!strcmp(dbg,"debug"))
386 Config->LogLevel = DEBUG;
387 Config->debugging = 1;
389 else if (!strcmp(dbg,"verbose"))
390 Config->LogLevel = VERBOSE;
391 else if (!strcmp(dbg,"default"))
392 Config->LogLevel = DEFAULT;
393 else if (!strcmp(dbg,"sparse"))
394 Config->LogLevel = SPARSE;
395 else if (!strcmp(dbg,"none"))
396 Config->LogLevel = NONE;
398 readfile(Config->MOTD,Config->motd);
399 log(DEFAULT,"Reading message of the day...");
400 readfile(Config->RULES,Config->rules);
401 log(DEFAULT,"Reading connect classes...");
404 for (int i = 0; i < ConfValueEnum("connect",&Config->config_f); i++)
407 ConfValue("connect","allow",i,Value,&Config->config_f);
408 ConfValue("connect","timeout",i,timeout,&Config->config_f);
409 ConfValue("connect","flood",i,flood,&Config->config_f);
410 ConfValue("connect","pingfreq",i,pfreq,&Config->config_f);
411 ConfValue("connect","threshold",i,thold,&Config->config_f);
412 ConfValue("connect","sendq",i,sqmax,&Config->config_f);
413 ConfValue("connect","recvq",i,rqmax,&Config->config_f);
414 ConfValue("connect","localmax",i,localmax,&Config->config_f);
415 ConfValue("connect","globalmax",i,globalmax,&Config->config_f);
421 strlcpy(Value,"",MAXBUF);
422 ConfValue("connect","password",i,Value,&Config->config_f);
424 c.registration_timeout = 90; // default is 2 minutes
426 c.flood = atoi(flood);
428 c.sendqmax = 262144; // 256k
429 c.recvqmax = 4096; // 4k
433 if (atoi(localmax)>0)
435 c.maxlocal = atoi(localmax);
438 if (atoi(globalmax)>0)
440 c.maxglobal = atoi(globalmax);
445 c.threshold = atoi(thold);
451 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());
456 c.sendqmax = atoi(sqmax);
460 c.recvqmax = atoi(rqmax);
464 c.registration_timeout = atoi(timeout);
468 c.pingtime = atoi(pfreq);
471 Classes.push_back(c);
475 ConfValue("connect","deny",i,Value,&Config->config_f);
478 Classes.push_back(c);
479 log(DEBUG,"Read connect class type DENY, host=%s",c.host.c_str());
483 Config->ulines.clear();
485 for (int i = 0; i < ConfValueEnum("uline",&Config->config_f); i++)
487 ConfValue("uline","server",i,ServName,&Config->config_f);
489 log(DEBUG,"Read ULINE '%s'",ServName);
490 Config->ulines.push_back(ServName);
495 char CM1[MAXBUF],CM2[MAXBUF];
497 for (int count = 0; count < Config->ConfValueEnum("banlist",&Config->config_f); count++)
499 Config->ConfValue("banlist","chan",count,CM1,&Config->config_f);
500 Config->ConfValue("banlist","limit",count,CM2,&Config->config_f);
501 maxbans[CM1] = atoi(CM2);
504 ReadClassesAndTypes();
505 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
506 read_xline_defaults();
507 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
508 apply_lines(APPLY_ALL);
510 ConfValue("pid","file",0,Config->PID,&Config->config_f);
511 // write once here, to try it out and make sure its ok
512 WritePID(Config->PID);
514 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
517 log(DEFAULT,"Adding and removing modules due to rehash...");
519 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
521 // store the old module names
522 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
524 old_module_names.push_back(*t);
527 // get the new module names
528 for (int count2 = 0; count2 < ConfValueEnum("module",&Config->config_f); count2++)
530 ConfValue("module","name",count2,Value,&Config->config_f);
531 new_module_names.push_back(Value);
534 // now create a list of new modules that are due to be loaded
535 // and a seperate list of modules which are due to be unloaded
536 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
540 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
547 added_modules.push_back(*_new);
550 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
553 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
560 removed_modules.push_back(*oldm);
564 * now we have added_modules, a vector of modules to be loaded,
565 * and removed_modules, a vector of modules
568 int rem = 0, add = 0;
569 if (!removed_modules.empty())
570 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
572 if (ServerInstance->UnloadModule(removing->c_str()))
574 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
577 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
584 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
588 if (!added_modules.empty())
589 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
591 if (ServerInstance->LoadModule(adding->c_str()))
593 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
596 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
603 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
607 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());
612 void Exit (int status)
614 if (Config->log_file)
615 fclose(Config->log_file);
616 send_error("Server shutdown.");
620 void Killed(int status)
622 if (Config->log_file)
623 fclose(Config->log_file);
624 send_error("Server terminated.");
628 char* CleanFilename(char* name)
630 char* p = name + strlen(name);
631 while ((p != name) && (*p != '/')) p--;
632 return (p != name ? ++p : p);
636 void Rehash(int status)
638 WriteOpers("Rehashing config file %s due to SIGHUP",CleanFilename(CONFIG_FILE));
639 fclose(Config->log_file);
641 Config->Read(false,NULL);
642 FOREACH_MOD(I_OnRehash,OnRehash(""));
649 printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
650 printf("(C) ChatSpike Development team.\033[0m\n\n");
651 printf("Developers:\033[1;32m Brain, FrostyCoolSlug, w00t, Om\033[0m\n");
652 printf("Others:\033[1;32m See /INFO Output\033[0m\n");
653 printf("Name concept:\033[1;32m Lord_Zathras\033[0m\n\n");
656 void WritePID(std::string filename)
658 ofstream outfile(filename.c_str());
659 if (outfile.is_open())
666 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
667 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
674 signal (SIGALRM, SIG_IGN);
675 signal (SIGHUP, Rehash);
676 signal (SIGPIPE, SIG_IGN);
677 signal (SIGTERM, Exit);
678 signal (SIGSEGV, Error);
682 int DaemonSeed (void)
685 if ((childpid = fork ()) < 0)
687 else if (childpid > 0)
689 /* We wait a few seconds here, so that the shell prompt doesnt come back over the output */
695 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
697 if (Config->unlimitcore)
700 if (getrlimit(RLIMIT_CORE, &rl) == -1)
702 log(DEFAULT,"Failed to getrlimit()!");
707 rl.rlim_cur = rl.rlim_max;
708 if (setrlimit(RLIMIT_CORE, &rl) == -1)
709 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
717 /* Make Sure Modules Are Avaliable!
718 * (BugFix By Craig.. See? I do work! :p)
719 * Modified by brain, requires const char*
720 * to work with other API functions
723 bool FileExists (const char* file)
726 if ((input = fopen (file, "r")) == NULL)
737 /* ConfProcess does the following things to a config line in the following order:
739 * Processes the line for syntax errors as shown below
740 * (1) Line void of quotes or equals (a malformed, illegal tag format)
741 * (2) Odd number of quotes on the line indicating a missing quote
742 * (3) number of equals signs not equal to number of quotes / 2 (missing an equals sign)
743 * (4) Spaces between the opening bracket (<) and the keyword
744 * (5) Spaces between a keyword and an equals sign
745 * (6) Spaces between an equals sign and a quote
746 * Removes trailing spaces
747 * Removes leading spaces
748 * Converts tabs to spaces
749 * Turns multiple spaces that are outside of quotes into single spaces
752 std::string ServerConfig::ConfProcess(char* buffer, long linenumber, std::stringstream* errorstream, bool &error, std::string filename)
754 long number_of_quotes = 0;
755 long number_of_equals = 0;
756 bool has_open_bracket = false;
757 bool in_quotes = false;
763 // firstly clean up the line by stripping spaces from the start and end and converting tabs to spaces
764 for (char* d = buffer; *d; d++)
767 while (*buffer == ' ') buffer++;
768 while ((buffer[strlen(buffer)-1] == ' ') && (*buffer)) buffer[strlen(buffer)-1] = '\0';
770 // empty lines are syntactically valid, as are comments
771 if (!(*buffer) || buffer[0] == '#')
774 for (unsigned int c = 0; c < strlen(buffer); c++)
776 // convert all spaces that are OUTSIDE quotes into hardspace (0xA0) as this will make them easier to
777 // search and replace later :)
778 if ((!in_quotes) && (buffer[c] == ' '))
780 if ((buffer[c] == '<') && (!in_quotes))
782 has_open_bracket = true;
783 if (strlen(buffer) == 1)
785 *errorstream << "Tag without identifier at " << filename << ":" << linenumber << endl;
789 else if ((tolower(buffer[c+1]) < 'a') || (tolower(buffer[c+1]) > 'z'))
791 *errorstream << "Invalid characters in identifier at " << filename << ":" << linenumber << endl;
796 if (buffer[c] == '"')
799 in_quotes = (!in_quotes);
801 if ((buffer[c] == '=') && (!in_quotes))
804 if (strlen(buffer) == c)
806 *errorstream << "Variable without a value at " << filename << ":" << linenumber << endl;
810 else if (buffer[c+1] != '"')
812 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
818 *errorstream << "Value without a variable (line starts with '=') at " << filename << ":" << linenumber << endl;
822 else if (buffer[c-1] == '\xA0')
824 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
830 // no quotes, and no equals. something freaky.
831 if ((!number_of_quotes) || (!number_of_equals) && (strlen(buffer)>2) && (buffer[0]=='<'))
833 *errorstream << "Malformed tag at " << filename << ":" << linenumber << endl;
837 // odd number of quotes. thats just wrong.
838 if ((number_of_quotes % 2) != 0)
840 *errorstream << "Missing \" at " << filename << ":" << linenumber << endl;
844 if (number_of_equals < (number_of_quotes/2))
846 *errorstream << "Missing '=' at " << filename << ":" << linenumber << endl;
848 if (number_of_equals > (number_of_quotes/2))
850 *errorstream << "Too many '=' at " << filename << ":" << linenumber << endl;
853 std::string parsedata = buffer;
854 // turn multispace into single space
855 while (parsedata.find("\xA0\xA0") != std::string::npos)
857 parsedata.erase(parsedata.find("\xA0\xA0"),1);
860 // turn our hardspace back into softspace
861 for (unsigned int d = 0; d < parsedata.length(); d++)
863 if (parsedata[d] == '\xA0')
867 // and we're done, the line is fine!
871 int ServerConfig::fgets_safe(char* buffer, size_t maxsize, FILE* &file)
874 unsigned int bufptr = 0;
875 while ((!feof(file)) && (c_read != '\n') && (c_read != '\r') && (bufptr < maxsize))
877 c_read = fgetc(file);
878 if ((c_read != '\n') && (c_read != '\r'))
879 buffer[bufptr++] = c_read;
881 buffer[bufptr] = '\0';
885 bool ServerConfig::LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream)
888 errorstream->str("");
890 // first, check that the file exists before we try to do anything with it
891 if (!FileExists(filename))
893 *errorstream << "File " << filename << " not found." << endl;
896 // Fix the chmod of the file to restrict it to the current user and group
897 chmod(filename,0600);
898 for (unsigned int t = 0; t < include_stack.size(); t++)
900 if (std::string(filename) == include_stack[t])
902 *errorstream << "File " << filename << " is included recursively (looped inclusion)." << endl;
906 include_stack.push_back(filename);
908 FILE* conf = fopen(filename,"r");
914 if (fgets_safe(buffer, MAXBUF, conf))
916 if ((!feof(conf)) && (buffer) && (strlen(buffer)))
918 if ((buffer[0] != '#') && (buffer[0] != '\r') && (buffer[0] != '\n'))
920 if (!strncmp(buffer,"<include file=\"",15))
923 char confpath[10240],newconf[10240];
924 // include file directive
925 buf += 15; // advance to filename
926 for (unsigned int j = 0; j < strlen(buf); j++)
936 log(DEBUG,"Opening included file '%s'",buf);
939 strlcpy(confpath,CONFIG_FILE,10240);
940 if (strstr(confpath,"/inspircd.conf"))
942 // leaves us with just the path
943 *(strstr(confpath,"/inspircd.conf")) = '\0';
945 snprintf(newconf,10240,"%s/%s",confpath,buf);
947 else strlcpy(newconf,buf,10240);
948 std::stringstream merge(stringstream::in | stringstream::out);
949 // recursively call LoadConf and get the new data, use the same errorstream
950 if (LoadConf(newconf, &merge, errorstream))
952 // append to the end of the file
953 std::string newstuff = merge.str();
958 // the error propogates up to its parent recursively
959 // causing the config reader to bail at the top level.
967 std::string data = this->ConfProcess(buffer,linenumber++,errorstream,error,filename);
985 /* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */
987 int ServerConfig::EnumConf(std::stringstream *config, const char* tag)
990 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
991 int in_token, in_quotes, tptr, idx = 0;
993 std::string x = config->str();
994 const char* buf = x.c_str();
996 long len = config->str().length();
1006 if ((c == '#') && (lastc == '\n'))
1008 while ((c != '\n') && (bptr<len))
1014 if ((c == '<') && (!in_quotes))
1029 in_quotes = (!in_quotes);
1031 if ((c == '>') && (!in_quotes))
1034 if (!strcmp(c_tag,tag))
1036 /* correct tag, but wrong index */
1046 if ((in_token) && (c != '\n') && (c != '\r'))
1056 /* Counts the number of values within a certain tag */
1058 int ServerConfig::EnumValues(std::stringstream *config, const char* tag, int index)
1061 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
1062 int in_token, in_quotes, tptr, idx = 0;
1064 bool correct_tag = false;
1067 const char* buf = config->str().c_str();
1069 long len = strlen(buf);
1079 if ((c == '#') && (lastc == '\n'))
1081 while ((c != '\n') && (bptr<len))
1087 if ((c == '<') && (!in_quotes))
1098 if ((!strcmp(c_tag,tag)) && (idx == index))
1107 in_quotes = (!in_quotes);
1110 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
1114 if ((c == '>') && (!in_quotes))
1118 correct_tag = false;
1119 if (!strcmp(c_tag,tag))
1121 /* correct tag, but wrong index */
1131 if ((in_token) && (c != '\n') && (c != '\r'))
1143 int ServerConfig::ConfValueEnum(char* tag, std::stringstream* config)
1145 return EnumConf(config,tag);
1150 /* Retrieves a value from the config file. If there is more than one value of the specified
1151 * key and section (e.g. for opers etc) then the index value specifies which to retreive, e.g.
1153 * ConfValue("oper","name",2,result);
1156 int ServerConfig::ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
1159 char buffer[65535], c_tag[MAXBUF], c, lastc;
1160 int in_token, in_quotes, tptr, idx = 0;
1163 std::string x = config->str();
1164 const char* buf = x.c_str();
1166 long len = config->str().length();
1178 // FIX: Treat tabs as spaces
1181 if ((c == '<') && (!in_quotes))
1192 // FIX: Tab can follow a tagname as well as space.
1193 } while ((c != ' ') && (c != 9));
1197 in_quotes = (!in_quotes);
1199 if ((c == '>') && (!in_quotes))
1204 if (!strcmp(c_tag,tag))
1206 if ((buffer) && (c_tag) && (var))
1208 key = strstr(buffer,var);
1211 /* value not found in tag */
1229 for (unsigned j = 0; j < strlen(key); j++)
1236 strlcpy(result,key,MAXBUF);
1242 if (!strcmp(c_tag,tag))
1244 /* correct tag, but wrong index */
1254 if ((in_token) && (c != '\n') && (c != '\r'))
1261 *result = 0; // value or its tag not found at all
1267 int ServerConfig::ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
1269 ReadConf(config, tag, var, index, result);
1275 // This will bind a socket to a port. It works for UDP/TCP
1276 int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
1278 memset((char *)&server,0,sizeof(server));
1279 struct in_addr addy;
1280 inet_aton(addr,&addy);
1281 server.sin_family = AF_INET;
1284 server.sin_addr.s_addr = htonl(INADDR_ANY);
1288 server.sin_addr = addy;
1290 server.sin_port = htons(port);
1291 if (bind(sockfd,(struct sockaddr*)&server,sizeof(server))<0)
1297 listen(sockfd, Config->MaxConn);
1303 // Open a TCP Socket
1304 int OpenTCPSocket (void)
1308 struct linger linger = { 0 };
1310 if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
1314 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
1315 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
1317 linger.l_linger = 1;
1318 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));
1325 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
1326 sockaddr_in client,server;
1327 int clientportcount = 0;
1328 int BoundPortCount = 0;
1330 for (int count = 0; count < Config->ConfValueEnum("bind",&Config->config_f); count++)
1332 Config->ConfValue("bind","port",count,configToken,&Config->config_f);
1333 Config->ConfValue("bind","address",count,Addr,&Config->config_f);
1334 Config->ConfValue("bind","type",count,Type,&Config->config_f);
1336 if ((!*Type) || (!strcmp(Type,"clients")))
1338 // modules handle server bind types now
1339 Config->ports[clientportcount] = atoi(configToken);
1341 // If the client put bind "*", this is an unrealism.
1342 // We don't actually support this as documented, but
1343 // i got fed up of people trying it, so now it converts
1344 // it to an empty string meaning the same 'bind to all'.
1348 strlcpy(Config->addrs[clientportcount],Addr,256);
1350 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
1354 int PortCount = clientportcount;
1356 for (int count = 0; count < PortCount; count++)
1358 if ((openSockfd[BoundPortCount] = OpenTCPSocket()) == ERROR)
1360 log(DEBUG,"InspIRCd: startup: bad fd %lu binding port [%s:%d]",(unsigned long)openSockfd[BoundPortCount],Config->addrs[count],(unsigned long)Config->ports[count]);
1364 if (BindSocket(openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]) == ERROR)
1366 log(DEFAULT,"InspIRCd: startup: failed to bind port [%s:%lu]: %s",Config->addrs[count],(unsigned long)Config->ports[count],strerror(errno));
1370 /* well we at least bound to one socket so we'll continue */
1375 /* if we didn't bind to anything then abort */
1376 if (!BoundPortCount)
1378 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
1379 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)PortCount);
1383 return BoundPortCount;