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>
30 #include "inspircd_io.h"
31 #include "inspstring.h"
32 #include "helperfuncs.h"
33 #include "userprocess.h"
36 extern ServerConfig *Config;
37 extern InspIRCd* ServerInstance;
38 extern int openSockfd[MAXSOCKS];
42 extern std::vector<Module*> modules;
43 extern std::vector<ircd_module*> factory;
45 ServerConfig::ServerConfig()
48 *TempDir = *ServerName = *Network = *ServerDesc = *AdminName = '\0';
49 *HideWhoisServer = *AdminEmail = *AdminNick = *diepass = *restartpass = '\0';
50 *CustomVersion = *motd = *rules = *PrefixQuit = *DieValue = *DNSServer = '\0';
51 *OperOnlyStats = *ModPath = *MyExecutable = *DisabledCommands = *PID = '\0';
53 nofork = HideBans = HideSplits = unlimitcore = false;
55 dns_timeout = DieDelay = 5;
57 NetBufferSize = 10240;
58 SoftLimit = MAXCLIENTS;
66 void ServerConfig::ClearStack()
68 include_stack.clear();
71 Module* ServerConfig::GetIOHook(int port)
73 std::map<int,Module*>::iterator x = IOHookModule.find(port);
74 return (x != IOHookModule.end() ? x->second : NULL);
77 bool ServerConfig::AddIOHook(int port, Module* iomod)
81 IOHookModule[port] = iomod;
86 ModuleException err("Port already hooked by another module");
92 bool ServerConfig::DelIOHook(int port)
94 std::map<int,Module*>::iterator x = IOHookModule.find(port);
95 if (x != IOHookModule.end())
97 IOHookModule.erase(x);
103 bool ServerConfig::CheckOnce(char* tag, bool bail, userrec* user)
105 int count = ConfValueEnum(tag,&Config->config_f);
110 printf("There were errors in your configuration:\nYou have more than one <%s> tag, this is not permitted.\n",tag);
117 WriteServ(user->fd,"There were errors in your configuration:");
118 WriteServ(user->fd,"You have more than one <%s> tag, this is not permitted.\n",tag);
122 WriteOpers("There were errors in the configuration file:");
123 WriteOpers("You have more than one <%s> tag, this is not permitted.\n",tag);
132 printf("There were errors in your configuration:\nYou have not defined a <%s> tag, this is required.\n",tag);
139 WriteServ(user->fd,"There were errors in your configuration:");
140 WriteServ(user->fd,"You have not defined a <%s> tag, this is required.",tag);
144 WriteOpers("There were errors in the configuration file:");
145 WriteOpers("You have not defined a <%s> tag, this is required.",tag);
153 bool NoValidation(const char* tag, const char* value, void* data)
155 log(DEBUG,"No validation for <%s:%s>",tag,value);
159 bool ValidateTempDir(const char* tag, const char* value, void* data)
161 char* x = (char*)data;
163 strlcpy(x,"/tmp",1024);
167 bool ValidateMaxTargets(const char* tag, const char* value, void* data)
170 if ((*x < 0) || (*x > 31))
172 log(DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
178 bool ValidateSoftLimit(const char* tag, const char* value, void* data)
181 if ((*x < 1) || (*x > MAXCLIENTS))
183 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
189 bool ValidateMaxConn(const char* tag, const char* value, void* data)
193 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
199 bool ValidateDnsTimeout(const char* tag, const char* value, void* data)
207 bool ValidateDnsServer(const char* tag, const char* value, void* data)
209 char* x = (char*)data;
212 // attempt to look up their nameserver from /etc/resolv.conf
213 log(DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
214 ifstream resolv("/etc/resolv.conf");
215 std::string nameserver;
216 bool found_server = false;
218 if (resolv.is_open())
220 while (resolv >> nameserver)
222 if ((nameserver == "nameserver") && (!found_server))
224 resolv >> nameserver;
225 strlcpy(x,nameserver.c_str(),MAXBUF);
227 log(DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
233 log(DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
234 strlcpy(x,"127.0.0.1",MAXBUF);
239 log(DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
240 strlcpy(x,"127.0.0.1",MAXBUF);
246 bool ValidateModPath(const char* tag, const char* value, void* data)
248 char* x = (char*)data;
250 strlcpy(x,MOD_PATH,MAXBUF);
255 bool ValidateServerName(const char* tag, const char* value, void* data)
257 char* x = (char*)data;
260 log(DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s%c'",x,x,'.');
261 charlcat(x,'.',MAXBUF);
267 bool ValidateNetBufferSize(const char* tag, const char* value, void* data)
269 if ((!Config->NetBufferSize) || (Config->NetBufferSize > 65535) || (Config->NetBufferSize < 1024))
271 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
272 Config->NetBufferSize = 10240;
277 bool ValidateMaxWho(const char* tag, const char* value, void* data)
279 if ((!Config->MaxWhoResults) || (Config->MaxWhoResults > 65535) || (Config->MaxWhoResults < 1))
281 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
282 Config->MaxWhoResults = 128;
287 bool ValidateLogLevel(const char* tag, const char* value, void* data)
289 const char* dbg = (const char*)data;
290 Config->LogLevel = DEFAULT;
291 if (!strcmp(dbg,"debug"))
293 Config->LogLevel = DEBUG;
294 Config->debugging = 1;
296 else if (!strcmp(dbg,"verbose"))
297 Config->LogLevel = VERBOSE;
298 else if (!strcmp(dbg,"default"))
299 Config->LogLevel = DEFAULT;
300 else if (!strcmp(dbg,"sparse"))
301 Config->LogLevel = SPARSE;
302 else if (!strcmp(dbg,"none"))
303 Config->LogLevel = NONE;
307 bool ValidateMotd(const char* tag, const char* value, void* data)
309 readfile(Config->MOTD,Config->motd);
313 bool ValidateRules(const char* tag, const char* value, void* data)
315 readfile(Config->RULES,Config->rules);
320 void ServerConfig::Read(bool bail, userrec* user)
323 char CM1[MAXBUF],CM2[MAXBUF];
324 char ServName[MAXBUF],Value[MAXBUF];
327 std::stringstream errstr;
329 static InitialConfig Values[] = {
330 {"options", "softlimit", &this->SoftLimit, DT_INTEGER, ValidateSoftLimit},
331 {"options", "somaxconn", &this->MaxConn, DT_INTEGER, ValidateMaxConn},
332 {"server", "name", &this->ServerName, DT_CHARPTR, ValidateServerName},
333 {"server", "description", &this->ServerDesc, DT_CHARPTR, NoValidation},
334 {"server", "network", &this->Network, DT_CHARPTR, NoValidation},
335 {"admin", "name", &this->AdminName, DT_CHARPTR, NoValidation},
336 {"admin", "email", &this->AdminEmail, DT_CHARPTR, NoValidation},
337 {"admin", "nick", &this->AdminNick, DT_CHARPTR, NoValidation},
338 {"files", "motd", &this->motd, DT_CHARPTR, ValidateMotd},
339 {"files", "rules", &this->rules, DT_CHARPTR, ValidateRules},
340 {"power", "diepass", &this->diepass, DT_CHARPTR, NoValidation},
341 {"power", "pauseval", &this->DieDelay, DT_INTEGER, NoValidation},
342 {"power", "restartpass", &this->restartpass, DT_CHARPTR, NoValidation},
343 {"options", "prefixquit", &this->PrefixQuit, DT_CHARPTR, NoValidation},
344 {"die", "value", &this->DieValue, DT_CHARPTR, NoValidation},
345 {"options", "loglevel", &debug, DT_CHARPTR, ValidateLogLevel},
346 {"options", "netbuffersize", &this->NetBufferSize, DT_INTEGER, ValidateNetBufferSize},
347 {"options", "maxwho", &this->MaxWhoResults, DT_INTEGER, ValidateMaxWho},
348 {"options", "allowhalfop", &this->AllowHalfop, DT_BOOLEAN, NoValidation},
349 {"dns", "server", &this->DNSServer, DT_CHARPTR, ValidateDnsServer},
350 {"dns", "timeout", &this->dns_timeout, DT_INTEGER, ValidateDnsTimeout},
351 {"options", "moduledir", &this->ModPath, DT_CHARPTR, ValidateModPath},
352 {"disabled", "commands", &this->DisabledCommands, DT_CHARPTR, NoValidation},
353 {"options", "operonlystats", &this->OperOnlyStats, DT_CHARPTR, NoValidation},
354 {"options", "customversion", &this->CustomVersion, DT_CHARPTR, NoValidation},
355 {"options", "hidesplits", &this->HideSplits, DT_BOOLEAN, NoValidation},
356 {"options", "hidebans", &this->HideBans, DT_BOOLEAN, NoValidation},
357 {"options", "hidewhois", &this->HideWhoisServer, DT_CHARPTR, NoValidation},
358 {"options", "tempdir", &this->TempDir, DT_CHARPTR, ValidateTempDir},
362 include_stack.clear();
364 if (!LoadConf(CONFIG_FILE,&Config->config_f,&errstr))
367 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
371 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
378 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
379 while (!errstr.eof())
381 errstr.getline(dataline,1024);
382 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
387 WriteOpers("There were errors in the configuration file:");
388 while (!errstr.eof())
390 errstr.getline(dataline,1024);
391 WriteOpers(dataline);
399 /* Check we dont have more than one of singular tags
401 if (!CheckOnce("server",bail,user) || !CheckOnce("admin",bail,user) || !CheckOnce("files",bail,user)
402 || !CheckOnce("power",bail,user) || !CheckOnce("options",bail,user) || !CheckOnce("pid",bail,user))
408 for (int Index = 0; Values[Index].tag; Index++)
410 int* val_i = (int*) Values[Index].val;
411 char* val_c = (char*) Values[Index].val;
413 switch (Values[Index].datatype)
416 ConfValue(Values[Index].tag, Values[Index].value, 0, val_c, &this->config_f);
420 convert = new char[MAXBUF];
421 ConfValue(Values[Index].tag, Values[Index].value, 0, convert, &this->config_f);
422 *val_i = atoi(convert);
427 convert = new char[MAXBUF];
428 ConfValue(Values[Index].tag, Values[Index].value, 0, convert, &this->config_f);
429 *val_i = ((*convert == tolower('y')) || (*convert == tolower('t')) || (*convert == '1'));
437 Values[Index].validation_function(Values[Index].tag, Values[Index].value, Values[Index].val);
440 log(DEFAULT,"Reading connect classes...");
443 for (int i = 0; i < ConfValueEnum("connect",&Config->config_f); i++)
446 ConfValue("connect","allow",i,Value,&Config->config_f);
452 ConfValue("connect","password",i,Value,&Config->config_f);
454 c.registration_timeout = ConfValueInteger("connect","timeout",i,&Config->config_f); // default is 2 minutes
455 c.pingtime = ConfValueInteger("connect","pingfreq",i,&Config->config_f);
456 c.flood = ConfValueInteger("connect","flood",i,&Config->config_f);
457 c.threshold = ConfValueInteger("connect","threshold",i,&Config->config_f);
458 c.sendqmax = ConfValueInteger("connect","sendq",i,&Config->config_f);
459 c.recvqmax = ConfValueInteger("connect","recvq",i,&Config->config_f);
460 c.maxlocal = ConfValueInteger("connect","localmax",i,&Config->config_f);
461 c.maxglobal = ConfValueInteger("connect","globalmax",i,&Config->config_f);
469 if (c.maxglobal == 0)
474 if (c.threshold == 0)
478 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());
489 if (c.registration_timeout == 0)
491 c.registration_timeout = 90;
498 Classes.push_back(c);
502 ConfValue("connect","deny",i,Value,&Config->config_f);
505 Classes.push_back(c);
506 log(DEBUG,"Read connect class type DENY, host=%s",c.host.c_str());
510 Config->ulines.clear();
512 for (int i = 0; i < ConfValueEnum("uline",&Config->config_f); i++)
514 ConfValue("uline","server",i,ServName,&Config->config_f);
516 log(DEBUG,"Read ULINE '%s'",ServName);
517 Config->ulines.push_back(ServName);
523 for (int count = 0; count < Config->ConfValueEnum("banlist",&Config->config_f); count++)
525 Config->ConfValue("banlist","chan",count,CM1,&Config->config_f);
526 Config->ConfValue("banlist","limit",count,CM2,&Config->config_f);
527 maxbans[CM1] = atoi(CM2);
530 ReadClassesAndTypes();
531 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
532 read_xline_defaults();
533 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
534 apply_lines(APPLY_ALL);
536 ConfValue("pid","file",0,Config->PID,&Config->config_f);
537 // write once here, to try it out and make sure its ok
538 WritePID(Config->PID);
540 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
543 log(DEFAULT,"Adding and removing modules due to rehash...");
545 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
547 // store the old module names
548 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
550 old_module_names.push_back(*t);
553 // get the new module names
554 for (int count2 = 0; count2 < ConfValueEnum("module",&Config->config_f); count2++)
556 ConfValue("module","name",count2,Value,&Config->config_f);
557 new_module_names.push_back(Value);
560 // now create a list of new modules that are due to be loaded
561 // and a seperate list of modules which are due to be unloaded
562 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
566 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
573 added_modules.push_back(*_new);
576 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
579 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
586 removed_modules.push_back(*oldm);
590 * now we have added_modules, a vector of modules to be loaded,
591 * and removed_modules, a vector of modules
594 int rem = 0, add = 0;
595 if (!removed_modules.empty())
596 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
598 if (ServerInstance->UnloadModule(removing->c_str()))
600 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
603 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
610 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
614 if (!added_modules.empty())
615 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
617 if (ServerInstance->LoadModule(adding->c_str()))
619 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
622 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
629 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
633 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());
638 void Exit (int status)
640 if (Config->log_file)
641 fclose(Config->log_file);
642 send_error("Server shutdown.");
646 void Killed(int status)
648 if (Config->log_file)
649 fclose(Config->log_file);
650 send_error("Server terminated.");
654 char* CleanFilename(char* name)
656 char* p = name + strlen(name);
657 while ((p != name) && (*p != '/')) p--;
658 return (p != name ? ++p : p);
662 void Rehash(int status)
664 WriteOpers("Rehashing config file %s due to SIGHUP",CleanFilename(CONFIG_FILE));
665 fclose(Config->log_file);
667 Config->Read(false,NULL);
668 FOREACH_MOD(I_OnRehash,OnRehash(""));
675 printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
676 printf("(C) ChatSpike Development team.\033[0m\n\n");
677 printf("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om\033[0m\n");
678 printf("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
679 printf("Name concept:\t\t\033[1;32mLord_Zathras\033[0m\n\n");
682 void WritePID(std::string filename)
684 ofstream outfile(filename.c_str());
685 if (outfile.is_open())
692 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
693 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
700 signal (SIGALRM, SIG_IGN);
701 signal (SIGHUP, Rehash);
702 signal (SIGPIPE, SIG_IGN);
703 signal (SIGTERM, Exit);
704 signal (SIGSEGV, Error);
708 int DaemonSeed (void)
711 if ((childpid = fork ()) < 0)
713 else if (childpid > 0)
715 /* We wait a few seconds here, so that the shell prompt doesnt come back over the output */
721 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
723 if (Config->unlimitcore)
726 if (getrlimit(RLIMIT_CORE, &rl) == -1)
728 log(DEFAULT,"Failed to getrlimit()!");
733 rl.rlim_cur = rl.rlim_max;
734 if (setrlimit(RLIMIT_CORE, &rl) == -1)
735 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
743 /* Make Sure Modules Are Avaliable!
744 * (BugFix By Craig.. See? I do work! :p)
745 * Modified by brain, requires const char*
746 * to work with other API functions
749 bool FileExists (const char* file)
752 if ((input = fopen (file, "r")) == NULL)
763 /* ConfProcess does the following things to a config line in the following order:
765 * Processes the line for syntax errors as shown below
766 * (1) Line void of quotes or equals (a malformed, illegal tag format)
767 * (2) Odd number of quotes on the line indicating a missing quote
768 * (3) number of equals signs not equal to number of quotes / 2 (missing an equals sign)
769 * (4) Spaces between the opening bracket (<) and the keyword
770 * (5) Spaces between a keyword and an equals sign
771 * (6) Spaces between an equals sign and a quote
772 * Removes trailing spaces
773 * Removes leading spaces
774 * Converts tabs to spaces
775 * Turns multiple spaces that are outside of quotes into single spaces
778 std::string ServerConfig::ConfProcess(char* buffer, long linenumber, std::stringstream* errorstream, bool &error, std::string filename)
780 long number_of_quotes = 0;
781 long number_of_equals = 0;
782 bool has_open_bracket = false;
783 bool in_quotes = false;
791 // firstly clean up the line by stripping spaces from the start and end and converting tabs to spaces
792 for (char* d = buffer; *d; d++)
795 while (*buffer == ' ') buffer++;
796 trailing = buffer + strlen(buffer) - 1;
797 while (*trailing == ' ') *trailing-- = '\0';
799 // empty lines are syntactically valid, as are comments
800 if (!(*buffer) || buffer[0] == '#')
803 for (char* c = buffer; *c; c++)
805 // convert all spaces that are OUTSIDE quotes into hardspace (0xA0) as this will make them easier to
806 // search and replace later :)
807 if ((!in_quotes) && (*c == ' '))
809 if ((*c == '<') && (!in_quotes))
811 has_open_bracket = true;
814 *errorstream << "Tag without identifier at " << filename << ":" << linenumber << endl;
818 else if ((tolower(*(c+1)) < 'a') || (tolower(*(c+1)) > 'z'))
820 *errorstream << "Invalid characters in identifier at " << filename << ":" << linenumber << endl;
828 in_quotes = (!in_quotes);
830 if ((*c == '=') && (!in_quotes))
835 *errorstream << "Variable without a value at " << filename << ":" << linenumber << endl;
839 else if (*(c+1) != '"')
841 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
845 else if (c == buffer)
847 *errorstream << "Value without a variable (line starts with '=') at " << filename << ":" << linenumber << endl;
851 else if (*(c-1) == '\xA0')
853 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
859 // no quotes, and no equals. something freaky.
860 if ((!number_of_quotes) || (!number_of_equals) && (strlen(buffer)>2) && (*buffer == '<'))
862 *errorstream << "Malformed tag at " << filename << ":" << linenumber << endl;
866 // odd number of quotes. thats just wrong.
867 if ((number_of_quotes % 2) != 0)
869 *errorstream << "Missing \" at " << filename << ":" << linenumber << endl;
873 if (number_of_equals < (number_of_quotes/2))
875 *errorstream << "Missing '=' at " << filename << ":" << linenumber << endl;
877 if (number_of_equals > (number_of_quotes/2))
879 *errorstream << "Too many '=' at " << filename << ":" << linenumber << endl;
882 std::string parsedata = buffer;
883 // turn multispace into single space
884 while (parsedata.find("\xA0\xA0") != std::string::npos)
886 parsedata.erase(parsedata.find("\xA0\xA0"),1);
889 // turn our hardspace back into softspace
890 for (unsigned int d = 0; d < parsedata.length(); d++)
892 if (parsedata[d] == '\xA0')
896 // and we're done, the line is fine!
900 int ServerConfig::fgets_safe(char* buffer, size_t maxsize, FILE* &file)
904 char* bufptr = buffer;
905 while ((!feof(file)) && (c_read != '\n') && (c_read != '\r') && (n < maxsize))
907 c_read = fgetc(file);
908 if ((c_read != '\n') && (c_read != '\r'))
915 return bufptr - buffer;
918 bool ServerConfig::LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream)
921 errorstream->str("");
923 // first, check that the file exists before we try to do anything with it
924 if (!FileExists(filename))
926 *errorstream << "File " << filename << " not found." << endl;
929 // Fix the chmod of the file to restrict it to the current user and group
930 chmod(filename,0600);
931 for (unsigned int t = 0; t < include_stack.size(); t++)
933 if (std::string(filename) == include_stack[t])
935 *errorstream << "File " << filename << " is included recursively (looped inclusion)." << endl;
939 include_stack.push_back(filename);
941 FILE* conf = fopen(filename,"r");
947 if (fgets_safe(buffer, MAXBUF, conf))
949 if ((!feof(conf)) && (buffer) && (*buffer))
951 if ((buffer[0] != '#') && (buffer[0] != '\r') && (buffer[0] != '\n'))
953 if (!strncmp(buffer,"<include file=\"",15))
956 char confpath[10240],newconf[10240];
957 // include file directive
958 buf += 15; // advance to filename
959 for (char* j = buf; *j; j++)
969 log(DEBUG,"Opening included file '%s'",buf);
972 strlcpy(confpath,CONFIG_FILE,10240);
973 if (strstr(confpath,"/inspircd.conf"))
975 // leaves us with just the path
976 *(strstr(confpath,"/inspircd.conf")) = '\0';
978 snprintf(newconf,10240,"%s/%s",confpath,buf);
980 else strlcpy(newconf,buf,10240);
981 std::stringstream merge(stringstream::in | stringstream::out);
982 // recursively call LoadConf and get the new data, use the same errorstream
983 if (LoadConf(newconf, &merge, errorstream))
985 // append to the end of the file
986 std::string newstuff = merge.str();
991 // the error propogates up to its parent recursively
992 // causing the config reader to bail at the top level.
1000 std::string data = this->ConfProcess(buffer,linenumber++,errorstream,error,filename);
1018 /* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */
1020 int ServerConfig::EnumConf(std::stringstream *config, const char* tag)
1023 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
1024 int in_token, in_quotes, tptr, idx = 0;
1026 std::string x = config->str();
1027 const char* buf = x.c_str();
1028 char* bptr = (char*)buf;
1038 if ((c == '#') && (lastc == '\n'))
1040 while ((c != '\n') && (*bptr))
1046 if ((c == '<') && (!in_quotes))
1061 in_quotes = (!in_quotes);
1063 if ((c == '>') && (!in_quotes))
1066 if (!strcmp(c_tag,tag))
1068 /* correct tag, but wrong index */
1078 if ((in_token) && (c != '\n') && (c != '\r'))
1088 /* Counts the number of values within a certain tag */
1090 int ServerConfig::EnumValues(std::stringstream *config, const char* tag, int index)
1093 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
1094 int in_token, in_quotes, tptr, idx = 0;
1095 bool correct_tag = false;
1097 const char* buf = config->str().c_str();
1098 char* bptr = (char*)buf;
1109 if ((c == '#') && (lastc == '\n'))
1111 while ((c != '\n') && (*bptr))
1117 if ((c == '<') && (!in_quotes))
1128 if ((!strcmp(c_tag,tag)) && (idx == index))
1137 in_quotes = (!in_quotes);
1140 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
1144 if ((c == '>') && (!in_quotes))
1148 correct_tag = false;
1149 if (!strcmp(c_tag,tag))
1151 /* correct tag, but wrong index */
1161 if ((in_token) && (c != '\n') && (c != '\r'))
1172 int ServerConfig::ConfValueEnum(char* tag, std::stringstream* config)
1174 return EnumConf(config,tag);
1178 int ServerConfig::ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
1181 char buffer[65535], c_tag[MAXBUF], c, lastc;
1182 int in_token, in_quotes, tptr, idx = 0;
1184 std::string x = config->str();
1185 const char* buf = x.c_str();
1186 char* bptr = (char*)buf;
1199 // FIX: Treat tabs as spaces
1202 if ((c == '<') && (!in_quotes))
1213 // FIX: Tab can follow a tagname as well as space.
1214 } while ((c != ' ') && (c != 9));
1218 in_quotes = (!in_quotes);
1220 if ((c == '>') && (!in_quotes))
1225 if (!strcmp(c_tag,tag))
1227 if ((buffer) && (c_tag) && (var))
1229 key = strstr(buffer,var);
1232 /* value not found in tag */
1250 for (char* j = key; *j; j++)
1258 strlcpy(result,key,MAXBUF);
1264 if (!strcmp(c_tag,tag))
1266 /* correct tag, but wrong index */
1276 if ((in_token) && (c != '\n') && (c != '\r'))
1283 *result = 0; // value or its tag not found at all
1289 int ServerConfig::ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
1291 ReadConf(config, tag, var, index, result);
1295 int ServerConfig::ConfValueInteger(char* tag, char* var, int index, std::stringstream *config)
1297 char result[MAXBUF];
1298 ReadConf(config, tag, var, index, result);
1299 return atoi(result);
1302 // This will bind a socket to a port. It works for UDP/TCP
1303 int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
1305 memset((char *)&server,0,sizeof(server));
1306 struct in_addr addy;
1307 bool resolved = false;
1308 char resolved_addr[128];
1313 if (*addr && !inet_aton(addr,&addy))
1315 /* If they gave a hostname, bind to the IP it resolves to */
1316 if (CleanAndResolve(resolved_addr, addr, true))
1318 inet_aton(resolved_addr,&addy);
1319 log(DEFAULT,"Resolved binding '%s' -> '%s'",addr,resolved_addr);
1320 server.sin_addr = addy;
1325 log(DEFAULT,"WARNING: Could not resolve '%s' to an IP for binding to on port %d",addr,port);
1329 server.sin_family = AF_INET;
1334 server.sin_addr.s_addr = htonl(INADDR_ANY);
1338 server.sin_addr = addy;
1341 server.sin_port = htons(port);
1342 if (bind(sockfd,(struct sockaddr*)&server,sizeof(server)) < 0)
1348 log(DEBUG,"Bound port %s:%d",*addr ? addr : "*",port);
1349 if (listen(sockfd, Config->MaxConn) == -1)
1351 log(DEFAULT,"ERROR in listen(): %s",strerror(errno));
1362 // Open a TCP Socket
1363 int OpenTCPSocket (void)
1367 struct linger linger = { 0 };
1369 if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
1373 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
1374 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
1376 linger.l_linger = 1;
1377 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));
1384 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
1385 sockaddr_in client,server;
1386 int clientportcount = 0;
1387 int BoundPortCount = 0;
1389 for (int count = 0; count < Config->ConfValueEnum("bind",&Config->config_f); count++)
1391 Config->ConfValue("bind","port",count,configToken,&Config->config_f);
1392 Config->ConfValue("bind","address",count,Addr,&Config->config_f);
1393 Config->ConfValue("bind","type",count,Type,&Config->config_f);
1395 if ((!*Type) || (!strcmp(Type,"clients")))
1397 // modules handle server bind types now
1398 Config->ports[clientportcount] = atoi(configToken);
1400 // If the client put bind "*", this is an unrealism.
1401 // We don't actually support this as documented, but
1402 // i got fed up of people trying it, so now it converts
1403 // it to an empty string meaning the same 'bind to all'.
1407 strlcpy(Config->addrs[clientportcount],Addr,256);
1409 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
1413 int PortCount = clientportcount;
1415 for (int count = 0; count < PortCount; count++)
1417 if ((openSockfd[BoundPortCount] = OpenTCPSocket()) == ERROR)
1419 log(DEBUG,"InspIRCd: startup: bad fd %lu binding port [%s:%d]",(unsigned long)openSockfd[BoundPortCount],Config->addrs[count],(unsigned long)Config->ports[count]);
1423 if (BindSocket(openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]) == ERROR)
1425 log(DEFAULT,"InspIRCd: startup: failed to bind port [%s:%lu]: %s",Config->addrs[count],(unsigned long)Config->ports[count],strerror(errno));
1429 /* well we at least bound to one socket so we'll continue */
1434 /* if we didn't bind to anything then abort */
1435 if (!BoundPortCount)
1437 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
1438 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)PortCount);
1442 return BoundPortCount;