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 ValidateNetworkName(const char* tag, const char* value, void* data)
271 char* x = (char*)data;
273 log(DEFAULT,"<server:network> '%s'",x);
278 bool ValidateServerDesc(const char* tag, const char* value, void* data)
280 char* x = (char*)data;
282 log(DEFAULT,"<server:description> '%s'",x);
287 bool ValidateNetBufferSize(const char* tag, const char* value, void* data)
289 if ((!Config->NetBufferSize) || (Config->NetBufferSize > 65535) || (Config->NetBufferSize < 1024))
291 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
292 Config->NetBufferSize = 10240;
297 bool ValidateMaxWho(const char* tag, const char* value, void* data)
299 if ((!Config->MaxWhoResults) || (Config->MaxWhoResults > 65535) || (Config->MaxWhoResults < 1))
301 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
302 Config->MaxWhoResults = 128;
307 bool ValidateLogLevel(const char* tag, const char* value, void* data)
309 const char* dbg = (const char*)data;
310 Config->LogLevel = DEFAULT;
311 if (!strcmp(dbg,"debug"))
313 Config->LogLevel = DEBUG;
314 Config->debugging = 1;
316 else if (!strcmp(dbg,"verbose"))
317 Config->LogLevel = VERBOSE;
318 else if (!strcmp(dbg,"default"))
319 Config->LogLevel = DEFAULT;
320 else if (!strcmp(dbg,"sparse"))
321 Config->LogLevel = SPARSE;
322 else if (!strcmp(dbg,"none"))
323 Config->LogLevel = NONE;
327 bool ValidateMotd(const char* tag, const char* value, void* data)
329 readfile(Config->MOTD,Config->motd);
333 bool ValidateRules(const char* tag, const char* value, void* data)
335 readfile(Config->RULES,Config->rules);
339 /* Callback called before processing the first <connect> tag
341 bool InitConnect(const char* tag)
343 log(DEFAULT,"Reading connect classes...");
344 Config->Classes.clear();
348 /* Callback called to process a single <connect> tag
350 bool DoConnect(const char* tag, char** entries, void** values, int* types)
353 char* allow = (char*)values[0]; /* Yeah, there are a lot of values. Live with it. */
354 char* deny = (char*)values[1];
355 char* password = (char*)values[2];
356 int* timeout = (int*)values[3];
357 int* pingfreq = (int*)values[4];
358 int* flood = (int*)values[5];
359 int* threshold = (int*)values[6];
360 int* sendq = (int*)values[7];
361 int* recvq = (int*)values[8];
362 int* localmax = (int*)values[9];
363 int* globalmax = (int*)values[10];
370 c.registration_timeout = *timeout;
371 c.pingtime = *pingfreq;
373 c.threshold = *threshold;
376 c.maxlocal = *localmax;
377 c.maxglobal = *globalmax;
382 if (c.maxglobal == 0)
384 if (c.threshold == 0)
388 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());
394 if (c.registration_timeout == 0)
395 c.registration_timeout = 90;
398 Config->Classes.push_back(c);
404 Config->Classes.push_back(c);
405 log(DEBUG,"Read connect class type DENY, host=%s",deny);
411 /* Callback called when there are no more <connect> tags
413 bool DoneConnect(const char* tag)
415 log(DEBUG,"DoneConnect called for tag: %s",tag);
419 /* Callback called before processing the first <uline> tag
421 bool InitULine(const char* tag)
423 Config->ulines.clear();
427 /* Callback called to process a single <uline> tag
429 bool DoULine(const char* tag, char** entries, void** values, int* types)
431 char* server = (char*)values[0];
432 log(DEBUG,"Read ULINE '%s'",server);
433 Config->ulines.push_back(server);
437 /* Callback called when there are no more <uline> tags
439 bool DoneULine(const char* tag)
444 /* Callback called before processing the first <module> tag
446 bool InitModule(const char* tag)
448 old_module_names.clear();
449 new_module_names.clear();
450 added_modules.clear();
451 removed_modules.clear();
452 for (std::vector<std::string>::iterator t = Config->module_names.begin(); t != Config->module_names.end(); t++)
454 old_module_names.push_back(*t);
459 /* Callback called to process a single <module> tag
461 bool DoModule(const char* tag, char** entries, void** values, int* types)
463 char* modname = (char*)values[0];
464 new_module_names.push_back(modname);
468 /* Callback called when there are no more <module> tags
470 bool DoneModule(const char* tag)
472 // now create a list of new modules that are due to be loaded
473 // and a seperate list of modules which are due to be unloaded
474 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
478 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
485 added_modules.push_back(*_new);
488 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
491 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
498 removed_modules.push_back(*oldm);
503 /* Callback called before processing the first <banlist> tag
505 bool InitMaxBans(const char* tag)
507 Config->maxbans.clear();
511 /* Callback called to process a single <banlist> tag
513 bool DoMaxBans(const char* tag, char** entries, void** values, int* types)
515 char* channel = (char*)values[0];
516 int* limit = (int*)values[1];
517 Config->maxbans[channel] = *limit;
521 /* Callback called when there are no more <banlist> tags.
523 bool DoneMaxBans(const char* tag)
528 void ServerConfig::Read(bool bail, userrec* user)
530 char debug[MAXBUF]; /* Temporary buffer for debugging value */
531 char dataline[1024]; /* Temporary buffer for error output */
532 char* convert; /* Temporary buffer used for reading singular values into */
533 char* data[12]; /* Temporary buffers for reading multiple occurance tags into */
534 void* ptr[12]; /* Temporary pointers for passing to callbacks */
535 int r_i[12]; /* Temporary array for casting */
536 int rem = 0, add = 0; /* Number of modules added, number of modules removed */
537 std::stringstream errstr; /* String stream containing the error output */
539 /* These tags MUST occur and must ONLY occur once in the config file */
540 static char* Once[] = { "server", "admin", "files", "power", "options", "pid", NULL };
542 /* These tags can occur ONCE or not at all */
543 static InitialConfig Values[] = {
544 {"options", "softlimit", &this->SoftLimit, DT_INTEGER, ValidateSoftLimit},
545 {"options", "somaxconn", &this->MaxConn, DT_INTEGER, ValidateMaxConn},
546 {"server", "name", &this->ServerName, DT_CHARPTR, ValidateServerName},
547 {"server", "description", &this->ServerDesc, DT_CHARPTR, ValidateServerDesc},
548 {"server", "network", &this->Network, DT_CHARPTR, ValidateNetworkName},
549 {"admin", "name", &this->AdminName, DT_CHARPTR, NoValidation},
550 {"admin", "email", &this->AdminEmail, DT_CHARPTR, NoValidation},
551 {"admin", "nick", &this->AdminNick, DT_CHARPTR, NoValidation},
552 {"files", "motd", &this->motd, DT_CHARPTR, ValidateMotd},
553 {"files", "rules", &this->rules, DT_CHARPTR, ValidateRules},
554 {"power", "diepass", &this->diepass, DT_CHARPTR, NoValidation},
555 {"power", "pauseval", &this->DieDelay, DT_INTEGER, NoValidation},
556 {"power", "restartpass", &this->restartpass, DT_CHARPTR, NoValidation},
557 {"options", "prefixquit", &this->PrefixQuit, DT_CHARPTR, NoValidation},
558 {"die", "value", &this->DieValue, DT_CHARPTR, NoValidation},
559 {"options", "loglevel", &debug, DT_CHARPTR, ValidateLogLevel},
560 {"options", "netbuffersize", &this->NetBufferSize, DT_INTEGER, ValidateNetBufferSize},
561 {"options", "maxwho", &this->MaxWhoResults, DT_INTEGER, ValidateMaxWho},
562 {"options", "allowhalfop", &this->AllowHalfop, DT_BOOLEAN, NoValidation},
563 {"dns", "server", &this->DNSServer, DT_CHARPTR, ValidateDnsServer},
564 {"dns", "timeout", &this->dns_timeout, DT_INTEGER, ValidateDnsTimeout},
565 {"options", "moduledir", &this->ModPath, DT_CHARPTR, ValidateModPath},
566 {"disabled", "commands", &this->DisabledCommands,DT_CHARPTR, NoValidation},
567 {"options", "operonlystats", &this->OperOnlyStats, DT_CHARPTR, NoValidation},
568 {"options", "customversion", &this->CustomVersion, DT_CHARPTR, NoValidation},
569 {"options", "hidesplits", &this->HideSplits, DT_BOOLEAN, NoValidation},
570 {"options", "hidebans", &this->HideBans, DT_BOOLEAN, NoValidation},
571 {"options", "hidewhois", &this->HideWhoisServer, DT_CHARPTR, NoValidation},
572 {"options", "operspywhois", &this->OperSpyWhois, DT_BOOLEAN, NoValidation},
573 {"options", "tempdir", &this->TempDir, DT_CHARPTR, ValidateTempDir},
574 {"pid", "file", &this->PID, DT_CHARPTR, NoValidation},
578 /* These tags can occur multiple times, and therefore they have special code to read them
579 * which is different to the code for reading the singular tags listed above.
581 static MultiConfig MultiValues[] = {
584 {"allow", "deny", "password", "timeout", "pingfreq", "flood",
585 "threshold", "sendq", "recvq", "localmax", "globalmax", NULL},
586 {DT_CHARPTR, DT_CHARPTR, DT_CHARPTR, DT_INTEGER, DT_INTEGER, DT_INTEGER,
587 DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER},
588 InitConnect, DoConnect, DoneConnect},
593 InitULine,DoULine,DoneULine},
596 {"chan", "limit", NULL},
597 {DT_CHARPTR, DT_INTEGER},
598 InitMaxBans, DoMaxBans, DoneMaxBans},
603 InitModule, DoModule, DoneModule},
606 {"reason", "ipmask", NULL},
607 {DT_CHARPTR, DT_CHARPTR},
608 InitXLine, DoZLine, DoneXLine},
611 {"reason", "nick", NULL},
612 {DT_CHARPTR, DT_CHARPTR},
613 InitXLine, DoQLine, DoneXLine},
616 {"reason", "host", NULL},
617 {DT_CHARPTR, DT_CHARPTR},
618 InitXLine, DoKLine, DoneXLine},
621 {"reason", "host", NULL},
622 {DT_CHARPTR, DT_CHARPTR},
623 InitXLine, DoELine, DoneXLine},
626 {"name", "classes", NULL},
627 {DT_CHARPTR, DT_CHARPTR},
628 InitTypes, DoType, DoneClassesAndTypes},
631 {"name", "commands", NULL},
632 {DT_CHARPTR, DT_CHARPTR},
633 InitClasses, DoClass, DoneClassesAndTypes},
638 include_stack.clear();
640 /* Initially, load the config into memory, bail if there are errors
642 if (!LoadConf(CONFIG_FILE,&Config->config_f,&errstr))
645 log(DEFAULT,"There were errors in your configuration:\n%s",errstr.str().c_str());
649 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
656 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
657 while (!errstr.eof())
659 errstr.getline(dataline,1024);
660 WriteServ(user->fd,"NOTICE %s :%s",user->nick,dataline);
665 WriteOpers("There were errors in the configuration file:");
666 while (!errstr.eof())
668 errstr.getline(dataline,1024);
669 WriteOpers(dataline);
677 /* Check we dont have more than one of singular tags, or any of them missing
679 for (int Index = 0; Once[Index]; Index++)
680 if (!CheckOnce(Once[Index],bail,user))
683 /* Read the values of all the tags which occur once or not at all, and call their callbacks.
685 for (int Index = 0; Values[Index].tag; Index++)
687 int* val_i = (int*) Values[Index].val;
688 char* val_c = (char*) Values[Index].val;
690 switch (Values[Index].datatype)
693 ConfValue(Values[Index].tag, Values[Index].value, 0, val_c, &this->config_f);
697 convert = new char[MAXBUF];
698 ConfValue(Values[Index].tag, Values[Index].value, 0, convert, &this->config_f);
699 *val_i = atoi(convert);
704 convert = new char[MAXBUF];
705 ConfValue(Values[Index].tag, Values[Index].value, 0, convert, &this->config_f);
706 *val_i = ((*convert == tolower('y')) || (*convert == tolower('t')) || (*convert == '1'));
714 Values[Index].validation_function(Values[Index].tag, Values[Index].value, Values[Index].val);
717 /* Claim memory for use when reading multiple tags
719 for (int n = 0; n < 12; n++)
720 data[n] = new char[MAXBUF];
722 /* Read the multiple-tag items (class tags, connect tags, etc)
723 * and call the callbacks associated with them. We have three
724 * callbacks for these, a 'start', 'item' and 'end' callback.
726 for (int Index = 0; MultiValues[Index].tag; Index++)
728 MultiValues[Index].init_function(MultiValues[Index].tag);
730 int number_of_tags = ConfValueEnum((char*)MultiValues[Index].tag, &this->config_f);
732 for (int tagnum = 0; tagnum < number_of_tags; tagnum++)
734 for (int valuenum = 0; MultiValues[Index].items[valuenum]; valuenum++)
736 ConfValue((char*)MultiValues[Index].tag,(char*)MultiValues[Index].items[valuenum], tagnum, data[valuenum], &this->config_f);
738 switch (MultiValues[Index].datatype[valuenum])
741 ptr[valuenum] = data[valuenum];
744 r_i[valuenum] = atoi(data[valuenum]);
745 ptr[valuenum] = &r_i[valuenum];
748 r_i[valuenum] = ((*data[valuenum] == tolower('y')) || (*data[valuenum] == tolower('t')) || (*data[valuenum] == '1'));
749 ptr[valuenum] = &r_i[valuenum];
755 MultiValues[Index].validation_function(MultiValues[Index].tag, (char**)MultiValues[Index].items, ptr, MultiValues[Index].datatype);
758 MultiValues[Index].finish_function(MultiValues[Index].tag);
761 /* Free any memory we claimed
763 for (int n = 0; n < 12; n++)
766 // write once here, to try it out and make sure its ok
767 WritePID(Config->PID);
769 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
771 /* If we're rehashing, let's load any new modules, and unload old ones
775 ServerInstance->stats->BoundPortCount = BindPorts(false);
777 if (!removed_modules.empty())
778 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
780 if (ServerInstance->UnloadModule(removing->c_str()))
782 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
785 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
792 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
796 if (!added_modules.empty())
797 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
799 if (ServerInstance->LoadModule(adding->c_str()))
801 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
804 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
811 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
815 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());
819 void Exit(int status)
821 if (Config->log_file)
822 fclose(Config->log_file);
823 send_error("Server shutdown.");
827 void Killed(int status)
829 if (Config->log_file)
830 fclose(Config->log_file);
831 send_error("Server terminated.");
835 char* CleanFilename(char* name)
837 char* p = name + strlen(name);
838 while ((p != name) && (*p != '/')) p--;
839 return (p != name ? ++p : p);
843 void Rehash(int status)
845 WriteOpers("Rehashing config file %s due to SIGHUP",CleanFilename(CONFIG_FILE));
846 fclose(Config->log_file);
848 Config->Read(false,NULL);
849 FOREACH_MOD(I_OnRehash,OnRehash(""));
856 printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
857 printf("(C) ChatSpike Development team.\033[0m\n\n");
858 printf("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om\033[0m\n");
859 printf("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
860 printf("Name concept:\t\t\033[1;32mLord_Zathras\033[0m\n\n");
863 void WritePID(const std::string &filename)
865 ofstream outfile(filename.c_str());
866 if (outfile.is_open())
873 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
874 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
881 signal (SIGALRM, SIG_IGN);
882 signal (SIGHUP, Rehash);
883 signal (SIGPIPE, SIG_IGN);
884 signal (SIGTERM, Exit);
885 signal (SIGSEGV, Error);
892 if ((childpid = fork ()) < 0)
894 else if (childpid > 0)
896 /* We wait a few seconds here, so that the shell prompt doesnt come back over the output */
902 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
904 if (Config->unlimitcore)
907 if (getrlimit(RLIMIT_CORE, &rl) == -1)
909 log(DEFAULT,"Failed to getrlimit()!");
914 rl.rlim_cur = rl.rlim_max;
915 if (setrlimit(RLIMIT_CORE, &rl) == -1)
916 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
924 /* Make Sure Modules Are Avaliable!
925 * (BugFix By Craig.. See? I do work! :p)
926 * Modified by brain, requires const char*
927 * to work with other API functions
930 bool FileExists (const char* file)
933 if ((input = fopen (file, "r")) == NULL)
944 /* ConfProcess does the following things to a config line in the following order:
946 * Processes the line for syntax errors as shown below
947 * (1) Line void of quotes or equals (a malformed, illegal tag format)
948 * (2) Odd number of quotes on the line indicating a missing quote
949 * (3) number of equals signs not equal to number of quotes / 2 (missing an equals sign)
950 * (4) Spaces between the opening bracket (<) and the keyword
951 * (5) Spaces between a keyword and an equals sign
952 * (6) Spaces between an equals sign and a quote
953 * Removes trailing spaces
954 * Removes leading spaces
955 * Converts tabs to spaces
956 * Turns multiple spaces that are outside of quotes into single spaces
959 std::string ServerConfig::ConfProcess(char* buffer, long linenumber, std::stringstream* errorstream, bool &error, std::string filename)
961 long number_of_quotes = 0;
962 long number_of_equals = 0;
963 bool has_open_bracket = false;
964 bool in_quotes = false;
972 // firstly clean up the line by stripping spaces from the start and end and converting tabs to spaces
973 for (char* d = buffer; *d; d++)
976 while (*buffer == ' ') buffer++;
977 trailing = buffer + strlen(buffer) - 1;
978 while (*trailing == ' ') *trailing-- = '\0';
980 // empty lines are syntactically valid, as are comments
981 if (!(*buffer) || buffer[0] == '#')
984 for (char* c = buffer; *c; c++)
986 // convert all spaces that are OUTSIDE quotes into hardspace (0xA0) as this will make them easier to
987 // search and replace later :)
988 if ((!in_quotes) && (*c == ' '))
990 if ((*c == '<') && (!in_quotes))
992 has_open_bracket = true;
995 *errorstream << "Tag without identifier at " << filename << ":" << linenumber << endl;
999 else if ((tolower(*(c+1)) < 'a') || (tolower(*(c+1)) > 'z'))
1001 *errorstream << "Invalid characters in identifier at " << filename << ":" << linenumber << endl;
1009 in_quotes = (!in_quotes);
1011 if ((*c == '=') && (!in_quotes))
1016 *errorstream << "Variable without a value at " << filename << ":" << linenumber << endl;
1020 else if (*(c+1) != '"')
1022 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
1026 else if (c == buffer)
1028 *errorstream << "Value without a variable (line starts with '=') at " << filename << ":" << linenumber << endl;
1032 else if (*(c-1) == '\xA0')
1034 *errorstream << "Variable name not followed immediately by its value at " << filename << ":" << linenumber << endl;
1040 // no quotes, and no equals. something freaky.
1041 if ((!number_of_quotes) || (!number_of_equals) && (strlen(buffer)>2) && (*buffer == '<'))
1043 *errorstream << "Malformed tag at " << filename << ":" << linenumber << endl;
1047 // odd number of quotes. thats just wrong.
1048 if ((number_of_quotes % 2) != 0)
1050 *errorstream << "Missing \" at " << filename << ":" << linenumber << endl;
1054 if (number_of_equals < (number_of_quotes/2))
1056 *errorstream << "Missing '=' at " << filename << ":" << linenumber << endl;
1058 if (number_of_equals > (number_of_quotes/2))
1060 *errorstream << "Too many '=' at " << filename << ":" << linenumber << endl;
1063 std::string parsedata = buffer;
1064 // turn multispace into single space
1065 while (parsedata.find("\xA0\xA0") != std::string::npos)
1067 parsedata.erase(parsedata.find("\xA0\xA0"),1);
1070 // turn our hardspace back into softspace
1071 for (unsigned int d = 0; d < parsedata.length(); d++)
1073 if (parsedata[d] == '\xA0')
1077 // and we're done, the line is fine!
1081 int ServerConfig::fgets_safe(char* buffer, size_t maxsize, FILE* &file)
1085 char* bufptr = buffer;
1086 while ((!feof(file)) && (c_read != '\n') && (c_read != '\r') && (n < maxsize))
1088 c_read = fgetc(file);
1089 if ((c_read != '\n') && (c_read != '\r'))
1096 return bufptr - buffer;
1099 bool ServerConfig::LoadConf(const char* filename, std::stringstream *target, std::stringstream* errorstream)
1102 errorstream->str("");
1103 long linenumber = 1;
1104 // first, check that the file exists before we try to do anything with it
1105 if (!FileExists(filename))
1107 *errorstream << "File " << filename << " not found." << endl;
1110 // Fix the chmod of the file to restrict it to the current user and group
1111 chmod(filename,0600);
1112 for (unsigned int t = 0; t < include_stack.size(); t++)
1114 if (std::string(filename) == include_stack[t])
1116 *errorstream << "File " << filename << " is included recursively (looped inclusion)." << endl;
1120 include_stack.push_back(filename);
1122 FILE* conf = fopen(filename,"r");
1123 char buffer[MAXBUF];
1128 if (fgets_safe(buffer, MAXBUF, conf))
1130 if ((!feof(conf)) && (buffer) && (*buffer))
1132 if ((buffer[0] != '#') && (buffer[0] != '\r') && (buffer[0] != '\n'))
1134 if (!strncmp(buffer,"<include file=\"",15))
1137 char confpath[10240],newconf[10240];
1138 // include file directive
1139 buf += 15; // advance to filename
1140 for (char* j = buf; *j; j++)
1150 log(DEBUG,"Opening included file '%s'",buf);
1153 strlcpy(confpath,CONFIG_FILE,10240);
1154 if (strstr(confpath,"/inspircd.conf"))
1156 // leaves us with just the path
1157 *(strstr(confpath,"/inspircd.conf")) = '\0';
1159 snprintf(newconf,10240,"%s/%s",confpath,buf);
1161 else strlcpy(newconf,buf,10240);
1162 std::stringstream merge(stringstream::in | stringstream::out);
1163 // recursively call LoadConf and get the new data, use the same errorstream
1164 if (LoadConf(newconf, &merge, errorstream))
1166 // append to the end of the file
1167 std::string newstuff = merge.str();
1168 *target << newstuff;
1172 // the error propogates up to its parent recursively
1173 // causing the config reader to bail at the top level.
1181 std::string data = this->ConfProcess(buffer,linenumber++,errorstream,error,filename);
1199 /* Counts the number of tags of a certain type within the config file, e.g. to enumerate opers */
1201 int ServerConfig::EnumConf(std::stringstream *config, const char* tag)
1204 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
1205 int in_token, in_quotes, tptr, idx = 0;
1207 std::string x = config->str();
1208 const char* buf = x.c_str();
1209 char* bptr = (char*)buf;
1219 if ((c == '#') && (lastc == '\n'))
1221 while ((c != '\n') && (*bptr))
1227 if ((c == '<') && (!in_quotes))
1242 in_quotes = (!in_quotes);
1244 if ((c == '>') && (!in_quotes))
1247 if (!strcmp(c_tag,tag))
1249 /* correct tag, but wrong index */
1259 if ((in_token) && (c != '\n') && (c != '\r'))
1269 /* Counts the number of values within a certain tag */
1271 int ServerConfig::EnumValues(std::stringstream *config, const char* tag, int index)
1274 char buffer[MAXBUF], c_tag[MAXBUF], c, lastc;
1275 int in_token, in_quotes, tptr, idx = 0;
1276 bool correct_tag = false;
1278 const char* buf = config->str().c_str();
1279 char* bptr = (char*)buf;
1290 if ((c == '#') && (lastc == '\n'))
1292 while ((c != '\n') && (*bptr))
1298 if ((c == '<') && (!in_quotes))
1309 if ((!strcmp(c_tag,tag)) && (idx == index))
1318 in_quotes = (!in_quotes);
1321 if ( (correct_tag) && (!in_quotes) && ( (c == ' ') || (c == '\n') || (c == '\r') ) )
1325 if ((c == '>') && (!in_quotes))
1329 correct_tag = false;
1330 if (!strcmp(c_tag,tag))
1332 /* correct tag, but wrong index */
1342 if ((in_token) && (c != '\n') && (c != '\r'))
1353 int ServerConfig::ConfValueEnum(char* tag, std::stringstream* config)
1355 return EnumConf(config,tag);
1359 int ServerConfig::ReadConf(std::stringstream *config, const char* tag, const char* var, int index, char *result)
1362 char buffer[65535], c_tag[MAXBUF], c, lastc, varname[MAXBUF];
1363 int in_token, in_quotes, tptr, idx = 0;
1365 char* bptr = (char*)config->str().c_str();
1375 * Fun bug here, if was searching for whatever var was *in the whole tag*,
1376 * so if you had the name of the var you were searching for in one of the values
1377 * it would try to use that part of a value as the varnme, usually giving a value
1378 * something like "anothervarname="
1380 strlcpy(varname, var, MAXBUF);
1381 strlcat(varname, "=", MAXBUF);
1387 // FIX: Treat tabs as spaces
1390 if ((c == '<') && (!in_quotes))
1401 // FIX: Tab can follow a tagname as well as space.
1402 } while ((c != ' ') && (c != 9));
1406 in_quotes = (!in_quotes);
1408 if ((c == '>') && (!in_quotes))
1413 if (!strcmp(c_tag,tag))
1415 if ((buffer) && (c_tag) && (var))
1417 key = strstr(buffer,varname);
1420 /* value not found in tag */
1438 for (char* j = key; *j; j++)
1446 strlcpy(result,key,MAXBUF);
1452 if (!strcmp(c_tag,tag))
1454 /* correct tag, but wrong index */
1464 if ((in_token) && (c != '\n') && (c != '\r'))
1472 *result = 0; // value or its tag not found at all
1478 int ServerConfig::ConfValue(char* tag, char* var, int index, char *result,std::stringstream *config)
1480 ReadConf(config, tag, var, index, result);
1484 int ServerConfig::ConfValueInteger(char* tag, char* var, int index, std::stringstream *config)
1486 char result[MAXBUF];
1487 ReadConf(config, tag, var, index, result);
1488 return atoi(result);
1491 /** This will bind a socket to a port. It works for UDP/TCP.
1492 * If a hostname is given to bind to, the function will first
1493 * attempt to resolve the hostname, then bind to the IP the
1494 * hostname resolves to. This is a blocking lookup blocking for
1495 * a maximum of one second before it times out, using the DNS
1496 * server specified in the configuration file.
1498 bool BindSocket(int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
1500 memset((char *)&server,0,sizeof(server));
1501 struct in_addr addy;
1502 bool resolved = false;
1503 char resolved_addr[128];
1508 if (*addr && !inet_aton(addr,&addy))
1510 /* If they gave a hostname, bind to the IP it resolves to */
1511 if (CleanAndResolve(resolved_addr, addr, true))
1513 inet_aton(resolved_addr,&addy);
1514 log(DEFAULT,"Resolved binding '%s' -> '%s'",addr,resolved_addr);
1515 server.sin_addr = addy;
1520 log(DEFAULT,"WARNING: Could not resolve '%s' to an IP for binding to on port %d",addr,port);
1524 server.sin_family = AF_INET;
1529 server.sin_addr.s_addr = htonl(INADDR_ANY);
1533 server.sin_addr = addy;
1536 server.sin_port = htons(port);
1537 if (bind(sockfd,(struct sockaddr*)&server,sizeof(server)) < 0)
1543 log(DEBUG,"Bound port %s:%d",*addr ? addr : "*",port);
1544 if (listen(sockfd, Config->MaxConn) == -1)
1546 log(DEFAULT,"ERROR in listen(): %s",strerror(errno));
1551 NonBlocking(sockfd);
1558 // Open a TCP Socket
1563 struct linger linger = { 0 };
1565 if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
1567 log(DEFAULT,"Error creating TCP socket: %s",strerror(errno));
1572 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
1573 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
1575 linger.l_linger = 1;
1576 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (const char*)&linger,sizeof(linger));
1581 bool HasPort(int port, char* addr)
1583 for (int count = 0; count < ServerInstance->stats->BoundPortCount; count++)
1585 if ((port == Config->ports[count]) && (!strcasecmp(Config->addrs[count],addr)))
1593 int BindPorts(bool bail)
1595 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
1596 sockaddr_in client,server;
1597 int clientportcount = 0;
1598 int BoundPortCount = 0;
1602 int InitialPortCount = ServerInstance->stats->BoundPortCount;
1603 log(DEBUG,"Initial port count: %d",InitialPortCount);
1605 for (int count = 0; count < Config->ConfValueEnum("bind",&Config->config_f); count++)
1607 Config->ConfValue("bind","port",count,configToken,&Config->config_f);
1608 Config->ConfValue("bind","address",count,Addr,&Config->config_f);
1609 Config->ConfValue("bind","type",count,Type,&Config->config_f);
1610 if (((!*Type) || (!strcmp(Type,"clients"))) && (!HasPort(atoi(configToken),Addr)))
1612 // modules handle server bind types now
1613 Config->ports[clientportcount+InitialPortCount] = atoi(configToken);
1617 strlcpy(Config->addrs[clientportcount+InitialPortCount],Addr,256);
1619 log(DEBUG,"NEW binding %s:%s [%s] from config",Addr,configToken, Type);
1622 int PortCount = clientportcount;
1625 for (int count = InitialPortCount; count < InitialPortCount + PortCount; count++)
1627 if ((openSockfd[count] = OpenTCPSocket()) == ERROR)
1629 log(DEBUG,"Bad fd %d binding port [%s:%d]",openSockfd[count],Config->addrs[count],Config->ports[count]);
1632 if (!BindSocket(openSockfd[count],client,server,Config->ports[count],Config->addrs[count]))
1634 log(DEFAULT,"Failed to bind port [%s:%d]: %s",Config->addrs[count],Config->ports[count],strerror(errno));
1638 /* Associate the new open port with a slot in the socket engine */
1639 ServerInstance->SE->AddFd(openSockfd[count],true,X_LISTEN);
1643 return InitialPortCount + BoundPortCount;
1647 log(DEBUG,"There is nothing new to bind!");
1649 return InitialPortCount;
1652 for (int count = 0; count < Config->ConfValueEnum("bind",&Config->config_f); count++)
1654 Config->ConfValue("bind","port",count,configToken,&Config->config_f);
1655 Config->ConfValue("bind","address",count,Addr,&Config->config_f);
1656 Config->ConfValue("bind","type",count,Type,&Config->config_f);
1658 if ((!*Type) || (!strcmp(Type,"clients")))
1660 // modules handle server bind types now
1661 Config->ports[clientportcount] = atoi(configToken);
1663 // If the client put bind "*", this is an unrealism.
1664 // We don't actually support this as documented, but
1665 // i got fed up of people trying it, so now it converts
1666 // it to an empty string meaning the same 'bind to all'.
1670 strlcpy(Config->addrs[clientportcount],Addr,256);
1672 log(DEBUG,"Binding %s:%s [%s] from config",Addr,configToken, Type);
1676 int PortCount = clientportcount;
1678 for (int count = 0; count < PortCount; count++)
1680 if ((openSockfd[BoundPortCount] = OpenTCPSocket()) == ERROR)
1682 log(DEBUG,"Bad fd %d binding port [%s:%d]",openSockfd[BoundPortCount],Config->addrs[count],Config->ports[count]);
1686 if (!BindSocket(openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]))
1688 log(DEFAULT,"Failed to bind port [%s:%d]: %s",Config->addrs[count],Config->ports[count],strerror(errno));
1692 /* well we at least bound to one socket so we'll continue */
1697 /* if we didn't bind to anything then abort */
1698 if (!BoundPortCount)
1700 log(DEFAULT,"No ports bound, bailing!");
1701 printf("\nERROR: Could not bind any of %d ports! Please check your configuration.\n\n", PortCount);
1705 return BoundPortCount;