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 *ServerName = *Network = *ServerDesc = *AdminName = '\0';
48 *AdminEmail = *AdminNick = *diepass = *restartpass = '\0';
49 *CustomVersion = *motd = *rules = *PrefixQuit = *DieValue = *DNSServer = '\0';
50 *OperOnlyStats = *ModPath = *MyExecutable = *DisabledCommands = *PID = '\0';
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;
86 bool ServerConfig::DelIOHook(int port)
88 std::map<int,Module*>::iterator x = IOHookModule.find(port);
89 if (x != IOHookModule.end())
91 IOHookModule.erase(x);
97 bool ServerConfig::CheckOnce(char* tag, bool bail, userrec* user)
99 int count = ConfValueEnum(tag,&Config->config_f);
104 printf("There were errors in your configuration:\nYou have more than one <%s> tag, this is not permitted.\n",tag);
111 WriteServ(user->fd,"There were errors in your configuration:");
112 WriteServ(user->fd,"You have more than one <%s> tag, this is not permitted.\n",tag);
116 WriteOpers("There were errors in the configuration file:");
117 WriteOpers("You have more than one <%s> tag, this is not permitted.\n",tag);
126 printf("There were errors in your configuration:\nYou have not defined a <%s> tag, this is required.\n",tag);
133 WriteServ(user->fd,"There were errors in your configuration:");
134 WriteServ(user->fd,"You have not defined a <%s> tag, this is required.",tag);
138 WriteOpers("There were errors in the configuration file:");
139 WriteOpers("You have not defined a <%s> tag, this is required.",tag);
147 void ServerConfig::Read(bool bail, userrec* user)
149 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF],MCON[MAXBUF];
150 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF],SLIMT[MAXBUF];
152 std::stringstream errstr;
153 include_stack.clear();
155 if (!LoadConf(CONFIG_FILE,&Config->config_f,&errstr))
158 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
161 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
169 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
170 while (!errstr.eof())
172 errstr.getline(dataline,1024);
173 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
178 WriteOpers("There were errors in the configuration file:");
179 while (!errstr.eof())
181 errstr.getline(dataline,1024);
182 WriteOpers(dataline);
189 /* Check we dont have more than one of singular tags
191 if (!CheckOnce("server",bail,user) || !CheckOnce("admin",bail,user) || !CheckOnce("files",bail,user)
192 || !CheckOnce("power",bail,user) || !CheckOnce("options",bail,user)
193 || !CheckOnce("dns",bail,user) || !CheckOnce("pid",bail,user))
198 ConfValue("server","name",0,Config->ServerName,&Config->config_f);
199 ConfValue("server","description",0,Config->ServerDesc,&Config->config_f);
200 ConfValue("server","network",0,Config->Network,&Config->config_f);
201 ConfValue("admin","name",0,Config->AdminName,&Config->config_f);
202 ConfValue("admin","email",0,Config->AdminEmail,&Config->config_f);
203 ConfValue("admin","nick",0,Config->AdminNick,&Config->config_f);
204 ConfValue("files","motd",0,Config->motd,&Config->config_f);
205 ConfValue("files","rules",0,Config->rules,&Config->config_f);
206 ConfValue("power","diepass",0,Config->diepass,&Config->config_f);
207 ConfValue("power","pause",0,pauseval,&Config->config_f);
208 ConfValue("power","restartpass",0,Config->restartpass,&Config->config_f);
209 ConfValue("options","prefixquit",0,Config->PrefixQuit,&Config->config_f);
210 ConfValue("die","value",0,Config->DieValue,&Config->config_f);
211 ConfValue("options","loglevel",0,dbg,&Config->config_f);
212 ConfValue("options","netbuffersize",0,NB,&Config->config_f);
213 ConfValue("options","maxwho",0,MW,&Config->config_f);
214 ConfValue("options","allowhalfop",0,AH,&Config->config_f);
215 ConfValue("options","allowprotect",0,AP,&Config->config_f);
216 ConfValue("options","allowfounder",0,AF,&Config->config_f);
217 ConfValue("dns","server",0,Config->DNSServer,&Config->config_f);
218 ConfValue("dns","timeout",0,DNT,&Config->config_f);
219 ConfValue("options","moduledir",0,Config->ModPath,&Config->config_f);
220 ConfValue("disabled","commands",0,Config->DisabledCommands,&Config->config_f);
221 ConfValue("options","somaxconn",0,MCON,&Config->config_f);
222 ConfValue("options","softlimit",0,SLIMT,&Config->config_f);
223 ConfValue("options","operonlystats",0,Config->OperOnlyStats,&Config->config_f);
224 ConfValue("options","customversion",0,Config->CustomVersion,&Config->config_f);
226 Config->SoftLimit = atoi(SLIMT);
227 if ((Config->SoftLimit < 1) || (Config->SoftLimit > MAXCLIENTS))
229 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
230 Config->SoftLimit = MAXCLIENTS;
232 Config->MaxConn = atoi(MCON);
233 if (Config->MaxConn > SOMAXCONN)
234 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
235 Config->NetBufferSize = atoi(NB);
236 Config->MaxWhoResults = atoi(MW);
237 Config->dns_timeout = atoi(DNT);
238 if (!Config->dns_timeout)
239 Config->dns_timeout = 5;
240 if (!Config->MaxConn)
241 Config->MaxConn = SOMAXCONN;
242 if (!*Config->DNSServer)
243 strlcpy(Config->DNSServer,"127.0.0.1",MAXBUF);
244 if (!*Config->ModPath)
245 strlcpy(Config->ModPath,MOD_PATH,MAXBUF);
246 Config->AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
247 if ((!Config->NetBufferSize) || (Config->NetBufferSize > 65535) || (Config->NetBufferSize < 1024))
249 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
250 Config->NetBufferSize = 10240;
252 if ((!Config->MaxWhoResults) || (Config->MaxWhoResults > 65535) || (Config->MaxWhoResults < 1))
254 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
255 Config->MaxWhoResults = 128;
257 Config->LogLevel = DEFAULT;
258 if (!strcmp(dbg,"debug"))
260 Config->LogLevel = DEBUG;
261 Config->debugging = 1;
263 if (!strcmp(dbg,"verbose"))
264 Config->LogLevel = VERBOSE;
265 if (!strcmp(dbg,"default"))
266 Config->LogLevel = DEFAULT;
267 if (!strcmp(dbg,"sparse"))
268 Config->LogLevel = SPARSE;
269 if (!strcmp(dbg,"none"))
270 Config->LogLevel = NONE;
272 readfile(Config->MOTD,Config->motd);
273 log(DEFAULT,"Reading message of the day...");
274 readfile(Config->RULES,Config->rules);
275 log(DEFAULT,"Reading connect classes...");
277 for (int i = 0; i < ConfValueEnum("connect",&Config->config_f); i++)
280 ConfValue("connect","allow",i,Value,&Config->config_f);
281 ConfValue("connect","timeout",i,timeout,&Config->config_f);
282 ConfValue("connect","flood",i,flood,&Config->config_f);
283 ConfValue("connect","pingfreq",i,pfreq,&Config->config_f);
284 ConfValue("connect","threshold",i,thold,&Config->config_f);
285 ConfValue("connect","sendq",i,sqmax,&Config->config_f);
286 ConfValue("connect","recvq",i,rqmax,&Config->config_f);
291 strlcpy(Value,"",MAXBUF);
292 ConfValue("connect","password",i,Value,&Config->config_f);
294 c.registration_timeout = 90; // default is 2 minutes
296 c.flood = atoi(flood);
298 c.sendqmax = 262144; // 256k
299 c.recvqmax = 4096; // 4k
302 c.threshold = atoi(thold);
306 c.sendqmax = atoi(sqmax);
310 c.recvqmax = atoi(rqmax);
314 c.registration_timeout = atoi(timeout);
318 c.pingtime = atoi(pfreq);
320 Classes.push_back(c);
324 ConfValue("connect","deny",i,Value,&Config->config_f);
327 Classes.push_back(c);
328 log(DEBUG,"Read connect class type DENY, host=%s",c.host.c_str());
332 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
333 read_xline_defaults();
334 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
335 apply_lines(APPLY_ALL);
337 ConfValue("pid","file",0,Config->PID,&Config->config_f);
338 // write once here, to try it out and make sure its ok
339 WritePID(Config->PID);
341 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
344 log(DEFAULT,"Adding and removing modules due to rehash...");
346 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
348 // store the old module names
349 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
351 old_module_names.push_back(*t);
354 // get the new module names
355 for (int count2 = 0; count2 < ConfValueEnum("module",&Config->config_f); count2++)
357 ConfValue("module","name",count2,Value,&Config->config_f);
358 new_module_names.push_back(Value);
361 // now create a list of new modules that are due to be loaded
362 // and a seperate list of modules which are due to be unloaded
363 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
366 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
372 added_modules.push_back(*_new);
374 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
377 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
383 removed_modules.push_back(*oldm);
385 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
387 int rem = 0, add = 0;
388 if (!removed_modules.empty())
389 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
391 if (ServerInstance->UnloadModule(removing->c_str()))
393 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
394 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
399 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
402 if (!added_modules.empty())
403 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
405 if (ServerInstance->LoadModule(adding->c_str()))
407 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
408 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
413 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
416 log(DEFAULT,"Successfully unloaded %lu of %lu modules and loaded %lu of %lu modules.",(unsigned long)rem,(unsigned long)removed_modules.size(),
417 (unsigned long)add,(unsigned long)added_modules.size());
422 void Exit (int status)
424 if (Config->log_file)
425 fclose(Config->log_file);
426 send_error("Server shutdown.");
430 void Killed(int status)
432 if (Config->log_file)
433 fclose(Config->log_file);
434 send_error("Server terminated.");
438 char* CleanFilename(char* name)
440 char* p = name + strlen(name);
441 while ((p != name) && (*p != '/')) p--;
442 return (p != name ? ++p : p);
446 void Rehash(int status)
448 WriteOpers("Rehashing config file %s due to SIGHUP",CleanFilename(CONFIG_FILE));
449 fclose(Config->log_file);
451 Config->Read(false,NULL);
452 FOREACH_MOD(I_OnRehash,OnRehash(""));
459 printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
460 printf("(C) ChatSpike Development team.\033[0m\n\n");
461 printf("Developers:\033[1;32m Brain, FrostyCoolSlug\033[0m\n");
462 printf("Documentation:\033[1;32m FrostyCoolSlug, w00t\033[0m\n");
463 printf("Testers:\033[1;32m typobox43, piggles, Lord_Zathras, CC\033[0m\n");
464 printf("Name concept:\033[1;32m Lord_Zathras\033[0m\n\n");
467 void WritePID(std::string filename)
469 ofstream outfile(filename.c_str());
470 if (outfile.is_open())
477 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
478 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
485 signal (SIGALRM, SIG_IGN);
486 signal (SIGHUP, Rehash);
487 signal (SIGPIPE, SIG_IGN);
488 signal (SIGTERM, Exit);
489 signal (SIGSEGV, Error);
493 int DaemonSeed (void)
496 if ((childpid = fork ()) < 0)
498 else if (childpid > 0)
502 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
504 setpriority(PRIO_PROCESS,(int)getpid(),15);
506 if (Config->unlimitcore)
509 if (getrlimit(RLIMIT_CORE, &rl) == -1)
511 log(DEFAULT,"Failed to getrlimit()!");
516 rl.rlim_cur = rl.rlim_max;
517 if (setrlimit(RLIMIT_CORE, &rl) == -1)
518 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
526 /* Make Sure Modules Are Avaliable!
527 * (BugFix By Craig.. See? I do work! :p)
528 * Modified by brain, requires const char*
529 * to work with other API functions
532 bool FileExists (const char* file)
535 if ((input = fopen (file, "r")) == NULL)
546 /* ConfProcess does the following things to a config line in the following order:
548 * Processes the line for syntax errors as shown below
549 * (1) Line void of quotes or equals (a malformed, illegal tag format)
550 * (2) Odd number of quotes on the line indicating a missing quote
551 * (3) number of equals signs not equal to number of quotes / 2 (missing an equals sign)
552 * (4) Spaces between the opening bracket (<) and the keyword
553 * (5) Spaces between a keyword and an equals sign
554 * (6) Spaces between an equals sign and a quote
555 * Removes trailing spaces
556 * Removes leading spaces
557 * Converts tabs to spaces
558 * Turns multiple spaces that are outside of quotes into single spaces
561 std::string ServerConfig::ConfProcess(char* buffer, long linenumber, std::stringstream* errorstream, bool &error, std::string filename)
563 long number_of_quotes = 0;
564 long number_of_equals = 0;
565 bool has_open_bracket = false;
566 bool in_quotes = false;
572 // firstly clean up the line by stripping spaces from the start and end and converting tabs to spaces
573 for (unsigned int d = 0; d < strlen(buffer); d++)
574 if ((buffer[d]) == 9)
576 while ((buffer[0] == ' ') && (strlen(buffer)>0)) buffer++;
577 while ((buffer[strlen(buffer)-1] == ' ') && (strlen(buffer)>0)) buffer[strlen(buffer)-1] = '\0';
579 // empty lines are syntactically valid, as are comments
580 if (!(*buffer) || buffer[0] == '#')
583 for (unsigned int c = 0; c < strlen(buffer); c++)
585 // convert all spaces that are OUTSIDE quotes into hardspace (0xA0) as this will make them easier to
586 // search and replace later :)
587 if ((!in_quotes) && (buffer[c] == ' '))
589 if ((buffer[c] == '<') && (!in_quotes))
591 has_open_bracket = true;
592 if (strlen(buffer) == 1)
594 *errorstream << "Tag without identifier at " << filename << ":" << linenumber << endl;
598 else if ((tolower(buffer[c+1]) < 'a') || (tolower(buffer[c+1]) > 'z'))
600 *errorstream << "Invalid characters in identifier at " << filename << ":" << linenumber << endl;
605 if (buffer[c] == '"')
608 in_quotes = (!in_quotes);
610 if ((buffer[c] == '=') && (!in_quotes))
613 if (strlen(buffer) == c)
615 *errorstream << "Variable without a value at " << filename << ":" << linenumber << endl;
619 else if (buffer[c+1] != '"')
621 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
627 *errorstream << "Value without a variable (line starts with '=') at " << filename << ":" << linenumber << endl;
631 else if (buffer[c-1] == '\xA0')
633 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
639 // no quotes, and no equals. something freaky.
640 if ((!number_of_quotes) || (!number_of_equals) && (strlen(buffer)>2) && (buffer[0]=='<'))
642 *errorstream << "Malformed tag at " << filename << ":" << linenumber << endl;
646 // odd number of quotes. thats just wrong.
647 if ((number_of_quotes % 2) != 0)
649 *errorstream << "Missing \" at " << filename << ":" << linenumber << endl;
653 if (number_of_equals < (number_of_quotes/2))
655 *errorstream << "Missing '=' at " << filename << ":" << linenumber << endl;
657 if (number_of_equals > (number_of_quotes/2))
659 *errorstream << "Too many '=' at " << filename << ":" << linenumber << endl;
662 std::string parsedata = buffer;
663 // turn multispace into single space
664 while (parsedata.find("\xA0\xA0") != std::string::npos)
666 parsedata.erase(parsedata.find("\xA0\xA0"),1);
669 // turn our hardspace back into softspace
670 for (unsigned int d = 0; d < parsedata.length(); d++)
672 if (parsedata[d] == '\xA0')
676 // and we're done, the line is fine!
680 int ServerConfig::fgets_safe(char* buffer, size_t maxsize, FILE* &file)
683 unsigned int bufptr = 0;
684 while ((!feof(file)) && (c_read != '\n') && (c_read != '\r') && (bufptr < maxsize))
686 c_read = fgetc(file);
687 if ((c_read != '\n') && (c_read != '\r'))
688 buffer[bufptr++] = c_read;
690 buffer[bufptr] = '\0';
694 bool ServerConfig::LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream)
697 errorstream->str("");
699 // first, check that the file exists before we try to do anything with it
700 if (!FileExists(filename))
702 *errorstream << "File " << filename << " not found." << endl;
705 // Fix the chmod of the file to restrict it to the current user and group
706 chmod(filename,0600);
707 for (unsigned int t = 0; t < include_stack.size(); t++)
709 if (std::string(filename) == include_stack[t])
711 *errorstream << "File " << filename << " is included recursively (looped inclusion)." << endl;
715 include_stack.push_back(filename);
717 FILE* conf = fopen(filename,"r");
723 if (fgets_safe(buffer, MAXBUF, conf))
725 if ((!feof(conf)) && (buffer) && (strlen(buffer)))
727 if ((buffer[0] != '#') && (buffer[0] != '\r') && (buffer[0] != '\n'))
729 if (!strncmp(buffer,"<include file=\"",15))
732 char confpath[10240],newconf[10240];
733 // include file directive
734 buf += 15; // advance to filename
735 for (unsigned int j = 0; j < strlen(buf); j++)
745 log(DEFAULT,"Opening included file '%s'",buf);
748 strlcpy(confpath,CONFIG_FILE,10240);
749 if (strstr(confpath,"/inspircd.conf"))
751 // leaves us with just the path
752 *(strstr(confpath,"/inspircd.conf")) = '\0';
754 snprintf(newconf,10240,"%s/%s",confpath,buf);
756 else strlcpy(newconf,buf,10240);
757 std::stringstream merge(stringstream::in | stringstream::out);
758 // recursively call LoadConf and get the new data, use the same errorstream
759 if (LoadConf(newconf, &merge, errorstream))
761 // append to the end of the file
762 std::string newstuff = merge.str();
767 // the error propogates up to its parent recursively
768 // causing the config reader to bail at the top level.
776 std::string data = this->ConfProcess(buffer,linenumber++,errorstream,error,filename);
794 /* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */
796 int ServerConfig::EnumConf(std::stringstream *config, const char* tag)
799 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
800 int in_token, in_quotes, tptr, idx = 0;
802 const char* buf = config->str().c_str();
804 long len = strlen(buf);
814 if ((c == '#') && (lastc == '\n'))
816 while ((c != '\n') && (bptr<len))
822 if ((c == '<') && (!in_quotes))
837 in_quotes = (!in_quotes);
839 if ((c == '>') && (!in_quotes))
842 if (!strcmp(c_tag,tag))
844 /* correct tag, but wrong index */
854 if ((in_token) && (c != '\n') && (c != '\r'))
864 /* Counts the number of values within a certain tag */
866 int ServerConfig::EnumValues(std::stringstream *config, const char* tag, int index)
869 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
870 int in_token, in_quotes, tptr, idx = 0;
872 bool correct_tag = false;
875 const char* buf = config->str().c_str();
877 long len = strlen(buf);
887 if ((c == '#') && (lastc == '\n'))
889 while ((c != '\n') && (bptr<len))
895 if ((c == '<') && (!in_quotes))
906 if ((!strcmp(c_tag,tag)) && (idx == index))
915 in_quotes = (!in_quotes);
918 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
922 if ((c == '>') && (!in_quotes))
927 if (!strcmp(c_tag,tag))
929 /* correct tag, but wrong index */
939 if ((in_token) && (c != '\n') && (c != '\r'))
951 int ServerConfig::ConfValueEnum(char* tag, std::stringstream* config)
953 return EnumConf(config,tag);
958 /* Retrieves a value from the config file. If there is more than one value of the specified
959 * key and section (e.g. for opers etc) then the index value specifies which to retreive, e.g.
961 * ConfValue("oper","name",2,result);
964 int ServerConfig::ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
967 char buffer[65535], c_tag[MAXBUF], c, lastc;
968 int in_token, in_quotes, tptr, idx = 0;
971 const char* buf = config->str().c_str();
973 long len = config->str().length();
985 // FIX: Treat tabs as spaces
988 if ((c == '<') && (!in_quotes))
999 // FIX: Tab can follow a tagname as well as space.
1000 } while ((c != ' ') && (c != 9));
1004 in_quotes = (!in_quotes);
1006 if ((c == '>') && (!in_quotes))
1011 if (!strcmp(c_tag,tag))
1013 if ((buffer) && (c_tag) && (var))
1015 key = strstr(buffer,var);
1018 /* value not found in tag */
1036 for (unsigned j = 0; j < strlen(key); j++)
1043 strlcpy(result,key,MAXBUF);
1049 if (!strcmp(c_tag,tag))
1051 /* correct tag, but wrong index */
1061 if ((in_token) && (c != '\n') && (c != '\r'))
1068 *result = 0; // value or its tag not found at all
1074 int ServerConfig::ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
1076 ReadConf(config, tag, var, index, result);
1082 // This will bind a socket to a port. It works for UDP/TCP
1083 int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
1085 memset((char *)&server,0,sizeof(server));
1086 struct in_addr addy;
1087 inet_aton(addr,&addy);
1088 server.sin_family = AF_INET;
1089 if (!strcmp(addr,""))
1091 server.sin_addr.s_addr = htonl(INADDR_ANY);
1095 server.sin_addr = addy;
1097 server.sin_port = htons(port);
1098 if (bind(sockfd,(struct sockaddr*)&server,sizeof(server))<0)
1104 listen(sockfd, Config->MaxConn);
1110 // Open a TCP Socket
1111 int OpenTCPSocket (void)
1115 struct linger linger = { 0 };
1117 if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
1121 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
1122 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
1124 linger.l_linger = 1;
1125 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));
1132 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
1133 sockaddr_in client,server;
1134 int clientportcount = 0;
1135 int BoundPortCount = 0;
1136 for (int count = 0; count < Config->ConfValueEnum("bind",&Config->config_f); count++)
1138 Config->ConfValue("bind","port",count,configToken,&Config->config_f);
1139 Config->ConfValue("bind","address",count,Addr,&Config->config_f);
1140 Config->ConfValue("bind","type",count,Type,&Config->config_f);
1141 if (strcmp(Type,"servers"))
1143 // modules handle server bind types now,
1144 // its not a typo in the strcmp.
1145 Config->ports[clientportcount] = atoi(configToken);
1146 strlcpy(Config->addrs[clientportcount],Addr,256);
1148 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
1151 int PortCount = clientportcount;
1153 for (int count = 0; count < PortCount; count++)
1155 if ((openSockfd[BoundPortCount] = OpenTCPSocket()) == ERROR)
1157 log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[BoundPortCount]);
1160 if (BindSocket(openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]) == ERROR)
1162 log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)Config->ports[count]);
1164 else /* well we at least bound to one socket so we'll continue */
1170 /* if we didn't bind to anything then abort */
1171 if (!BoundPortCount)
1173 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
1174 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)PortCount);
1178 return BoundPortCount;