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';
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;
87 bool ServerConfig::DelIOHook(int port)
89 std::map<int,Module*>::iterator x = IOHookModule.find(port);
90 if (x != IOHookModule.end())
92 IOHookModule.erase(x);
98 bool ServerConfig::CheckOnce(char* tag, bool bail, userrec* user)
100 int count = ConfValueEnum(tag,&Config->config_f);
105 printf("There were errors in your configuration:\nYou have more than one <%s> tag, this is not permitted.\n",tag);
112 WriteServ(user->fd,"There were errors in your configuration:");
113 WriteServ(user->fd,"You have more than one <%s> tag, this is not permitted.\n",tag);
117 WriteOpers("There were errors in the configuration file:");
118 WriteOpers("You have more than one <%s> tag, this is not permitted.\n",tag);
127 printf("There were errors in your configuration:\nYou have not defined a <%s> tag, this is required.\n",tag);
134 WriteServ(user->fd,"There were errors in your configuration:");
135 WriteServ(user->fd,"You have not defined a <%s> tag, this is required.",tag);
139 WriteOpers("There were errors in the configuration file:");
140 WriteOpers("You have not defined a <%s> tag, this is required.",tag);
148 void ServerConfig::Read(bool bail, userrec* user)
150 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF],MCON[MAXBUF],MT[MAXBUF];
151 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF],SLIMT[MAXBUF];
152 char localmax[MAXBUF],globalmax[MAXBUF];
154 std::stringstream errstr;
155 include_stack.clear();
157 if (!LoadConf(CONFIG_FILE,&Config->config_f,&errstr))
160 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
163 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
171 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
172 while (!errstr.eof())
174 errstr.getline(dataline,1024);
175 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
180 WriteOpers("There were errors in the configuration file:");
181 while (!errstr.eof())
183 errstr.getline(dataline,1024);
184 WriteOpers(dataline);
191 /* Check we dont have more than one of singular tags
193 if (!CheckOnce("server",bail,user) || !CheckOnce("admin",bail,user) || !CheckOnce("files",bail,user)
194 || !CheckOnce("power",bail,user) || !CheckOnce("options",bail,user)
195 || !CheckOnce("dns",bail,user) || !CheckOnce("pid",bail,user))
200 ConfValue("server","name",0,Config->ServerName,&Config->config_f);
201 ConfValue("server","description",0,Config->ServerDesc,&Config->config_f);
202 ConfValue("server","network",0,Config->Network,&Config->config_f);
203 ConfValue("admin","name",0,Config->AdminName,&Config->config_f);
204 ConfValue("admin","email",0,Config->AdminEmail,&Config->config_f);
205 ConfValue("admin","nick",0,Config->AdminNick,&Config->config_f);
206 ConfValue("files","motd",0,Config->motd,&Config->config_f);
207 ConfValue("files","rules",0,Config->rules,&Config->config_f);
208 ConfValue("power","diepass",0,Config->diepass,&Config->config_f);
209 ConfValue("power","pause",0,pauseval,&Config->config_f);
210 ConfValue("power","restartpass",0,Config->restartpass,&Config->config_f);
211 ConfValue("options","prefixquit",0,Config->PrefixQuit,&Config->config_f);
212 ConfValue("die","value",0,Config->DieValue,&Config->config_f);
213 ConfValue("options","loglevel",0,dbg,&Config->config_f);
214 ConfValue("options","netbuffersize",0,NB,&Config->config_f);
215 ConfValue("options","maxwho",0,MW,&Config->config_f);
216 ConfValue("options","allowhalfop",0,AH,&Config->config_f);
217 ConfValue("options","allowprotect",0,AP,&Config->config_f);
218 ConfValue("options","allowfounder",0,AF,&Config->config_f);
219 ConfValue("dns","server",0,Config->DNSServer,&Config->config_f);
220 ConfValue("dns","timeout",0,DNT,&Config->config_f);
221 ConfValue("options","moduledir",0,Config->ModPath,&Config->config_f);
222 ConfValue("disabled","commands",0,Config->DisabledCommands,&Config->config_f);
223 ConfValue("options","somaxconn",0,MCON,&Config->config_f);
224 ConfValue("options","softlimit",0,SLIMT,&Config->config_f);
225 ConfValue("options","operonlystats",0,Config->OperOnlyStats,&Config->config_f);
226 ConfValue("options","customversion",0,Config->CustomVersion,&Config->config_f);
227 ConfValue("options","maxtargets",0,MT,&Config->config_f);
229 Config->SoftLimit = atoi(SLIMT);
231 Config->MaxTargets = atoi(MT);
232 if ((Config->MaxTargets < 0) || (Config->MaxTargets > 31))
234 log(DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
235 Config->MaxTargets = 20;
237 if ((Config->SoftLimit < 1) || (Config->SoftLimit > MAXCLIENTS))
239 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
240 Config->SoftLimit = MAXCLIENTS;
242 Config->MaxConn = atoi(MCON);
243 if (Config->MaxConn > SOMAXCONN)
244 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
245 Config->NetBufferSize = atoi(NB);
246 Config->MaxWhoResults = atoi(MW);
247 Config->dns_timeout = atoi(DNT);
248 if (!Config->dns_timeout)
249 Config->dns_timeout = 5;
250 if (!Config->MaxConn)
251 Config->MaxConn = SOMAXCONN;
252 if (!*Config->DNSServer)
253 strlcpy(Config->DNSServer,"127.0.0.1",MAXBUF);
254 if (!*Config->ModPath)
255 strlcpy(Config->ModPath,MOD_PATH,MAXBUF);
256 Config->AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
257 if ((!Config->NetBufferSize) || (Config->NetBufferSize > 65535) || (Config->NetBufferSize < 1024))
259 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
260 Config->NetBufferSize = 10240;
262 if ((!Config->MaxWhoResults) || (Config->MaxWhoResults > 65535) || (Config->MaxWhoResults < 1))
264 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
265 Config->MaxWhoResults = 128;
267 Config->LogLevel = DEFAULT;
268 if (!strcmp(dbg,"debug"))
270 Config->LogLevel = DEBUG;
271 Config->debugging = 1;
273 if (!strcmp(dbg,"verbose"))
274 Config->LogLevel = VERBOSE;
275 if (!strcmp(dbg,"default"))
276 Config->LogLevel = DEFAULT;
277 if (!strcmp(dbg,"sparse"))
278 Config->LogLevel = SPARSE;
279 if (!strcmp(dbg,"none"))
280 Config->LogLevel = NONE;
282 readfile(Config->MOTD,Config->motd);
283 log(DEFAULT,"Reading message of the day...");
284 readfile(Config->RULES,Config->rules);
285 log(DEFAULT,"Reading connect classes...");
287 for (int i = 0; i < ConfValueEnum("connect",&Config->config_f); i++)
290 ConfValue("connect","allow",i,Value,&Config->config_f);
291 ConfValue("connect","timeout",i,timeout,&Config->config_f);
292 ConfValue("connect","flood",i,flood,&Config->config_f);
293 ConfValue("connect","pingfreq",i,pfreq,&Config->config_f);
294 ConfValue("connect","threshold",i,thold,&Config->config_f);
295 ConfValue("connect","sendq",i,sqmax,&Config->config_f);
296 ConfValue("connect","recvq",i,rqmax,&Config->config_f);
297 ConfValue("connect","localmax",i,localmax,&Config->config_f);
298 ConfValue("connect","globalmax",i,globalmax,&Config->config_f);
303 strlcpy(Value,"",MAXBUF);
304 ConfValue("connect","password",i,Value,&Config->config_f);
306 c.registration_timeout = 90; // default is 2 minutes
308 c.flood = atoi(flood);
310 c.sendqmax = 262144; // 256k
311 c.recvqmax = 4096; // 4k
314 if (atoi(localmax)>0)
316 c.maxlocal = atoi(localmax);
318 if (atoi(globalmax)>0)
320 c.maxglobal = atoi(globalmax);
324 c.threshold = atoi(thold);
328 c.sendqmax = atoi(sqmax);
332 c.recvqmax = atoi(rqmax);
336 c.registration_timeout = atoi(timeout);
340 c.pingtime = atoi(pfreq);
342 Classes.push_back(c);
346 ConfValue("connect","deny",i,Value,&Config->config_f);
349 Classes.push_back(c);
350 log(DEBUG,"Read connect class type DENY, host=%s",c.host.c_str());
354 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
355 read_xline_defaults();
356 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
357 apply_lines(APPLY_ALL);
359 ConfValue("pid","file",0,Config->PID,&Config->config_f);
360 // write once here, to try it out and make sure its ok
361 WritePID(Config->PID);
363 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
366 log(DEFAULT,"Adding and removing modules due to rehash...");
368 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
370 // store the old module names
371 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
373 old_module_names.push_back(*t);
376 // get the new module names
377 for (int count2 = 0; count2 < ConfValueEnum("module",&Config->config_f); count2++)
379 ConfValue("module","name",count2,Value,&Config->config_f);
380 new_module_names.push_back(Value);
383 // now create a list of new modules that are due to be loaded
384 // and a seperate list of modules which are due to be unloaded
385 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
388 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
394 added_modules.push_back(*_new);
396 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
399 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
405 removed_modules.push_back(*oldm);
407 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
409 int rem = 0, add = 0;
410 if (!removed_modules.empty())
411 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
413 if (ServerInstance->UnloadModule(removing->c_str()))
415 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
416 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
421 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
424 if (!added_modules.empty())
425 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
427 if (ServerInstance->LoadModule(adding->c_str()))
429 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
430 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
435 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
438 log(DEFAULT,"Successfully unloaded %lu of %lu modules and loaded %lu of %lu modules.",(unsigned long)rem,(unsigned long)removed_modules.size(),
439 (unsigned long)add,(unsigned long)added_modules.size());
444 void Exit (int status)
446 if (Config->log_file)
447 fclose(Config->log_file);
448 send_error("Server shutdown.");
452 void Killed(int status)
454 if (Config->log_file)
455 fclose(Config->log_file);
456 send_error("Server terminated.");
460 char* CleanFilename(char* name)
462 char* p = name + strlen(name);
463 while ((p != name) && (*p != '/')) p--;
464 return (p != name ? ++p : p);
468 void Rehash(int status)
470 WriteOpers("Rehashing config file %s due to SIGHUP",CleanFilename(CONFIG_FILE));
471 fclose(Config->log_file);
473 Config->Read(false,NULL);
474 FOREACH_MOD(I_OnRehash,OnRehash(""));
481 printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
482 printf("(C) ChatSpike Development team.\033[0m\n\n");
483 printf("Developers:\033[1;32m Brain, FrostyCoolSlug\033[0m\n");
484 printf("Documentation:\033[1;32m FrostyCoolSlug, w00t\033[0m\n");
485 printf("Testers:\033[1;32m typobox43, piggles, Lord_Zathras, CC\033[0m\n");
486 printf("Name concept:\033[1;32m Lord_Zathras\033[0m\n\n");
489 void WritePID(std::string filename)
491 ofstream outfile(filename.c_str());
492 if (outfile.is_open())
499 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
500 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
507 signal (SIGALRM, SIG_IGN);
508 signal (SIGHUP, Rehash);
509 signal (SIGPIPE, SIG_IGN);
510 signal (SIGTERM, Exit);
511 signal (SIGSEGV, Error);
515 int DaemonSeed (void)
518 if ((childpid = fork ()) < 0)
520 else if (childpid > 0)
524 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
526 setpriority(PRIO_PROCESS,(int)getpid(),15);
528 if (Config->unlimitcore)
531 if (getrlimit(RLIMIT_CORE, &rl) == -1)
533 log(DEFAULT,"Failed to getrlimit()!");
538 rl.rlim_cur = rl.rlim_max;
539 if (setrlimit(RLIMIT_CORE, &rl) == -1)
540 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
548 /* Make Sure Modules Are Avaliable!
549 * (BugFix By Craig.. See? I do work! :p)
550 * Modified by brain, requires const char*
551 * to work with other API functions
554 bool FileExists (const char* file)
557 if ((input = fopen (file, "r")) == NULL)
568 /* ConfProcess does the following things to a config line in the following order:
570 * Processes the line for syntax errors as shown below
571 * (1) Line void of quotes or equals (a malformed, illegal tag format)
572 * (2) Odd number of quotes on the line indicating a missing quote
573 * (3) number of equals signs not equal to number of quotes / 2 (missing an equals sign)
574 * (4) Spaces between the opening bracket (<) and the keyword
575 * (5) Spaces between a keyword and an equals sign
576 * (6) Spaces between an equals sign and a quote
577 * Removes trailing spaces
578 * Removes leading spaces
579 * Converts tabs to spaces
580 * Turns multiple spaces that are outside of quotes into single spaces
583 std::string ServerConfig::ConfProcess(char* buffer, long linenumber, std::stringstream* errorstream, bool &error, std::string filename)
585 long number_of_quotes = 0;
586 long number_of_equals = 0;
587 bool has_open_bracket = false;
588 bool in_quotes = false;
594 // firstly clean up the line by stripping spaces from the start and end and converting tabs to spaces
595 for (unsigned int d = 0; d < strlen(buffer); d++)
596 if ((buffer[d]) == 9)
598 while ((buffer[0] == ' ') && (strlen(buffer)>0)) buffer++;
599 while ((buffer[strlen(buffer)-1] == ' ') && (strlen(buffer)>0)) buffer[strlen(buffer)-1] = '\0';
601 // empty lines are syntactically valid, as are comments
602 if (!(*buffer) || buffer[0] == '#')
605 for (unsigned int c = 0; c < strlen(buffer); c++)
607 // convert all spaces that are OUTSIDE quotes into hardspace (0xA0) as this will make them easier to
608 // search and replace later :)
609 if ((!in_quotes) && (buffer[c] == ' '))
611 if ((buffer[c] == '<') && (!in_quotes))
613 has_open_bracket = true;
614 if (strlen(buffer) == 1)
616 *errorstream << "Tag without identifier at " << filename << ":" << linenumber << endl;
620 else if ((tolower(buffer[c+1]) < 'a') || (tolower(buffer[c+1]) > 'z'))
622 *errorstream << "Invalid characters in identifier at " << filename << ":" << linenumber << endl;
627 if (buffer[c] == '"')
630 in_quotes = (!in_quotes);
632 if ((buffer[c] == '=') && (!in_quotes))
635 if (strlen(buffer) == c)
637 *errorstream << "Variable without a value at " << filename << ":" << linenumber << endl;
641 else if (buffer[c+1] != '"')
643 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
649 *errorstream << "Value without a variable (line starts with '=') at " << filename << ":" << linenumber << endl;
653 else if (buffer[c-1] == '\xA0')
655 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
661 // no quotes, and no equals. something freaky.
662 if ((!number_of_quotes) || (!number_of_equals) && (strlen(buffer)>2) && (buffer[0]=='<'))
664 *errorstream << "Malformed tag at " << filename << ":" << linenumber << endl;
668 // odd number of quotes. thats just wrong.
669 if ((number_of_quotes % 2) != 0)
671 *errorstream << "Missing \" at " << filename << ":" << linenumber << endl;
675 if (number_of_equals < (number_of_quotes/2))
677 *errorstream << "Missing '=' at " << filename << ":" << linenumber << endl;
679 if (number_of_equals > (number_of_quotes/2))
681 *errorstream << "Too many '=' at " << filename << ":" << linenumber << endl;
684 std::string parsedata = buffer;
685 // turn multispace into single space
686 while (parsedata.find("\xA0\xA0") != std::string::npos)
688 parsedata.erase(parsedata.find("\xA0\xA0"),1);
691 // turn our hardspace back into softspace
692 for (unsigned int d = 0; d < parsedata.length(); d++)
694 if (parsedata[d] == '\xA0')
698 // and we're done, the line is fine!
702 int ServerConfig::fgets_safe(char* buffer, size_t maxsize, FILE* &file)
705 unsigned int bufptr = 0;
706 while ((!feof(file)) && (c_read != '\n') && (c_read != '\r') && (bufptr < maxsize))
708 c_read = fgetc(file);
709 if ((c_read != '\n') && (c_read != '\r'))
710 buffer[bufptr++] = c_read;
712 buffer[bufptr] = '\0';
716 bool ServerConfig::LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream)
719 errorstream->str("");
721 // first, check that the file exists before we try to do anything with it
722 if (!FileExists(filename))
724 *errorstream << "File " << filename << " not found." << endl;
727 // Fix the chmod of the file to restrict it to the current user and group
728 chmod(filename,0600);
729 for (unsigned int t = 0; t < include_stack.size(); t++)
731 if (std::string(filename) == include_stack[t])
733 *errorstream << "File " << filename << " is included recursively (looped inclusion)." << endl;
737 include_stack.push_back(filename);
739 FILE* conf = fopen(filename,"r");
745 if (fgets_safe(buffer, MAXBUF, conf))
747 if ((!feof(conf)) && (buffer) && (strlen(buffer)))
749 if ((buffer[0] != '#') && (buffer[0] != '\r') && (buffer[0] != '\n'))
751 if (!strncmp(buffer,"<include file=\"",15))
754 char confpath[10240],newconf[10240];
755 // include file directive
756 buf += 15; // advance to filename
757 for (unsigned int j = 0; j < strlen(buf); j++)
767 log(DEFAULT,"Opening included file '%s'",buf);
770 strlcpy(confpath,CONFIG_FILE,10240);
771 if (strstr(confpath,"/inspircd.conf"))
773 // leaves us with just the path
774 *(strstr(confpath,"/inspircd.conf")) = '\0';
776 snprintf(newconf,10240,"%s/%s",confpath,buf);
778 else strlcpy(newconf,buf,10240);
779 std::stringstream merge(stringstream::in | stringstream::out);
780 // recursively call LoadConf and get the new data, use the same errorstream
781 if (LoadConf(newconf, &merge, errorstream))
783 // append to the end of the file
784 std::string newstuff = merge.str();
789 // the error propogates up to its parent recursively
790 // causing the config reader to bail at the top level.
798 std::string data = this->ConfProcess(buffer,linenumber++,errorstream,error,filename);
816 /* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */
818 int ServerConfig::EnumConf(std::stringstream *config, const char* tag)
821 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
822 int in_token, in_quotes, tptr, idx = 0;
824 const char* buf = config->str().c_str();
826 long len = strlen(buf);
836 if ((c == '#') && (lastc == '\n'))
838 while ((c != '\n') && (bptr<len))
844 if ((c == '<') && (!in_quotes))
859 in_quotes = (!in_quotes);
861 if ((c == '>') && (!in_quotes))
864 if (!strcmp(c_tag,tag))
866 /* correct tag, but wrong index */
876 if ((in_token) && (c != '\n') && (c != '\r'))
886 /* Counts the number of values within a certain tag */
888 int ServerConfig::EnumValues(std::stringstream *config, const char* tag, int index)
891 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
892 int in_token, in_quotes, tptr, idx = 0;
894 bool correct_tag = false;
897 const char* buf = config->str().c_str();
899 long len = strlen(buf);
909 if ((c == '#') && (lastc == '\n'))
911 while ((c != '\n') && (bptr<len))
917 if ((c == '<') && (!in_quotes))
928 if ((!strcmp(c_tag,tag)) && (idx == index))
937 in_quotes = (!in_quotes);
940 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
944 if ((c == '>') && (!in_quotes))
949 if (!strcmp(c_tag,tag))
951 /* correct tag, but wrong index */
961 if ((in_token) && (c != '\n') && (c != '\r'))
973 int ServerConfig::ConfValueEnum(char* tag, std::stringstream* config)
975 return EnumConf(config,tag);
980 /* Retrieves a value from the config file. If there is more than one value of the specified
981 * key and section (e.g. for opers etc) then the index value specifies which to retreive, e.g.
983 * ConfValue("oper","name",2,result);
986 int ServerConfig::ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
989 char buffer[65535], c_tag[MAXBUF], c, lastc;
990 int in_token, in_quotes, tptr, idx = 0;
993 const char* buf = config->str().c_str();
995 long len = config->str().length();
1007 // FIX: Treat tabs as spaces
1010 if ((c == '<') && (!in_quotes))
1021 // FIX: Tab can follow a tagname as well as space.
1022 } while ((c != ' ') && (c != 9));
1026 in_quotes = (!in_quotes);
1028 if ((c == '>') && (!in_quotes))
1033 if (!strcmp(c_tag,tag))
1035 if ((buffer) && (c_tag) && (var))
1037 key = strstr(buffer,var);
1040 /* value not found in tag */
1058 for (unsigned j = 0; j < strlen(key); j++)
1065 strlcpy(result,key,MAXBUF);
1071 if (!strcmp(c_tag,tag))
1073 /* correct tag, but wrong index */
1083 if ((in_token) && (c != '\n') && (c != '\r'))
1090 *result = 0; // value or its tag not found at all
1096 int ServerConfig::ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
1098 ReadConf(config, tag, var, index, result);
1104 // This will bind a socket to a port. It works for UDP/TCP
1105 int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
1107 memset((char *)&server,0,sizeof(server));
1108 struct in_addr addy;
1109 inet_aton(addr,&addy);
1110 server.sin_family = AF_INET;
1111 if (!strcmp(addr,""))
1113 server.sin_addr.s_addr = htonl(INADDR_ANY);
1117 server.sin_addr = addy;
1119 server.sin_port = htons(port);
1120 if (bind(sockfd,(struct sockaddr*)&server,sizeof(server))<0)
1126 listen(sockfd, Config->MaxConn);
1132 // Open a TCP Socket
1133 int OpenTCPSocket (void)
1137 struct linger linger = { 0 };
1139 if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
1143 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
1144 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
1146 linger.l_linger = 1;
1147 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));
1154 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
1155 sockaddr_in client,server;
1156 int clientportcount = 0;
1157 int BoundPortCount = 0;
1158 for (int count = 0; count < Config->ConfValueEnum("bind",&Config->config_f); count++)
1160 Config->ConfValue("bind","port",count,configToken,&Config->config_f);
1161 Config->ConfValue("bind","address",count,Addr,&Config->config_f);
1162 Config->ConfValue("bind","type",count,Type,&Config->config_f);
1163 if ((!*Type) || (!strcmp(Type,"clients")))
1165 // modules handle server bind types now,
1166 // its not a typo in the strcmp.
1167 Config->ports[clientportcount] = atoi(configToken);
1168 strlcpy(Config->addrs[clientportcount],Addr,256);
1170 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
1173 int PortCount = clientportcount;
1175 for (int count = 0; count < PortCount; count++)
1177 if ((openSockfd[BoundPortCount] = OpenTCPSocket()) == ERROR)
1179 log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[BoundPortCount]);
1182 if (BindSocket(openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]) == ERROR)
1184 log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)Config->ports[count]);
1186 else /* well we at least bound to one socket so we'll continue */
1192 /* if we didn't bind to anything then abort */
1193 if (!BoundPortCount)
1195 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
1196 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)PortCount);
1200 return BoundPortCount;