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 if (ConfValueEnum(tag,&Config->config_f) > 1)
103 printf("There were errors in your configuration:\nYou have more than one <%s> tag, this is not permitted.\n",tag);
110 WriteServ(user->fd,"There were errors in your configuration:");
111 WriteServ(user->fd,"You have more than one <%s> tag, this is not permitted.\n",tag);
115 WriteOpers("There were errors in the configuration file:");
116 WriteOpers("You have more than one <%s> tag, this is not permitted.\n",tag);
124 void ServerConfig::Read(bool bail, userrec* user)
126 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF],MCON[MAXBUF];
127 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF],SLIMT[MAXBUF];
129 std::stringstream errstr;
130 include_stack.clear();
132 if (!LoadConf(CONFIG_FILE,&Config->config_f,&errstr))
135 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
138 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
146 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
147 while (!errstr.eof())
149 errstr.getline(dataline,1024);
150 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
155 WriteOpers("There were errors in the configuration file:");
156 while (!errstr.eof())
158 errstr.getline(dataline,1024);
159 WriteOpers(dataline);
166 /* Check we dont have more than one of singular tags
168 if (!CheckOnce("server",bail,user) || !CheckOnce("admin",bail,user) || !CheckOnce("files",bail,user)
169 || !CheckOnce("power",bail,user) || !CheckOnce("options",bail,user)
170 || !CheckOnce("dns",bail,user) || !CheckOnce("options",bail,user)
171 || !CheckOnce("disabled",bail,user) || !CheckOnce("pid",bail,user))
176 ConfValue("server","name",0,Config->ServerName,&Config->config_f);
177 ConfValue("server","description",0,Config->ServerDesc,&Config->config_f);
178 ConfValue("server","network",0,Config->Network,&Config->config_f);
179 ConfValue("admin","name",0,Config->AdminName,&Config->config_f);
180 ConfValue("admin","email",0,Config->AdminEmail,&Config->config_f);
181 ConfValue("admin","nick",0,Config->AdminNick,&Config->config_f);
182 ConfValue("files","motd",0,Config->motd,&Config->config_f);
183 ConfValue("files","rules",0,Config->rules,&Config->config_f);
184 ConfValue("power","diepass",0,Config->diepass,&Config->config_f);
185 ConfValue("power","pause",0,pauseval,&Config->config_f);
186 ConfValue("power","restartpass",0,Config->restartpass,&Config->config_f);
187 ConfValue("options","prefixquit",0,Config->PrefixQuit,&Config->config_f);
188 ConfValue("die","value",0,Config->DieValue,&Config->config_f);
189 ConfValue("options","loglevel",0,dbg,&Config->config_f);
190 ConfValue("options","netbuffersize",0,NB,&Config->config_f);
191 ConfValue("options","maxwho",0,MW,&Config->config_f);
192 ConfValue("options","allowhalfop",0,AH,&Config->config_f);
193 ConfValue("options","allowprotect",0,AP,&Config->config_f);
194 ConfValue("options","allowfounder",0,AF,&Config->config_f);
195 ConfValue("dns","server",0,Config->DNSServer,&Config->config_f);
196 ConfValue("dns","timeout",0,DNT,&Config->config_f);
197 ConfValue("options","moduledir",0,Config->ModPath,&Config->config_f);
198 ConfValue("disabled","commands",0,Config->DisabledCommands,&Config->config_f);
199 ConfValue("options","somaxconn",0,MCON,&Config->config_f);
200 ConfValue("options","softlimit",0,SLIMT,&Config->config_f);
201 ConfValue("options","operonlystats",0,Config->OperOnlyStats,&Config->config_f);
202 ConfValue("options","customversion",0,Config->CustomVersion,&Config->config_f);
204 Config->SoftLimit = atoi(SLIMT);
205 if ((Config->SoftLimit < 1) || (Config->SoftLimit > MAXCLIENTS))
207 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
208 Config->SoftLimit = MAXCLIENTS;
210 Config->MaxConn = atoi(MCON);
211 if (Config->MaxConn > SOMAXCONN)
212 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
213 Config->NetBufferSize = atoi(NB);
214 Config->MaxWhoResults = atoi(MW);
215 Config->dns_timeout = atoi(DNT);
216 if (!Config->dns_timeout)
217 Config->dns_timeout = 5;
218 if (!Config->MaxConn)
219 Config->MaxConn = SOMAXCONN;
220 if (!*Config->DNSServer)
221 strlcpy(Config->DNSServer,"127.0.0.1",MAXBUF);
222 if (!*Config->ModPath)
223 strlcpy(Config->ModPath,MOD_PATH,MAXBUF);
224 Config->AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
225 if ((!Config->NetBufferSize) || (Config->NetBufferSize > 65535) || (Config->NetBufferSize < 1024))
227 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
228 Config->NetBufferSize = 10240;
230 if ((!Config->MaxWhoResults) || (Config->MaxWhoResults > 65535) || (Config->MaxWhoResults < 1))
232 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
233 Config->MaxWhoResults = 128;
235 Config->LogLevel = DEFAULT;
236 if (!strcmp(dbg,"debug"))
238 Config->LogLevel = DEBUG;
239 Config->debugging = 1;
241 if (!strcmp(dbg,"verbose"))
242 Config->LogLevel = VERBOSE;
243 if (!strcmp(dbg,"default"))
244 Config->LogLevel = DEFAULT;
245 if (!strcmp(dbg,"sparse"))
246 Config->LogLevel = SPARSE;
247 if (!strcmp(dbg,"none"))
248 Config->LogLevel = NONE;
250 readfile(Config->MOTD,Config->motd);
251 log(DEFAULT,"Reading message of the day...");
252 readfile(Config->RULES,Config->rules);
253 log(DEFAULT,"Reading connect classes...");
255 for (int i = 0; i < ConfValueEnum("connect",&Config->config_f); i++)
258 ConfValue("connect","allow",i,Value,&Config->config_f);
259 ConfValue("connect","timeout",i,timeout,&Config->config_f);
260 ConfValue("connect","flood",i,flood,&Config->config_f);
261 ConfValue("connect","pingfreq",i,pfreq,&Config->config_f);
262 ConfValue("connect","threshold",i,thold,&Config->config_f);
263 ConfValue("connect","sendq",i,sqmax,&Config->config_f);
264 ConfValue("connect","recvq",i,rqmax,&Config->config_f);
269 strlcpy(Value,"",MAXBUF);
270 ConfValue("connect","password",i,Value,&Config->config_f);
272 c.registration_timeout = 90; // default is 2 minutes
274 c.flood = atoi(flood);
276 c.sendqmax = 262144; // 256k
277 c.recvqmax = 4096; // 4k
280 c.threshold = atoi(thold);
284 c.sendqmax = atoi(sqmax);
288 c.recvqmax = atoi(rqmax);
292 c.registration_timeout = atoi(timeout);
296 c.pingtime = atoi(pfreq);
298 Classes.push_back(c);
302 ConfValue("connect","deny",i,Value,&Config->config_f);
305 Classes.push_back(c);
306 log(DEBUG,"Read connect class type DENY, host=%s",c.host.c_str());
310 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
311 read_xline_defaults();
312 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
313 apply_lines(APPLY_ALL);
315 ConfValue("pid","file",0,Config->PID,&Config->config_f);
316 // write once here, to try it out and make sure its ok
317 WritePID(Config->PID);
319 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
322 log(DEFAULT,"Adding and removing modules due to rehash...");
324 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
326 // store the old module names
327 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
329 old_module_names.push_back(*t);
332 // get the new module names
333 for (int count2 = 0; count2 < ConfValueEnum("module",&Config->config_f); count2++)
335 ConfValue("module","name",count2,Value,&Config->config_f);
336 new_module_names.push_back(Value);
339 // now create a list of new modules that are due to be loaded
340 // and a seperate list of modules which are due to be unloaded
341 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
344 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
350 added_modules.push_back(*_new);
352 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
355 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
361 removed_modules.push_back(*oldm);
363 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
365 int rem = 0, add = 0;
366 if (!removed_modules.empty())
367 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
369 if (ServerInstance->UnloadModule(removing->c_str()))
371 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
372 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
377 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
380 if (!added_modules.empty())
381 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
383 if (ServerInstance->LoadModule(adding->c_str()))
385 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
386 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
391 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
394 log(DEFAULT,"Successfully unloaded %lu of %lu modules and loaded %lu of %lu modules.",(unsigned long)rem,(unsigned long)removed_modules.size(),
395 (unsigned long)add,(unsigned long)added_modules.size());
400 void Exit (int status)
402 if (Config->log_file)
403 fclose(Config->log_file);
404 send_error("Server shutdown.");
408 void Killed(int status)
410 if (Config->log_file)
411 fclose(Config->log_file);
412 send_error("Server terminated.");
416 char* CleanFilename(char* name)
418 char* p = name + strlen(name);
419 while ((p != name) && (*p != '/')) p--;
420 return (p != name ? ++p : p);
424 void Rehash(int status)
426 WriteOpers("Rehashing config file %s due to SIGHUP",CleanFilename(CONFIG_FILE));
427 fclose(Config->log_file);
429 Config->Read(false,NULL);
430 FOREACH_MOD(I_OnRehash,OnRehash(""));
437 printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
438 printf("(C) ChatSpike Development team.\033[0m\n\n");
439 printf("Developers:\033[1;32m Brain, FrostyCoolSlug\033[0m\n");
440 printf("Documentation:\033[1;32m FrostyCoolSlug, w00t\033[0m\n");
441 printf("Testers:\033[1;32m typobox43, piggles, Lord_Zathras, CC\033[0m\n");
442 printf("Name concept:\033[1;32m Lord_Zathras\033[0m\n\n");
445 void WritePID(std::string filename)
447 ofstream outfile(filename.c_str());
448 if (outfile.is_open())
455 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
456 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
463 signal (SIGALRM, SIG_IGN);
464 signal (SIGHUP, Rehash);
465 signal (SIGPIPE, SIG_IGN);
466 signal (SIGTERM, Exit);
467 signal (SIGSEGV, Error);
471 int DaemonSeed (void)
474 if ((childpid = fork ()) < 0)
476 else if (childpid > 0)
480 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
482 setpriority(PRIO_PROCESS,(int)getpid(),15);
484 if (Config->unlimitcore)
487 if (getrlimit(RLIMIT_CORE, &rl) == -1)
489 log(DEFAULT,"Failed to getrlimit()!");
494 rl.rlim_cur = rl.rlim_max;
495 if (setrlimit(RLIMIT_CORE, &rl) == -1)
496 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
504 /* Make Sure Modules Are Avaliable!
505 * (BugFix By Craig.. See? I do work! :p)
506 * Modified by brain, requires const char*
507 * to work with other API functions
510 bool FileExists (const char* file)
513 if ((input = fopen (file, "r")) == NULL)
524 /* ConfProcess does the following things to a config line in the following order:
526 * Processes the line for syntax errors as shown below
527 * (1) Line void of quotes or equals (a malformed, illegal tag format)
528 * (2) Odd number of quotes on the line indicating a missing quote
529 * (3) number of equals signs not equal to number of quotes / 2 (missing an equals sign)
530 * (4) Spaces between the opening bracket (<) and the keyword
531 * (5) Spaces between a keyword and an equals sign
532 * (6) Spaces between an equals sign and a quote
533 * Removes trailing spaces
534 * Removes leading spaces
535 * Converts tabs to spaces
536 * Turns multiple spaces that are outside of quotes into single spaces
539 std::string ServerConfig::ConfProcess(char* buffer, long linenumber, std::stringstream* errorstream, bool &error, std::string filename)
541 long number_of_quotes = 0;
542 long number_of_equals = 0;
543 bool has_open_bracket = false;
544 bool in_quotes = false;
550 // firstly clean up the line by stripping spaces from the start and end and converting tabs to spaces
551 for (unsigned int d = 0; d < strlen(buffer); d++)
552 if ((buffer[d]) == 9)
554 while ((buffer[0] == ' ') && (strlen(buffer)>0)) buffer++;
555 while ((buffer[strlen(buffer)-1] == ' ') && (strlen(buffer)>0)) buffer[strlen(buffer)-1] = '\0';
557 // empty lines are syntactically valid, as are comments
558 if (!(*buffer) || buffer[0] == '#')
561 for (unsigned int c = 0; c < strlen(buffer); c++)
563 // convert all spaces that are OUTSIDE quotes into hardspace (0xA0) as this will make them easier to
564 // search and replace later :)
565 if ((!in_quotes) && (buffer[c] == ' '))
567 if ((buffer[c] == '<') && (!in_quotes))
569 has_open_bracket = true;
570 if (strlen(buffer) == 1)
572 *errorstream << "Tag without identifier at " << filename << ":" << linenumber << endl;
576 else if ((tolower(buffer[c+1]) < 'a') || (tolower(buffer[c+1]) > 'z'))
578 *errorstream << "Invalid characters in identifier at " << filename << ":" << linenumber << endl;
583 if (buffer[c] == '"')
586 in_quotes = (!in_quotes);
588 if ((buffer[c] == '=') && (!in_quotes))
591 if (strlen(buffer) == c)
593 *errorstream << "Variable without a value at " << filename << ":" << linenumber << endl;
597 else if (buffer[c+1] != '"')
599 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
605 *errorstream << "Value without a variable (line starts with '=') at " << filename << ":" << linenumber << endl;
609 else if (buffer[c-1] == '\xA0')
611 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
617 // no quotes, and no equals. something freaky.
618 if ((!number_of_quotes) || (!number_of_equals) && (strlen(buffer)>2) && (buffer[0]=='<'))
620 *errorstream << "Malformed tag at " << filename << ":" << linenumber << endl;
624 // odd number of quotes. thats just wrong.
625 if ((number_of_quotes % 2) != 0)
627 *errorstream << "Missing \" at " << filename << ":" << linenumber << endl;
631 if (number_of_equals < (number_of_quotes/2))
633 *errorstream << "Missing '=' at " << filename << ":" << linenumber << endl;
635 if (number_of_equals > (number_of_quotes/2))
637 *errorstream << "Too many '=' at " << filename << ":" << linenumber << endl;
640 std::string parsedata = buffer;
641 // turn multispace into single space
642 while (parsedata.find("\xA0\xA0") != std::string::npos)
644 parsedata.erase(parsedata.find("\xA0\xA0"),1);
647 // turn our hardspace back into softspace
648 for (unsigned int d = 0; d < parsedata.length(); d++)
650 if (parsedata[d] == '\xA0')
654 // and we're done, the line is fine!
658 int ServerConfig::fgets_safe(char* buffer, size_t maxsize, FILE* &file)
661 unsigned int bufptr = 0;
662 while ((!feof(file)) && (c_read != '\n') && (c_read != '\r') && (bufptr < maxsize))
664 c_read = fgetc(file);
665 if ((c_read != '\n') && (c_read != '\r'))
666 buffer[bufptr++] = c_read;
668 buffer[bufptr] = '\0';
672 bool ServerConfig::LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream)
675 errorstream->str("");
677 // first, check that the file exists before we try to do anything with it
678 if (!FileExists(filename))
680 *errorstream << "File " << filename << " not found." << endl;
683 // Fix the chmod of the file to restrict it to the current user and group
684 chmod(filename,0600);
685 for (unsigned int t = 0; t < include_stack.size(); t++)
687 if (std::string(filename) == include_stack[t])
689 *errorstream << "File " << filename << " is included recursively (looped inclusion)." << endl;
693 include_stack.push_back(filename);
695 FILE* conf = fopen(filename,"r");
701 if (fgets_safe(buffer, MAXBUF, conf))
703 if ((!feof(conf)) && (buffer) && (strlen(buffer)))
705 if ((buffer[0] != '#') && (buffer[0] != '\r') && (buffer[0] != '\n'))
707 if (!strncmp(buffer,"<include file=\"",15))
710 char confpath[10240],newconf[10240];
711 // include file directive
712 buf += 15; // advance to filename
713 for (unsigned int j = 0; j < strlen(buf); j++)
723 log(DEFAULT,"Opening included file '%s'",buf);
726 strlcpy(confpath,CONFIG_FILE,10240);
727 if (strstr(confpath,"/inspircd.conf"))
729 // leaves us with just the path
730 *(strstr(confpath,"/inspircd.conf")) = '\0';
732 snprintf(newconf,10240,"%s/%s",confpath,buf);
734 else strlcpy(newconf,buf,10240);
735 std::stringstream merge(stringstream::in | stringstream::out);
736 // recursively call LoadConf and get the new data, use the same errorstream
737 if (LoadConf(newconf, &merge, errorstream))
739 // append to the end of the file
740 std::string newstuff = merge.str();
745 // the error propogates up to its parent recursively
746 // causing the config reader to bail at the top level.
754 std::string data = this->ConfProcess(buffer,linenumber++,errorstream,error,filename);
772 /* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */
774 int ServerConfig::EnumConf(std::stringstream *config, const char* tag)
777 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
778 int in_token, in_quotes, tptr, idx = 0;
780 const char* buf = config->str().c_str();
782 long len = strlen(buf);
792 if ((c == '#') && (lastc == '\n'))
794 while ((c != '\n') && (bptr<len))
800 if ((c == '<') && (!in_quotes))
815 in_quotes = (!in_quotes);
817 if ((c == '>') && (!in_quotes))
820 if (!strcmp(c_tag,tag))
822 /* correct tag, but wrong index */
832 if ((in_token) && (c != '\n') && (c != '\r'))
842 /* Counts the number of values within a certain tag */
844 int ServerConfig::EnumValues(std::stringstream *config, const char* tag, int index)
847 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
848 int in_token, in_quotes, tptr, idx = 0;
850 bool correct_tag = false;
853 const char* buf = config->str().c_str();
855 long len = strlen(buf);
865 if ((c == '#') && (lastc == '\n'))
867 while ((c != '\n') && (bptr<len))
873 if ((c == '<') && (!in_quotes))
884 if ((!strcmp(c_tag,tag)) && (idx == index))
893 in_quotes = (!in_quotes);
896 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
900 if ((c == '>') && (!in_quotes))
905 if (!strcmp(c_tag,tag))
907 /* correct tag, but wrong index */
917 if ((in_token) && (c != '\n') && (c != '\r'))
929 int ServerConfig::ConfValueEnum(char* tag, std::stringstream* config)
931 return EnumConf(config,tag);
936 /* Retrieves a value from the config file. If there is more than one value of the specified
937 * key and section (e.g. for opers etc) then the index value specifies which to retreive, e.g.
939 * ConfValue("oper","name",2,result);
942 int ServerConfig::ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
945 char buffer[65535], c_tag[MAXBUF], c, lastc;
946 int in_token, in_quotes, tptr, idx = 0;
949 const char* buf = config->str().c_str();
951 long len = config->str().length();
963 // FIX: Treat tabs as spaces
966 if ((c == '<') && (!in_quotes))
977 // FIX: Tab can follow a tagname as well as space.
978 } while ((c != ' ') && (c != 9));
982 in_quotes = (!in_quotes);
984 if ((c == '>') && (!in_quotes))
989 if (!strcmp(c_tag,tag))
991 if ((buffer) && (c_tag) && (var))
993 key = strstr(buffer,var);
996 /* value not found in tag */
1014 for (unsigned j = 0; j < strlen(key); j++)
1021 strlcpy(result,key,MAXBUF);
1027 if (!strcmp(c_tag,tag))
1029 /* correct tag, but wrong index */
1039 if ((in_token) && (c != '\n') && (c != '\r'))
1046 *result = 0; // value or its tag not found at all
1052 int ServerConfig::ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
1054 ReadConf(config, tag, var, index, result);
1060 // This will bind a socket to a port. It works for UDP/TCP
1061 int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
1063 memset((char *)&server,0,sizeof(server));
1064 struct in_addr addy;
1065 inet_aton(addr,&addy);
1066 server.sin_family = AF_INET;
1067 if (!strcmp(addr,""))
1069 server.sin_addr.s_addr = htonl(INADDR_ANY);
1073 server.sin_addr = addy;
1075 server.sin_port = htons(port);
1076 if (bind(sockfd,(struct sockaddr*)&server,sizeof(server))<0)
1082 listen(sockfd, Config->MaxConn);
1088 // Open a TCP Socket
1089 int OpenTCPSocket (void)
1093 struct linger linger = { 0 };
1095 if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
1099 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
1100 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
1102 linger.l_linger = 1;
1103 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));
1110 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
1111 sockaddr_in client,server;
1112 int clientportcount = 0;
1113 int BoundPortCount = 0;
1114 for (int count = 0; count < Config->ConfValueEnum("bind",&Config->config_f); count++)
1116 Config->ConfValue("bind","port",count,configToken,&Config->config_f);
1117 Config->ConfValue("bind","address",count,Addr,&Config->config_f);
1118 Config->ConfValue("bind","type",count,Type,&Config->config_f);
1119 if (strcmp(Type,"servers"))
1121 // modules handle server bind types now,
1122 // its not a typo in the strcmp.
1123 Config->ports[clientportcount] = atoi(configToken);
1124 strlcpy(Config->addrs[clientportcount],Addr,256);
1126 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
1129 int PortCount = clientportcount;
1131 for (int count = 0; count < PortCount; count++)
1133 if ((openSockfd[BoundPortCount] = OpenTCPSocket()) == ERROR)
1135 log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[BoundPortCount]);
1138 if (BindSocket(openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]) == ERROR)
1140 log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)Config->ports[count]);
1142 else /* well we at least bound to one socket so we'll continue */
1148 /* if we didn't bind to anything then abort */
1149 if (!BoundPortCount)
1151 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
1152 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)PortCount);
1156 return BoundPortCount;