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';
52 nofork = HideBans = HideSplits = unlimitcore = false;
54 dns_timeout = DieDelay = 5;
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;
85 ModuleException err("Port already hooked by another module");
91 bool ServerConfig::DelIOHook(int port)
93 std::map<int,Module*>::iterator x = IOHookModule.find(port);
94 if (x != IOHookModule.end())
96 IOHookModule.erase(x);
102 bool ServerConfig::CheckOnce(char* tag, bool bail, userrec* user)
104 int count = ConfValueEnum(tag,&Config->config_f);
109 printf("There were errors in your configuration:\nYou have more than one <%s> tag, this is not permitted.\n",tag);
116 WriteServ(user->fd,"There were errors in your configuration:");
117 WriteServ(user->fd,"You have more than one <%s> tag, this is not permitted.\n",tag);
121 WriteOpers("There were errors in the configuration file:");
122 WriteOpers("You have more than one <%s> tag, this is not permitted.\n",tag);
131 printf("There were errors in your configuration:\nYou have not defined a <%s> tag, this is required.\n",tag);
138 WriteServ(user->fd,"There were errors in your configuration:");
139 WriteServ(user->fd,"You have not defined a <%s> tag, this is required.",tag);
143 WriteOpers("There were errors in the configuration file:");
144 WriteOpers("You have not defined a <%s> tag, this is required.",tag);
152 typedef bool (*Validator)(const char*, const char*, void*);
154 enum ConfigDataType { DT_NOTHING, DT_INTEGER, DT_CHARPTR, DT_BOOLEAN };
156 struct InitialConfig {
161 Validator validation_function;
164 bool NoValidation(const char* tag, const char* value, void* data)
166 log(DEBUG,"No validation for <%s:%s>",tag,value);
170 void ServerConfig::Read(bool bail, userrec* user)
174 static InitialConfig Values[] = {
175 {"options", "softlimit", &this->SoftLimit, DT_INTEGER, NoValidation},
176 {"options", "somaxconn", &this->MaxConn, DT_INTEGER, NoValidation},
177 {"server", "name", &this->ServerName, DT_CHARPTR, NoValidation},
178 {"server", "description", &this->ServerDesc, DT_CHARPTR, NoValidation},
179 {"server", "network", &this->Network, DT_CHARPTR, NoValidation},
180 {"admin", "name", &this->AdminName, DT_CHARPTR, NoValidation},
181 {"admin", "email", &this->AdminEmail, DT_CHARPTR, NoValidation},
182 {"admin", "nick", &this->AdminNick, DT_CHARPTR, NoValidation},
183 {"files", "motd", &this->motd, DT_CHARPTR, NoValidation},
184 {"files", "rules", &this->rules, DT_CHARPTR, NoValidation},
185 {"power", "diepass", &this->diepass, DT_CHARPTR, NoValidation},
186 {"power", "pauseval", &this->DieDelay, DT_INTEGER, NoValidation},
187 {"power", "restartpass", &this->restartpass, DT_CHARPTR, NoValidation},
188 {"options", "prefixquit", &this->PrefixQuit, DT_CHARPTR, NoValidation},
189 {"die", "value", &this->DieValue, DT_CHARPTR, NoValidation},
190 {"options", "loglevel", &debug, DT_CHARPTR, NoValidation},
191 {"options", "netbuffersize", &this->NetBufferSize, DT_INTEGER, NoValidation},
192 {"options", "maxwho", &this->MaxWhoResults, DT_INTEGER, NoValidation},
193 {"options", "allowhalfop", &this->AllowHalfop, DT_BOOLEAN, NoValidation},
194 {"dns", "server", &this->DNSServer, DT_CHARPTR, NoValidation},
195 {"dns", "timeout", &this->dns_timeout, DT_INTEGER, NoValidation},
196 {"options", "moduledir", &this->ModPath, DT_CHARPTR, NoValidation},
197 {"disabled", "commands", &this->DisabledCommands, DT_CHARPTR, NoValidation},
198 {"options", "operonlystats", &this->OperOnlyStats, DT_CHARPTR, NoValidation},
199 {"options", "customversion", &this->CustomVersion, DT_CHARPTR, NoValidation},
200 {"options", "hidesplits", &this->HideSplits, DT_BOOLEAN, NoValidation},
201 {"options", "hidebans", &this->HideBans, DT_BOOLEAN, NoValidation},
202 {"options", "hidewhois", &this->HideWhoisServer, DT_CHARPTR, NoValidation},
203 {"options", "tempdir", &this->TempDir, DT_CHARPTR, NoValidation},
207 /* XXX - this needs a rework someday, BAD. */
208 char timeout[MAXBUF],flood[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF],SLIMT[MAXBUF];
209 char localmax[MAXBUF],globalmax[MAXBUF],ServName[MAXBUF];
212 std::stringstream errstr;
214 include_stack.clear();
216 if (!LoadConf(CONFIG_FILE,&Config->config_f,&errstr))
219 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
223 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
232 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
233 while (!errstr.eof())
235 errstr.getline(dataline,1024);
236 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
241 WriteOpers("There were errors in the configuration file:");
242 while (!errstr.eof())
244 errstr.getline(dataline,1024);
245 WriteOpers(dataline);
253 /* Check we dont have more than one of singular tags
255 if (!CheckOnce("server",bail,user) || !CheckOnce("admin",bail,user) || !CheckOnce("files",bail,user)
256 || !CheckOnce("power",bail,user) || !CheckOnce("options",bail,user) || !CheckOnce("pid",bail,user))
262 for (int Index = 0; Values[Index].tag; Index++)
264 int* val_i = (int*) Values[Index].val;
265 char* val_c = (char*) Values[Index].val;
267 switch (Values[Index].datatype)
270 ConfValue(Values[Index].tag, Values[Index].value, 0, val_c, &this->config_f);
274 convert = new char[MAXBUF];
275 ConfValue(Values[Index].tag, Values[Index].value, 0, convert, &this->config_f);
276 *val_i = atoi(convert);
281 convert = new char[MAXBUF];
282 ConfValue(Values[Index].tag, Values[Index].value, 0, convert, &this->config_f);
283 *val_i = ((*convert == tolower('y')) || (*convert == tolower('t')) || (*convert == '1'));
291 Values[Index].validation_function(Values[Index].tag, Values[Index].value, Values[Index].val);
294 strlower(this->ServerName);
296 if (!*Config->TempDir)
297 strlcpy(Config->TempDir,"/tmp",1024);
299 if ((Config->MaxTargets < 0) || (Config->MaxTargets > 31))
301 log(DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
302 Config->MaxTargets = 20;
305 if ((Config->SoftLimit < 1) || (Config->SoftLimit > MAXCLIENTS))
307 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
308 Config->SoftLimit = MAXCLIENTS;
311 Config->MaxConn = atoi(MCON);
313 if (Config->MaxConn > SOMAXCONN)
314 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
316 Config->NetBufferSize = atoi(NB);
317 Config->MaxWhoResults = atoi(MW);
318 Config->dns_timeout = atoi(DNT);
320 if (!strchr(Config->ServerName,'.'))
322 log(DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s%c'",Config->ServerName,Config->ServerName,'.');
323 charlcat(Config->ServerName,'.',MAXBUF);
326 if (!Config->dns_timeout)
327 Config->dns_timeout = 5;
329 if (!Config->MaxConn)
330 Config->MaxConn = SOMAXCONN;
332 if (!*Config->DNSServer)
334 // attempt to look up their nameserver from /etc/resolv.conf
335 log(DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
336 ifstream resolv("/etc/resolv.conf");
337 std::string nameserver;
338 bool found_server = false;
340 if (resolv.is_open())
342 while (resolv >> nameserver)
344 if ((nameserver == "nameserver") && (!found_server))
346 resolv >> nameserver;
347 strlcpy(Config->DNSServer,nameserver.c_str(),MAXBUF);
349 log(DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
355 log(DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
356 strlcpy(Config->DNSServer,"127.0.0.1",MAXBUF);
361 log(DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
362 strlcpy(Config->DNSServer,"127.0.0.1",MAXBUF);
366 if (!*Config->ModPath)
367 strlcpy(Config->ModPath,MOD_PATH,MAXBUF);
369 Config->AllowHalfop = ((!strcasecmp(AH,"true")) || (!strcasecmp(AH,"1")) || (!strcasecmp(AH,"yes")));
371 if ((!Config->NetBufferSize) || (Config->NetBufferSize > 65535) || (Config->NetBufferSize < 1024))
373 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
374 Config->NetBufferSize = 10240;
377 if ((!Config->MaxWhoResults) || (Config->MaxWhoResults > 65535) || (Config->MaxWhoResults < 1))
379 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
380 Config->MaxWhoResults = 128;
383 Config->LogLevel = DEFAULT;
385 if (!strcmp(dbg,"debug"))
387 Config->LogLevel = DEBUG;
388 Config->debugging = 1;
390 else if (!strcmp(dbg,"verbose"))
391 Config->LogLevel = VERBOSE;
392 else if (!strcmp(dbg,"default"))
393 Config->LogLevel = DEFAULT;
394 else if (!strcmp(dbg,"sparse"))
395 Config->LogLevel = SPARSE;
396 else if (!strcmp(dbg,"none"))
397 Config->LogLevel = NONE;
399 readfile(Config->MOTD,Config->motd);
400 log(DEFAULT,"Reading message of the day...");
401 readfile(Config->RULES,Config->rules);
402 log(DEFAULT,"Reading connect classes...");
405 for (int i = 0; i < ConfValueEnum("connect",&Config->config_f); i++)
408 ConfValue("connect","allow",i,Value,&Config->config_f);
409 ConfValue("connect","timeout",i,timeout,&Config->config_f);
410 ConfValue("connect","flood",i,flood,&Config->config_f);
411 ConfValue("connect","pingfreq",i,pfreq,&Config->config_f);
412 ConfValue("connect","threshold",i,thold,&Config->config_f);
413 ConfValue("connect","sendq",i,sqmax,&Config->config_f);
414 ConfValue("connect","recvq",i,rqmax,&Config->config_f);
415 ConfValue("connect","localmax",i,localmax,&Config->config_f);
416 ConfValue("connect","globalmax",i,globalmax,&Config->config_f);
422 strlcpy(Value,"",MAXBUF);
423 ConfValue("connect","password",i,Value,&Config->config_f);
425 c.registration_timeout = 90; // default is 2 minutes
427 c.flood = atoi(flood);
429 c.sendqmax = 262144; // 256k
430 c.recvqmax = 4096; // 4k
434 if (atoi(localmax)>0)
436 c.maxlocal = atoi(localmax);
439 if (atoi(globalmax)>0)
441 c.maxglobal = atoi(globalmax);
446 c.threshold = atoi(thold);
452 log(DEFAULT,"Warning: Connect allow line '%s' has no flood/threshold settings. Setting this tag to 999 lines in 1 second.",c.host.c_str());
457 c.sendqmax = atoi(sqmax);
461 c.recvqmax = atoi(rqmax);
465 c.registration_timeout = atoi(timeout);
469 c.pingtime = atoi(pfreq);
472 Classes.push_back(c);
476 ConfValue("connect","deny",i,Value,&Config->config_f);
479 Classes.push_back(c);
480 log(DEBUG,"Read connect class type DENY, host=%s",c.host.c_str());
484 Config->ulines.clear();
486 for (int i = 0; i < ConfValueEnum("uline",&Config->config_f); i++)
488 ConfValue("uline","server",i,ServName,&Config->config_f);
490 log(DEBUG,"Read ULINE '%s'",ServName);
491 Config->ulines.push_back(ServName);
496 char CM1[MAXBUF],CM2[MAXBUF];
498 for (int count = 0; count < Config->ConfValueEnum("banlist",&Config->config_f); count++)
500 Config->ConfValue("banlist","chan",count,CM1,&Config->config_f);
501 Config->ConfValue("banlist","limit",count,CM2,&Config->config_f);
502 maxbans[CM1] = atoi(CM2);
505 ReadClassesAndTypes();
506 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
507 read_xline_defaults();
508 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
509 apply_lines(APPLY_ALL);
511 ConfValue("pid","file",0,Config->PID,&Config->config_f);
512 // write once here, to try it out and make sure its ok
513 WritePID(Config->PID);
515 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
518 log(DEFAULT,"Adding and removing modules due to rehash...");
520 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
522 // store the old module names
523 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
525 old_module_names.push_back(*t);
528 // get the new module names
529 for (int count2 = 0; count2 < ConfValueEnum("module",&Config->config_f); count2++)
531 ConfValue("module","name",count2,Value,&Config->config_f);
532 new_module_names.push_back(Value);
535 // now create a list of new modules that are due to be loaded
536 // and a seperate list of modules which are due to be unloaded
537 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
541 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
548 added_modules.push_back(*_new);
551 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
554 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
561 removed_modules.push_back(*oldm);
565 * now we have added_modules, a vector of modules to be loaded,
566 * and removed_modules, a vector of modules
569 int rem = 0, add = 0;
570 if (!removed_modules.empty())
571 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
573 if (ServerInstance->UnloadModule(removing->c_str()))
575 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
578 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
585 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
589 if (!added_modules.empty())
590 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
592 if (ServerInstance->LoadModule(adding->c_str()))
594 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
597 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
604 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
608 log(DEFAULT,"Successfully unloaded %lu of %lu modules and loaded %lu of %lu modules.",(unsigned long)rem,(unsigned long)removed_modules.size(),(unsigned long)add,(unsigned long)added_modules.size());
613 void Exit (int status)
615 if (Config->log_file)
616 fclose(Config->log_file);
617 send_error("Server shutdown.");
621 void Killed(int status)
623 if (Config->log_file)
624 fclose(Config->log_file);
625 send_error("Server terminated.");
629 char* CleanFilename(char* name)
631 char* p = name + strlen(name);
632 while ((p != name) && (*p != '/')) p--;
633 return (p != name ? ++p : p);
637 void Rehash(int status)
639 WriteOpers("Rehashing config file %s due to SIGHUP",CleanFilename(CONFIG_FILE));
640 fclose(Config->log_file);
642 Config->Read(false,NULL);
643 FOREACH_MOD(I_OnRehash,OnRehash(""));
650 printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
651 printf("(C) ChatSpike Development team.\033[0m\n\n");
652 printf("Developers:\033[1;32m Brain, FrostyCoolSlug, w00t, Om\033[0m\n");
653 printf("Others:\033[1;32m See /INFO Output\033[0m\n");
654 printf("Name concept:\033[1;32m Lord_Zathras\033[0m\n\n");
657 void WritePID(std::string filename)
659 ofstream outfile(filename.c_str());
660 if (outfile.is_open())
667 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
668 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
675 signal (SIGALRM, SIG_IGN);
676 signal (SIGHUP, Rehash);
677 signal (SIGPIPE, SIG_IGN);
678 signal (SIGTERM, Exit);
679 signal (SIGSEGV, Error);
683 int DaemonSeed (void)
686 if ((childpid = fork ()) < 0)
688 else if (childpid > 0)
690 /* We wait a few seconds here, so that the shell prompt doesnt come back over the output */
696 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
698 if (Config->unlimitcore)
701 if (getrlimit(RLIMIT_CORE, &rl) == -1)
703 log(DEFAULT,"Failed to getrlimit()!");
708 rl.rlim_cur = rl.rlim_max;
709 if (setrlimit(RLIMIT_CORE, &rl) == -1)
710 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
718 /* Make Sure Modules Are Avaliable!
719 * (BugFix By Craig.. See? I do work! :p)
720 * Modified by brain, requires const char*
721 * to work with other API functions
724 bool FileExists (const char* file)
727 if ((input = fopen (file, "r")) == NULL)
738 /* ConfProcess does the following things to a config line in the following order:
740 * Processes the line for syntax errors as shown below
741 * (1) Line void of quotes or equals (a malformed, illegal tag format)
742 * (2) Odd number of quotes on the line indicating a missing quote
743 * (3) number of equals signs not equal to number of quotes / 2 (missing an equals sign)
744 * (4) Spaces between the opening bracket (<) and the keyword
745 * (5) Spaces between a keyword and an equals sign
746 * (6) Spaces between an equals sign and a quote
747 * Removes trailing spaces
748 * Removes leading spaces
749 * Converts tabs to spaces
750 * Turns multiple spaces that are outside of quotes into single spaces
753 std::string ServerConfig::ConfProcess(char* buffer, long linenumber, std::stringstream* errorstream, bool &error, std::string filename)
755 long number_of_quotes = 0;
756 long number_of_equals = 0;
757 bool has_open_bracket = false;
758 bool in_quotes = false;
764 // firstly clean up the line by stripping spaces from the start and end and converting tabs to spaces
765 for (char* d = buffer; *d; d++)
768 while (*buffer == ' ') buffer++;
769 while ((buffer[strlen(buffer)-1] == ' ') && (*buffer)) buffer[strlen(buffer)-1] = '\0';
771 // empty lines are syntactically valid, as are comments
772 if (!(*buffer) || buffer[0] == '#')
775 for (unsigned int c = 0; c < strlen(buffer); c++)
777 // convert all spaces that are OUTSIDE quotes into hardspace (0xA0) as this will make them easier to
778 // search and replace later :)
779 if ((!in_quotes) && (buffer[c] == ' '))
781 if ((buffer[c] == '<') && (!in_quotes))
783 has_open_bracket = true;
784 if (strlen(buffer) == 1)
786 *errorstream << "Tag without identifier at " << filename << ":" << linenumber << endl;
790 else if ((tolower(buffer[c+1]) < 'a') || (tolower(buffer[c+1]) > 'z'))
792 *errorstream << "Invalid characters in identifier at " << filename << ":" << linenumber << endl;
797 if (buffer[c] == '"')
800 in_quotes = (!in_quotes);
802 if ((buffer[c] == '=') && (!in_quotes))
805 if (strlen(buffer) == c)
807 *errorstream << "Variable without a value at " << filename << ":" << linenumber << endl;
811 else if (buffer[c+1] != '"')
813 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
819 *errorstream << "Value without a variable (line starts with '=') at " << filename << ":" << linenumber << endl;
823 else if (buffer[c-1] == '\xA0')
825 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
831 // no quotes, and no equals. something freaky.
832 if ((!number_of_quotes) || (!number_of_equals) && (strlen(buffer)>2) && (buffer[0]=='<'))
834 *errorstream << "Malformed tag at " << filename << ":" << linenumber << endl;
838 // odd number of quotes. thats just wrong.
839 if ((number_of_quotes % 2) != 0)
841 *errorstream << "Missing \" at " << filename << ":" << linenumber << endl;
845 if (number_of_equals < (number_of_quotes/2))
847 *errorstream << "Missing '=' at " << filename << ":" << linenumber << endl;
849 if (number_of_equals > (number_of_quotes/2))
851 *errorstream << "Too many '=' at " << filename << ":" << linenumber << endl;
854 std::string parsedata = buffer;
855 // turn multispace into single space
856 while (parsedata.find("\xA0\xA0") != std::string::npos)
858 parsedata.erase(parsedata.find("\xA0\xA0"),1);
861 // turn our hardspace back into softspace
862 for (unsigned int d = 0; d < parsedata.length(); d++)
864 if (parsedata[d] == '\xA0')
868 // and we're done, the line is fine!
872 int ServerConfig::fgets_safe(char* buffer, size_t maxsize, FILE* &file)
875 unsigned int bufptr = 0;
876 while ((!feof(file)) && (c_read != '\n') && (c_read != '\r') && (bufptr < maxsize))
878 c_read = fgetc(file);
879 if ((c_read != '\n') && (c_read != '\r'))
880 buffer[bufptr++] = c_read;
882 buffer[bufptr] = '\0';
886 bool ServerConfig::LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream)
889 errorstream->str("");
891 // first, check that the file exists before we try to do anything with it
892 if (!FileExists(filename))
894 *errorstream << "File " << filename << " not found." << endl;
897 // Fix the chmod of the file to restrict it to the current user and group
898 chmod(filename,0600);
899 for (unsigned int t = 0; t < include_stack.size(); t++)
901 if (std::string(filename) == include_stack[t])
903 *errorstream << "File " << filename << " is included recursively (looped inclusion)." << endl;
907 include_stack.push_back(filename);
909 FILE* conf = fopen(filename,"r");
915 if (fgets_safe(buffer, MAXBUF, conf))
917 if ((!feof(conf)) && (buffer) && (strlen(buffer)))
919 if ((buffer[0] != '#') && (buffer[0] != '\r') && (buffer[0] != '\n'))
921 if (!strncmp(buffer,"<include file=\"",15))
924 char confpath[10240],newconf[10240];
925 // include file directive
926 buf += 15; // advance to filename
927 for (unsigned int j = 0; j < strlen(buf); j++)
937 log(DEBUG,"Opening included file '%s'",buf);
940 strlcpy(confpath,CONFIG_FILE,10240);
941 if (strstr(confpath,"/inspircd.conf"))
943 // leaves us with just the path
944 *(strstr(confpath,"/inspircd.conf")) = '\0';
946 snprintf(newconf,10240,"%s/%s",confpath,buf);
948 else strlcpy(newconf,buf,10240);
949 std::stringstream merge(stringstream::in | stringstream::out);
950 // recursively call LoadConf and get the new data, use the same errorstream
951 if (LoadConf(newconf, &merge, errorstream))
953 // append to the end of the file
954 std::string newstuff = merge.str();
959 // the error propogates up to its parent recursively
960 // causing the config reader to bail at the top level.
968 std::string data = this->ConfProcess(buffer,linenumber++,errorstream,error,filename);
986 /* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */
988 int ServerConfig::EnumConf(std::stringstream *config, const char* tag)
991 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
992 int in_token, in_quotes, tptr, idx = 0;
994 std::string x = config->str();
995 const char* buf = x.c_str();
997 long len = config->str().length();
1007 if ((c == '#') && (lastc == '\n'))
1009 while ((c != '\n') && (bptr<len))
1015 if ((c == '<') && (!in_quotes))
1030 in_quotes = (!in_quotes);
1032 if ((c == '>') && (!in_quotes))
1035 if (!strcmp(c_tag,tag))
1037 /* correct tag, but wrong index */
1047 if ((in_token) && (c != '\n') && (c != '\r'))
1057 /* Counts the number of values within a certain tag */
1059 int ServerConfig::EnumValues(std::stringstream *config, const char* tag, int index)
1062 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
1063 int in_token, in_quotes, tptr, idx = 0;
1065 bool correct_tag = false;
1068 const char* buf = config->str().c_str();
1070 long len = strlen(buf);
1080 if ((c == '#') && (lastc == '\n'))
1082 while ((c != '\n') && (bptr<len))
1088 if ((c == '<') && (!in_quotes))
1099 if ((!strcmp(c_tag,tag)) && (idx == index))
1108 in_quotes = (!in_quotes);
1111 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
1115 if ((c == '>') && (!in_quotes))
1119 correct_tag = false;
1120 if (!strcmp(c_tag,tag))
1122 /* correct tag, but wrong index */
1132 if ((in_token) && (c != '\n') && (c != '\r'))
1144 int ServerConfig::ConfValueEnum(char* tag, std::stringstream* config)
1146 return EnumConf(config,tag);
1151 /* Retrieves a value from the config file. If there is more than one value of the specified
1152 * key and section (e.g. for opers etc) then the index value specifies which to retreive, e.g.
1154 * ConfValue("oper","name",2,result);
1157 int ServerConfig::ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
1160 char buffer[65535], c_tag[MAXBUF], c, lastc;
1161 int in_token, in_quotes, tptr, idx = 0;
1164 std::string x = config->str();
1165 const char* buf = x.c_str();
1167 long len = config->str().length();
1179 // FIX: Treat tabs as spaces
1182 if ((c == '<') && (!in_quotes))
1193 // FIX: Tab can follow a tagname as well as space.
1194 } while ((c != ' ') && (c != 9));
1198 in_quotes = (!in_quotes);
1200 if ((c == '>') && (!in_quotes))
1205 if (!strcmp(c_tag,tag))
1207 if ((buffer) && (c_tag) && (var))
1209 key = strstr(buffer,var);
1212 /* value not found in tag */
1230 for (unsigned j = 0; j < strlen(key); j++)
1237 strlcpy(result,key,MAXBUF);
1243 if (!strcmp(c_tag,tag))
1245 /* correct tag, but wrong index */
1255 if ((in_token) && (c != '\n') && (c != '\r'))
1262 *result = 0; // value or its tag not found at all
1268 int ServerConfig::ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
1270 ReadConf(config, tag, var, index, result);
1276 // This will bind a socket to a port. It works for UDP/TCP
1277 int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
1279 memset((char *)&server,0,sizeof(server));
1280 struct in_addr addy;
1281 inet_aton(addr,&addy);
1282 server.sin_family = AF_INET;
1285 server.sin_addr.s_addr = htonl(INADDR_ANY);
1289 server.sin_addr = addy;
1291 server.sin_port = htons(port);
1292 if (bind(sockfd,(struct sockaddr*)&server,sizeof(server))<0)
1298 listen(sockfd, Config->MaxConn);
1304 // Open a TCP Socket
1305 int OpenTCPSocket (void)
1309 struct linger linger = { 0 };
1311 if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
1315 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
1316 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
1318 linger.l_linger = 1;
1319 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));
1326 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
1327 sockaddr_in client,server;
1328 int clientportcount = 0;
1329 int BoundPortCount = 0;
1331 for (int count = 0; count < Config->ConfValueEnum("bind",&Config->config_f); count++)
1333 Config->ConfValue("bind","port",count,configToken,&Config->config_f);
1334 Config->ConfValue("bind","address",count,Addr,&Config->config_f);
1335 Config->ConfValue("bind","type",count,Type,&Config->config_f);
1337 if ((!*Type) || (!strcmp(Type,"clients")))
1339 // modules handle server bind types now
1340 Config->ports[clientportcount] = atoi(configToken);
1342 // If the client put bind "*", this is an unrealism.
1343 // We don't actually support this as documented, but
1344 // i got fed up of people trying it, so now it converts
1345 // it to an empty string meaning the same 'bind to all'.
1349 strlcpy(Config->addrs[clientportcount],Addr,256);
1351 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
1355 int PortCount = clientportcount;
1357 for (int count = 0; count < PortCount; count++)
1359 if ((openSockfd[BoundPortCount] = OpenTCPSocket()) == ERROR)
1361 log(DEBUG,"InspIRCd: startup: bad fd %lu binding port [%s:%d]",(unsigned long)openSockfd[BoundPortCount],Config->addrs[count],(unsigned long)Config->ports[count]);
1365 if (BindSocket(openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]) == ERROR)
1367 log(DEFAULT,"InspIRCd: startup: failed to bind port [%s:%lu]: %s",Config->addrs[count],(unsigned long)Config->ports[count],strerror(errno));
1371 /* well we at least bound to one socket so we'll continue */
1376 /* if we didn't bind to anything then abort */
1377 if (!BoundPortCount)
1379 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
1380 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)PortCount);
1384 return BoundPortCount;