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];
153 std::stringstream errstr;
154 include_stack.clear();
156 if (!LoadConf(CONFIG_FILE,&Config->config_f,&errstr))
159 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
162 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
170 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
171 while (!errstr.eof())
173 errstr.getline(dataline,1024);
174 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
179 WriteOpers("There were errors in the configuration file:");
180 while (!errstr.eof())
182 errstr.getline(dataline,1024);
183 WriteOpers(dataline);
190 /* Check we dont have more than one of singular tags
192 if (!CheckOnce("server",bail,user) || !CheckOnce("admin",bail,user) || !CheckOnce("files",bail,user)
193 || !CheckOnce("power",bail,user) || !CheckOnce("options",bail,user)
194 || !CheckOnce("dns",bail,user) || !CheckOnce("pid",bail,user))
199 ConfValue("server","name",0,Config->ServerName,&Config->config_f);
200 ConfValue("server","description",0,Config->ServerDesc,&Config->config_f);
201 ConfValue("server","network",0,Config->Network,&Config->config_f);
202 ConfValue("admin","name",0,Config->AdminName,&Config->config_f);
203 ConfValue("admin","email",0,Config->AdminEmail,&Config->config_f);
204 ConfValue("admin","nick",0,Config->AdminNick,&Config->config_f);
205 ConfValue("files","motd",0,Config->motd,&Config->config_f);
206 ConfValue("files","rules",0,Config->rules,&Config->config_f);
207 ConfValue("power","diepass",0,Config->diepass,&Config->config_f);
208 ConfValue("power","pause",0,pauseval,&Config->config_f);
209 ConfValue("power","restartpass",0,Config->restartpass,&Config->config_f);
210 ConfValue("options","prefixquit",0,Config->PrefixQuit,&Config->config_f);
211 ConfValue("die","value",0,Config->DieValue,&Config->config_f);
212 ConfValue("options","loglevel",0,dbg,&Config->config_f);
213 ConfValue("options","netbuffersize",0,NB,&Config->config_f);
214 ConfValue("options","maxwho",0,MW,&Config->config_f);
215 ConfValue("options","allowhalfop",0,AH,&Config->config_f);
216 ConfValue("options","allowprotect",0,AP,&Config->config_f);
217 ConfValue("options","allowfounder",0,AF,&Config->config_f);
218 ConfValue("dns","server",0,Config->DNSServer,&Config->config_f);
219 ConfValue("dns","timeout",0,DNT,&Config->config_f);
220 ConfValue("options","moduledir",0,Config->ModPath,&Config->config_f);
221 ConfValue("disabled","commands",0,Config->DisabledCommands,&Config->config_f);
222 ConfValue("options","somaxconn",0,MCON,&Config->config_f);
223 ConfValue("options","softlimit",0,SLIMT,&Config->config_f);
224 ConfValue("options","operonlystats",0,Config->OperOnlyStats,&Config->config_f);
225 ConfValue("options","customversion",0,Config->CustomVersion,&Config->config_f);
226 ConfValue("options","maxtargets",0,MT,&Config->config_f);
228 Config->SoftLimit = atoi(SLIMT);
230 Config->MaxTargets = atoi(MT);
231 if ((Config->MaxTargets < 0) || (Config->MaxTargets > 31))
233 log(DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
234 Config->MaxTargets = 20;
236 if ((Config->SoftLimit < 1) || (Config->SoftLimit > MAXCLIENTS))
238 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
239 Config->SoftLimit = MAXCLIENTS;
241 Config->MaxConn = atoi(MCON);
242 if (Config->MaxConn > SOMAXCONN)
243 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
244 Config->NetBufferSize = atoi(NB);
245 Config->MaxWhoResults = atoi(MW);
246 Config->dns_timeout = atoi(DNT);
247 if (!Config->dns_timeout)
248 Config->dns_timeout = 5;
249 if (!Config->MaxConn)
250 Config->MaxConn = SOMAXCONN;
251 if (!*Config->DNSServer)
252 strlcpy(Config->DNSServer,"127.0.0.1",MAXBUF);
253 if (!*Config->ModPath)
254 strlcpy(Config->ModPath,MOD_PATH,MAXBUF);
255 Config->AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
256 if ((!Config->NetBufferSize) || (Config->NetBufferSize > 65535) || (Config->NetBufferSize < 1024))
258 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
259 Config->NetBufferSize = 10240;
261 if ((!Config->MaxWhoResults) || (Config->MaxWhoResults > 65535) || (Config->MaxWhoResults < 1))
263 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
264 Config->MaxWhoResults = 128;
266 Config->LogLevel = DEFAULT;
267 if (!strcmp(dbg,"debug"))
269 Config->LogLevel = DEBUG;
270 Config->debugging = 1;
272 if (!strcmp(dbg,"verbose"))
273 Config->LogLevel = VERBOSE;
274 if (!strcmp(dbg,"default"))
275 Config->LogLevel = DEFAULT;
276 if (!strcmp(dbg,"sparse"))
277 Config->LogLevel = SPARSE;
278 if (!strcmp(dbg,"none"))
279 Config->LogLevel = NONE;
281 readfile(Config->MOTD,Config->motd);
282 log(DEFAULT,"Reading message of the day...");
283 readfile(Config->RULES,Config->rules);
284 log(DEFAULT,"Reading connect classes...");
286 for (int i = 0; i < ConfValueEnum("connect",&Config->config_f); i++)
289 ConfValue("connect","allow",i,Value,&Config->config_f);
290 ConfValue("connect","timeout",i,timeout,&Config->config_f);
291 ConfValue("connect","flood",i,flood,&Config->config_f);
292 ConfValue("connect","pingfreq",i,pfreq,&Config->config_f);
293 ConfValue("connect","threshold",i,thold,&Config->config_f);
294 ConfValue("connect","sendq",i,sqmax,&Config->config_f);
295 ConfValue("connect","recvq",i,rqmax,&Config->config_f);
300 strlcpy(Value,"",MAXBUF);
301 ConfValue("connect","password",i,Value,&Config->config_f);
303 c.registration_timeout = 90; // default is 2 minutes
305 c.flood = atoi(flood);
307 c.sendqmax = 262144; // 256k
308 c.recvqmax = 4096; // 4k
311 c.threshold = atoi(thold);
315 c.sendqmax = atoi(sqmax);
319 c.recvqmax = atoi(rqmax);
323 c.registration_timeout = atoi(timeout);
327 c.pingtime = atoi(pfreq);
329 Classes.push_back(c);
333 ConfValue("connect","deny",i,Value,&Config->config_f);
336 Classes.push_back(c);
337 log(DEBUG,"Read connect class type DENY, host=%s",c.host.c_str());
341 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
342 read_xline_defaults();
343 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
344 apply_lines(APPLY_ALL);
346 ConfValue("pid","file",0,Config->PID,&Config->config_f);
347 // write once here, to try it out and make sure its ok
348 WritePID(Config->PID);
350 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
353 log(DEFAULT,"Adding and removing modules due to rehash...");
355 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
357 // store the old module names
358 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
360 old_module_names.push_back(*t);
363 // get the new module names
364 for (int count2 = 0; count2 < ConfValueEnum("module",&Config->config_f); count2++)
366 ConfValue("module","name",count2,Value,&Config->config_f);
367 new_module_names.push_back(Value);
370 // now create a list of new modules that are due to be loaded
371 // and a seperate list of modules which are due to be unloaded
372 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
375 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
381 added_modules.push_back(*_new);
383 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
386 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
392 removed_modules.push_back(*oldm);
394 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
396 int rem = 0, add = 0;
397 if (!removed_modules.empty())
398 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
400 if (ServerInstance->UnloadModule(removing->c_str()))
402 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
403 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
408 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
411 if (!added_modules.empty())
412 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
414 if (ServerInstance->LoadModule(adding->c_str()))
416 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
417 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
422 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
425 log(DEFAULT,"Successfully unloaded %lu of %lu modules and loaded %lu of %lu modules.",(unsigned long)rem,(unsigned long)removed_modules.size(),
426 (unsigned long)add,(unsigned long)added_modules.size());
431 void Exit (int status)
433 if (Config->log_file)
434 fclose(Config->log_file);
435 send_error("Server shutdown.");
439 void Killed(int status)
441 if (Config->log_file)
442 fclose(Config->log_file);
443 send_error("Server terminated.");
447 char* CleanFilename(char* name)
449 char* p = name + strlen(name);
450 while ((p != name) && (*p != '/')) p--;
451 return (p != name ? ++p : p);
455 void Rehash(int status)
457 WriteOpers("Rehashing config file %s due to SIGHUP",CleanFilename(CONFIG_FILE));
458 fclose(Config->log_file);
460 Config->Read(false,NULL);
461 FOREACH_MOD(I_OnRehash,OnRehash(""));
468 printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
469 printf("(C) ChatSpike Development team.\033[0m\n\n");
470 printf("Developers:\033[1;32m Brain, FrostyCoolSlug\033[0m\n");
471 printf("Documentation:\033[1;32m FrostyCoolSlug, w00t\033[0m\n");
472 printf("Testers:\033[1;32m typobox43, piggles, Lord_Zathras, CC\033[0m\n");
473 printf("Name concept:\033[1;32m Lord_Zathras\033[0m\n\n");
476 void WritePID(std::string filename)
478 ofstream outfile(filename.c_str());
479 if (outfile.is_open())
486 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
487 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
494 signal (SIGALRM, SIG_IGN);
495 signal (SIGHUP, Rehash);
496 signal (SIGPIPE, SIG_IGN);
497 signal (SIGTERM, Exit);
498 signal (SIGSEGV, Error);
502 int DaemonSeed (void)
505 if ((childpid = fork ()) < 0)
507 else if (childpid > 0)
511 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
513 setpriority(PRIO_PROCESS,(int)getpid(),15);
515 if (Config->unlimitcore)
518 if (getrlimit(RLIMIT_CORE, &rl) == -1)
520 log(DEFAULT,"Failed to getrlimit()!");
525 rl.rlim_cur = rl.rlim_max;
526 if (setrlimit(RLIMIT_CORE, &rl) == -1)
527 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
535 /* Make Sure Modules Are Avaliable!
536 * (BugFix By Craig.. See? I do work! :p)
537 * Modified by brain, requires const char*
538 * to work with other API functions
541 bool FileExists (const char* file)
544 if ((input = fopen (file, "r")) == NULL)
555 /* ConfProcess does the following things to a config line in the following order:
557 * Processes the line for syntax errors as shown below
558 * (1) Line void of quotes or equals (a malformed, illegal tag format)
559 * (2) Odd number of quotes on the line indicating a missing quote
560 * (3) number of equals signs not equal to number of quotes / 2 (missing an equals sign)
561 * (4) Spaces between the opening bracket (<) and the keyword
562 * (5) Spaces between a keyword and an equals sign
563 * (6) Spaces between an equals sign and a quote
564 * Removes trailing spaces
565 * Removes leading spaces
566 * Converts tabs to spaces
567 * Turns multiple spaces that are outside of quotes into single spaces
570 std::string ServerConfig::ConfProcess(char* buffer, long linenumber, std::stringstream* errorstream, bool &error, std::string filename)
572 long number_of_quotes = 0;
573 long number_of_equals = 0;
574 bool has_open_bracket = false;
575 bool in_quotes = false;
581 // firstly clean up the line by stripping spaces from the start and end and converting tabs to spaces
582 for (unsigned int d = 0; d < strlen(buffer); d++)
583 if ((buffer[d]) == 9)
585 while ((buffer[0] == ' ') && (strlen(buffer)>0)) buffer++;
586 while ((buffer[strlen(buffer)-1] == ' ') && (strlen(buffer)>0)) buffer[strlen(buffer)-1] = '\0';
588 // empty lines are syntactically valid, as are comments
589 if (!(*buffer) || buffer[0] == '#')
592 for (unsigned int c = 0; c < strlen(buffer); c++)
594 // convert all spaces that are OUTSIDE quotes into hardspace (0xA0) as this will make them easier to
595 // search and replace later :)
596 if ((!in_quotes) && (buffer[c] == ' '))
598 if ((buffer[c] == '<') && (!in_quotes))
600 has_open_bracket = true;
601 if (strlen(buffer) == 1)
603 *errorstream << "Tag without identifier at " << filename << ":" << linenumber << endl;
607 else if ((tolower(buffer[c+1]) < 'a') || (tolower(buffer[c+1]) > 'z'))
609 *errorstream << "Invalid characters in identifier at " << filename << ":" << linenumber << endl;
614 if (buffer[c] == '"')
617 in_quotes = (!in_quotes);
619 if ((buffer[c] == '=') && (!in_quotes))
622 if (strlen(buffer) == c)
624 *errorstream << "Variable without a value at " << filename << ":" << linenumber << endl;
628 else if (buffer[c+1] != '"')
630 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
636 *errorstream << "Value without a variable (line starts with '=') at " << filename << ":" << linenumber << endl;
640 else if (buffer[c-1] == '\xA0')
642 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
648 // no quotes, and no equals. something freaky.
649 if ((!number_of_quotes) || (!number_of_equals) && (strlen(buffer)>2) && (buffer[0]=='<'))
651 *errorstream << "Malformed tag at " << filename << ":" << linenumber << endl;
655 // odd number of quotes. thats just wrong.
656 if ((number_of_quotes % 2) != 0)
658 *errorstream << "Missing \" at " << filename << ":" << linenumber << endl;
662 if (number_of_equals < (number_of_quotes/2))
664 *errorstream << "Missing '=' at " << filename << ":" << linenumber << endl;
666 if (number_of_equals > (number_of_quotes/2))
668 *errorstream << "Too many '=' at " << filename << ":" << linenumber << endl;
671 std::string parsedata = buffer;
672 // turn multispace into single space
673 while (parsedata.find("\xA0\xA0") != std::string::npos)
675 parsedata.erase(parsedata.find("\xA0\xA0"),1);
678 // turn our hardspace back into softspace
679 for (unsigned int d = 0; d < parsedata.length(); d++)
681 if (parsedata[d] == '\xA0')
685 // and we're done, the line is fine!
689 int ServerConfig::fgets_safe(char* buffer, size_t maxsize, FILE* &file)
692 unsigned int bufptr = 0;
693 while ((!feof(file)) && (c_read != '\n') && (c_read != '\r') && (bufptr < maxsize))
695 c_read = fgetc(file);
696 if ((c_read != '\n') && (c_read != '\r'))
697 buffer[bufptr++] = c_read;
699 buffer[bufptr] = '\0';
703 bool ServerConfig::LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream)
706 errorstream->str("");
708 // first, check that the file exists before we try to do anything with it
709 if (!FileExists(filename))
711 *errorstream << "File " << filename << " not found." << endl;
714 // Fix the chmod of the file to restrict it to the current user and group
715 chmod(filename,0600);
716 for (unsigned int t = 0; t < include_stack.size(); t++)
718 if (std::string(filename) == include_stack[t])
720 *errorstream << "File " << filename << " is included recursively (looped inclusion)." << endl;
724 include_stack.push_back(filename);
726 FILE* conf = fopen(filename,"r");
732 if (fgets_safe(buffer, MAXBUF, conf))
734 if ((!feof(conf)) && (buffer) && (strlen(buffer)))
736 if ((buffer[0] != '#') && (buffer[0] != '\r') && (buffer[0] != '\n'))
738 if (!strncmp(buffer,"<include file=\"",15))
741 char confpath[10240],newconf[10240];
742 // include file directive
743 buf += 15; // advance to filename
744 for (unsigned int j = 0; j < strlen(buf); j++)
754 log(DEFAULT,"Opening included file '%s'",buf);
757 strlcpy(confpath,CONFIG_FILE,10240);
758 if (strstr(confpath,"/inspircd.conf"))
760 // leaves us with just the path
761 *(strstr(confpath,"/inspircd.conf")) = '\0';
763 snprintf(newconf,10240,"%s/%s",confpath,buf);
765 else strlcpy(newconf,buf,10240);
766 std::stringstream merge(stringstream::in | stringstream::out);
767 // recursively call LoadConf and get the new data, use the same errorstream
768 if (LoadConf(newconf, &merge, errorstream))
770 // append to the end of the file
771 std::string newstuff = merge.str();
776 // the error propogates up to its parent recursively
777 // causing the config reader to bail at the top level.
785 std::string data = this->ConfProcess(buffer,linenumber++,errorstream,error,filename);
803 /* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */
805 int ServerConfig::EnumConf(std::stringstream *config, const char* tag)
808 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
809 int in_token, in_quotes, tptr, idx = 0;
811 const char* buf = config->str().c_str();
813 long len = strlen(buf);
823 if ((c == '#') && (lastc == '\n'))
825 while ((c != '\n') && (bptr<len))
831 if ((c == '<') && (!in_quotes))
846 in_quotes = (!in_quotes);
848 if ((c == '>') && (!in_quotes))
851 if (!strcmp(c_tag,tag))
853 /* correct tag, but wrong index */
863 if ((in_token) && (c != '\n') && (c != '\r'))
873 /* Counts the number of values within a certain tag */
875 int ServerConfig::EnumValues(std::stringstream *config, const char* tag, int index)
878 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
879 int in_token, in_quotes, tptr, idx = 0;
881 bool correct_tag = false;
884 const char* buf = config->str().c_str();
886 long len = strlen(buf);
896 if ((c == '#') && (lastc == '\n'))
898 while ((c != '\n') && (bptr<len))
904 if ((c == '<') && (!in_quotes))
915 if ((!strcmp(c_tag,tag)) && (idx == index))
924 in_quotes = (!in_quotes);
927 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
931 if ((c == '>') && (!in_quotes))
936 if (!strcmp(c_tag,tag))
938 /* correct tag, but wrong index */
948 if ((in_token) && (c != '\n') && (c != '\r'))
960 int ServerConfig::ConfValueEnum(char* tag, std::stringstream* config)
962 return EnumConf(config,tag);
967 /* Retrieves a value from the config file. If there is more than one value of the specified
968 * key and section (e.g. for opers etc) then the index value specifies which to retreive, e.g.
970 * ConfValue("oper","name",2,result);
973 int ServerConfig::ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
976 char buffer[65535], c_tag[MAXBUF], c, lastc;
977 int in_token, in_quotes, tptr, idx = 0;
980 const char* buf = config->str().c_str();
982 long len = config->str().length();
994 // FIX: Treat tabs as spaces
997 if ((c == '<') && (!in_quotes))
1008 // FIX: Tab can follow a tagname as well as space.
1009 } while ((c != ' ') && (c != 9));
1013 in_quotes = (!in_quotes);
1015 if ((c == '>') && (!in_quotes))
1020 if (!strcmp(c_tag,tag))
1022 if ((buffer) && (c_tag) && (var))
1024 key = strstr(buffer,var);
1027 /* value not found in tag */
1045 for (unsigned j = 0; j < strlen(key); j++)
1052 strlcpy(result,key,MAXBUF);
1058 if (!strcmp(c_tag,tag))
1060 /* correct tag, but wrong index */
1070 if ((in_token) && (c != '\n') && (c != '\r'))
1077 *result = 0; // value or its tag not found at all
1083 int ServerConfig::ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
1085 ReadConf(config, tag, var, index, result);
1091 // This will bind a socket to a port. It works for UDP/TCP
1092 int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
1094 memset((char *)&server,0,sizeof(server));
1095 struct in_addr addy;
1096 inet_aton(addr,&addy);
1097 server.sin_family = AF_INET;
1098 if (!strcmp(addr,""))
1100 server.sin_addr.s_addr = htonl(INADDR_ANY);
1104 server.sin_addr = addy;
1106 server.sin_port = htons(port);
1107 if (bind(sockfd,(struct sockaddr*)&server,sizeof(server))<0)
1113 listen(sockfd, Config->MaxConn);
1119 // Open a TCP Socket
1120 int OpenTCPSocket (void)
1124 struct linger linger = { 0 };
1126 if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
1130 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
1131 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
1133 linger.l_linger = 1;
1134 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));
1141 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
1142 sockaddr_in client,server;
1143 int clientportcount = 0;
1144 int BoundPortCount = 0;
1145 for (int count = 0; count < Config->ConfValueEnum("bind",&Config->config_f); count++)
1147 Config->ConfValue("bind","port",count,configToken,&Config->config_f);
1148 Config->ConfValue("bind","address",count,Addr,&Config->config_f);
1149 Config->ConfValue("bind","type",count,Type,&Config->config_f);
1150 if ((!*Type) || (!strcmp(Type,"clients")))
1152 // modules handle server bind types now,
1153 // its not a typo in the strcmp.
1154 Config->ports[clientportcount] = atoi(configToken);
1155 strlcpy(Config->addrs[clientportcount],Addr,256);
1157 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
1160 int PortCount = clientportcount;
1162 for (int count = 0; count < PortCount; count++)
1164 if ((openSockfd[BoundPortCount] = OpenTCPSocket()) == ERROR)
1166 log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[BoundPortCount]);
1169 if (BindSocket(openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]) == ERROR)
1171 log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)Config->ports[count]);
1173 else /* well we at least bound to one socket so we'll continue */
1179 /* if we didn't bind to anything then abort */
1180 if (!BoundPortCount)
1182 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
1183 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)PortCount);
1187 return BoundPortCount;