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 bool ValidateTempDir(const char* tag, const char* value, void* data)
172 char* x = (char*)data;
174 strlcpy(x,"/tmp",1024);
178 bool ValidateMaxTargets(const char* tag, const char* value, void* data)
181 if ((*x < 0) || (*x > 31))
183 log(DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
189 bool ValidateSoftLimit(const char* tag, const char* value, void* data)
192 if ((*x < 1) || (*x > MAXCLIENTS))
194 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
200 bool ValidateMaxConn(const char* tag, const char* value, void* data)
204 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
210 bool ValidateDnsTimeout(const char* tag, const char* value, void* data)
218 bool ValidateDnsServer(const char* tag, const char* value, void* data)
220 char* x = (char*)data;
223 // attempt to look up their nameserver from /etc/resolv.conf
224 log(DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
225 ifstream resolv("/etc/resolv.conf");
226 std::string nameserver;
227 bool found_server = false;
229 if (resolv.is_open())
231 while (resolv >> nameserver)
233 if ((nameserver == "nameserver") && (!found_server))
235 resolv >> nameserver;
236 strlcpy(x,nameserver.c_str(),MAXBUF);
238 log(DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
244 log(DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
245 strlcpy(x,"127.0.0.1",MAXBUF);
250 log(DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
251 strlcpy(x,"127.0.0.1",MAXBUF);
257 bool ValidateModPath(const char* tag, const char* value, void* data)
259 char* x = (char*)data;
261 strlcpy(x,MOD_PATH,MAXBUF);
266 bool ValidateServerName(const char* tag, const char* value, void* data)
268 char* x = (char*)data;
271 log(DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s%c'",x,x,'.');
272 charlcat(x,'.',MAXBUF);
278 bool ValidateNetBufferSize(const char* tag, const char* value, void* data)
280 if ((!Config->NetBufferSize) || (Config->NetBufferSize > 65535) || (Config->NetBufferSize < 1024))
282 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
283 Config->NetBufferSize = 10240;
288 bool ValidateMaxWho(const char* tag, const char* value, void* data)
290 if ((!Config->MaxWhoResults) || (Config->MaxWhoResults > 65535) || (Config->MaxWhoResults < 1))
292 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
293 Config->MaxWhoResults = 128;
298 bool ValidateLogLevel(const char* tag, const char* value, void* data)
300 const char* dbg = (const char*)data;
301 Config->LogLevel = DEFAULT;
302 if (!strcmp(dbg,"debug"))
304 Config->LogLevel = DEBUG;
305 Config->debugging = 1;
307 else if (!strcmp(dbg,"verbose"))
308 Config->LogLevel = VERBOSE;
309 else if (!strcmp(dbg,"default"))
310 Config->LogLevel = DEFAULT;
311 else if (!strcmp(dbg,"sparse"))
312 Config->LogLevel = SPARSE;
313 else if (!strcmp(dbg,"none"))
314 Config->LogLevel = NONE;
318 bool ValidateMotd(const char* tag, const char* value, void* data)
320 readfile(Config->MOTD,Config->motd);
324 bool ValidateRules(const char* tag, const char* value, void* data)
326 readfile(Config->RULES,Config->rules);
331 void ServerConfig::Read(bool bail, userrec* user)
335 static InitialConfig Values[] = {
336 {"options", "softlimit", &this->SoftLimit, DT_INTEGER, ValidateSoftLimit},
337 {"options", "somaxconn", &this->MaxConn, DT_INTEGER, ValidateMaxConn},
338 {"server", "name", &this->ServerName, DT_CHARPTR, ValidateServerName},
339 {"server", "description", &this->ServerDesc, DT_CHARPTR, ValidateServerName},
340 {"server", "network", &this->Network, DT_CHARPTR, NoValidation},
341 {"admin", "name", &this->AdminName, DT_CHARPTR, NoValidation},
342 {"admin", "email", &this->AdminEmail, DT_CHARPTR, NoValidation},
343 {"admin", "nick", &this->AdminNick, DT_CHARPTR, NoValidation},
344 {"files", "motd", &this->motd, DT_CHARPTR, ValidateMotd},
345 {"files", "rules", &this->rules, DT_CHARPTR, ValidateRules},
346 {"power", "diepass", &this->diepass, DT_CHARPTR, NoValidation},
347 {"power", "pauseval", &this->DieDelay, DT_INTEGER, NoValidation},
348 {"power", "restartpass", &this->restartpass, DT_CHARPTR, NoValidation},
349 {"options", "prefixquit", &this->PrefixQuit, DT_CHARPTR, NoValidation},
350 {"die", "value", &this->DieValue, DT_CHARPTR, NoValidation},
351 {"options", "loglevel", &debug, DT_CHARPTR, ValidateLogLevel},
352 {"options", "netbuffersize", &this->NetBufferSize, DT_INTEGER, ValidateNetBufferSize},
353 {"options", "maxwho", &this->MaxWhoResults, DT_INTEGER, ValidateMaxWho},
354 {"options", "allowhalfop", &this->AllowHalfop, DT_BOOLEAN, NoValidation},
355 {"dns", "server", &this->DNSServer, DT_CHARPTR, ValidateDnsServer},
356 {"dns", "timeout", &this->dns_timeout, DT_INTEGER, ValidateDnsTimeout},
357 {"options", "moduledir", &this->ModPath, DT_CHARPTR, NoValidation},
358 {"disabled", "commands", &this->DisabledCommands, DT_CHARPTR, NoValidation},
359 {"options", "operonlystats", &this->OperOnlyStats, DT_CHARPTR, NoValidation},
360 {"options", "customversion", &this->CustomVersion, DT_CHARPTR, NoValidation},
361 {"options", "hidesplits", &this->HideSplits, DT_BOOLEAN, NoValidation},
362 {"options", "hidebans", &this->HideBans, DT_BOOLEAN, NoValidation},
363 {"options", "hidewhois", &this->HideWhoisServer, DT_CHARPTR, NoValidation},
364 {"options", "tempdir", &this->TempDir, DT_CHARPTR, ValidateTempDir},
369 char timeout[MAXBUF],flood[MAXBUF],pfreq[MAXBUF],thold[MAXBUF],sqmax[MAXBUF],rqmax[MAXBUF];
370 char localmax[MAXBUF],globalmax[MAXBUF],ServName[MAXBUF],Value[MAXBUF];
373 std::stringstream errstr;
375 include_stack.clear();
377 if (!LoadConf(CONFIG_FILE,&Config->config_f,&errstr))
380 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
384 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
393 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
394 while (!errstr.eof())
396 errstr.getline(dataline,1024);
397 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
402 WriteOpers("There were errors in the configuration file:");
403 while (!errstr.eof())
405 errstr.getline(dataline,1024);
406 WriteOpers(dataline);
414 /* Check we dont have more than one of singular tags
416 if (!CheckOnce("server",bail,user) || !CheckOnce("admin",bail,user) || !CheckOnce("files",bail,user)
417 || !CheckOnce("power",bail,user) || !CheckOnce("options",bail,user) || !CheckOnce("pid",bail,user))
423 for (int Index = 0; Values[Index].tag; Index++)
425 int* val_i = (int*) Values[Index].val;
426 char* val_c = (char*) Values[Index].val;
428 switch (Values[Index].datatype)
431 ConfValue(Values[Index].tag, Values[Index].value, 0, val_c, &this->config_f);
435 convert = new char[MAXBUF];
436 ConfValue(Values[Index].tag, Values[Index].value, 0, convert, &this->config_f);
437 *val_i = atoi(convert);
442 convert = new char[MAXBUF];
443 ConfValue(Values[Index].tag, Values[Index].value, 0, convert, &this->config_f);
444 *val_i = ((*convert == tolower('y')) || (*convert == tolower('t')) || (*convert == '1'));
452 Values[Index].validation_function(Values[Index].tag, Values[Index].value, Values[Index].val);
455 log(DEFAULT,"Reading connect classes...");
458 for (int i = 0; i < ConfValueEnum("connect",&Config->config_f); i++)
461 ConfValue("connect","allow",i,Value,&Config->config_f);
462 ConfValue("connect","timeout",i,timeout,&Config->config_f);
463 ConfValue("connect","flood",i,flood,&Config->config_f);
464 ConfValue("connect","pingfreq",i,pfreq,&Config->config_f);
465 ConfValue("connect","threshold",i,thold,&Config->config_f);
466 ConfValue("connect","sendq",i,sqmax,&Config->config_f);
467 ConfValue("connect","recvq",i,rqmax,&Config->config_f);
468 ConfValue("connect","localmax",i,localmax,&Config->config_f);
469 ConfValue("connect","globalmax",i,globalmax,&Config->config_f);
475 strlcpy(Value,"",MAXBUF);
476 ConfValue("connect","password",i,Value,&Config->config_f);
478 c.registration_timeout = 90; // default is 2 minutes
480 c.flood = atoi(flood);
482 c.sendqmax = 262144; // 256k
483 c.recvqmax = 4096; // 4k
487 if (atoi(localmax)>0)
489 c.maxlocal = atoi(localmax);
492 if (atoi(globalmax)>0)
494 c.maxglobal = atoi(globalmax);
499 c.threshold = atoi(thold);
505 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());
510 c.sendqmax = atoi(sqmax);
514 c.recvqmax = atoi(rqmax);
518 c.registration_timeout = atoi(timeout);
522 c.pingtime = atoi(pfreq);
525 Classes.push_back(c);
529 ConfValue("connect","deny",i,Value,&Config->config_f);
532 Classes.push_back(c);
533 log(DEBUG,"Read connect class type DENY, host=%s",c.host.c_str());
537 Config->ulines.clear();
539 for (int i = 0; i < ConfValueEnum("uline",&Config->config_f); i++)
541 ConfValue("uline","server",i,ServName,&Config->config_f);
543 log(DEBUG,"Read ULINE '%s'",ServName);
544 Config->ulines.push_back(ServName);
549 char CM1[MAXBUF],CM2[MAXBUF];
551 for (int count = 0; count < Config->ConfValueEnum("banlist",&Config->config_f); count++)
553 Config->ConfValue("banlist","chan",count,CM1,&Config->config_f);
554 Config->ConfValue("banlist","limit",count,CM2,&Config->config_f);
555 maxbans[CM1] = atoi(CM2);
558 ReadClassesAndTypes();
559 log(DEFAULT,"Reading K lines,Q lines and Z lines from config...");
560 read_xline_defaults();
561 log(DEFAULT,"Applying K lines, Q lines and Z lines...");
562 apply_lines(APPLY_ALL);
564 ConfValue("pid","file",0,Config->PID,&Config->config_f);
565 // write once here, to try it out and make sure its ok
566 WritePID(Config->PID);
568 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
571 log(DEFAULT,"Adding and removing modules due to rehash...");
573 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
575 // store the old module names
576 for (std::vector<std::string>::iterator t = module_names.begin(); t != module_names.end(); t++)
578 old_module_names.push_back(*t);
581 // get the new module names
582 for (int count2 = 0; count2 < ConfValueEnum("module",&Config->config_f); count2++)
584 ConfValue("module","name",count2,Value,&Config->config_f);
585 new_module_names.push_back(Value);
588 // now create a list of new modules that are due to be loaded
589 // and a seperate list of modules which are due to be unloaded
590 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
594 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
601 added_modules.push_back(*_new);
604 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
607 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
614 removed_modules.push_back(*oldm);
618 * now we have added_modules, a vector of modules to be loaded,
619 * and removed_modules, a vector of modules
622 int rem = 0, add = 0;
623 if (!removed_modules.empty())
624 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
626 if (ServerInstance->UnloadModule(removing->c_str()))
628 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
631 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
638 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
642 if (!added_modules.empty())
643 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
645 if (ServerInstance->LoadModule(adding->c_str()))
647 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
650 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
657 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
661 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());
666 void Exit (int status)
668 if (Config->log_file)
669 fclose(Config->log_file);
670 send_error("Server shutdown.");
674 void Killed(int status)
676 if (Config->log_file)
677 fclose(Config->log_file);
678 send_error("Server terminated.");
682 char* CleanFilename(char* name)
684 char* p = name + strlen(name);
685 while ((p != name) && (*p != '/')) p--;
686 return (p != name ? ++p : p);
690 void Rehash(int status)
692 WriteOpers("Rehashing config file %s due to SIGHUP",CleanFilename(CONFIG_FILE));
693 fclose(Config->log_file);
695 Config->Read(false,NULL);
696 FOREACH_MOD(I_OnRehash,OnRehash(""));
703 printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
704 printf("(C) ChatSpike Development team.\033[0m\n\n");
705 printf("Developers:\033[1;32m Brain, FrostyCoolSlug, w00t, Om\033[0m\n");
706 printf("Others:\033[1;32m See /INFO Output\033[0m\n");
707 printf("Name concept:\033[1;32m Lord_Zathras\033[0m\n\n");
710 void WritePID(std::string filename)
712 ofstream outfile(filename.c_str());
713 if (outfile.is_open())
720 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
721 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
728 signal (SIGALRM, SIG_IGN);
729 signal (SIGHUP, Rehash);
730 signal (SIGPIPE, SIG_IGN);
731 signal (SIGTERM, Exit);
732 signal (SIGSEGV, Error);
736 int DaemonSeed (void)
739 if ((childpid = fork ()) < 0)
741 else if (childpid > 0)
743 /* We wait a few seconds here, so that the shell prompt doesnt come back over the output */
749 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
751 if (Config->unlimitcore)
754 if (getrlimit(RLIMIT_CORE, &rl) == -1)
756 log(DEFAULT,"Failed to getrlimit()!");
761 rl.rlim_cur = rl.rlim_max;
762 if (setrlimit(RLIMIT_CORE, &rl) == -1)
763 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
771 /* Make Sure Modules Are Avaliable!
772 * (BugFix By Craig.. See? I do work! :p)
773 * Modified by brain, requires const char*
774 * to work with other API functions
777 bool FileExists (const char* file)
780 if ((input = fopen (file, "r")) == NULL)
791 /* ConfProcess does the following things to a config line in the following order:
793 * Processes the line for syntax errors as shown below
794 * (1) Line void of quotes or equals (a malformed, illegal tag format)
795 * (2) Odd number of quotes on the line indicating a missing quote
796 * (3) number of equals signs not equal to number of quotes / 2 (missing an equals sign)
797 * (4) Spaces between the opening bracket (<) and the keyword
798 * (5) Spaces between a keyword and an equals sign
799 * (6) Spaces between an equals sign and a quote
800 * Removes trailing spaces
801 * Removes leading spaces
802 * Converts tabs to spaces
803 * Turns multiple spaces that are outside of quotes into single spaces
806 std::string ServerConfig::ConfProcess(char* buffer, long linenumber, std::stringstream* errorstream, bool &error, std::string filename)
808 long number_of_quotes = 0;
809 long number_of_equals = 0;
810 bool has_open_bracket = false;
811 bool in_quotes = false;
817 // firstly clean up the line by stripping spaces from the start and end and converting tabs to spaces
818 for (char* d = buffer; *d; d++)
821 while (*buffer == ' ') buffer++;
822 while ((buffer[strlen(buffer)-1] == ' ') && (*buffer)) buffer[strlen(buffer)-1] = '\0';
824 // empty lines are syntactically valid, as are comments
825 if (!(*buffer) || buffer[0] == '#')
828 for (unsigned int c = 0; c < strlen(buffer); c++)
830 // convert all spaces that are OUTSIDE quotes into hardspace (0xA0) as this will make them easier to
831 // search and replace later :)
832 if ((!in_quotes) && (buffer[c] == ' '))
834 if ((buffer[c] == '<') && (!in_quotes))
836 has_open_bracket = true;
837 if (strlen(buffer) == 1)
839 *errorstream << "Tag without identifier at " << filename << ":" << linenumber << endl;
843 else if ((tolower(buffer[c+1]) < 'a') || (tolower(buffer[c+1]) > 'z'))
845 *errorstream << "Invalid characters in identifier at " << filename << ":" << linenumber << endl;
850 if (buffer[c] == '"')
853 in_quotes = (!in_quotes);
855 if ((buffer[c] == '=') && (!in_quotes))
858 if (strlen(buffer) == c)
860 *errorstream << "Variable without a value at " << filename << ":" << linenumber << endl;
864 else if (buffer[c+1] != '"')
866 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
872 *errorstream << "Value without a variable (line starts with '=') at " << filename << ":" << linenumber << endl;
876 else if (buffer[c-1] == '\xA0')
878 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
884 // no quotes, and no equals. something freaky.
885 if ((!number_of_quotes) || (!number_of_equals) && (strlen(buffer)>2) && (buffer[0]=='<'))
887 *errorstream << "Malformed tag at " << filename << ":" << linenumber << endl;
891 // odd number of quotes. thats just wrong.
892 if ((number_of_quotes % 2) != 0)
894 *errorstream << "Missing \" at " << filename << ":" << linenumber << endl;
898 if (number_of_equals < (number_of_quotes/2))
900 *errorstream << "Missing '=' at " << filename << ":" << linenumber << endl;
902 if (number_of_equals > (number_of_quotes/2))
904 *errorstream << "Too many '=' at " << filename << ":" << linenumber << endl;
907 std::string parsedata = buffer;
908 // turn multispace into single space
909 while (parsedata.find("\xA0\xA0") != std::string::npos)
911 parsedata.erase(parsedata.find("\xA0\xA0"),1);
914 // turn our hardspace back into softspace
915 for (unsigned int d = 0; d < parsedata.length(); d++)
917 if (parsedata[d] == '\xA0')
921 // and we're done, the line is fine!
925 int ServerConfig::fgets_safe(char* buffer, size_t maxsize, FILE* &file)
928 unsigned int bufptr = 0;
929 while ((!feof(file)) && (c_read != '\n') && (c_read != '\r') && (bufptr < maxsize))
931 c_read = fgetc(file);
932 if ((c_read != '\n') && (c_read != '\r'))
933 buffer[bufptr++] = c_read;
935 buffer[bufptr] = '\0';
939 bool ServerConfig::LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream)
942 errorstream->str("");
944 // first, check that the file exists before we try to do anything with it
945 if (!FileExists(filename))
947 *errorstream << "File " << filename << " not found." << endl;
950 // Fix the chmod of the file to restrict it to the current user and group
951 chmod(filename,0600);
952 for (unsigned int t = 0; t < include_stack.size(); t++)
954 if (std::string(filename) == include_stack[t])
956 *errorstream << "File " << filename << " is included recursively (looped inclusion)." << endl;
960 include_stack.push_back(filename);
962 FILE* conf = fopen(filename,"r");
968 if (fgets_safe(buffer, MAXBUF, conf))
970 if ((!feof(conf)) && (buffer) && (strlen(buffer)))
972 if ((buffer[0] != '#') && (buffer[0] != '\r') && (buffer[0] != '\n'))
974 if (!strncmp(buffer,"<include file=\"",15))
977 char confpath[10240],newconf[10240];
978 // include file directive
979 buf += 15; // advance to filename
980 for (unsigned int j = 0; j < strlen(buf); j++)
990 log(DEBUG,"Opening included file '%s'",buf);
993 strlcpy(confpath,CONFIG_FILE,10240);
994 if (strstr(confpath,"/inspircd.conf"))
996 // leaves us with just the path
997 *(strstr(confpath,"/inspircd.conf")) = '\0';
999 snprintf(newconf,10240,"%s/%s",confpath,buf);
1001 else strlcpy(newconf,buf,10240);
1002 std::stringstream merge(stringstream::in | stringstream::out);
1003 // recursively call LoadConf and get the new data, use the same errorstream
1004 if (LoadConf(newconf, &merge, errorstream))
1006 // append to the end of the file
1007 std::string newstuff = merge.str();
1008 *target << newstuff;
1012 // the error propogates up to its parent recursively
1013 // causing the config reader to bail at the top level.
1021 std::string data = this->ConfProcess(buffer,linenumber++,errorstream,error,filename);
1039 /* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */
1041 int ServerConfig::EnumConf(std::stringstream *config, const char* tag)
1044 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
1045 int in_token, in_quotes, tptr, idx = 0;
1047 std::string x = config->str();
1048 const char* buf = x.c_str();
1050 long len = config->str().length();
1060 if ((c == '#') && (lastc == '\n'))
1062 while ((c != '\n') && (bptr<len))
1068 if ((c == '<') && (!in_quotes))
1083 in_quotes = (!in_quotes);
1085 if ((c == '>') && (!in_quotes))
1088 if (!strcmp(c_tag,tag))
1090 /* correct tag, but wrong index */
1100 if ((in_token) && (c != '\n') && (c != '\r'))
1110 /* Counts the number of values within a certain tag */
1112 int ServerConfig::EnumValues(std::stringstream *config, const char* tag, int index)
1115 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
1116 int in_token, in_quotes, tptr, idx = 0;
1118 bool correct_tag = false;
1121 const char* buf = config->str().c_str();
1123 long len = strlen(buf);
1133 if ((c == '#') && (lastc == '\n'))
1135 while ((c != '\n') && (bptr<len))
1141 if ((c == '<') && (!in_quotes))
1152 if ((!strcmp(c_tag,tag)) && (idx == index))
1161 in_quotes = (!in_quotes);
1164 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
1168 if ((c == '>') && (!in_quotes))
1172 correct_tag = false;
1173 if (!strcmp(c_tag,tag))
1175 /* correct tag, but wrong index */
1185 if ((in_token) && (c != '\n') && (c != '\r'))
1197 int ServerConfig::ConfValueEnum(char* tag, std::stringstream* config)
1199 return EnumConf(config,tag);
1204 /* Retrieves a value from the config file. If there is more than one value of the specified
1205 * key and section (e.g. for opers etc) then the index value specifies which to retreive, e.g.
1207 * ConfValue("oper","name",2,result);
1210 int ServerConfig::ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
1213 char buffer[65535], c_tag[MAXBUF], c, lastc;
1214 int in_token, in_quotes, tptr, idx = 0;
1217 std::string x = config->str();
1218 const char* buf = x.c_str();
1220 long len = config->str().length();
1232 // FIX: Treat tabs as spaces
1235 if ((c == '<') && (!in_quotes))
1246 // FIX: Tab can follow a tagname as well as space.
1247 } while ((c != ' ') && (c != 9));
1251 in_quotes = (!in_quotes);
1253 if ((c == '>') && (!in_quotes))
1258 if (!strcmp(c_tag,tag))
1260 if ((buffer) && (c_tag) && (var))
1262 key = strstr(buffer,var);
1265 /* value not found in tag */
1283 for (unsigned j = 0; j < strlen(key); j++)
1290 strlcpy(result,key,MAXBUF);
1296 if (!strcmp(c_tag,tag))
1298 /* correct tag, but wrong index */
1308 if ((in_token) && (c != '\n') && (c != '\r'))
1315 *result = 0; // value or its tag not found at all
1321 int ServerConfig::ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
1323 ReadConf(config, tag, var, index, result);
1329 // This will bind a socket to a port. It works for UDP/TCP
1330 int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
1332 memset((char *)&server,0,sizeof(server));
1333 struct in_addr addy;
1334 inet_aton(addr,&addy);
1335 server.sin_family = AF_INET;
1338 server.sin_addr.s_addr = htonl(INADDR_ANY);
1342 server.sin_addr = addy;
1344 server.sin_port = htons(port);
1345 if (bind(sockfd,(struct sockaddr*)&server,sizeof(server))<0)
1351 listen(sockfd, Config->MaxConn);
1357 // Open a TCP Socket
1358 int OpenTCPSocket (void)
1362 struct linger linger = { 0 };
1364 if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
1368 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
1369 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
1371 linger.l_linger = 1;
1372 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));
1379 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
1380 sockaddr_in client,server;
1381 int clientportcount = 0;
1382 int BoundPortCount = 0;
1384 for (int count = 0; count < Config->ConfValueEnum("bind",&Config->config_f); count++)
1386 Config->ConfValue("bind","port",count,configToken,&Config->config_f);
1387 Config->ConfValue("bind","address",count,Addr,&Config->config_f);
1388 Config->ConfValue("bind","type",count,Type,&Config->config_f);
1390 if ((!*Type) || (!strcmp(Type,"clients")))
1392 // modules handle server bind types now
1393 Config->ports[clientportcount] = atoi(configToken);
1395 // If the client put bind "*", this is an unrealism.
1396 // We don't actually support this as documented, but
1397 // i got fed up of people trying it, so now it converts
1398 // it to an empty string meaning the same 'bind to all'.
1402 strlcpy(Config->addrs[clientportcount],Addr,256);
1404 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
1408 int PortCount = clientportcount;
1410 for (int count = 0; count < PortCount; count++)
1412 if ((openSockfd[BoundPortCount] = OpenTCPSocket()) == ERROR)
1414 log(DEBUG,"InspIRCd: startup: bad fd %lu binding port [%s:%d]",(unsigned long)openSockfd[BoundPortCount],Config->addrs[count],(unsigned long)Config->ports[count]);
1418 if (BindSocket(openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]) == ERROR)
1420 log(DEFAULT,"InspIRCd: startup: failed to bind port [%s:%lu]: %s",Config->addrs[count],(unsigned long)Config->ports[count],strerror(errno));
1424 /* well we at least bound to one socket so we'll continue */
1429 /* if we didn't bind to anything then abort */
1430 if (!BoundPortCount)
1432 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
1433 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)PortCount);
1437 return BoundPortCount;