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 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", "tempdir", &this->TempDir, DT_CHARPTR, ValidateTempDir},
555 {"pid", "file", &this->PID, DT_CHARPTR, NoValidation},
559 /* These tags can occur multiple times, and therefore they have special code to read them
560 * which is different to the code for reading the singular tags listed above.
562 static MultiConfig MultiValues[] = {
565 {"allow", "deny", "password", "timeout", "pingfreq", "flood",
566 "threshold", "sendq", "recvq", "localmax", "globalmax", NULL},
567 {DT_CHARPTR, DT_CHARPTR, DT_CHARPTR, DT_INTEGER, DT_INTEGER, DT_INTEGER,
568 DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER},
569 InitConnect, DoConnect, DoneConnect},
574 InitULine,DoULine,DoneULine},
577 {"chan", "limit", NULL},
578 {DT_CHARPTR, DT_INTEGER},
579 InitMaxBans, DoMaxBans, DoneMaxBans},
584 InitModule, DoModule, DoneModule},
587 {"reason", "ipmask", NULL},
588 {DT_CHARPTR, DT_CHARPTR},
589 InitXLine, DoZLine, DoneXLine},
592 {"reason", "nick", NULL},
593 {DT_CHARPTR, DT_CHARPTR},
594 InitXLine, DoQLine, DoneXLine},
597 {"reason", "host", NULL},
598 {DT_CHARPTR, DT_CHARPTR},
599 InitXLine, DoKLine, DoneXLine},
602 {"reason", "host", NULL},
603 {DT_CHARPTR, DT_CHARPTR},
604 InitXLine, DoELine, DoneXLine},
607 {"name", "classes", NULL},
608 {DT_CHARPTR, DT_CHARPTR},
609 InitTypes, DoType, DoneClassesAndTypes},
612 {"name", "commands", NULL},
613 {DT_CHARPTR, DT_CHARPTR},
614 InitClasses, DoClass, DoneClassesAndTypes},
619 include_stack.clear();
621 /* Initially, load the config into memory, bail if there are errors
623 if (!LoadConf(CONFIG_FILE,&Config->config_f,&errstr))
626 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
630 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
637 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
638 while (!errstr.eof())
640 errstr.getline(dataline,1024);
641 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
646 WriteOpers("There were errors in the configuration file:");
647 while (!errstr.eof())
649 errstr.getline(dataline,1024);
650 WriteOpers(dataline);
658 /* Check we dont have more than one of singular tags, or any of them missing
660 for (int Index = 0; Once[Index]; Index++)
661 if (!CheckOnce(Once[Index],bail,user))
664 /* Read the values of all the tags which occur once or not at all, and call their callbacks.
666 for (int Index = 0; Values[Index].tag; Index++)
668 int* val_i = (int*) Values[Index].val;
669 char* val_c = (char*) Values[Index].val;
671 switch (Values[Index].datatype)
674 ConfValue(Values[Index].tag, Values[Index].value, 0, val_c, &this->config_f);
678 convert = new char[MAXBUF];
679 ConfValue(Values[Index].tag, Values[Index].value, 0, convert, &this->config_f);
680 *val_i = atoi(convert);
685 convert = new char[MAXBUF];
686 ConfValue(Values[Index].tag, Values[Index].value, 0, convert, &this->config_f);
687 *val_i = ((*convert == tolower('y')) || (*convert == tolower('t')) || (*convert == '1'));
695 Values[Index].validation_function(Values[Index].tag, Values[Index].value, Values[Index].val);
698 /* Claim memory for use when reading multiple tags
700 for (int n = 0; n < 12; n++)
701 data[n] = new char[MAXBUF];
703 /* Read the multiple-tag items (class tags, connect tags, etc)
704 * and call the callbacks associated with them. We have three
705 * callbacks for these, a 'start', 'item' and 'end' callback.
707 for (int Index = 0; MultiValues[Index].tag; Index++)
709 MultiValues[Index].init_function(MultiValues[Index].tag);
711 int number_of_tags = ConfValueEnum((char*)MultiValues[Index].tag, &this->config_f);
713 for (int tagnum = 0; tagnum < number_of_tags; tagnum++)
715 for (int valuenum = 0; MultiValues[Index].items[valuenum]; valuenum++)
717 ConfValue((char*)MultiValues[Index].tag,(char*)MultiValues[Index].items[valuenum], tagnum, data[valuenum], &this->config_f);
719 switch (MultiValues[Index].datatype[valuenum])
722 ptr[valuenum] = data[valuenum];
725 r_i[valuenum] = atoi(data[valuenum]);
726 ptr[valuenum] = &r_i[valuenum];
729 r_i[valuenum] = ((*data[valuenum] == tolower('y')) || (*data[valuenum] == tolower('t')) || (*data[valuenum] == '1'));
730 ptr[valuenum] = &r_i[valuenum];
736 MultiValues[Index].validation_function(MultiValues[Index].tag, (char**)MultiValues[Index].items, ptr, MultiValues[Index].datatype);
739 MultiValues[Index].finish_function(MultiValues[Index].tag);
742 /* Free any memory we claimed
744 for (int n = 0; n < 12; n++)
747 // write once here, to try it out and make sure its ok
748 WritePID(Config->PID);
750 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
752 /* If we're rehashing, let's load any new modules, and unload old ones
756 ServerInstance->stats->BoundPortCount = BindPorts(false);
758 if (!removed_modules.empty())
759 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
761 if (ServerInstance->UnloadModule(removing->c_str()))
763 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
766 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
773 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
777 if (!added_modules.empty())
778 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
780 if (ServerInstance->LoadModule(adding->c_str()))
782 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
785 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
792 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
796 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());
800 void Exit(int status)
802 if (Config->log_file)
803 fclose(Config->log_file);
804 send_error("Server shutdown.");
808 void Killed(int status)
810 if (Config->log_file)
811 fclose(Config->log_file);
812 send_error("Server terminated.");
816 char* CleanFilename(char* name)
818 char* p = name + strlen(name);
819 while ((p != name) && (*p != '/')) p--;
820 return (p != name ? ++p : p);
824 void Rehash(int status)
826 WriteOpers("Rehashing config file %s due to SIGHUP",CleanFilename(CONFIG_FILE));
827 fclose(Config->log_file);
829 Config->Read(false,NULL);
830 FOREACH_MOD(I_OnRehash,OnRehash(""));
837 printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
838 printf("(C) ChatSpike Development team.\033[0m\n\n");
839 printf("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om\033[0m\n");
840 printf("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
841 printf("Name concept:\t\t\033[1;32mLord_Zathras\033[0m\n\n");
844 void WritePID(const std::string &filename)
846 ofstream outfile(filename.c_str());
847 if (outfile.is_open())
854 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
855 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
862 signal (SIGALRM, SIG_IGN);
863 signal (SIGHUP, Rehash);
864 signal (SIGPIPE, SIG_IGN);
865 signal (SIGTERM, Exit);
866 signal (SIGSEGV, Error);
873 if ((childpid = fork ()) < 0)
875 else if (childpid > 0)
877 /* We wait a few seconds here, so that the shell prompt doesnt come back over the output */
883 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
885 if (Config->unlimitcore)
888 if (getrlimit(RLIMIT_CORE, &rl) == -1)
890 log(DEFAULT,"Failed to getrlimit()!");
895 rl.rlim_cur = rl.rlim_max;
896 if (setrlimit(RLIMIT_CORE, &rl) == -1)
897 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
905 /* Make Sure Modules Are Avaliable!
906 * (BugFix By Craig.. See? I do work! :p)
907 * Modified by brain, requires const char*
908 * to work with other API functions
911 bool FileExists (const char* file)
914 if ((input = fopen (file, "r")) == NULL)
925 /* ConfProcess does the following things to a config line in the following order:
927 * Processes the line for syntax errors as shown below
928 * (1) Line void of quotes or equals (a malformed, illegal tag format)
929 * (2) Odd number of quotes on the line indicating a missing quote
930 * (3) number of equals signs not equal to number of quotes / 2 (missing an equals sign)
931 * (4) Spaces between the opening bracket (<) and the keyword
932 * (5) Spaces between a keyword and an equals sign
933 * (6) Spaces between an equals sign and a quote
934 * Removes trailing spaces
935 * Removes leading spaces
936 * Converts tabs to spaces
937 * Turns multiple spaces that are outside of quotes into single spaces
940 std::string ServerConfig::ConfProcess(char* buffer, long linenumber, std::stringstream* errorstream, bool &error, std::string filename)
942 long number_of_quotes = 0;
943 long number_of_equals = 0;
944 bool has_open_bracket = false;
945 bool in_quotes = false;
953 // firstly clean up the line by stripping spaces from the start and end and converting tabs to spaces
954 for (char* d = buffer; *d; d++)
957 while (*buffer == ' ') buffer++;
958 trailing = buffer + strlen(buffer) - 1;
959 while (*trailing == ' ') *trailing-- = '\0';
961 // empty lines are syntactically valid, as are comments
962 if (!(*buffer) || buffer[0] == '#')
965 for (char* c = buffer; *c; c++)
967 // convert all spaces that are OUTSIDE quotes into hardspace (0xA0) as this will make them easier to
968 // search and replace later :)
969 if ((!in_quotes) && (*c == ' '))
971 if ((*c == '<') && (!in_quotes))
973 has_open_bracket = true;
976 *errorstream << "Tag without identifier at " << filename << ":" << linenumber << endl;
980 else if ((tolower(*(c+1)) < 'a') || (tolower(*(c+1)) > 'z'))
982 *errorstream << "Invalid characters in identifier at " << filename << ":" << linenumber << endl;
990 in_quotes = (!in_quotes);
992 if ((*c == '=') && (!in_quotes))
997 *errorstream << "Variable without a value at " << filename << ":" << linenumber << endl;
1001 else if (*(c+1) != '"')
1003 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
1007 else if (c == buffer)
1009 *errorstream << "Value without a variable (line starts with '=') at " << filename << ":" << linenumber << endl;
1013 else if (*(c-1) == '\xA0')
1015 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
1021 // no quotes, and no equals. something freaky.
1022 if ((!number_of_quotes) || (!number_of_equals) && (strlen(buffer)>2) && (*buffer == '<'))
1024 *errorstream << "Malformed tag at " << filename << ":" << linenumber << endl;
1028 // odd number of quotes. thats just wrong.
1029 if ((number_of_quotes % 2) != 0)
1031 *errorstream << "Missing \" at " << filename << ":" << linenumber << endl;
1035 if (number_of_equals < (number_of_quotes/2))
1037 *errorstream << "Missing '=' at " << filename << ":" << linenumber << endl;
1039 if (number_of_equals > (number_of_quotes/2))
1041 *errorstream << "Too many '=' at " << filename << ":" << linenumber << endl;
1044 std::string parsedata = buffer;
1045 // turn multispace into single space
1046 while (parsedata.find("\xA0\xA0") != std::string::npos)
1048 parsedata.erase(parsedata.find("\xA0\xA0"),1);
1051 // turn our hardspace back into softspace
1052 for (unsigned int d = 0; d < parsedata.length(); d++)
1054 if (parsedata[d] == '\xA0')
1058 // and we're done, the line is fine!
1062 int ServerConfig::fgets_safe(char* buffer, size_t maxsize, FILE* &file)
1066 char* bufptr = buffer;
1067 while ((!feof(file)) && (c_read != '\n') && (c_read != '\r') && (n < maxsize))
1069 c_read = fgetc(file);
1070 if ((c_read != '\n') && (c_read != '\r'))
1077 return bufptr - buffer;
1080 bool ServerConfig::LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream)
1083 errorstream->str("");
1084 long linenumber = 1;
1085 // first, check that the file exists before we try to do anything with it
1086 if (!FileExists(filename))
1088 *errorstream << "File " << filename << " not found." << endl;
1091 // Fix the chmod of the file to restrict it to the current user and group
1092 chmod(filename,0600);
1093 for (unsigned int t = 0; t < include_stack.size(); t++)
1095 if (std::string(filename) == include_stack[t])
1097 *errorstream << "File " << filename << " is included recursively (looped inclusion)." << endl;
1101 include_stack.push_back(filename);
1103 FILE* conf = fopen(filename,"r");
1104 char buffer[MAXBUF];
1109 if (fgets_safe(buffer, MAXBUF, conf))
1111 if ((!feof(conf)) && (buffer) && (*buffer))
1113 if ((buffer[0] != '#') && (buffer[0] != '\r') && (buffer[0] != '\n'))
1115 if (!strncmp(buffer,"<include file=\"",15))
1118 char confpath[10240],newconf[10240];
1119 // include file directive
1120 buf += 15; // advance to filename
1121 for (char* j = buf; *j; j++)
1131 log(DEBUG,"Opening included file '%s'",buf);
1134 strlcpy(confpath,CONFIG_FILE,10240);
1135 if (strstr(confpath,"/inspircd.conf"))
1137 // leaves us with just the path
1138 *(strstr(confpath,"/inspircd.conf")) = '\0';
1140 snprintf(newconf,10240,"%s/%s",confpath,buf);
1142 else strlcpy(newconf,buf,10240);
1143 std::stringstream merge(stringstream::in | stringstream::out);
1144 // recursively call LoadConf and get the new data, use the same errorstream
1145 if (LoadConf(newconf, &merge, errorstream))
1147 // append to the end of the file
1148 std::string newstuff = merge.str();
1149 *target << newstuff;
1153 // the error propogates up to its parent recursively
1154 // causing the config reader to bail at the top level.
1162 std::string data = this->ConfProcess(buffer,linenumber++,errorstream,error,filename);
1180 /* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */
1182 int ServerConfig::EnumConf(std::stringstream *config, const char* tag)
1185 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
1186 int in_token, in_quotes, tptr, idx = 0;
1188 std::string x = config->str();
1189 const char* buf = x.c_str();
1190 char* bptr = (char*)buf;
1200 if ((c == '#') && (lastc == '\n'))
1202 while ((c != '\n') && (*bptr))
1208 if ((c == '<') && (!in_quotes))
1223 in_quotes = (!in_quotes);
1225 if ((c == '>') && (!in_quotes))
1228 if (!strcmp(c_tag,tag))
1230 /* correct tag, but wrong index */
1240 if ((in_token) && (c != '\n') && (c != '\r'))
1250 /* Counts the number of values within a certain tag */
1252 int ServerConfig::EnumValues(std::stringstream *config, const char* tag, int index)
1255 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
1256 int in_token, in_quotes, tptr, idx = 0;
1257 bool correct_tag = false;
1259 const char* buf = config->str().c_str();
1260 char* bptr = (char*)buf;
1271 if ((c == '#') && (lastc == '\n'))
1273 while ((c != '\n') && (*bptr))
1279 if ((c == '<') && (!in_quotes))
1290 if ((!strcmp(c_tag,tag)) && (idx == index))
1299 in_quotes = (!in_quotes);
1302 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
1306 if ((c == '>') && (!in_quotes))
1310 correct_tag = false;
1311 if (!strcmp(c_tag,tag))
1313 /* correct tag, but wrong index */
1323 if ((in_token) && (c != '\n') && (c != '\r'))
1334 int ServerConfig::ConfValueEnum(char* tag, std::stringstream* config)
1336 return EnumConf(config,tag);
1340 int ServerConfig::ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
1343 char buffer[65535], c_tag[MAXBUF], c, lastc;
1344 int in_token, in_quotes, tptr, idx = 0;
1346 std::string x = config->str();
1347 const char* buf = x.c_str();
1348 char* bptr = (char*)buf;
1361 // FIX: Treat tabs as spaces
1364 if ((c == '<') && (!in_quotes))
1375 // FIX: Tab can follow a tagname as well as space.
1376 } while ((c != ' ') && (c != 9));
1380 in_quotes = (!in_quotes);
1382 if ((c == '>') && (!in_quotes))
1387 if (!strcmp(c_tag,tag))
1389 if ((buffer) && (c_tag) && (var))
1391 key = strstr(buffer,var);
1394 /* value not found in tag */
1412 for (char* j = key; *j; j++)
1420 strlcpy(result,key,MAXBUF);
1426 if (!strcmp(c_tag,tag))
1428 /* correct tag, but wrong index */
1438 if ((in_token) && (c != '\n') && (c != '\r'))
1445 *result = 0; // value or its tag not found at all
1451 int ServerConfig::ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
1453 ReadConf(config, tag, var, index, result);
1457 int ServerConfig::ConfValueInteger(char* tag, char* var, int index, std::stringstream *config)
1459 char result[MAXBUF];
1460 ReadConf(config, tag, var, index, result);
1461 return atoi(result);
1464 /** This will bind a socket to a port. It works for UDP/TCP.
1465 * If a hostname is given to bind to, the function will first
1466 * attempt to resolve the hostname, then bind to the IP the
1467 * hostname resolves to. This is a blocking lookup blocking for
1468 * a maximum of one second before it times out, using the DNS
1469 * server specified in the configuration file.
1471 bool BindSocket (int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
1473 memset((char *)&server,0,sizeof(server));
1474 struct in_addr addy;
1475 bool resolved = false;
1476 char resolved_addr[128];
1481 if (*addr && !inet_aton(addr,&addy))
1483 /* If they gave a hostname, bind to the IP it resolves to */
1484 if (CleanAndResolve(resolved_addr, addr, true))
1486 inet_aton(resolved_addr,&addy);
1487 log(DEFAULT,"Resolved binding '%s' -> '%s'",addr,resolved_addr);
1488 server.sin_addr = addy;
1493 log(DEFAULT,"WARNING: Could not resolve '%s' to an IP for binding to on port %d",addr,port);
1497 server.sin_family = AF_INET;
1502 server.sin_addr.s_addr = htonl(INADDR_ANY);
1506 server.sin_addr = addy;
1509 server.sin_port = htons(port);
1510 if (bind(sockfd,(struct sockaddr*)&server,sizeof(server)) < 0)
1516 log(DEBUG,"Bound port %s:%d",*addr ? addr : "*",port);
1517 if (listen(sockfd, Config->MaxConn) == -1)
1519 log(DEFAULT,"ERROR in listen(): %s",strerror(errno));
1530 // Open a TCP Socket
1535 struct linger linger = { 0 };
1537 if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
1539 log(DEFAULT,"Error creating TCP socket: %s",strerror(errno));
1544 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
1545 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
1547 linger.l_linger = 1;
1548 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));
1553 bool HasPort(int port, char* addr)
1555 for (int count = 0; count < ServerInstance->stats->BoundPortCount; count++)
1557 if ((port == Config->ports[count]) && (!strcasecmp(Config->addrs[count],addr)))
1565 int BindPorts(bool bail)
1567 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
1568 sockaddr_in client,server;
1569 int clientportcount = 0;
1570 int BoundPortCount = 0;
1574 int InitialPortCount = ServerInstance->stats->BoundPortCount;
1575 log(DEBUG,"Initial port count: %d",InitialPortCount);
1577 for (int count = 0; count < Config->ConfValueEnum("bind",&Config->config_f); count++)
1579 Config->ConfValue("bind","port",count,configToken,&Config->config_f);
1580 Config->ConfValue("bind","address",count,Addr,&Config->config_f);
1581 Config->ConfValue("bind","type",count,Type,&Config->config_f);
1582 if (((!*Type) || (!strcmp(Type,"clients"))) && (!HasPort(atoi(configToken),Addr)))
1584 // modules handle server bind types now
1585 Config->ports[clientportcount+InitialPortCount] = atoi(configToken);
1589 strlcpy(Config->addrs[clientportcount+InitialPortCount],Addr,256);
1591 log(DEBUG,"NEW binding %s:%s [%s] from config",Addr,configToken, Type);
1594 int PortCount = clientportcount;
1597 for (int count = InitialPortCount; count < InitialPortCount + PortCount; count++)
1599 if ((openSockfd[count] = OpenTCPSocket()) == ERROR)
1601 log(DEBUG,"Bad fd %d binding port [%s:%d]",openSockfd[count],Config->addrs[count],Config->ports[count]);
1604 if (!BindSocket(openSockfd[count],client,server,Config->ports[count],Config->addrs[count]))
1606 log(DEFAULT,"Failed to bind port [%s:%d]: %s",Config->addrs[count],Config->ports[count],strerror(errno));
1610 /* Associate the new open port with a slot in the socket engine */
1611 ServerInstance->SE->AddFd(openSockfd[count],true,X_LISTEN);
1615 return InitialPortCount + BoundPortCount;
1619 log(DEBUG,"There is nothing new to bind!");
1621 return InitialPortCount;
1624 for (int count = 0; count < Config->ConfValueEnum("bind",&Config->config_f); count++)
1626 Config->ConfValue("bind","port",count,configToken,&Config->config_f);
1627 Config->ConfValue("bind","address",count,Addr,&Config->config_f);
1628 Config->ConfValue("bind","type",count,Type,&Config->config_f);
1630 if ((!*Type) || (!strcmp(Type,"clients")))
1632 // modules handle server bind types now
1633 Config->ports[clientportcount] = atoi(configToken);
1635 // If the client put bind "*", this is an unrealism.
1636 // We don't actually support this as documented, but
1637 // i got fed up of people trying it, so now it converts
1638 // it to an empty string meaning the same 'bind to all'.
1642 strlcpy(Config->addrs[clientportcount],Addr,256);
1644 log(DEBUG,"Binding %s:%s [%s] from config",Addr,configToken, Type);
1648 int PortCount = clientportcount;
1650 for (int count = 0; count < PortCount; count++)
1652 if ((openSockfd[BoundPortCount] = OpenTCPSocket()) == ERROR)
1654 log(DEBUG,"Bad fd %d binding port [%s:%d]",openSockfd[BoundPortCount],Config->addrs[count],Config->ports[count]);
1658 if (!BindSocket(openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]))
1660 log(DEFAULT,"Failed to bind port [%s:%d]: %s",Config->addrs[count],Config->ports[count],strerror(errno));
1664 /* well we at least bound to one socket so we'll continue */
1669 /* if we didn't bind to anything then abort */
1670 if (!BoundPortCount)
1672 log(DEFAULT,"No ports bound, bailing!");
1673 printf("\nERROR: Could not bind any of %d ports! Please check your configuration.\n\n", PortCount);
1677 return BoundPortCount;