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 forcedebug = OperSpyWhois = nofork = HideBans = HideSplits = false;
56 writelog = AllowHalfop = true;
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(Config->config_data, tag);
113 printf("There were errors in your configuration:\nYou have more than one <%s> tag, this is not permitted.\n",tag);
120 WriteServ(user->fd,"There were errors in your configuration:");
121 WriteServ(user->fd,"You have more than one <%s> tag, this is not permitted.\n",tag);
125 WriteOpers("There were errors in the configuration file:");
126 WriteOpers("You have more than one <%s> tag, this is not permitted.\n",tag);
135 printf("There were errors in your configuration:\nYou have not defined a <%s> tag, this is required.\n",tag);
142 WriteServ(user->fd,"There were errors in your configuration:");
143 WriteServ(user->fd,"You have not defined a <%s> tag, this is required.",tag);
147 WriteOpers("There were errors in the configuration file:");
148 WriteOpers("You have not defined a <%s> tag, this is required.",tag);
156 bool NoValidation(const char* tag, const char* value, void* data)
158 log(DEBUG,"No validation for <%s:%s>",tag,value);
162 bool ValidateTempDir(const char* tag, const char* value, void* data)
164 char* x = (char*)data;
166 strlcpy(x,"/tmp",1024);
170 bool ValidateMaxTargets(const char* tag, const char* value, void* data)
173 if ((*x < 0) || (*x > 31))
175 log(DEFAULT,"WARNING: <options:maxtargets> value is greater than 31 or less than 0, set to 20.");
181 bool ValidateSoftLimit(const char* tag, const char* value, void* data)
184 if ((*x < 1) || (*x > MAXCLIENTS))
186 log(DEFAULT,"WARNING: <options:softlimit> value is greater than %d or less than 0, set to %d.",MAXCLIENTS,MAXCLIENTS);
192 bool ValidateMaxConn(const char* tag, const char* value, void* data)
196 log(DEFAULT,"WARNING: <options:somaxconn> value may be higher than the system-defined SOMAXCONN value!");
202 bool ValidateDnsTimeout(const char* tag, const char* value, void* data)
210 bool ValidateDnsServer(const char* tag, const char* value, void* data)
212 char* x = (char*)data;
215 // attempt to look up their nameserver from /etc/resolv.conf
216 log(DEFAULT,"WARNING: <dns:server> not defined, attempting to find working server in /etc/resolv.conf...");
217 ifstream resolv("/etc/resolv.conf");
218 std::string nameserver;
219 bool found_server = false;
221 if (resolv.is_open())
223 while (resolv >> nameserver)
225 if ((nameserver == "nameserver") && (!found_server))
227 resolv >> nameserver;
228 strlcpy(x,nameserver.c_str(),MAXBUF);
230 log(DEFAULT,"<dns:server> set to '%s' as first resolver in /etc/resolv.conf.",nameserver.c_str());
236 log(DEFAULT,"/etc/resolv.conf contains no viable nameserver entries! Defaulting to nameserver '127.0.0.1'!");
237 strlcpy(x,"127.0.0.1",MAXBUF);
242 log(DEFAULT,"/etc/resolv.conf can't be opened! Defaulting to nameserver '127.0.0.1'!");
243 strlcpy(x,"127.0.0.1",MAXBUF);
249 bool ValidateModPath(const char* tag, const char* value, void* data)
251 char* x = (char*)data;
253 strlcpy(x,MOD_PATH,MAXBUF);
258 bool ValidateServerName(const char* tag, const char* value, void* data)
260 char* x = (char*)data;
263 log(DEFAULT,"WARNING: <server:name> '%s' is not a fully-qualified domain name. Changed to '%s%c'",x,x,'.');
264 charlcat(x,'.',MAXBUF);
270 bool ValidateNetBufferSize(const char* tag, const char* value, void* data)
272 if ((!Config->NetBufferSize) || (Config->NetBufferSize > 65535) || (Config->NetBufferSize < 1024))
274 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
275 Config->NetBufferSize = 10240;
280 bool ValidateMaxWho(const char* tag, const char* value, void* data)
282 if ((!Config->MaxWhoResults) || (Config->MaxWhoResults > 65535) || (Config->MaxWhoResults < 1))
284 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
285 Config->MaxWhoResults = 128;
290 bool ValidateLogLevel(const char* tag, const char* value, void* data)
292 const char* dbg = (const char*)data;
293 Config->LogLevel = DEFAULT;
294 if (!strcmp(dbg,"debug"))
296 Config->LogLevel = DEBUG;
297 Config->debugging = 1;
299 else if (!strcmp(dbg,"verbose"))
300 Config->LogLevel = VERBOSE;
301 else if (!strcmp(dbg,"default"))
302 Config->LogLevel = DEFAULT;
303 else if (!strcmp(dbg,"sparse"))
304 Config->LogLevel = SPARSE;
305 else if (!strcmp(dbg,"none"))
306 Config->LogLevel = NONE;
310 bool ValidateMotd(const char* tag, const char* value, void* data)
312 readfile(Config->MOTD,Config->motd);
316 bool ValidateRules(const char* tag, const char* value, void* data)
318 readfile(Config->RULES,Config->rules);
322 /* Callback called before processing the first <connect> tag
324 bool InitConnect(const char* tag)
326 log(DEFAULT,"Reading connect classes...");
327 Config->Classes.clear();
331 /* Callback called to process a single <connect> tag
333 bool DoConnect(const char* tag, char** entries, void** values, int* types)
336 char* allow = (char*)values[0]; /* Yeah, there are a lot of values. Live with it. */
337 char* deny = (char*)values[1];
338 char* password = (char*)values[2];
339 int* timeout = (int*)values[3];
340 int* pingfreq = (int*)values[4];
341 int* flood = (int*)values[5];
342 int* threshold = (int*)values[6];
343 int* sendq = (int*)values[7];
344 int* recvq = (int*)values[8];
345 int* localmax = (int*)values[9];
346 int* globalmax = (int*)values[10];
353 c.registration_timeout = *timeout;
354 c.pingtime = *pingfreq;
356 c.threshold = *threshold;
359 c.maxlocal = *localmax;
360 c.maxglobal = *globalmax;
365 if (c.maxglobal == 0)
367 if (c.threshold == 0)
371 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());
377 if (c.registration_timeout == 0)
378 c.registration_timeout = 90;
381 Config->Classes.push_back(c);
387 Config->Classes.push_back(c);
388 log(DEBUG,"Read connect class type DENY, host=%s",deny);
394 /* Callback called when there are no more <connect> tags
396 bool DoneConnect(const char* tag)
398 log(DEBUG,"DoneConnect called for tag: %s",tag);
402 /* Callback called before processing the first <uline> tag
404 bool InitULine(const char* tag)
406 Config->ulines.clear();
410 /* Callback called to process a single <uline> tag
412 bool DoULine(const char* tag, char** entries, void** values, int* types)
414 char* server = (char*)values[0];
415 log(DEBUG,"Read ULINE '%s'",server);
416 Config->ulines.push_back(server);
420 /* Callback called when there are no more <uline> tags
422 bool DoneULine(const char* tag)
427 /* Callback called before processing the first <module> tag
429 bool InitModule(const char* tag)
431 old_module_names.clear();
432 new_module_names.clear();
433 added_modules.clear();
434 removed_modules.clear();
435 for (std::vector<std::string>::iterator t = Config->module_names.begin(); t != Config->module_names.end(); t++)
437 old_module_names.push_back(*t);
442 /* Callback called to process a single <module> tag
444 bool DoModule(const char* tag, char** entries, void** values, int* types)
446 char* modname = (char*)values[0];
447 new_module_names.push_back(modname);
451 /* Callback called when there are no more <module> tags
453 bool DoneModule(const char* tag)
455 // now create a list of new modules that are due to be loaded
456 // and a seperate list of modules which are due to be unloaded
457 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
461 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
468 added_modules.push_back(*_new);
471 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
474 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
481 removed_modules.push_back(*oldm);
486 /* Callback called before processing the first <banlist> tag
488 bool InitMaxBans(const char* tag)
490 Config->maxbans.clear();
494 /* Callback called to process a single <banlist> tag
496 bool DoMaxBans(const char* tag, char** entries, void** values, int* types)
498 char* channel = (char*)values[0];
499 int* limit = (int*)values[1];
500 Config->maxbans[channel] = *limit;
504 /* Callback called when there are no more <banlist> tags.
506 bool DoneMaxBans(const char* tag)
511 void ServerConfig::Read(bool bail, userrec* user)
513 char debug[MAXBUF]; /* Temporary buffer for debugging value */
514 char* data[12]; /* Temporary buffers for reading multiple occurance tags into */
515 void* ptr[12]; /* Temporary pointers for passing to callbacks */
516 int r_i[12]; /* Temporary array for casting */
517 int rem = 0, add = 0; /* Number of modules added, number of modules removed */
518 std::ostringstream errstr; /* String stream containing the error output */
520 /* These tags MUST occur and must ONLY occur once in the config file */
521 static char* Once[] = { "server", "admin", "files", "power", "options", "pid", NULL };
523 /* These tags can occur ONCE or not at all */
524 static InitialConfig Values[] = {
525 {"options", "softlimit", &this->SoftLimit, DT_INTEGER, ValidateSoftLimit},
526 {"options", "somaxconn", &this->MaxConn, DT_INTEGER, ValidateMaxConn},
527 {"server", "name", &this->ServerName, DT_CHARPTR, ValidateServerName},
528 {"server", "description", &this->ServerDesc, DT_CHARPTR, NoValidation},
529 {"server", "network", &this->Network, DT_CHARPTR, NoValidation},
530 {"admin", "name", &this->AdminName, DT_CHARPTR, NoValidation},
531 {"admin", "email", &this->AdminEmail, DT_CHARPTR, NoValidation},
532 {"admin", "nick", &this->AdminNick, DT_CHARPTR, NoValidation},
533 {"files", "motd", &this->motd, DT_CHARPTR, ValidateMotd},
534 {"files", "rules", &this->rules, DT_CHARPTR, ValidateRules},
535 {"power", "diepass", &this->diepass, DT_CHARPTR, NoValidation},
536 {"power", "pauseval", &this->DieDelay, DT_INTEGER, NoValidation},
537 {"power", "restartpass", &this->restartpass, DT_CHARPTR, NoValidation},
538 {"options", "prefixquit", &this->PrefixQuit, DT_CHARPTR, NoValidation},
539 {"die", "value", &this->DieValue, DT_CHARPTR, NoValidation},
540 {"options", "loglevel", &debug, DT_CHARPTR, ValidateLogLevel},
541 {"options", "netbuffersize", &this->NetBufferSize, DT_INTEGER, ValidateNetBufferSize},
542 {"options", "maxwho", &this->MaxWhoResults, DT_INTEGER, ValidateMaxWho},
543 {"options", "allowhalfop", &this->AllowHalfop, DT_BOOLEAN, NoValidation},
544 {"dns", "server", &this->DNSServer, DT_CHARPTR, ValidateDnsServer},
545 {"dns", "timeout", &this->dns_timeout, DT_INTEGER, ValidateDnsTimeout},
546 {"options", "moduledir", &this->ModPath, DT_CHARPTR, ValidateModPath},
547 {"disabled", "commands", &this->DisabledCommands, DT_CHARPTR, NoValidation},
548 {"options", "operonlystats", &this->OperOnlyStats, DT_CHARPTR, NoValidation},
549 {"options", "customversion", &this->CustomVersion, DT_CHARPTR, NoValidation},
550 {"options", "hidesplits", &this->HideSplits, DT_BOOLEAN, NoValidation},
551 {"options", "hidebans", &this->HideBans, DT_BOOLEAN, NoValidation},
552 {"options", "hidewhois", &this->HideWhoisServer, DT_CHARPTR, NoValidation},
553 {"options", "operspywhois", &this->OperSpyWhois, DT_BOOLEAN, 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 /* Load and parse the config file, if there are any errors then explode */
623 /* Make a copy here so if it fails then we can carry on running with an unaffected config */
624 ConfigDataHash newconfig;
626 if (this->LoadConf(newconfig, CONFIG_FILE, errstr))
628 /* If we succeeded, set the ircd config to the new one */
629 Config->config_data = newconfig;
634 for(ConfigDataHash::const_iterator i = this->config_data.begin(); i != this->config_data.end(); i++)
636 c = (i->first != last) ? 1 : c+1;
639 std::cout << "[" << i->first << " " << c << "/" << this->config_data.count(i->first) << "]" << std::endl;
641 for(KeyValList::const_iterator j = i->second.begin(); j != i->second.end(); j++)
642 std::cout << "\t" << j->first << " = " << j->second << std::endl;
644 std::cout << "[/" << i->first << " " << c << "/" << this->config_data.count(i->first) << "]" << std::endl;
649 log(DEFAULT, "There were errors in your configuration:\n%s", errstr.str().c_str());
653 /* Unneeded because of the log() aboive? */
654 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
659 std::string errors = errstr.str();
660 std::string::size_type start;
661 unsigned int prefixlen;
664 /* ":Config->ServerName NOTICE user->nick :" */
665 prefixlen = strlen(Config->ServerName) + strlen(user->nick) + 11;
669 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
671 while(start < errors.length())
673 WriteServ(user->fd, "NOTICE %s :%s",user->nick, errors.substr(start, 510 - prefixlen).c_str());
674 start += 510 - prefixlen;
679 WriteOpers("There were errors in the configuration file:");
681 while(start < errors.length())
683 WriteOpers(errors.substr(start, 360).c_str());
692 /* Check we dont have more than one of singular tags, or any of them missing
694 for (int Index = 0; Once[Index]; Index++)
695 if (!CheckOnce(Once[Index],bail,user))
698 /* Read the values of all the tags which occur once or not at all, and call their callbacks.
700 for (int Index = 0; Values[Index].tag; Index++)
702 int* val_i = (int*) Values[Index].val;
703 char* val_c = (char*) Values[Index].val;
705 switch (Values[Index].datatype)
708 /* Assuming MAXBUF here, potentially unsafe */
709 ConfValue(this->config_data, Values[Index].tag, Values[Index].value, 0, val_c, MAXBUF);
713 ConfValueInteger(this->config_data, Values[Index].tag, Values[Index].value, 0, *val_i);
717 *val_i = ConfValueBool(this->config_data, Values[Index].tag, Values[Index].value, 0);
724 Values[Index].validation_function(Values[Index].tag, Values[Index].value, Values[Index].val);
727 /* Claim memory for use when reading multiple tags
729 for (int n = 0; n < 12; n++)
730 data[n] = new char[MAXBUF];
732 /* Read the multiple-tag items (class tags, connect tags, etc)
733 * and call the callbacks associated with them. We have three
734 * callbacks for these, a 'start', 'item' and 'end' callback.
737 /* XXX - Make this use ConfValueInteger and so on */
738 for (int Index = 0; MultiValues[Index].tag; Index++)
740 MultiValues[Index].init_function(MultiValues[Index].tag);
742 int number_of_tags = ConfValueEnum(this->config_data, MultiValues[Index].tag);
744 for (int tagnum = 0; tagnum < number_of_tags; tagnum++)
746 for (int valuenum = 0; MultiValues[Index].items[valuenum]; valuenum++)
748 ConfValue(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], tagnum, data[valuenum], MAXBUF);
750 switch (MultiValues[Index].datatype[valuenum])
753 ptr[valuenum] = data[valuenum];
756 r_i[valuenum] = atoi(data[valuenum]);
757 ptr[valuenum] = &r_i[valuenum];
760 r_i[valuenum] = ((*data[valuenum] == tolower('y')) || (*data[valuenum] == tolower('t')) || (*data[valuenum] == '1'));
761 ptr[valuenum] = &r_i[valuenum];
767 MultiValues[Index].validation_function(MultiValues[Index].tag, (char**)MultiValues[Index].items, ptr, MultiValues[Index].datatype);
770 MultiValues[Index].finish_function(MultiValues[Index].tag);
773 /* Free any memory we claimed
775 for (int n = 0; n < 12; n++)
778 // write once here, to try it out and make sure its ok
779 WritePID(Config->PID);
781 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
783 /* If we're rehashing, let's load any new modules, and unload old ones
787 ServerInstance->stats->BoundPortCount = BindPorts(false);
789 if (!removed_modules.empty())
790 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
792 if (ServerInstance->UnloadModule(removing->c_str()))
794 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
797 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
804 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
808 if (!added_modules.empty())
809 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
811 if (ServerInstance->LoadModule(adding->c_str()))
813 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
816 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
823 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
827 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());
831 void Exit(int status)
833 if (Config->log_file)
834 fclose(Config->log_file);
835 send_error("Server shutdown.");
839 void Killed(int status)
841 if (Config->log_file)
842 fclose(Config->log_file);
843 send_error("Server terminated.");
847 char* CleanFilename(char* name)
849 char* p = name + strlen(name);
850 while ((p != name) && (*p != '/')) p--;
851 return (p != name ? ++p : p);
855 void Rehash(int status)
857 WriteOpers("Rehashing config file %s due to SIGHUP",CleanFilename(CONFIG_FILE));
858 fclose(Config->log_file);
860 Config->Read(false,NULL);
861 FOREACH_MOD(I_OnRehash,OnRehash(""));
868 printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
869 printf("(C) ChatSpike Development team.\033[0m\n\n");
870 printf("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om\033[0m\n");
871 printf("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
872 printf("Name concept:\t\t\033[1;32mLord_Zathras\033[0m\n\n");
875 void WritePID(const std::string &filename)
877 ofstream outfile(filename.c_str());
878 if (outfile.is_open())
885 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
886 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
893 signal (SIGALRM, SIG_IGN);
894 signal (SIGHUP, Rehash);
895 signal (SIGPIPE, SIG_IGN);
896 signal (SIGTERM, Exit);
897 signal (SIGSEGV, Error);
904 if ((childpid = fork ()) < 0)
906 else if (childpid > 0)
908 /* We wait a few seconds here, so that the shell prompt doesnt come back over the output */
914 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
917 if (getrlimit(RLIMIT_CORE, &rl) == -1)
919 log(DEFAULT,"Failed to getrlimit()!");
924 rl.rlim_cur = rl.rlim_max;
925 if (setrlimit(RLIMIT_CORE, &rl) == -1)
926 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
933 /* Make Sure Modules Are Avaliable!
934 * (BugFix By Craig.. See? I do work! :p)
935 * Modified by brain, requires const char*
936 * to work with other API functions
940 bool FileExists (const char* file)
943 if ((input = fopen (file, "r")) == NULL)
954 bool ServerConfig::LoadConf(ConfigDataHash &target, const char* filename, std::ostringstream &errorstream)
956 std::ifstream conf(filename);
969 /* Check if the file open failed first */
972 errorstream << "LoadConf: Couldn't open config file: " << filename << std::endl;
976 /* Fix the chmod of the file to restrict it to the current user and group */
977 chmod(filename,0600);
979 for (unsigned int t = 0; t < include_stack.size(); t++)
981 if (std::string(filename) == include_stack[t])
983 errorstream << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
988 /* It's not already included, add it to the list of files we've loaded */
989 include_stack.push_back(filename);
991 /* Start reading characters... */
995 * Here we try and get individual tags on separate lines,
996 * this would be so easy if we just made people format
997 * their config files like that, but they don't so...
998 * We check for a '<' and then know the line is over when
999 * we get a '>' not inside quotes. If we find two '<' and
1000 * no '>' then die with an error.
1003 if((ch == '#') && !in_quote)
1006 if(((ch == '\n') || (ch == '\r')) && in_quote)
1008 errorstream << "Got a newline within a quoted section, this is probably a typo: " << filename << ":" << linenumber << std::endl;
1035 errorstream << "Got another opening < when the first one wasn't closed: " << filename << ":" << linenumber << std::endl;
1043 errorstream << "We're in a quote but outside a tag, interesting. " << filename << ":" << linenumber << std::endl;
1048 // errorstream << "Opening new config tag on line " << linenumber << std::endl;
1059 // errorstream << "Closing quote in config tag on line " << linenumber << std::endl;
1064 // errorstream << "Opening quote in config tag on line " << linenumber << std::endl;
1072 errorstream << "Found a (closing) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1076 errorstream << "Found a (opening) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1086 // errorstream << "Closing config tag on line " << linenumber << std::endl;
1090 * If this finds an <include> then ParseLine can simply call
1091 * LoadConf() and load the included config into the same ConfigDataHash
1094 if(!this->ParseLine(target, line, linenumber, errorstream))
1101 errorstream << "Got a closing > when we weren't inside a tag: " << filename << ":" << linenumber << std::endl;
1111 bool ServerConfig::LoadConf(ConfigDataHash &target, const std::string &filename, std::ostringstream &errorstream)
1113 return this->LoadConf(target, filename.c_str(), errorstream);
1116 bool ServerConfig::ParseLine(ConfigDataHash &target, std::string &line, long linenumber, std::ostringstream &errorstream)
1118 std::string tagname;
1119 std::string current_key;
1120 std::string current_value;
1126 got_name = got_key = in_quote = false;
1128 // std::cout << "ParseLine(data, '" << line << "', " << linenumber << ", stream)" << std::endl;
1130 for(std::string::iterator c = line.begin(); c != line.end(); c++)
1134 /* We don't know the tag name yet. */
1145 /* We got to a space, we should have the tagname now. */
1146 if(tagname.length())
1154 /* We have the tag name */
1157 /* We're still reading the key name */
1167 /* We got an '=', end of the key name. */
1173 /* We have the key name, now we're looking for quotes and the value */
1178 /* We're not already in a quote. */
1183 /* Leaving quotes, we have the value */
1184 results.push_back(KeyVal(current_key, current_value));
1186 // std::cout << "<" << tagname << ":" << current_key << "> " << current_value << std::endl;
1191 if((tagname == "include") && (current_key == "file"))
1193 if(!this->DoInclude(target, current_value, errorstream))
1197 current_key.clear();
1198 current_value.clear();
1205 current_value += *c;
1212 /* Finished parsing the tag, add it to the config hash */
1213 target.insert(std::pair<std::string, KeyValList > (tagname, results));
1218 bool ServerConfig::DoInclude(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream)
1220 std::string confpath;
1221 std::string newfile;
1222 std::string::size_type pos;
1224 confpath = CONFIG_FILE;
1227 for (std::string::iterator c = newfile.begin(); c != newfile.end(); c++)
1237 if((pos = confpath.find("/inspircd.conf")) != std::string::npos)
1239 /* Leaves us with just the path */
1240 newfile = confpath.substr(0, pos) + std::string("/") + newfile;
1244 errorstream << "Couldn't get config path from: " << confpath << std::endl;
1249 return LoadConf(target, newfile, errorstream);
1252 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, int index, char* result, int length)
1255 bool r = ConfValue(target, std::string(tag), std::string(var), index, value);
1256 strlcpy(result, value.c_str(), length);
1260 bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, std::string &result)
1262 ConfigDataHash::size_type pos = index;
1263 if((pos >= 0) && (pos < target.count(tag)))
1265 ConfigDataHash::const_iterator iter = target.find(tag);
1267 for(int i = 0; i < index; i++)
1270 for(KeyValList::const_iterator j = iter->second.begin(); j != iter->second.end(); j++)
1281 log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1285 log(DEBUG, "ConfValue got an out-of-range index %d, there are only %d occurences of %s", pos, target.count(tag), tag.c_str());
1291 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, int index, int &result)
1293 return ConfValueInteger(target, std::string(tag), std::string(var), index, result);
1296 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, int &result)
1299 std::istringstream stream;
1300 bool r = ConfValue(target, tag, var, index, value);
1302 if(!(stream >> result))
1307 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, int index)
1309 return ConfValueBool(target, std::string(tag), std::string(var), index);
1312 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, int index)
1315 if(!ConfValue(target, tag, var, index, result))
1318 return ((result == "yes") || (result == "true") || (result == "1"));
1321 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const char* tag)
1323 return target.count(tag);
1326 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const std::string &tag)
1328 return target.count(tag);
1331 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const char* tag, int index)
1333 return ConfVarEnum(target, std::string(tag), index);
1336 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const std::string &tag, int index)
1338 ConfigDataHash::size_type pos = index;
1340 if((pos >= 0) && (pos < target.count(tag)))
1342 ConfigDataHash::const_iterator iter = target.find(tag);
1344 for(int i = 0; i < index; i++)
1347 return iter->second.size();
1351 log(DEBUG, "No <%s> tags in config file.", tag.c_str());
1355 log(DEBUG, "ConfVarEnum got an out-of-range index %d, there are only %d occurences of %s", pos, target.count(tag), tag.c_str());
1361 /** This will bind a socket to a port. It works for UDP/TCP.
1362 * If a hostname is given to bind to, the function will first
1363 * attempt to resolve the hostname, then bind to the IP the
1364 * hostname resolves to. This is a blocking lookup blocking for
1365 * a maximum of one second before it times out, using the DNS
1366 * server specified in the configuration file.
1368 bool BindSocket(int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
1370 memset(&server,0,sizeof(server));
1371 struct in_addr addy;
1372 bool resolved = false;
1373 char resolved_addr[128];
1378 if (*addr && !inet_aton(addr,&addy))
1380 /* If they gave a hostname, bind to the IP it resolves to */
1381 if (CleanAndResolve(resolved_addr, addr, true))
1383 inet_aton(resolved_addr,&addy);
1384 log(DEFAULT,"Resolved binding '%s' -> '%s'",addr,resolved_addr);
1385 server.sin_addr = addy;
1390 log(DEFAULT,"WARNING: Could not resolve '%s' to an IP for binding to on port %d",addr,port);
1394 server.sin_family = AF_INET;
1399 server.sin_addr.s_addr = htonl(INADDR_ANY);
1403 server.sin_addr = addy;
1406 server.sin_port = htons(port);
1407 if (bind(sockfd,(struct sockaddr*)&server,sizeof(server)) < 0)
1413 log(DEBUG,"Bound port %s:%d",*addr ? addr : "*",port);
1414 if (listen(sockfd, Config->MaxConn) == -1)
1416 log(DEFAULT,"ERROR in listen(): %s",strerror(errno));
1421 NonBlocking(sockfd);
1428 // Open a TCP Socket
1433 struct linger linger = { 0 };
1435 if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
1437 log(DEFAULT,"Error creating TCP socket: %s",strerror(errno));
1442 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
1443 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
1445 linger.l_linger = 1;
1446 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, &linger,sizeof(linger));
1451 bool HasPort(int port, char* addr)
1453 for (int count = 0; count < ServerInstance->stats->BoundPortCount; count++)
1455 if ((port == Config->ports[count]) && (!strcasecmp(Config->addrs[count],addr)))
1463 int BindPorts(bool bail)
1465 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
1466 sockaddr_in client,server;
1467 int clientportcount = 0;
1468 int BoundPortCount = 0;
1472 int InitialPortCount = ServerInstance->stats->BoundPortCount;
1473 log(DEBUG,"Initial port count: %d",InitialPortCount);
1475 for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "bind"); count++)
1477 Config->ConfValue(Config->config_data, "bind", "port", count, configToken, MAXBUF);
1478 Config->ConfValue(Config->config_data, "bind", "address", count, Addr, MAXBUF);
1479 Config->ConfValue(Config->config_data, "bind", "type", count, Type, MAXBUF);
1481 if (((!*Type) || (!strcmp(Type,"clients"))) && (!HasPort(atoi(configToken),Addr)))
1483 // modules handle server bind types now
1484 Config->ports[clientportcount+InitialPortCount] = atoi(configToken);
1488 strlcpy(Config->addrs[clientportcount+InitialPortCount],Addr,256);
1490 log(DEBUG,"NEW binding %s:%s [%s] from config",Addr,configToken, Type);
1493 int PortCount = clientportcount;
1496 for (int count = InitialPortCount; count < InitialPortCount + PortCount; count++)
1498 if ((openSockfd[count] = OpenTCPSocket()) == ERROR)
1500 log(DEBUG,"Bad fd %d binding port [%s:%d]",openSockfd[count],Config->addrs[count],Config->ports[count]);
1503 if (!BindSocket(openSockfd[count],client,server,Config->ports[count],Config->addrs[count]))
1505 log(DEFAULT,"Failed to bind port [%s:%d]: %s",Config->addrs[count],Config->ports[count],strerror(errno));
1509 /* Associate the new open port with a slot in the socket engine */
1510 ServerInstance->SE->AddFd(openSockfd[count],true,X_LISTEN);
1514 return InitialPortCount + BoundPortCount;
1518 log(DEBUG,"There is nothing new to bind!");
1520 return InitialPortCount;
1523 for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "bind"); count++)
1525 Config->ConfValue(Config->config_data, "bind", "port", count, configToken, MAXBUF);
1526 Config->ConfValue(Config->config_data, "bind", "address", count, Addr, MAXBUF);
1527 Config->ConfValue(Config->config_data, "bind", "type", count, Type, MAXBUF);
1529 if ((!*Type) || (!strcmp(Type,"clients")))
1531 // modules handle server bind types now
1532 Config->ports[clientportcount] = atoi(configToken);
1534 // If the client put bind "*", this is an unrealism.
1535 // We don't actually support this as documented, but
1536 // i got fed up of people trying it, so now it converts
1537 // it to an empty string meaning the same 'bind to all'.
1541 strlcpy(Config->addrs[clientportcount],Addr,256);
1543 log(DEBUG,"Binding %s:%s [%s] from config",Addr,configToken, Type);
1547 int PortCount = clientportcount;
1549 for (int count = 0; count < PortCount; count++)
1551 if ((openSockfd[BoundPortCount] = OpenTCPSocket()) == ERROR)
1553 log(DEBUG,"Bad fd %d binding port [%s:%d]",openSockfd[BoundPortCount],Config->addrs[count],Config->ports[count]);
1557 if (!BindSocket(openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]))
1559 log(DEFAULT,"Failed to bind port [%s:%d]: %s",Config->addrs[count],Config->ports[count],strerror(errno));
1563 /* well we at least bound to one socket so we'll continue */
1568 /* if we didn't bind to anything then abort */
1569 if (!BoundPortCount)
1571 log(DEFAULT,"No ports bound, bailing!");
1572 printf("\nERROR: Could not bind any of %d ports! Please check your configuration.\n\n", PortCount);
1576 return BoundPortCount;