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>
30 #include "inspircd_io.h"
31 #include "inspstring.h"
32 #include "helperfuncs.h"
33 #include "userprocess.h"
36 extern ServerConfig *Config;
37 extern InspIRCd* ServerInstance;
38 extern int openSockfd[MAXSOCKS];
42 extern std::vector<Module*> modules;
43 extern std::vector<ircd_module*> factory;
45 std::vector<std::string> old_module_names, new_module_names, added_modules, removed_modules;
47 ServerConfig::ServerConfig()
50 *TempDir = *ServerName = *Network = *ServerDesc = *AdminName = '\0';
51 *HideWhoisServer = *AdminEmail = *AdminNick = *diepass = *restartpass = '\0';
52 *CustomVersion = *motd = *rules = *PrefixQuit = *DieValue = *DNSServer = '\0';
53 *OperOnlyStats = *ModPath = *MyExecutable = *DisabledCommands = *PID = '\0';
55 nofork = HideBans = HideSplits = unlimitcore = false;
57 dns_timeout = DieDelay = 5;
59 NetBufferSize = 10240;
60 SoftLimit = MAXCLIENTS;
68 void ServerConfig::ClearStack()
70 include_stack.clear();
73 Module* ServerConfig::GetIOHook(int port)
75 std::map<int,Module*>::iterator x = IOHookModule.find(port);
76 return (x != IOHookModule.end() ? x->second : NULL);
79 bool ServerConfig::AddIOHook(int port, Module* iomod)
83 IOHookModule[port] = iomod;
88 ModuleException err("Port already hooked by another module");
94 bool ServerConfig::DelIOHook(int port)
96 std::map<int,Module*>::iterator x = IOHookModule.find(port);
97 if (x != IOHookModule.end())
99 IOHookModule.erase(x);
105 bool ServerConfig::CheckOnce(char* tag, bool bail, userrec* user)
107 int count = ConfValueEnum(tag,&Config->config_f);
112 printf("There were errors in your configuration:\nYou have more than one <%s> tag, this is not permitted.\n",tag);
119 WriteServ(user->fd,"There were errors in your configuration:");
120 WriteServ(user->fd,"You have more than one <%s> tag, this is not permitted.\n",tag);
124 WriteOpers("There were errors in the configuration file:");
125 WriteOpers("You have more than one <%s> tag, this is not permitted.\n",tag);
134 printf("There were errors in your configuration:\nYou have not defined a <%s> tag, this is required.\n",tag);
141 WriteServ(user->fd,"There were errors in your configuration:");
142 WriteServ(user->fd,"You have not defined a <%s> tag, this is required.",tag);
146 WriteOpers("There were errors in the configuration file:");
147 WriteOpers("You have not defined a <%s> tag, this is required.",tag);
155 bool NoValidation(const char* tag, const char* value, void* data)
157 log(DEBUG,"No validation for <%s:%s>",tag,value);
161 bool ValidateTempDir(const char* tag, const char* value, void* data)
163 char* x = (char*)data;
165 strlcpy(x,"/tmp",1024);
169 bool ValidateMaxTargets(const char* tag, const char* value, void* data)
172 if ((*x < 0) || (*x > 31))
174 log(DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
180 bool ValidateSoftLimit(const char* tag, const char* value, void* data)
183 if ((*x < 1) || (*x > MAXCLIENTS))
185 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
191 bool ValidateMaxConn(const char* tag, const char* value, void* data)
195 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
201 bool ValidateDnsTimeout(const char* tag, const char* value, void* data)
209 bool ValidateDnsServer(const char* tag, const char* value, void* data)
211 char* x = (char*)data;
214 // attempt to look up their nameserver from /etc/resolv.conf
215 log(DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
216 ifstream resolv("/etc/resolv.conf");
217 std::string nameserver;
218 bool found_server = false;
220 if (resolv.is_open())
222 while (resolv >> nameserver)
224 if ((nameserver == "nameserver") && (!found_server))
226 resolv >> nameserver;
227 strlcpy(x,nameserver.c_str(),MAXBUF);
229 log(DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
235 log(DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
236 strlcpy(x,"127.0.0.1",MAXBUF);
241 log(DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
242 strlcpy(x,"127.0.0.1",MAXBUF);
248 bool ValidateModPath(const char* tag, const char* value, void* data)
250 char* x = (char*)data;
252 strlcpy(x,MOD_PATH,MAXBUF);
257 bool ValidateServerName(const char* tag, const char* value, void* data)
259 char* x = (char*)data;
262 log(DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s%c'",x,x,'.');
263 charlcat(x,'.',MAXBUF);
269 bool ValidateNetBufferSize(const char* tag, const char* value, void* data)
271 if ((!Config->NetBufferSize) || (Config->NetBufferSize > 65535) || (Config->NetBufferSize < 1024))
273 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
274 Config->NetBufferSize = 10240;
279 bool ValidateMaxWho(const char* tag, const char* value, void* data)
281 if ((!Config->MaxWhoResults) || (Config->MaxWhoResults > 65535) || (Config->MaxWhoResults < 1))
283 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
284 Config->MaxWhoResults = 128;
289 bool ValidateLogLevel(const char* tag, const char* value, void* data)
291 const char* dbg = (const char*)data;
292 Config->LogLevel = DEFAULT;
293 if (!strcmp(dbg,"debug"))
295 Config->LogLevel = DEBUG;
296 Config->debugging = 1;
298 else if (!strcmp(dbg,"verbose"))
299 Config->LogLevel = VERBOSE;
300 else if (!strcmp(dbg,"default"))
301 Config->LogLevel = DEFAULT;
302 else if (!strcmp(dbg,"sparse"))
303 Config->LogLevel = SPARSE;
304 else if (!strcmp(dbg,"none"))
305 Config->LogLevel = NONE;
309 bool ValidateMotd(const char* tag, const char* value, void* data)
311 readfile(Config->MOTD,Config->motd);
315 bool ValidateRules(const char* tag, const char* value, void* data)
317 readfile(Config->RULES,Config->rules);
321 bool InitConnect(const char* tag)
323 log(DEFAULT,"Reading connect classes...");
324 Config->Classes.clear();
328 bool DoConnect(const char* tag, char** entries, void** values, int* types)
331 char* allow = (char*)values[0];
332 char* deny = (char*)values[1];
333 char* password = (char*)values[2];
334 int* timeout = (int*)values[3];
335 int* pingfreq = (int*)values[4];
336 int* flood = (int*)values[5];
337 int* threshold = (int*)values[6];
338 int* sendq = (int*)values[7];
339 int* recvq = (int*)values[8];
340 int* localmax = (int*)values[9];
341 int* globalmax = (int*)values[10];
348 c.registration_timeout = *timeout;
349 c.pingtime = *pingfreq;
351 c.threshold = *threshold;
354 c.maxlocal = *localmax;
355 c.maxglobal = *globalmax;
360 if (c.maxglobal == 0)
362 if (c.threshold == 0)
366 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());
372 if (c.registration_timeout == 0)
373 c.registration_timeout = 90;
376 Config->Classes.push_back(c);
382 Config->Classes.push_back(c);
383 log(DEBUG,"Read connect class type DENY, host=%s",deny);
389 bool DoneConnect(const char* tag)
391 log(DEBUG,"DoneConnect called for tag: %s",tag);
395 bool InitULine(const char* tag)
397 Config->ulines.clear();
401 bool DoULine(const char* tag, char** entries, void** values, int* types)
403 char* server = (char*)values[0];
404 log(DEBUG,"Read ULINE '%s'",server);
405 Config->ulines.push_back(server);
409 bool DoneULine(const char* tag)
414 bool InitModule(const char* tag)
416 old_module_names.clear();
417 new_module_names.clear();
418 added_modules.clear();
419 removed_modules.clear();
420 for (std::vector<std::string>::iterator t = Config->module_names.begin(); t != Config->module_names.end(); t++)
422 old_module_names.push_back(*t);
427 bool DoModule(const char* tag, char** entries, void** values, int* types)
429 char* modname = (char*)values[0];
430 new_module_names.push_back(modname);
434 bool DoneModule(const char* tag)
436 // now create a list of new modules that are due to be loaded
437 // and a seperate list of modules which are due to be unloaded
438 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
442 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
449 added_modules.push_back(*_new);
452 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
455 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
462 removed_modules.push_back(*oldm);
467 bool InitMaxBans(const char* tag)
469 Config->maxbans.clear();
473 bool DoMaxBans(const char* tag, char** entries, void** values, int* types)
475 char* channel = (char*)values[0];
476 int* limit = (int*)values[1];
477 Config->maxbans[channel] = *limit;
481 bool DoneMaxBans(const char* tag)
486 void ServerConfig::Read(bool bail, userrec* user)
490 std::stringstream errstr;
492 static InitialConfig Values[] = {
493 {"options", "softlimit", &this->SoftLimit, DT_INTEGER, ValidateSoftLimit},
494 {"options", "somaxconn", &this->MaxConn, DT_INTEGER, ValidateMaxConn},
495 {"server", "name", &this->ServerName, DT_CHARPTR, ValidateServerName},
496 {"server", "description", &this->ServerDesc, DT_CHARPTR, NoValidation},
497 {"server", "network", &this->Network, DT_CHARPTR, NoValidation},
498 {"admin", "name", &this->AdminName, DT_CHARPTR, NoValidation},
499 {"admin", "email", &this->AdminEmail, DT_CHARPTR, NoValidation},
500 {"admin", "nick", &this->AdminNick, DT_CHARPTR, NoValidation},
501 {"files", "motd", &this->motd, DT_CHARPTR, ValidateMotd},
502 {"files", "rules", &this->rules, DT_CHARPTR, ValidateRules},
503 {"power", "diepass", &this->diepass, DT_CHARPTR, NoValidation},
504 {"power", "pauseval", &this->DieDelay, DT_INTEGER, NoValidation},
505 {"power", "restartpass", &this->restartpass, DT_CHARPTR, NoValidation},
506 {"options", "prefixquit", &this->PrefixQuit, DT_CHARPTR, NoValidation},
507 {"die", "value", &this->DieValue, DT_CHARPTR, NoValidation},
508 {"options", "loglevel", &debug, DT_CHARPTR, ValidateLogLevel},
509 {"options", "netbuffersize", &this->NetBufferSize, DT_INTEGER, ValidateNetBufferSize},
510 {"options", "maxwho", &this->MaxWhoResults, DT_INTEGER, ValidateMaxWho},
511 {"options", "allowhalfop", &this->AllowHalfop, DT_BOOLEAN, NoValidation},
512 {"dns", "server", &this->DNSServer, DT_CHARPTR, ValidateDnsServer},
513 {"dns", "timeout", &this->dns_timeout, DT_INTEGER, ValidateDnsTimeout},
514 {"options", "moduledir", &this->ModPath, DT_CHARPTR, ValidateModPath},
515 {"disabled", "commands", &this->DisabledCommands, DT_CHARPTR, NoValidation},
516 {"options", "operonlystats", &this->OperOnlyStats, DT_CHARPTR, NoValidation},
517 {"options", "customversion", &this->CustomVersion, DT_CHARPTR, NoValidation},
518 {"options", "hidesplits", &this->HideSplits, DT_BOOLEAN, NoValidation},
519 {"options", "hidebans", &this->HideBans, DT_BOOLEAN, NoValidation},
520 {"options", "hidewhois", &this->HideWhoisServer, DT_CHARPTR, NoValidation},
521 {"options", "tempdir", &this->TempDir, DT_CHARPTR, ValidateTempDir},
522 {"pid", "file", &this->PID, DT_CHARPTR, NoValidation},
526 static MultiConfig MultiValues[] = {
529 {"allow", "deny", "password", "timeout", "pingfreq", "flood",
530 "threshold", "sendq", "recvq", "localmax", "globalmax", NULL},
531 {DT_CHARPTR, DT_CHARPTR, DT_CHARPTR, DT_INTEGER, DT_INTEGER, DT_INTEGER,
532 DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER},
533 InitConnect, DoConnect, DoneConnect},
538 InitULine,DoULine,DoneULine},
541 {"chan", "limit", NULL},
542 {DT_CHARPTR, DT_INTEGER},
543 InitMaxBans, DoMaxBans, DoneMaxBans},
548 InitModule, DoModule, DoneModule},
551 {"reason", "ipmask", NULL},
552 {DT_CHARPTR, DT_CHARPTR},
553 InitXLine, DoZLine, DoneXLine},
556 {"reason", "nick", NULL},
557 {DT_CHARPTR, DT_CHARPTR},
558 InitXLine, DoQLine, DoneXLine},
561 {"reason", "host", NULL},
562 {DT_CHARPTR, DT_CHARPTR},
563 InitXLine, DoKLine, DoneXLine},
566 {"reason", "host", NULL},
567 {DT_CHARPTR, DT_CHARPTR},
568 InitXLine, DoELine, DoneXLine},
571 {"name", "classes", NULL},
572 {DT_CHARPTR, DT_CHARPTR},
573 InitTypes, DoType, DoneClassesAndTypes},
576 {"name", "commands", NULL},
577 {DT_CHARPTR, DT_CHARPTR},
578 InitClasss, DoClass, DoneClassesAndTypes},
583 include_stack.clear();
585 if (!LoadConf(CONFIG_FILE,&Config->config_f,&errstr))
588 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
592 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
599 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
600 while (!errstr.eof())
602 errstr.getline(dataline,1024);
603 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
608 WriteOpers("There were errors in the configuration file:");
609 while (!errstr.eof())
611 errstr.getline(dataline,1024);
612 WriteOpers(dataline);
620 /* Check we dont have more than one of singular tags
622 if (!CheckOnce("server",bail,user) || !CheckOnce("admin",bail,user) || !CheckOnce("files",bail,user)
623 || !CheckOnce("power",bail,user) || !CheckOnce("options",bail,user) || !CheckOnce("pid",bail,user))
629 for (int Index = 0; Values[Index].tag; Index++)
631 int* val_i = (int*) Values[Index].val;
632 char* val_c = (char*) Values[Index].val;
634 switch (Values[Index].datatype)
637 ConfValue(Values[Index].tag, Values[Index].value, 0, val_c, &this->config_f);
641 convert = new char[MAXBUF];
642 ConfValue(Values[Index].tag, Values[Index].value, 0, convert, &this->config_f);
643 *val_i = atoi(convert);
648 convert = new char[MAXBUF];
649 ConfValue(Values[Index].tag, Values[Index].value, 0, convert, &this->config_f);
650 *val_i = ((*convert == tolower('y')) || (*convert == tolower('t')) || (*convert == '1'));
658 Values[Index].validation_function(Values[Index].tag, Values[Index].value, Values[Index].val);
665 for (int n = 0; n < 12; n++)
666 data[n] = new char[MAXBUF];
668 for (int Index = 0; MultiValues[Index].tag; Index++)
670 MultiValues[Index].init_function(MultiValues[Index].tag);
672 int number_of_tags = ConfValueEnum((char*)MultiValues[Index].tag, &this->config_f);
674 for (int tagnum = 0; tagnum < number_of_tags; tagnum++)
676 for (int valuenum = 0; MultiValues[Index].items[valuenum]; valuenum++)
678 ConfValue((char*)MultiValues[Index].tag,(char*)MultiValues[Index].items[valuenum], tagnum, data[valuenum], &this->config_f);
680 switch (MultiValues[Index].datatype[valuenum])
683 ptr[valuenum] = data[valuenum];
686 r_i[valuenum] = atoi(data[valuenum]);
687 ptr[valuenum] = &r_i[valuenum];
690 r_i[valuenum] = ((*data[valuenum] == tolower('y')) || (*data[valuenum] == tolower('t')) || (*data[valuenum] == '1'));
691 ptr[valuenum] = &r_i[valuenum];
697 MultiValues[Index].validation_function(MultiValues[Index].tag, (char**)MultiValues[Index].items, ptr, MultiValues[Index].datatype);
700 MultiValues[Index].finish_function(MultiValues[Index].tag);
703 for (int n = 0; n < 12; n++)
706 // write once here, to try it out and make sure its ok
707 WritePID(Config->PID);
709 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
712 log(DEFAULT,"Adding and removing modules due to rehash...");
714 int rem = 0, add = 0;
715 if (!removed_modules.empty())
716 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
718 if (ServerInstance->UnloadModule(removing->c_str()))
720 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
723 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
730 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
734 if (!added_modules.empty())
735 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
737 if (ServerInstance->LoadModule(adding->c_str()))
739 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
742 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
749 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
753 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());
758 void Exit (int status)
760 if (Config->log_file)
761 fclose(Config->log_file);
762 send_error("Server shutdown.");
766 void Killed(int status)
768 if (Config->log_file)
769 fclose(Config->log_file);
770 send_error("Server terminated.");
774 char* CleanFilename(char* name)
776 char* p = name + strlen(name);
777 while ((p != name) && (*p != '/')) p--;
778 return (p != name ? ++p : p);
782 void Rehash(int status)
784 WriteOpers("Rehashing config file %s due to SIGHUP",CleanFilename(CONFIG_FILE));
785 fclose(Config->log_file);
787 Config->Read(false,NULL);
788 FOREACH_MOD(I_OnRehash,OnRehash(""));
795 printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
796 printf("(C) ChatSpike Development team.\033[0m\n\n");
797 printf("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om\033[0m\n");
798 printf("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
799 printf("Name concept:\t\t\033[1;32mLord_Zathras\033[0m\n\n");
802 void WritePID(std::string filename)
804 ofstream outfile(filename.c_str());
805 if (outfile.is_open())
812 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
813 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
820 signal (SIGALRM, SIG_IGN);
821 signal (SIGHUP, Rehash);
822 signal (SIGPIPE, SIG_IGN);
823 signal (SIGTERM, Exit);
824 signal (SIGSEGV, Error);
828 int DaemonSeed (void)
831 if ((childpid = fork ()) < 0)
833 else if (childpid > 0)
835 /* We wait a few seconds here, so that the shell prompt doesnt come back over the output */
841 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
843 if (Config->unlimitcore)
846 if (getrlimit(RLIMIT_CORE, &rl) == -1)
848 log(DEFAULT,"Failed to getrlimit()!");
853 rl.rlim_cur = rl.rlim_max;
854 if (setrlimit(RLIMIT_CORE, &rl) == -1)
855 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
863 /* Make Sure Modules Are Avaliable!
864 * (BugFix By Craig.. See? I do work! :p)
865 * Modified by brain, requires const char*
866 * to work with other API functions
869 bool FileExists (const char* file)
872 if ((input = fopen (file, "r")) == NULL)
883 /* ConfProcess does the following things to a config line in the following order:
885 * Processes the line for syntax errors as shown below
886 * (1) Line void of quotes or equals (a malformed, illegal tag format)
887 * (2) Odd number of quotes on the line indicating a missing quote
888 * (3) number of equals signs not equal to number of quotes / 2 (missing an equals sign)
889 * (4) Spaces between the opening bracket (<) and the keyword
890 * (5) Spaces between a keyword and an equals sign
891 * (6) Spaces between an equals sign and a quote
892 * Removes trailing spaces
893 * Removes leading spaces
894 * Converts tabs to spaces
895 * Turns multiple spaces that are outside of quotes into single spaces
898 std::string ServerConfig::ConfProcess(char* buffer, long linenumber, std::stringstream* errorstream, bool &error, std::string filename)
900 long number_of_quotes = 0;
901 long number_of_equals = 0;
902 bool has_open_bracket = false;
903 bool in_quotes = false;
911 // firstly clean up the line by stripping spaces from the start and end and converting tabs to spaces
912 for (char* d = buffer; *d; d++)
915 while (*buffer == ' ') buffer++;
916 trailing = buffer + strlen(buffer) - 1;
917 while (*trailing == ' ') *trailing-- = '\0';
919 // empty lines are syntactically valid, as are comments
920 if (!(*buffer) || buffer[0] == '#')
923 for (char* c = buffer; *c; c++)
925 // convert all spaces that are OUTSIDE quotes into hardspace (0xA0) as this will make them easier to
926 // search and replace later :)
927 if ((!in_quotes) && (*c == ' '))
929 if ((*c == '<') && (!in_quotes))
931 has_open_bracket = true;
934 *errorstream << "Tag without identifier at " << filename << ":" << linenumber << endl;
938 else if ((tolower(*(c+1)) < 'a') || (tolower(*(c+1)) > 'z'))
940 *errorstream << "Invalid characters in identifier at " << filename << ":" << linenumber << endl;
948 in_quotes = (!in_quotes);
950 if ((*c == '=') && (!in_quotes))
955 *errorstream << "Variable without a value at " << filename << ":" << linenumber << endl;
959 else if (*(c+1) != '"')
961 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
965 else if (c == buffer)
967 *errorstream << "Value without a variable (line starts with '=') at " << filename << ":" << linenumber << endl;
971 else if (*(c-1) == '\xA0')
973 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
979 // no quotes, and no equals. something freaky.
980 if ((!number_of_quotes) || (!number_of_equals) && (strlen(buffer)>2) && (*buffer == '<'))
982 *errorstream << "Malformed tag at " << filename << ":" << linenumber << endl;
986 // odd number of quotes. thats just wrong.
987 if ((number_of_quotes % 2) != 0)
989 *errorstream << "Missing \" at " << filename << ":" << linenumber << endl;
993 if (number_of_equals < (number_of_quotes/2))
995 *errorstream << "Missing '=' at " << filename << ":" << linenumber << endl;
997 if (number_of_equals > (number_of_quotes/2))
999 *errorstream << "Too many '=' at " << filename << ":" << linenumber << endl;
1002 std::string parsedata = buffer;
1003 // turn multispace into single space
1004 while (parsedata.find("\xA0\xA0") != std::string::npos)
1006 parsedata.erase(parsedata.find("\xA0\xA0"),1);
1009 // turn our hardspace back into softspace
1010 for (unsigned int d = 0; d < parsedata.length(); d++)
1012 if (parsedata[d] == '\xA0')
1016 // and we're done, the line is fine!
1020 int ServerConfig::fgets_safe(char* buffer, size_t maxsize, FILE* &file)
1024 char* bufptr = buffer;
1025 while ((!feof(file)) && (c_read != '\n') && (c_read != '\r') && (n < maxsize))
1027 c_read = fgetc(file);
1028 if ((c_read != '\n') && (c_read != '\r'))
1035 return bufptr - buffer;
1038 bool ServerConfig::LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream)
1041 errorstream->str("");
1042 long linenumber = 1;
1043 // first, check that the file exists before we try to do anything with it
1044 if (!FileExists(filename))
1046 *errorstream << "File " << filename << " not found." << endl;
1049 // Fix the chmod of the file to restrict it to the current user and group
1050 chmod(filename,0600);
1051 for (unsigned int t = 0; t < include_stack.size(); t++)
1053 if (std::string(filename) == include_stack[t])
1055 *errorstream << "File " << filename << " is included recursively (looped inclusion)." << endl;
1059 include_stack.push_back(filename);
1061 FILE* conf = fopen(filename,"r");
1062 char buffer[MAXBUF];
1067 if (fgets_safe(buffer, MAXBUF, conf))
1069 if ((!feof(conf)) && (buffer) && (*buffer))
1071 if ((buffer[0] != '#') && (buffer[0] != '\r') && (buffer[0] != '\n'))
1073 if (!strncmp(buffer,"<include file=\"",15))
1076 char confpath[10240],newconf[10240];
1077 // include file directive
1078 buf += 15; // advance to filename
1079 for (char* j = buf; *j; j++)
1089 log(DEBUG,"Opening included file '%s'",buf);
1092 strlcpy(confpath,CONFIG_FILE,10240);
1093 if (strstr(confpath,"/inspircd.conf"))
1095 // leaves us with just the path
1096 *(strstr(confpath,"/inspircd.conf")) = '\0';
1098 snprintf(newconf,10240,"%s/%s",confpath,buf);
1100 else strlcpy(newconf,buf,10240);
1101 std::stringstream merge(stringstream::in | stringstream::out);
1102 // recursively call LoadConf and get the new data, use the same errorstream
1103 if (LoadConf(newconf, &merge, errorstream))
1105 // append to the end of the file
1106 std::string newstuff = merge.str();
1107 *target << newstuff;
1111 // the error propogates up to its parent recursively
1112 // causing the config reader to bail at the top level.
1120 std::string data = this->ConfProcess(buffer,linenumber++,errorstream,error,filename);
1138 /* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */
1140 int ServerConfig::EnumConf(std::stringstream *config, const char* tag)
1143 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
1144 int in_token, in_quotes, tptr, idx = 0;
1146 std::string x = config->str();
1147 const char* buf = x.c_str();
1148 char* bptr = (char*)buf;
1158 if ((c == '#') && (lastc == '\n'))
1160 while ((c != '\n') && (*bptr))
1166 if ((c == '<') && (!in_quotes))
1181 in_quotes = (!in_quotes);
1183 if ((c == '>') && (!in_quotes))
1186 if (!strcmp(c_tag,tag))
1188 /* correct tag, but wrong index */
1198 if ((in_token) && (c != '\n') && (c != '\r'))
1208 /* Counts the number of values within a certain tag */
1210 int ServerConfig::EnumValues(std::stringstream *config, const char* tag, int index)
1213 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
1214 int in_token, in_quotes, tptr, idx = 0;
1215 bool correct_tag = false;
1217 const char* buf = config->str().c_str();
1218 char* bptr = (char*)buf;
1229 if ((c == '#') && (lastc == '\n'))
1231 while ((c != '\n') && (*bptr))
1237 if ((c == '<') && (!in_quotes))
1248 if ((!strcmp(c_tag,tag)) && (idx == index))
1257 in_quotes = (!in_quotes);
1260 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
1264 if ((c == '>') && (!in_quotes))
1268 correct_tag = false;
1269 if (!strcmp(c_tag,tag))
1271 /* correct tag, but wrong index */
1281 if ((in_token) && (c != '\n') && (c != '\r'))
1292 int ServerConfig::ConfValueEnum(char* tag, std::stringstream* config)
1294 return EnumConf(config,tag);
1298 int ServerConfig::ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
1301 char buffer[65535], c_tag[MAXBUF], c, lastc;
1302 int in_token, in_quotes, tptr, idx = 0;
1304 std::string x = config->str();
1305 const char* buf = x.c_str();
1306 char* bptr = (char*)buf;
1319 // FIX: Treat tabs as spaces
1322 if ((c == '<') && (!in_quotes))
1333 // FIX: Tab can follow a tagname as well as space.
1334 } while ((c != ' ') && (c != 9));
1338 in_quotes = (!in_quotes);
1340 if ((c == '>') && (!in_quotes))
1345 if (!strcmp(c_tag,tag))
1347 if ((buffer) && (c_tag) && (var))
1349 key = strstr(buffer,var);
1352 /* value not found in tag */
1370 for (char* j = key; *j; j++)
1378 strlcpy(result,key,MAXBUF);
1384 if (!strcmp(c_tag,tag))
1386 /* correct tag, but wrong index */
1396 if ((in_token) && (c != '\n') && (c != '\r'))
1403 *result = 0; // value or its tag not found at all
1409 int ServerConfig::ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
1411 ReadConf(config, tag, var, index, result);
1415 int ServerConfig::ConfValueInteger(char* tag, char* var, int index, std::stringstream *config)
1417 char result[MAXBUF];
1418 ReadConf(config, tag, var, index, result);
1419 return atoi(result);
1422 // This will bind a socket to a port. It works for UDP/TCP
1423 int BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
1425 memset((char *)&server,0,sizeof(server));
1426 struct in_addr addy;
1427 bool resolved = false;
1428 char resolved_addr[128];
1433 if (*addr && !inet_aton(addr,&addy))
1435 /* If they gave a hostname, bind to the IP it resolves to */
1436 if (CleanAndResolve(resolved_addr, addr, true))
1438 inet_aton(resolved_addr,&addy);
1439 log(DEFAULT,"Resolved binding '%s' -> '%s'",addr,resolved_addr);
1440 server.sin_addr = addy;
1445 log(DEFAULT,"WARNING: Could not resolve '%s' to an IP for binding to on port %d",addr,port);
1449 server.sin_family = AF_INET;
1454 server.sin_addr.s_addr = htonl(INADDR_ANY);
1458 server.sin_addr = addy;
1461 server.sin_port = htons(port);
1462 if (bind(sockfd,(struct sockaddr*)&server,sizeof(server)) < 0)
1468 log(DEBUG,"Bound port %s:%d",*addr ? addr : "*",port);
1469 if (listen(sockfd, Config->MaxConn) == -1)
1471 log(DEFAULT,"ERROR in listen(): %s",strerror(errno));
1482 // Open a TCP Socket
1483 int OpenTCPSocket (void)
1487 struct linger linger = { 0 };
1489 if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
1493 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
1494 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
1496 linger.l_linger = 1;
1497 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));
1504 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
1505 sockaddr_in client,server;
1506 int clientportcount = 0;
1507 int BoundPortCount = 0;
1509 for (int count = 0; count < Config->ConfValueEnum("bind",&Config->config_f); count++)
1511 Config->ConfValue("bind","port",count,configToken,&Config->config_f);
1512 Config->ConfValue("bind","address",count,Addr,&Config->config_f);
1513 Config->ConfValue("bind","type",count,Type,&Config->config_f);
1515 if ((!*Type) || (!strcmp(Type,"clients")))
1517 // modules handle server bind types now
1518 Config->ports[clientportcount] = atoi(configToken);
1520 // If the client put bind "*", this is an unrealism.
1521 // We don't actually support this as documented, but
1522 // i got fed up of people trying it, so now it converts
1523 // it to an empty string meaning the same 'bind to all'.
1527 strlcpy(Config->addrs[clientportcount],Addr,256);
1529 log(DEBUG,"InspIRCd: startup: read binding %s:%s [%s] from config",Addr,configToken, Type);
1533 int PortCount = clientportcount;
1535 for (int count = 0; count < PortCount; count++)
1537 if ((openSockfd[BoundPortCount] = OpenTCPSocket()) == ERROR)
1539 log(DEBUG,"InspIRCd: startup: bad fd %lu binding port [%s:%d]",(unsigned long)openSockfd[BoundPortCount],Config->addrs[count],(unsigned long)Config->ports[count]);
1543 if (BindSocket(openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]) == ERROR)
1545 log(DEFAULT,"InspIRCd: startup: failed to bind port [%s:%lu]: %s",Config->addrs[count],(unsigned long)Config->ports[count],strerror(errno));
1549 /* well we at least bound to one socket so we'll continue */
1554 /* if we didn't bind to anything then abort */
1555 if (!BoundPortCount)
1557 log(DEFAULT,"InspIRCd: startup: no ports bound, bailing!");
1558 printf("\nERROR: Was not able to bind any of %lu ports! Please check your configuration.\n\n", (unsigned long)PortCount);
1562 return BoundPortCount;