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 *TempDir = *ServerName = *Network = *ServerDesc = *AdminName = '\0';
48 *HideWhoisServer = *AdminEmail = *AdminNick = *diepass = *restartpass = '\0';
49 *CustomVersion = *motd = *rules = *PrefixQuit = *DieValue = *DNSServer = '\0';
50 *OperOnlyStats = *ModPath = *MyExecutable = *DisabledCommands = *PID = '\0';
58 NetBufferSize = 10240;
59 SoftLimit = MAXCLIENTS;
67 void ServerConfig::ClearStack()
69 include_stack.clear();
72 Module* ServerConfig::GetIOHook(int port)
74 std::map<int,Module*>::iterator x = IOHookModule.find(port);
75 return (x != IOHookModule.end() ? x->second : NULL);
78 bool ServerConfig::AddIOHook(int port, Module* iomod)
82 IOHookModule[port] = iomod;
88 bool ServerConfig::DelIOHook(int port)
90 std::map<int,Module*>::iterator x = IOHookModule.find(port);
91 if (x != IOHookModule.end())
93 IOHookModule.erase(x);
99 bool ServerConfig::CheckOnce(char* tag, bool bail, userrec* user)
101 int count = ConfValueEnum(tag,&Config->config_f);
106 printf("There were errors in your configuration:\nYou have more than one <%s> tag, this is not permitted.\n",tag);
113 WriteServ(user->fd,"There were errors in your configuration:");
114 WriteServ(user->fd,"You have more than one <%s> tag, this is not permitted.\n",tag);
118 WriteOpers("There were errors in the configuration file:");
119 WriteOpers("You have more than one <%s> tag, this is not permitted.\n",tag);
128 printf("There were errors in your configuration:\nYou have not defined a <%s> tag, this is required.\n",tag);
135 WriteServ(user->fd,"There were errors in your configuration:");
136 WriteServ(user->fd,"You have not defined a <%s> tag, this is required.",tag);
140 WriteOpers("There were errors in the configuration file:");
141 WriteOpers("You have not defined a <%s> tag, this is required.",tag);
149 void ServerConfig::Read(bool bail, userrec* user)
151 char dbg[MAXBUF],pauseval[MAXBUF],Value[MAXBUF],timeout[MAXBUF],NB[MAXBUF],flood[MAXBUF],MW[MAXBUF],MCON[MAXBUF],MT[MAXBUF];
152 char AH[MAXBUF],AP[MAXBUF],AF[MAXBUF],DNT[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF],SLIMT[MAXBUF];
153 char localmax[MAXBUF],globalmax[MAXBUF],HS[MAXBUF];
155 std::stringstream errstr;
156 include_stack.clear();
158 if (!LoadConf(CONFIG_FILE,&Config->config_f,&errstr))
161 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
164 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
172 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
173 while (!errstr.eof())
175 errstr.getline(dataline,1024);
176 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
181 WriteOpers("There were errors in the configuration file:");
182 while (!errstr.eof())
184 errstr.getline(dataline,1024);
185 WriteOpers(dataline);
192 /* Check we dont have more than one of singular tags
194 if (!CheckOnce("server",bail,user) || !CheckOnce("admin",bail,user) || !CheckOnce("files",bail,user)
195 || !CheckOnce("power",bail,user) || !CheckOnce("options",bail,user)
196 || !CheckOnce("dns",bail,user) || !CheckOnce("pid",bail,user))
201 ConfValue("server","name",0,Config->ServerName,&Config->config_f);
202 ConfValue("server","description",0,Config->ServerDesc,&Config->config_f);
203 ConfValue("server","network",0,Config->Network,&Config->config_f);
204 ConfValue("admin","name",0,Config->AdminName,&Config->config_f);
205 ConfValue("admin","email",0,Config->AdminEmail,&Config->config_f);
206 ConfValue("admin","nick",0,Config->AdminNick,&Config->config_f);
207 ConfValue("files","motd",0,Config->motd,&Config->config_f);
208 ConfValue("files","rules",0,Config->rules,&Config->config_f);
209 ConfValue("power","diepass",0,Config->diepass,&Config->config_f);
210 ConfValue("power","pause",0,pauseval,&Config->config_f);
211 ConfValue("power","restartpass",0,Config->restartpass,&Config->config_f);
212 ConfValue("options","prefixquit",0,Config->PrefixQuit,&Config->config_f);
213 ConfValue("die","value",0,Config->DieValue,&Config->config_f);
214 ConfValue("options","loglevel",0,dbg,&Config->config_f);
215 ConfValue("options","netbuffersize",0,NB,&Config->config_f);
216 ConfValue("options","maxwho",0,MW,&Config->config_f);
217 ConfValue("options","allowhalfop",0,AH,&Config->config_f);
218 ConfValue("options","allowprotect",0,AP,&Config->config_f);
219 ConfValue("options","allowfounder",0,AF,&Config->config_f);
220 ConfValue("dns","server",0,Config->DNSServer,&Config->config_f);
221 ConfValue("dns","timeout",0,DNT,&Config->config_f);
222 ConfValue("options","moduledir",0,Config->ModPath,&Config->config_f);
223 ConfValue("disabled","commands",0,Config->DisabledCommands,&Config->config_f);
224 ConfValue("options","somaxconn",0,MCON,&Config->config_f);
225 ConfValue("options","softlimit",0,SLIMT,&Config->config_f);
226 ConfValue("options","operonlystats",0,Config->OperOnlyStats,&Config->config_f);
227 ConfValue("options","customversion",0,Config->CustomVersion,&Config->config_f);
228 ConfValue("options","maxtargets",0,MT,&Config->config_f);
229 ConfValue("options","hidesplits",0,HS,&Config->config_f);
230 ConfValue("options","hidewhois",0,Config->HideWhoisServer,&Config->config_f);
231 ConfValue("options","tempdir",0,Config->TempDir,&Config->config_f);
233 if (!*Config->TempDir)
234 strlcpy(Config->TempDir,"/tmp",1024);
235 Config->HideSplits = ((*HS == 'y') || (*HS == 'Y') || (*HS == '1') || (*HS == 't') || (*HS == 'T'));
236 Config->SoftLimit = atoi(SLIMT);
238 Config->MaxTargets = atoi(MT);
239 if ((Config->MaxTargets < 0) || (Config->MaxTargets > 31))
241 log(DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
242 Config->MaxTargets = 20;
244 if ((Config->SoftLimit < 1) || (Config->SoftLimit > MAXCLIENTS))
246 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
247 Config->SoftLimit = MAXCLIENTS;
249 Config->MaxConn = atoi(MCON);
250 if (Config->MaxConn > SOMAXCONN)
251 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
252 Config->NetBufferSize = atoi(NB);
253 Config->MaxWhoResults = atoi(MW);
254 Config->dns_timeout = atoi(DNT);
255 if (!Config->dns_timeout)
256 Config->dns_timeout = 5;
257 if (!Config->MaxConn)
258 Config->MaxConn = SOMAXCONN;
259 if (!*Config->DNSServer)
260 strlcpy(Config->DNSServer,"127.0.0.1",MAXBUF);
261 if (!*Config->ModPath)
262 strlcpy(Config->ModPath,MOD_PATH,MAXBUF);
263 Config->AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
264 if ((!Config->NetBufferSize) || (Config->NetBufferSize > 65535) || (Config->NetBufferSize < 1024))
266 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
267 Config->NetBufferSize = 10240;
269 if ((!Config->MaxWhoResults) || (Config->MaxWhoResults > 65535) || (Config->MaxWhoResults < 1))
271 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
272 Config->MaxWhoResults = 128;
274 Config->LogLevel = DEFAULT;
275 if (!strcmp(dbg,"debug"))
277 Config->LogLevel = DEBUG;
278 Config->debugging = 1;
280 if (!strcmp(dbg,"verbose"))
281 Config->LogLevel = VERBOSE;
282 if (!strcmp(dbg,"default"))
283 Config->LogLevel = DEFAULT;
284 if (!strcmp(dbg,"sparse"))
285 Config->LogLevel = SPARSE;
286 if (!strcmp(dbg,"none"))
287 Config->LogLevel = NONE;
289 readfile(Config->MOTD,Config->motd);
290 log(DEFAULT,"Reading message of the day...");
291 readfile(Config->RULES,Config->rules);
292 log(DEFAULT,"Reading connect classes...");
294 for (int i = 0; i < ConfValueEnum("connect",&Config->config_f); i++)
297 ConfValue("connect","allow",i,Value,&Config->config_f);
298 ConfValue("connect","timeout",i,timeout,&Config->config_f);
299 ConfValue("connect","flood",i,flood,&Config->config_f);
300 ConfValue("connect","pingfreq",i,pfreq,&Config->config_f);
301 ConfValue("connect","threshold",i,thold,&Config->config_f);
302 ConfValue("connect","sendq",i,sqmax,&Config->config_f);
303 ConfValue("connect","recvq",i,rqmax,&Config->config_f);
304 ConfValue("connect","localmax",i,localmax,&Config->config_f);
305 ConfValue("connect","globalmax",i,globalmax,&Config->config_f);
310 strlcpy(Value,"",MAXBUF);
311 ConfValue("connect","password",i,Value,&Config->config_f);
313 c.registration_timeout = 90; // default is 2 minutes
315 c.flood = atoi(flood);
317 c.sendqmax = 262144; // 256k
318 c.recvqmax = 4096; // 4k
321 if (atoi(localmax)>0)
323 c.maxlocal = atoi(localmax);
325 if (atoi(globalmax)>0)
327 c.maxglobal = atoi(globalmax);
331 c.threshold = atoi(thold);
335 c.sendqmax = atoi(sqmax);
339 c.recvqmax = atoi(rqmax);
343 c.registration_timeout = atoi(timeout);
347 c.pingtime = atoi(pfreq);
349 Classes.push_back(c);
353 ConfValue("connect","deny",i,Value,&Config->config_f);
356 Classes.push_back(c);
357 log(DEBUG,"Read connect class type DENY, host=%s",c.host.c_str());
361 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
362 read_xline_defaults();
363 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
364 apply_lines(APPLY_ALL);
366 ConfValue("pid","file",0,Config->PID,&Config->config_f);
367 // write once here, to try it out and make sure its ok
368 WritePID(Config->PID);
370 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
373 log(DEFAULT,"Adding and removing modules due to rehash...");
375 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
377 // store the old module names
378 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
380 old_module_names.push_back(*t);
383 // get the new module names
384 for (int count2 = 0; count2 < ConfValueEnum("module",&Config->config_f); count2++)
386 ConfValue("module","name",count2,Value,&Config->config_f);
387 new_module_names.push_back(Value);
390 // now create a list of new modules that are due to be loaded
391 // and a seperate list of modules which are due to be unloaded
392 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
395 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
401 added_modules.push_back(*_new);
403 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
406 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
412 removed_modules.push_back(*oldm);
414 // now we have added_modules, a vector of modules to be loaded, and removed_modules, a vector of modules
416 int rem = 0, add = 0;
417 if (!removed_modules.empty())
418 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
420 if (ServerInstance->UnloadModule(removing->c_str()))
422 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
424 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
430 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
433 if (!added_modules.empty())
434 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
436 if (ServerInstance->LoadModule(adding->c_str()))
438 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
440 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
446 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
449 log(DEFAULT,"Successfully unloaded %lu of %lu modules and loaded %lu of %lu modules.",(unsigned long)rem,(unsigned long)removed_modules.size(),
450 (unsigned long)add,(unsigned long)added_modules.size());
455 void Exit (int status)
457 if (Config->log_file)
458 fclose(Config->log_file);
459 send_error("Server shutdown.");
463 void Killed(int status)
465 if (Config->log_file)
466 fclose(Config->log_file);
467 send_error("Server terminated.");
471 char* CleanFilename(char* name)
473 char* p = name + strlen(name);
474 while ((p != name) && (*p != '/')) p--;
475 return (p != name ? ++p : p);
479 void Rehash(int status)
481 WriteOpers("Rehashing config file %s due to SIGHUP",CleanFilename(CONFIG_FILE));
482 fclose(Config->log_file);
484 Config->Read(false,NULL);
485 FOREACH_MOD(I_OnRehash,OnRehash(""));
492 printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
493 printf("(C) ChatSpike Development team.\033[0m\n\n");
494 printf("Developers:\033[1;32m Brain, FrostyCoolSlug\033[0m\n");
495 printf("Documentation:\033[1;32m FrostyCoolSlug, w00t\033[0m\n");
496 printf("Testers:\033[1;32m typobox43, piggles, Lord_Zathras, CC\033[0m\n");
497 printf("Name concept:\033[1;32m Lord_Zathras\033[0m\n\n");
500 void WritePID(std::string filename)
502 ofstream outfile(filename.c_str());
503 if (outfile.is_open())
510 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
511 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
518 signal (SIGALRM, SIG_IGN);
519 signal (SIGHUP, Rehash);
520 signal (SIGPIPE, SIG_IGN);
521 signal (SIGTERM, Exit);
522 signal (SIGSEGV, Error);
526 int DaemonSeed (void)
529 if ((childpid = fork ()) < 0)
531 else if (childpid > 0)
535 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
537 setpriority(PRIO_PROCESS,(int)getpid(),15);
539 if (Config->unlimitcore)
542 if (getrlimit(RLIMIT_CORE, &rl) == -1)
544 log(DEFAULT,"Failed to getrlimit()!");
549 rl.rlim_cur = rl.rlim_max;
550 if (setrlimit(RLIMIT_CORE, &rl) == -1)
551 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
559 /* Make Sure Modules Are Avaliable!
560 * (BugFix By Craig.. See? I do work! :p)
561 * Modified by brain, requires const char*
562 * to work with other API functions
565 bool FileExists (const char* file)
568 if ((input = fopen (file, "r")) == NULL)
579 /* ConfProcess does the following things to a config line in the following order:
581 * Processes the line for syntax errors as shown below
582 * (1) Line void of quotes or equals (a malformed, illegal tag format)
583 * (2) Odd number of quotes on the line indicating a missing quote
584 * (3) number of equals signs not equal to number of quotes / 2 (missing an equals sign)
585 * (4) Spaces between the opening bracket (<) and the keyword
586 * (5) Spaces between a keyword and an equals sign
587 * (6) Spaces between an equals sign and a quote
588 * Removes trailing spaces
589 * Removes leading spaces
590 * Converts tabs to spaces
591 * Turns multiple spaces that are outside of quotes into single spaces
594 std::string ServerConfig::ConfProcess(char* buffer, long linenumber, std::stringstream* errorstream, bool &error, std::string filename)
596 long number_of_quotes = 0;
597 long number_of_equals = 0;
598 bool has_open_bracket = false;
599 bool in_quotes = false;
605 // firstly clean up the line by stripping spaces from the start and end and converting tabs to spaces
606 for (char* d = buffer; *d; d++)
609 while (*buffer == ' ') buffer++;
610 while ((buffer[strlen(buffer)-1] == ' ') && (*buffer)) buffer[strlen(buffer)-1] = '\0';
612 // empty lines are syntactically valid, as are comments
613 if (!(*buffer) || buffer[0] == '#')
616 for (unsigned int c = 0; c < strlen(buffer); c++)
618 // convert all spaces that are OUTSIDE quotes into hardspace (0xA0) as this will make them easier to
619 // search and replace later :)
620 if ((!in_quotes) && (buffer[c] == ' '))
622 if ((buffer[c] == '<') && (!in_quotes))
624 has_open_bracket = true;
625 if (strlen(buffer) == 1)
627 *errorstream << "Tag without identifier at " << filename << ":" << linenumber << endl;
631 else if ((tolower(buffer[c+1]) < 'a') || (tolower(buffer[c+1]) > 'z'))
633 *errorstream << "Invalid characters in identifier at " << filename << ":" << linenumber << endl;
638 if (buffer[c] == '"')
641 in_quotes = (!in_quotes);
643 if ((buffer[c] == '=') && (!in_quotes))
646 if (strlen(buffer) == c)
648 *errorstream << "Variable without a value at " << filename << ":" << linenumber << endl;
652 else if (buffer[c+1] != '"')
654 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
660 *errorstream << "Value without a variable (line starts with '=') at " << filename << ":" << linenumber << endl;
664 else if (buffer[c-1] == '\xA0')
666 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
672 // no quotes, and no equals. something freaky.
673 if ((!number_of_quotes) || (!number_of_equals) && (strlen(buffer)>2) && (buffer[0]=='<'))
675 *errorstream << "Malformed tag at " << filename << ":" << linenumber << endl;
679 // odd number of quotes. thats just wrong.
680 if ((number_of_quotes % 2) != 0)
682 *errorstream << "Missing \" at " << filename << ":" << linenumber << endl;
686 if (number_of_equals < (number_of_quotes/2))
688 *errorstream << "Missing '=' at " << filename << ":" << linenumber << endl;
690 if (number_of_equals > (number_of_quotes/2))
692 *errorstream << "Too many '=' at " << filename << ":" << linenumber << endl;
695 std::string parsedata = buffer;
696 // turn multispace into single space
697 while (parsedata.find("\xA0\xA0") != std::string::npos)
699 parsedata.erase(parsedata.find("\xA0\xA0"),1);
702 // turn our hardspace back into softspace
703 for (unsigned int d = 0; d < parsedata.length(); d++)
705 if (parsedata[d] == '\xA0')
709 // and we're done, the line is fine!
713 int ServerConfig::fgets_safe(char* buffer, size_t maxsize, FILE* &file)
716 unsigned int bufptr = 0;
717 while ((!feof(file)) && (c_read != '\n') && (c_read != '\r') && (bufptr < maxsize))
719 c_read = fgetc(file);
720 if ((c_read != '\n') && (c_read != '\r'))
721 buffer[bufptr++] = c_read;
723 buffer[bufptr] = '\0';
727 bool ServerConfig::LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream)
730 errorstream->str("");
732 // first, check that the file exists before we try to do anything with it
733 if (!FileExists(filename))
735 *errorstream << "File " << filename << " not found." << endl;
738 // Fix the chmod of the file to restrict it to the current user and group
739 chmod(filename,0600);
740 for (unsigned int t = 0; t < include_stack.size(); t++)
742 if (std::string(filename) == include_stack[t])
744 *errorstream << "File " << filename << " is included recursively (looped inclusion)." << endl;
748 include_stack.push_back(filename);
750 FILE* conf = fopen(filename,"r");
756 if (fgets_safe(buffer, MAXBUF, conf))
758 if ((!feof(conf)) && (buffer) && (strlen(buffer)))
760 if ((buffer[0] != '#') && (buffer[0] != '\r') && (buffer[0] != '\n'))
762 if (!strncmp(buffer,"<include file=\"",15))
765 char confpath[10240],newconf[10240];
766 // include file directive
767 buf += 15; // advance to filename
768 for (unsigned int j = 0; j < strlen(buf); j++)
778 log(DEBUG,"Opening included file '%s'",buf);
781 strlcpy(confpath,CONFIG_FILE,10240);
782 if (strstr(confpath,"/inspircd.conf"))
784 // leaves us with just the path
785 *(strstr(confpath,"/inspircd.conf")) = '\0';
787 snprintf(newconf,10240,"%s/%s",confpath,buf);
789 else strlcpy(newconf,buf,10240);
790 std::stringstream merge(stringstream::in | stringstream::out);
791 // recursively call LoadConf and get the new data, use the same errorstream
792 if (LoadConf(newconf, &merge, errorstream))
794 // append to the end of the file
795 std::string newstuff = merge.str();
800 // the error propogates up to its parent recursively
801 // causing the config reader to bail at the top level.
809 std::string data = this->ConfProcess(buffer,linenumber++,errorstream,error,filename);
827 /* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */
829 int ServerConfig::EnumConf(std::stringstream *config, const char* tag)
832 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
833 int in_token, in_quotes, tptr, idx = 0;
835 const char* buf = config->str().c_str();
837 long len = strlen(buf);
847 if ((c == '#') && (lastc == '\n'))
849 while ((c != '\n') && (bptr<len))
855 if ((c == '<') && (!in_quotes))
870 in_quotes = (!in_quotes);
872 if ((c == '>') && (!in_quotes))
875 if (!strcmp(c_tag,tag))
877 /* correct tag, but wrong index */
887 if ((in_token) && (c != '\n') && (c != '\r'))
897 /* Counts the number of values within a certain tag */
899 int ServerConfig::EnumValues(std::stringstream *config, const char* tag, int index)
902 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
903 int in_token, in_quotes, tptr, idx = 0;
905 bool correct_tag = false;
908 const char* buf = config->str().c_str();
910 long len = strlen(buf);
920 if ((c == '#') && (lastc == '\n'))
922 while ((c != '\n') && (bptr<len))
928 if ((c == '<') && (!in_quotes))
939 if ((!strcmp(c_tag,tag)) && (idx == index))
948 in_quotes = (!in_quotes);
951 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
955 if ((c == '>') && (!in_quotes))
960 if (!strcmp(c_tag,tag))
962 /* correct tag, but wrong index */
972 if ((in_token) && (c != '\n') && (c != '\r'))
984 int ServerConfig::ConfValueEnum(char* tag, std::stringstream* config)
986 return EnumConf(config,tag);
991 /* Retrieves a value from the config file. If there is more than one value of the specified
992 * key and section (e.g. for opers etc) then the index value specifies which to retreive, e.g.
994 * ConfValue("oper","name",2,result);
997 int ServerConfig::ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
1000 char buffer[65535], c_tag[MAXBUF], c, lastc;
1001 int in_token, in_quotes, tptr, idx = 0;
1004 const char* buf = config->str().c_str();
1006 long len = config->str().length();
1018 // FIX: Treat tabs as spaces
1021 if ((c == '<') && (!in_quotes))
1032 // FIX: Tab can follow a tagname as well as space.
1033 } while ((c != ' ') && (c != 9));
1037 in_quotes = (!in_quotes);
1039 if ((c == '>') && (!in_quotes))
1044 if (!strcmp(c_tag,tag))
1046 if ((buffer) && (c_tag) && (var))
1048 key = strstr(buffer,var);
1051 /* value not found in tag */
1069 for (unsigned j = 0; j < strlen(key); j++)
1076 strlcpy(result,key,MAXBUF);
1082 if (!strcmp(c_tag,tag))
1084 /* correct tag, but wrong index */
1094 if ((in_token) && (c != '\n') && (c != '\r'))
1101 *result = 0; // value or its tag not found at all
1107 int ServerConfig::ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
1109 ReadConf(config, tag, var, index, result);
1115 // This will bind a socket to a port. It works for UDP/TCP
1116 int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
1118 memset((char *)&server,0,sizeof(server));
1119 struct in_addr addy;
1120 inet_aton(addr,&addy);
1121 server.sin_family = AF_INET;
1122 if (!strcmp(addr,""))
1124 server.sin_addr.s_addr = htonl(INADDR_ANY);
1128 server.sin_addr = addy;
1130 server.sin_port = htons(port);
1131 if (bind(sockfd,(struct sockaddr*)&server,sizeof(server))<0)
1137 listen(sockfd, Config->MaxConn);
1143 // Open a TCP Socket
1144 int OpenTCPSocket (void)
1148 struct linger linger = { 0 };
1150 if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
1154 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
1155 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
1157 linger.l_linger = 1;
1158 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));
1165 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
1166 sockaddr_in client,server;
1167 int clientportcount = 0;
1168 int BoundPortCount = 0;
1169 for (int count = 0; count < Config->ConfValueEnum("bind",&Config->config_f); count++)
1171 Config->ConfValue("bind","port",count,configToken,&Config->config_f);
1172 Config->ConfValue("bind","address",count,Addr,&Config->config_f);
1173 Config->ConfValue("bind","type",count,Type,&Config->config_f);
1174 if ((!*Type) || (!strcmp(Type,"clients")))
1176 // modules handle server bind types now,
1177 // its not a typo in the strcmp.
1178 Config->ports[clientportcount] = atoi(configToken);
1179 strlcpy(Config->addrs[clientportcount],Addr,256);
1181 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
1184 int PortCount = clientportcount;
1186 for (int count = 0; count < PortCount; count++)
1188 if ((openSockfd[BoundPortCount] = OpenTCPSocket()) == ERROR)
1190 log(DEBUG,"InspIRCd: startup: bad fd %lu",(unsigned long)openSockfd[BoundPortCount]);
1193 if (BindSocket(openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]) == ERROR)
1195 log(DEFAULT,"InspIRCd: startup: failed to bind port %lu",(unsigned long)Config->ports[count]);
1197 else /* well we at least bound to one socket so we'll continue */
1203 /* if we didn't bind to anything then abort */
1204 if (!BoundPortCount)
1206 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
1207 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)PortCount);
1211 return BoundPortCount;