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[MAX_DESCRIPTORS];
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 OperSpyWhois = 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 /* Callback called before processing the first <connect> tag
323 bool InitConnect(const char* tag)
325 log(DEFAULT,"Reading connect classes...");
326 Config->Classes.clear();
330 /* Callback called to process a single <connect> tag
332 bool DoConnect(const char* tag, char** entries, void** values, int* types)
335 char* allow = (char*)values[0]; /* Yeah, there are a lot of values. Live with it. */
336 char* deny = (char*)values[1];
337 char* password = (char*)values[2];
338 int* timeout = (int*)values[3];
339 int* pingfreq = (int*)values[4];
340 int* flood = (int*)values[5];
341 int* threshold = (int*)values[6];
342 int* sendq = (int*)values[7];
343 int* recvq = (int*)values[8];
344 int* localmax = (int*)values[9];
345 int* globalmax = (int*)values[10];
352 c.registration_timeout = *timeout;
353 c.pingtime = *pingfreq;
355 c.threshold = *threshold;
358 c.maxlocal = *localmax;
359 c.maxglobal = *globalmax;
364 if (c.maxglobal == 0)
366 if (c.threshold == 0)
370 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());
376 if (c.registration_timeout == 0)
377 c.registration_timeout = 90;
380 Config->Classes.push_back(c);
386 Config->Classes.push_back(c);
387 log(DEBUG,"Read connect class type DENY, host=%s",deny);
393 /* Callback called when there are no more <connect> tags
395 bool DoneConnect(const char* tag)
397 log(DEBUG,"DoneConnect called for tag: %s",tag);
401 /* Callback called before processing the first <uline> tag
403 bool InitULine(const char* tag)
405 Config->ulines.clear();
409 /* Callback called to process a single <uline> tag
411 bool DoULine(const char* tag, char** entries, void** values, int* types)
413 char* server = (char*)values[0];
414 log(DEBUG,"Read ULINE '%s'",server);
415 Config->ulines.push_back(server);
419 /* Callback called when there are no more <uline> tags
421 bool DoneULine(const char* tag)
426 /* Callback called before processing the first <module> tag
428 bool InitModule(const char* tag)
430 old_module_names.clear();
431 new_module_names.clear();
432 added_modules.clear();
433 removed_modules.clear();
434 for (std::vector<std::string>::iterator t = Config->module_names.begin(); t != Config->module_names.end(); t++)
436 old_module_names.push_back(*t);
441 /* Callback called to process a single <module> tag
443 bool DoModule(const char* tag, char** entries, void** values, int* types)
445 char* modname = (char*)values[0];
446 new_module_names.push_back(modname);
450 /* Callback called when there are no more <module> tags
452 bool DoneModule(const char* tag)
454 // now create a list of new modules that are due to be loaded
455 // and a seperate list of modules which are due to be unloaded
456 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
460 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
467 added_modules.push_back(*_new);
470 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
473 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
480 removed_modules.push_back(*oldm);
485 /* Callback called before processing the first <banlist> tag
487 bool InitMaxBans(const char* tag)
489 Config->maxbans.clear();
493 /* Callback called to process a single <banlist> tag
495 bool DoMaxBans(const char* tag, char** entries, void** values, int* types)
497 char* channel = (char*)values[0];
498 int* limit = (int*)values[1];
499 Config->maxbans[channel] = *limit;
503 /* Callback called when there are no more <banlist> tags.
505 bool DoneMaxBans(const char* tag)
510 void ServerConfig::Read(bool bail, userrec* user)
512 char debug[MAXBUF]; /* Temporary buffer for debugging value */
513 char dataline[1024]; /* Temporary buffer for error output */
514 char* convert; /* Temporary buffer used for reading singular values into */
515 char* data[12]; /* Temporary buffers for reading multiple occurance tags into */
516 void* ptr[12]; /* Temporary pointers for passing to callbacks */
517 int r_i[12]; /* Temporary array for casting */
518 int rem = 0, add = 0; /* Number of modules added, number of modules removed */
519 std::stringstream errstr; /* String stream containing the error output */
521 /* These tags MUST occur and must ONLY occur once in the config file */
522 static char* Once[] = { "server", "admin", "files", "power", "options", "pid", NULL };
524 /* These tags can occur ONCE or not at all */
525 static InitialConfig Values[] = {
526 {"options", "softlimit", &this->SoftLimit, DT_INTEGER, ValidateSoftLimit},
527 {"options", "somaxconn", &this->MaxConn, DT_INTEGER, ValidateMaxConn},
528 {"server", "name", &this->ServerName, DT_CHARPTR, ValidateServerName},
529 {"server", "description", &this->ServerDesc, DT_CHARPTR, NoValidation},
530 {"server", "network", &this->Network, DT_CHARPTR, NoValidation},
531 {"admin", "name", &this->AdminName, DT_CHARPTR, NoValidation},
532 {"admin", "email", &this->AdminEmail, DT_CHARPTR, NoValidation},
533 {"admin", "nick", &this->AdminNick, DT_CHARPTR, NoValidation},
534 {"files", "motd", &this->motd, DT_CHARPTR, ValidateMotd},
535 {"files", "rules", &this->rules, DT_CHARPTR, ValidateRules},
536 {"power", "diepass", &this->diepass, DT_CHARPTR, NoValidation},
537 {"power", "pauseval", &this->DieDelay, DT_INTEGER, NoValidation},
538 {"power", "restartpass", &this->restartpass, DT_CHARPTR, NoValidation},
539 {"options", "prefixquit", &this->PrefixQuit, DT_CHARPTR, NoValidation},
540 {"die", "value", &this->DieValue, DT_CHARPTR, NoValidation},
541 {"options", "loglevel", &debug, DT_CHARPTR, ValidateLogLevel},
542 {"options", "netbuffersize", &this->NetBufferSize, DT_INTEGER, ValidateNetBufferSize},
543 {"options", "maxwho", &this->MaxWhoResults, DT_INTEGER, ValidateMaxWho},
544 {"options", "allowhalfop", &this->AllowHalfop, DT_BOOLEAN, NoValidation},
545 {"dns", "server", &this->DNSServer, DT_CHARPTR, ValidateDnsServer},
546 {"dns", "timeout", &this->dns_timeout, DT_INTEGER, ValidateDnsTimeout},
547 {"options", "moduledir", &this->ModPath, DT_CHARPTR, ValidateModPath},
548 {"disabled", "commands", &this->DisabledCommands,DT_CHARPTR, NoValidation},
549 {"options", "operonlystats", &this->OperOnlyStats, DT_CHARPTR, NoValidation},
550 {"options", "customversion", &this->CustomVersion, DT_CHARPTR, NoValidation},
551 {"options", "hidesplits", &this->HideSplits, DT_BOOLEAN, NoValidation},
552 {"options", "hidebans", &this->HideBans, DT_BOOLEAN, NoValidation},
553 {"options", "hidewhois", &this->HideWhoisServer, DT_CHARPTR, NoValidation},
554 {"options", "operspywhois", &this->OperSpyWhois, DT_BOOLEAN, NoValidation},
555 {"options", "tempdir", &this->TempDir, DT_CHARPTR, ValidateTempDir},
556 {"pid", "file", &this->PID, DT_CHARPTR, NoValidation},
560 /* These tags can occur multiple times, and therefore they have special code to read them
561 * which is different to the code for reading the singular tags listed above.
563 static MultiConfig MultiValues[] = {
566 {"allow", "deny", "password", "timeout", "pingfreq", "flood",
567 "threshold", "sendq", "recvq", "localmax", "globalmax", NULL},
568 {DT_CHARPTR, DT_CHARPTR, DT_CHARPTR, DT_INTEGER, DT_INTEGER, DT_INTEGER,
569 DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER},
570 InitConnect, DoConnect, DoneConnect},
575 InitULine,DoULine,DoneULine},
578 {"chan", "limit", NULL},
579 {DT_CHARPTR, DT_INTEGER},
580 InitMaxBans, DoMaxBans, DoneMaxBans},
585 InitModule, DoModule, DoneModule},
588 {"reason", "ipmask", NULL},
589 {DT_CHARPTR, DT_CHARPTR},
590 InitXLine, DoZLine, DoneXLine},
593 {"reason", "nick", NULL},
594 {DT_CHARPTR, DT_CHARPTR},
595 InitXLine, DoQLine, DoneXLine},
598 {"reason", "host", NULL},
599 {DT_CHARPTR, DT_CHARPTR},
600 InitXLine, DoKLine, DoneXLine},
603 {"reason", "host", NULL},
604 {DT_CHARPTR, DT_CHARPTR},
605 InitXLine, DoELine, DoneXLine},
608 {"name", "classes", NULL},
609 {DT_CHARPTR, DT_CHARPTR},
610 InitTypes, DoType, DoneClassesAndTypes},
613 {"name", "commands", NULL},
614 {DT_CHARPTR, DT_CHARPTR},
615 InitClasses, DoClass, DoneClassesAndTypes},
620 include_stack.clear();
622 /* Initially, load the config into memory, bail if there are errors
624 if (!LoadConf(CONFIG_FILE,&Config->config_f,&errstr))
627 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
631 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
638 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
639 while (!errstr.eof())
641 errstr.getline(dataline,1024);
642 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
647 WriteOpers("There were errors in the configuration file:");
648 while (!errstr.eof())
650 errstr.getline(dataline,1024);
651 WriteOpers(dataline);
659 /* Check we dont have more than one of singular tags, or any of them missing
661 for (int Index = 0; Once[Index]; Index++)
662 if (!CheckOnce(Once[Index],bail,user))
665 /* Read the values of all the tags which occur once or not at all, and call their callbacks.
667 for (int Index = 0; Values[Index].tag; Index++)
669 int* val_i = (int*) Values[Index].val;
670 char* val_c = (char*) Values[Index].val;
672 switch (Values[Index].datatype)
675 ConfValue(Values[Index].tag, Values[Index].value, 0, val_c, &this->config_f);
679 convert = new char[MAXBUF];
680 ConfValue(Values[Index].tag, Values[Index].value, 0, convert, &this->config_f);
681 *val_i = atoi(convert);
686 convert = new char[MAXBUF];
687 ConfValue(Values[Index].tag, Values[Index].value, 0, convert, &this->config_f);
688 *val_i = ((*convert == tolower('y')) || (*convert == tolower('t')) || (*convert == '1'));
696 Values[Index].validation_function(Values[Index].tag, Values[Index].value, Values[Index].val);
699 /* Claim memory for use when reading multiple tags
701 for (int n = 0; n < 12; n++)
702 data[n] = new char[MAXBUF];
704 /* Read the multiple-tag items (class tags, connect tags, etc)
705 * and call the callbacks associated with them. We have three
706 * callbacks for these, a 'start', 'item' and 'end' callback.
708 for (int Index = 0; MultiValues[Index].tag; Index++)
710 MultiValues[Index].init_function(MultiValues[Index].tag);
712 int number_of_tags = ConfValueEnum((char*)MultiValues[Index].tag, &this->config_f);
714 for (int tagnum = 0; tagnum < number_of_tags; tagnum++)
716 for (int valuenum = 0; MultiValues[Index].items[valuenum]; valuenum++)
718 ConfValue((char*)MultiValues[Index].tag,(char*)MultiValues[Index].items[valuenum], tagnum, data[valuenum], &this->config_f);
720 switch (MultiValues[Index].datatype[valuenum])
723 ptr[valuenum] = data[valuenum];
726 r_i[valuenum] = atoi(data[valuenum]);
727 ptr[valuenum] = &r_i[valuenum];
730 r_i[valuenum] = ((*data[valuenum] == tolower('y')) || (*data[valuenum] == tolower('t')) || (*data[valuenum] == '1'));
731 ptr[valuenum] = &r_i[valuenum];
737 MultiValues[Index].validation_function(MultiValues[Index].tag, (char**)MultiValues[Index].items, ptr, MultiValues[Index].datatype);
740 MultiValues[Index].finish_function(MultiValues[Index].tag);
743 /* Free any memory we claimed
745 for (int n = 0; n < 12; n++)
748 // write once here, to try it out and make sure its ok
749 WritePID(Config->PID);
751 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
753 /* If we're rehashing, let's load any new modules, and unload old ones
757 ServerInstance->stats->BoundPortCount = BindPorts(false);
759 if (!removed_modules.empty())
760 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
762 if (ServerInstance->UnloadModule(removing->c_str()))
764 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
767 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
774 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
778 if (!added_modules.empty())
779 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
781 if (ServerInstance->LoadModule(adding->c_str()))
783 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
786 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
793 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
797 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());
801 void Exit(int status)
803 if (Config->log_file)
804 fclose(Config->log_file);
805 send_error("Server shutdown.");
809 void Killed(int status)
811 if (Config->log_file)
812 fclose(Config->log_file);
813 send_error("Server terminated.");
817 char* CleanFilename(char* name)
819 char* p = name + strlen(name);
820 while ((p != name) && (*p != '/')) p--;
821 return (p != name ? ++p : p);
825 void Rehash(int status)
827 WriteOpers("Rehashing config file %s due to SIGHUP",CleanFilename(CONFIG_FILE));
828 fclose(Config->log_file);
830 Config->Read(false,NULL);
831 FOREACH_MOD(I_OnRehash,OnRehash(""));
838 printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
839 printf("(C) ChatSpike Development team.\033[0m\n\n");
840 printf("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om\033[0m\n");
841 printf("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
842 printf("Name concept:\t\t\033[1;32mLord_Zathras\033[0m\n\n");
845 void WritePID(const std::string &filename)
847 ofstream outfile(filename.c_str());
848 if (outfile.is_open())
855 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
856 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
863 signal (SIGALRM, SIG_IGN);
864 signal (SIGHUP, Rehash);
865 signal (SIGPIPE, SIG_IGN);
866 signal (SIGTERM, Exit);
867 signal (SIGSEGV, Error);
874 if ((childpid = fork ()) < 0)
876 else if (childpid > 0)
878 /* We wait a few seconds here, so that the shell prompt doesnt come back over the output */
884 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
886 if (Config->unlimitcore)
889 if (getrlimit(RLIMIT_CORE, &rl) == -1)
891 log(DEFAULT,"Failed to getrlimit()!");
896 rl.rlim_cur = rl.rlim_max;
897 if (setrlimit(RLIMIT_CORE, &rl) == -1)
898 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
906 /* Make Sure Modules Are Avaliable!
907 * (BugFix By Craig.. See? I do work! :p)
908 * Modified by brain, requires const char*
909 * to work with other API functions
912 bool FileExists (const char* file)
915 if ((input = fopen (file, "r")) == NULL)
926 /* ConfProcess does the following things to a config line in the following order:
928 * Processes the line for syntax errors as shown below
929 * (1) Line void of quotes or equals (a malformed, illegal tag format)
930 * (2) Odd number of quotes on the line indicating a missing quote
931 * (3) number of equals signs not equal to number of quotes / 2 (missing an equals sign)
932 * (4) Spaces between the opening bracket (<) and the keyword
933 * (5) Spaces between a keyword and an equals sign
934 * (6) Spaces between an equals sign and a quote
935 * Removes trailing spaces
936 * Removes leading spaces
937 * Converts tabs to spaces
938 * Turns multiple spaces that are outside of quotes into single spaces
941 std::string ServerConfig::ConfProcess(char* buffer, long linenumber, std::stringstream* errorstream, bool &error, std::string filename)
943 long number_of_quotes = 0;
944 long number_of_equals = 0;
945 bool has_open_bracket = false;
946 bool in_quotes = false;
954 // firstly clean up the line by stripping spaces from the start and end and converting tabs to spaces
955 for (char* d = buffer; *d; d++)
958 while (*buffer == ' ') buffer++;
959 trailing = buffer + strlen(buffer) - 1;
960 while (*trailing == ' ') *trailing-- = '\0';
962 // empty lines are syntactically valid, as are comments
963 if (!(*buffer) || buffer[0] == '#')
966 for (char* c = buffer; *c; c++)
968 // convert all spaces that are OUTSIDE quotes into hardspace (0xA0) as this will make them easier to
969 // search and replace later :)
970 if ((!in_quotes) && (*c == ' '))
972 if ((*c == '<') && (!in_quotes))
974 has_open_bracket = true;
977 *errorstream << "Tag without identifier at " << filename << ":" << linenumber << endl;
981 else if ((tolower(*(c+1)) < 'a') || (tolower(*(c+1)) > 'z'))
983 *errorstream << "Invalid characters in identifier at " << filename << ":" << linenumber << endl;
991 in_quotes = (!in_quotes);
993 if ((*c == '=') && (!in_quotes))
998 *errorstream << "Variable without a value at " << filename << ":" << linenumber << endl;
1002 else if (*(c+1) != '"')
1004 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
1008 else if (c == buffer)
1010 *errorstream << "Value without a variable (line starts with '=') at " << filename << ":" << linenumber << endl;
1014 else if (*(c-1) == '\xA0')
1016 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
1022 // no quotes, and no equals. something freaky.
1023 if ((!number_of_quotes) || (!number_of_equals) && (strlen(buffer)>2) && (*buffer == '<'))
1025 *errorstream << "Malformed tag at " << filename << ":" << linenumber << endl;
1029 // odd number of quotes. thats just wrong.
1030 if ((number_of_quotes % 2) != 0)
1032 *errorstream << "Missing \" at " << filename << ":" << linenumber << endl;
1036 if (number_of_equals < (number_of_quotes/2))
1038 *errorstream << "Missing '=' at " << filename << ":" << linenumber << endl;
1040 if (number_of_equals > (number_of_quotes/2))
1042 *errorstream << "Too many '=' at " << filename << ":" << linenumber << endl;
1045 std::string parsedata = buffer;
1046 // turn multispace into single space
1047 while (parsedata.find("\xA0\xA0") != std::string::npos)
1049 parsedata.erase(parsedata.find("\xA0\xA0"),1);
1052 // turn our hardspace back into softspace
1053 for (unsigned int d = 0; d < parsedata.length(); d++)
1055 if (parsedata[d] == '\xA0')
1059 // and we're done, the line is fine!
1063 int ServerConfig::fgets_safe(char* buffer, size_t maxsize, FILE* &file)
1067 char* bufptr = buffer;
1068 while ((!feof(file)) && (c_read != '\n') && (c_read != '\r') && (n < maxsize))
1070 c_read = fgetc(file);
1071 if ((c_read != '\n') && (c_read != '\r'))
1078 return bufptr - buffer;
1081 bool ServerConfig::LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream)
1084 errorstream->str("");
1085 long linenumber = 1;
1086 // first, check that the file exists before we try to do anything with it
1087 if (!FileExists(filename))
1089 *errorstream << "File " << filename << " not found." << endl;
1092 // Fix the chmod of the file to restrict it to the current user and group
1093 chmod(filename,0600);
1094 for (unsigned int t = 0; t < include_stack.size(); t++)
1096 if (std::string(filename) == include_stack[t])
1098 *errorstream << "File " << filename << " is included recursively (looped inclusion)." << endl;
1102 include_stack.push_back(filename);
1104 FILE* conf = fopen(filename,"r");
1105 char buffer[MAXBUF];
1110 if (fgets_safe(buffer, MAXBUF, conf))
1112 if ((!feof(conf)) && (buffer) && (*buffer))
1114 if ((buffer[0] != '#') && (buffer[0] != '\r') && (buffer[0] != '\n'))
1116 if (!strncmp(buffer,"<include file=\"",15))
1119 char confpath[10240],newconf[10240];
1120 // include file directive
1121 buf += 15; // advance to filename
1122 for (char* j = buf; *j; j++)
1132 log(DEBUG,"Opening included file '%s'",buf);
1135 strlcpy(confpath,CONFIG_FILE,10240);
1136 if (strstr(confpath,"/inspircd.conf"))
1138 // leaves us with just the path
1139 *(strstr(confpath,"/inspircd.conf")) = '\0';
1141 snprintf(newconf,10240,"%s/%s",confpath,buf);
1143 else strlcpy(newconf,buf,10240);
1144 std::stringstream merge(stringstream::in | stringstream::out);
1145 // recursively call LoadConf and get the new data, use the same errorstream
1146 if (LoadConf(newconf, &merge, errorstream))
1148 // append to the end of the file
1149 std::string newstuff = merge.str();
1150 *target << newstuff;
1154 // the error propogates up to its parent recursively
1155 // causing the config reader to bail at the top level.
1163 std::string data = this->ConfProcess(buffer,linenumber++,errorstream,error,filename);
1181 /* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */
1183 int ServerConfig::EnumConf(std::stringstream *config, const char* tag)
1186 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
1187 int in_token, in_quotes, tptr, idx = 0;
1189 std::string x = config->str();
1190 const char* buf = x.c_str();
1191 char* bptr = (char*)buf;
1201 if ((c == '#') && (lastc == '\n'))
1203 while ((c != '\n') && (*bptr))
1209 if ((c == '<') && (!in_quotes))
1224 in_quotes = (!in_quotes);
1226 if ((c == '>') && (!in_quotes))
1229 if (!strcmp(c_tag,tag))
1231 /* correct tag, but wrong index */
1241 if ((in_token) && (c != '\n') && (c != '\r'))
1251 /* Counts the number of values within a certain tag */
1253 int ServerConfig::EnumValues(std::stringstream *config, const char* tag, int index)
1256 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
1257 int in_token, in_quotes, tptr, idx = 0;
1258 bool correct_tag = false;
1260 const char* buf = config->str().c_str();
1261 char* bptr = (char*)buf;
1272 if ((c == '#') && (lastc == '\n'))
1274 while ((c != '\n') && (*bptr))
1280 if ((c == '<') && (!in_quotes))
1291 if ((!strcmp(c_tag,tag)) && (idx == index))
1300 in_quotes = (!in_quotes);
1303 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
1307 if ((c == '>') && (!in_quotes))
1311 correct_tag = false;
1312 if (!strcmp(c_tag,tag))
1314 /* correct tag, but wrong index */
1324 if ((in_token) && (c != '\n') && (c != '\r'))
1335 int ServerConfig::ConfValueEnum(char* tag, std::stringstream* config)
1337 return EnumConf(config,tag);
1341 int ServerConfig::ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
1344 char buffer[65535], c_tag[MAXBUF], c, lastc;
1345 int in_token, in_quotes, tptr, idx = 0;
1347 std::string x = config->str();
1348 const char* buf = x.c_str();
1349 char* bptr = (char*)buf;
1362 // FIX: Treat tabs as spaces
1365 if ((c == '<') && (!in_quotes))
1376 // FIX: Tab can follow a tagname as well as space.
1377 } while ((c != ' ') && (c != 9));
1381 in_quotes = (!in_quotes);
1383 if ((c == '>') && (!in_quotes))
1388 if (!strcmp(c_tag,tag))
1390 if ((buffer) && (c_tag) && (var))
1392 key = strstr(buffer,var);
1395 /* value not found in tag */
1413 for (char* j = key; *j; j++)
1421 strlcpy(result,key,MAXBUF);
1427 if (!strcmp(c_tag,tag))
1429 /* correct tag, but wrong index */
1439 if ((in_token) && (c != '\n') && (c != '\r'))
1446 *result = 0; // value or its tag not found at all
1452 int ServerConfig::ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
1454 ReadConf(config, tag, var, index, result);
1458 int ServerConfig::ConfValueInteger(char* tag, char* var, int index, std::stringstream *config)
1460 char result[MAXBUF];
1461 ReadConf(config, tag, var, index, result);
1462 return atoi(result);
1465 /** This will bind a socket to a port. It works for UDP/TCP.
1466 * If a hostname is given to bind to, the function will first
1467 * attempt to resolve the hostname, then bind to the IP the
1468 * hostname resolves to. This is a blocking lookup blocking for
1469 * a maximum of one second before it times out, using the DNS
1470 * server specified in the configuration file.
1472 bool BindSocket(int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
1474 memset((char *)&server,0,sizeof(server));
1475 struct in_addr addy;
1476 bool resolved = false;
1477 char resolved_addr[128];
1482 if (*addr && !inet_aton(addr,&addy))
1484 /* If they gave a hostname, bind to the IP it resolves to */
1485 if (CleanAndResolve(resolved_addr, addr, true))
1487 inet_aton(resolved_addr,&addy);
1488 log(DEFAULT,"Resolved binding '%s' -> '%s'",addr,resolved_addr);
1489 server.sin_addr = addy;
1494 log(DEFAULT,"WARNING: Could not resolve '%s' to an IP for binding to on port %d",addr,port);
1498 server.sin_family = AF_INET;
1503 server.sin_addr.s_addr = htonl(INADDR_ANY);
1507 server.sin_addr = addy;
1510 server.sin_port = htons(port);
1511 if (bind(sockfd,(struct sockaddr*)&server,sizeof(server)) < 0)
1517 log(DEBUG,"Bound port %s:%d",*addr ? addr : "*",port);
1518 if (listen(sockfd, Config->MaxConn) == -1)
1520 log(DEFAULT,"ERROR in listen(): %s",strerror(errno));
1525 NonBlocking(sockfd);
1532 // Open a TCP Socket
1537 struct linger linger = { 0 };
1539 if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
1541 log(DEFAULT,"Error creating TCP socket: %s",strerror(errno));
1546 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
1547 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
1549 linger.l_linger = 1;
1550 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));
1555 bool HasPort(int port, char* addr)
1557 for (int count = 0; count < ServerInstance->stats->BoundPortCount; count++)
1559 if ((port == Config->ports[count]) && (!strcasecmp(Config->addrs[count],addr)))
1567 int BindPorts(bool bail)
1569 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
1570 sockaddr_in client,server;
1571 int clientportcount = 0;
1572 int BoundPortCount = 0;
1576 int InitialPortCount = ServerInstance->stats->BoundPortCount;
1577 log(DEBUG,"Initial port count: %d",InitialPortCount);
1579 for (int count = 0; count < Config->ConfValueEnum("bind",&Config->config_f); count++)
1581 Config->ConfValue("bind","port",count,configToken,&Config->config_f);
1582 Config->ConfValue("bind","address",count,Addr,&Config->config_f);
1583 Config->ConfValue("bind","type",count,Type,&Config->config_f);
1584 if (((!*Type) || (!strcmp(Type,"clients"))) && (!HasPort(atoi(configToken),Addr)))
1586 // modules handle server bind types now
1587 Config->ports[clientportcount+InitialPortCount] = atoi(configToken);
1591 strlcpy(Config->addrs[clientportcount+InitialPortCount],Addr,256);
1593 log(DEBUG,"NEW binding %s:%s [%s] from config",Addr,configToken, Type);
1596 int PortCount = clientportcount;
1599 for (int count = InitialPortCount; count < InitialPortCount + PortCount; count++)
1601 if ((openSockfd[count] = OpenTCPSocket()) == ERROR)
1603 log(DEBUG,"Bad fd %d binding port [%s:%d]",openSockfd[count],Config->addrs[count],Config->ports[count]);
1606 if (!BindSocket(openSockfd[count],client,server,Config->ports[count],Config->addrs[count]))
1608 log(DEFAULT,"Failed to bind port [%s:%d]: %s",Config->addrs[count],Config->ports[count],strerror(errno));
1612 /* Associate the new open port with a slot in the socket engine */
1613 ServerInstance->SE->AddFd(openSockfd[count],true,X_LISTEN);
1617 return InitialPortCount + BoundPortCount;
1621 log(DEBUG,"There is nothing new to bind!");
1623 return InitialPortCount;
1626 for (int count = 0; count < Config->ConfValueEnum("bind",&Config->config_f); count++)
1628 Config->ConfValue("bind","port",count,configToken,&Config->config_f);
1629 Config->ConfValue("bind","address",count,Addr,&Config->config_f);
1630 Config->ConfValue("bind","type",count,Type,&Config->config_f);
1632 if ((!*Type) || (!strcmp(Type,"clients")))
1634 // modules handle server bind types now
1635 Config->ports[clientportcount] = atoi(configToken);
1637 // If the client put bind "*", this is an unrealism.
1638 // We don't actually support this as documented, but
1639 // i got fed up of people trying it, so now it converts
1640 // it to an empty string meaning the same 'bind to all'.
1644 strlcpy(Config->addrs[clientportcount],Addr,256);
1646 log(DEBUG,"Binding %s:%s [%s] from config",Addr,configToken, Type);
1650 int PortCount = clientportcount;
1652 for (int count = 0; count < PortCount; count++)
1654 if ((openSockfd[BoundPortCount] = OpenTCPSocket()) == ERROR)
1656 log(DEBUG,"Bad fd %d binding port [%s:%d]",openSockfd[BoundPortCount],Config->addrs[count],Config->ports[count]);
1660 if (!BindSocket(openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]))
1662 log(DEFAULT,"Failed to bind port [%s:%d]: %s",Config->addrs[count],Config->ports[count],strerror(errno));
1666 /* well we at least bound to one socket so we'll continue */
1671 /* if we didn't bind to anything then abort */
1672 if (!BoundPortCount)
1674 log(DEFAULT,"No ports bound, bailing!");
1675 printf("\nERROR: Could not bind any of %d ports! Please check your configuration.\n\n", PortCount);
1679 return BoundPortCount;