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 = 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(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 ValidateNetworkName(const char* tag, const char* value, void* data)
272 char* x = (char*)data;
274 log(DEFAULT,"<server:network> '%s'",x);
279 bool ValidateServerDesc(const char* tag, const char* value, void* data)
281 char* x = (char*)data;
283 log(DEFAULT,"<server:description> '%s'",x);
288 bool ValidateNetBufferSize(const char* tag, const char* value, void* data)
290 if ((!Config->NetBufferSize) || (Config->NetBufferSize > 65535) || (Config->NetBufferSize < 1024))
292 log(DEFAULT,"No NetBufferSize specified or size out of range, setting to default of 10240.");
293 Config->NetBufferSize = 10240;
298 bool ValidateMaxWho(const char* tag, const char* value, void* data)
300 if ((!Config->MaxWhoResults) || (Config->MaxWhoResults > 65535) || (Config->MaxWhoResults < 1))
302 log(DEFAULT,"No MaxWhoResults specified or size out of range, setting to default of 128.");
303 Config->MaxWhoResults = 128;
308 bool ValidateLogLevel(const char* tag, const char* value, void* data)
310 const char* dbg = (const char*)data;
311 Config->LogLevel = DEFAULT;
312 if (!strcmp(dbg,"debug"))
314 Config->LogLevel = DEBUG;
315 Config->debugging = 1;
317 else if (!strcmp(dbg,"verbose"))
318 Config->LogLevel = VERBOSE;
319 else if (!strcmp(dbg,"default"))
320 Config->LogLevel = DEFAULT;
321 else if (!strcmp(dbg,"sparse"))
322 Config->LogLevel = SPARSE;
323 else if (!strcmp(dbg,"none"))
324 Config->LogLevel = NONE;
328 bool ValidateMotd(const char* tag, const char* value, void* data)
330 readfile(Config->MOTD,Config->motd);
334 bool ValidateRules(const char* tag, const char* value, void* data)
336 readfile(Config->RULES,Config->rules);
340 /* Callback called before processing the first <connect> tag
342 bool InitConnect(const char* tag)
344 log(DEFAULT,"Reading connect classes...");
345 Config->Classes.clear();
349 /* Callback called to process a single <connect> tag
351 bool DoConnect(const char* tag, char** entries, void** values, int* types)
354 char* allow = (char*)values[0]; /* Yeah, there are a lot of values. Live with it. */
355 char* deny = (char*)values[1];
356 char* password = (char*)values[2];
357 int* timeout = (int*)values[3];
358 int* pingfreq = (int*)values[4];
359 int* flood = (int*)values[5];
360 int* threshold = (int*)values[6];
361 int* sendq = (int*)values[7];
362 int* recvq = (int*)values[8];
363 int* localmax = (int*)values[9];
364 int* globalmax = (int*)values[10];
371 c.registration_timeout = *timeout;
372 c.pingtime = *pingfreq;
374 c.threshold = *threshold;
377 c.maxlocal = *localmax;
378 c.maxglobal = *globalmax;
383 if (c.maxglobal == 0)
385 if (c.threshold == 0)
389 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());
395 if (c.registration_timeout == 0)
396 c.registration_timeout = 90;
399 Config->Classes.push_back(c);
405 Config->Classes.push_back(c);
406 log(DEBUG,"Read connect class type DENY, host=%s",deny);
412 /* Callback called when there are no more <connect> tags
414 bool DoneConnect(const char* tag)
416 log(DEBUG,"DoneConnect called for tag: %s",tag);
420 /* Callback called before processing the first <uline> tag
422 bool InitULine(const char* tag)
424 Config->ulines.clear();
428 /* Callback called to process a single <uline> tag
430 bool DoULine(const char* tag, char** entries, void** values, int* types)
432 char* server = (char*)values[0];
433 log(DEBUG,"Read ULINE '%s'",server);
434 Config->ulines.push_back(server);
438 /* Callback called when there are no more <uline> tags
440 bool DoneULine(const char* tag)
445 /* Callback called before processing the first <module> tag
447 bool InitModule(const char* tag)
449 old_module_names.clear();
450 new_module_names.clear();
451 added_modules.clear();
452 removed_modules.clear();
453 for (std::vector<std::string>::iterator t = Config->module_names.begin(); t != Config->module_names.end(); t++)
455 old_module_names.push_back(*t);
460 /* Callback called to process a single <module> tag
462 bool DoModule(const char* tag, char** entries, void** values, int* types)
464 char* modname = (char*)values[0];
465 new_module_names.push_back(modname);
469 /* Callback called when there are no more <module> tags
471 bool DoneModule(const char* tag)
473 // now create a list of new modules that are due to be loaded
474 // and a seperate list of modules which are due to be unloaded
475 for (std::vector<std::string>::iterator _new = new_module_names.begin(); _new != new_module_names.end(); _new++)
479 for (std::vector<std::string>::iterator old = old_module_names.begin(); old != old_module_names.end(); old++)
486 added_modules.push_back(*_new);
489 for (std::vector<std::string>::iterator oldm = old_module_names.begin(); oldm != old_module_names.end(); oldm++)
492 for (std::vector<std::string>::iterator newm = new_module_names.begin(); newm != new_module_names.end(); newm++)
499 removed_modules.push_back(*oldm);
504 /* Callback called before processing the first <banlist> tag
506 bool InitMaxBans(const char* tag)
508 Config->maxbans.clear();
512 /* Callback called to process a single <banlist> tag
514 bool DoMaxBans(const char* tag, char** entries, void** values, int* types)
516 char* channel = (char*)values[0];
517 int* limit = (int*)values[1];
518 Config->maxbans[channel] = *limit;
522 /* Callback called when there are no more <banlist> tags.
524 bool DoneMaxBans(const char* tag)
529 void ServerConfig::Read(bool bail, userrec* user)
531 char debug[MAXBUF]; /* Temporary buffer for debugging value */
532 char* data[12]; /* Temporary buffers for reading multiple occurance tags into */
533 void* ptr[12]; /* Temporary pointers for passing to callbacks */
534 int r_i[12]; /* Temporary array for casting */
535 int rem = 0, add = 0; /* Number of modules added, number of modules removed */
536 std::ostringstream errstr; /* String stream containing the error output */
538 /* These tags MUST occur and must ONLY occur once in the config file */
539 static char* Once[] = { "server", "admin", "files", "power", "options", "pid", NULL };
541 /* These tags can occur ONCE or not at all */
542 static InitialConfig Values[] = {
543 {"options", "softlimit", &this->SoftLimit, DT_INTEGER, ValidateSoftLimit},
544 {"options", "somaxconn", &this->MaxConn, DT_INTEGER, ValidateMaxConn},
545 {"server", "name", &this->ServerName, DT_CHARPTR, ValidateServerName},
546 {"server", "description", &this->ServerDesc, DT_CHARPTR, ValidateServerDesc},
547 {"server", "network", &this->Network, DT_CHARPTR, ValidateNetworkName},
548 {"admin", "name", &this->AdminName, DT_CHARPTR, NoValidation},
549 {"admin", "email", &this->AdminEmail, DT_CHARPTR, NoValidation},
550 {"admin", "nick", &this->AdminNick, DT_CHARPTR, NoValidation},
551 {"files", "motd", &this->motd, DT_CHARPTR, ValidateMotd},
552 {"files", "rules", &this->rules, DT_CHARPTR, ValidateRules},
553 {"power", "diepass", &this->diepass, DT_CHARPTR, NoValidation},
554 {"power", "pauseval", &this->DieDelay, DT_INTEGER, NoValidation},
555 {"power", "restartpass", &this->restartpass, DT_CHARPTR, NoValidation},
556 {"options", "prefixquit", &this->PrefixQuit, DT_CHARPTR, NoValidation},
557 {"die", "value", &this->DieValue, DT_CHARPTR, NoValidation},
558 {"options", "loglevel", &debug, DT_CHARPTR, ValidateLogLevel},
559 {"options", "netbuffersize", &this->NetBufferSize, DT_INTEGER, ValidateNetBufferSize},
560 {"options", "maxwho", &this->MaxWhoResults, DT_INTEGER, ValidateMaxWho},
561 {"options", "allowhalfop", &this->AllowHalfop, DT_BOOLEAN, NoValidation},
562 {"dns", "server", &this->DNSServer, DT_CHARPTR, ValidateDnsServer},
563 {"dns", "timeout", &this->dns_timeout, DT_INTEGER, ValidateDnsTimeout},
564 {"options", "moduledir", &this->ModPath, DT_CHARPTR, ValidateModPath},
565 {"disabled", "commands", &this->DisabledCommands,DT_CHARPTR, NoValidation},
566 {"options", "operonlystats", &this->OperOnlyStats, DT_CHARPTR, NoValidation},
567 {"options", "customversion", &this->CustomVersion, DT_CHARPTR, NoValidation},
568 {"options", "hidesplits", &this->HideSplits, DT_BOOLEAN, NoValidation},
569 {"options", "hidebans", &this->HideBans, DT_BOOLEAN, NoValidation},
570 {"options", "hidewhois", &this->HideWhoisServer, DT_CHARPTR, NoValidation},
571 {"options", "operspywhois", &this->OperSpyWhois, DT_BOOLEAN, NoValidation},
572 {"options", "tempdir", &this->TempDir, DT_CHARPTR, ValidateTempDir},
573 {"pid", "file", &this->PID, DT_CHARPTR, NoValidation},
577 /* These tags can occur multiple times, and therefore they have special code to read them
578 * which is different to the code for reading the singular tags listed above.
580 static MultiConfig MultiValues[] = {
583 {"allow", "deny", "password", "timeout", "pingfreq", "flood",
584 "threshold", "sendq", "recvq", "localmax", "globalmax", NULL},
585 {DT_CHARPTR, DT_CHARPTR, DT_CHARPTR, DT_INTEGER, DT_INTEGER, DT_INTEGER,
586 DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER, DT_INTEGER},
587 InitConnect, DoConnect, DoneConnect},
592 InitULine,DoULine,DoneULine},
595 {"chan", "limit", NULL},
596 {DT_CHARPTR, DT_INTEGER},
597 InitMaxBans, DoMaxBans, DoneMaxBans},
602 InitModule, DoModule, DoneModule},
605 {"reason", "ipmask", NULL},
606 {DT_CHARPTR, DT_CHARPTR},
607 InitXLine, DoZLine, DoneXLine},
610 {"reason", "nick", NULL},
611 {DT_CHARPTR, DT_CHARPTR},
612 InitXLine, DoQLine, DoneXLine},
615 {"reason", "host", NULL},
616 {DT_CHARPTR, DT_CHARPTR},
617 InitXLine, DoKLine, DoneXLine},
620 {"reason", "host", NULL},
621 {DT_CHARPTR, DT_CHARPTR},
622 InitXLine, DoELine, DoneXLine},
625 {"name", "classes", NULL},
626 {DT_CHARPTR, DT_CHARPTR},
627 InitTypes, DoType, DoneClassesAndTypes},
630 {"name", "commands", NULL},
631 {DT_CHARPTR, DT_CHARPTR},
632 InitClasses, DoClass, DoneClassesAndTypes},
637 include_stack.clear();
639 /* Load and parse the config file, if there are any errors then explode */
641 /* Make a copy here so if it fails then we can carry on running with an unaffected config */
642 ConfigDataHash newconfig;
644 if (this->LoadConf(newconfig, CONFIG_FILE, errstr))
646 /* If we succeeded, set the ircd config to the new one */
647 Config->config_data = newconfig;
652 for(ConfigDataHash::const_iterator i = this->config_data.begin(); i != this->config_data.end(); i++)
659 std::cout << "[" << i->first << " " << c << "/" << this->config_data.count(i->first) << "]" << std::endl;
661 for(KeyValList::const_iterator j = i->second.begin(); j != i->second.end(); j++)
663 std::cout << "\t" << j->first << " = " << j->second << std::endl;
666 std::cout << "[/" << i->first << " " << c << "/" << this->config_data.count(i->first) << "]" << std::endl;
671 for(ConfigDataHash::const_iterator i = this->config_data.begin(); i != this->config_data.end(); i++)
673 std::cout << "There are " << ConfValueEnum(this->config_data, i->first) << " <" << i->first << "> tags" << std::endl;
675 for(int j = 0; j < ConfValueEnum(this->config_data, i->first); j++)
678 if(ConfValue(this->config_data, i->first, "name", j, foo))
680 std::cout << "<" << i->first << ":name> " << foo << std::endl;
684 std::cout << "<" << i->first << ":name> undef" << std::endl;
691 log(DEFAULT, "There were errors in your configuration:\n%s", errstr.str().c_str());
695 printf("There were errors in your configuration:\n%s",errstr.str().c_str());
700 std::string errors = errstr.str();
701 std::string::size_type start;
702 unsigned int prefixlen;
705 /* ":Config->ServerName NOTICE user->nick :" */
706 prefixlen = strlen(Config->ServerName) + strlen(user->nick) + 11;
710 WriteServ(user->fd,"NOTICE %s :There were errors in the configuration file:",user->nick);
712 while(start < errors.length())
714 WriteServ(user->fd, "NOTICE %s :%s",user->nick, errors.substr(start, 510 - prefixlen).c_str());
715 start += 510 - prefixlen;
720 WriteOpers("There were errors in the configuration file:");
722 while(start < errors.length())
724 WriteOpers(errors.substr(start, 360).c_str());
733 /* Check we dont have more than one of singular tags, or any of them missing
735 for (int Index = 0; Once[Index]; Index++)
736 if (!CheckOnce(Once[Index],bail,user))
739 /* Read the values of all the tags which occur once or not at all, and call their callbacks.
741 for (int Index = 0; Values[Index].tag; Index++)
743 int* val_i = (int*) Values[Index].val;
744 char* val_c = (char*) Values[Index].val;
746 switch (Values[Index].datatype)
749 /* Assuming MAXBUF here, potentially unsafe */
750 ConfValue(this->config_data, Values[Index].tag, Values[Index].value, 0, val_c, MAXBUF);
754 ConfValueInteger(this->config_data, Values[Index].tag, Values[Index].value, 0, *val_i);
758 *val_i = ConfValueBool(this->config_data, Values[Index].tag, Values[Index].value, 0);
765 Values[Index].validation_function(Values[Index].tag, Values[Index].value, Values[Index].val);
768 /* Claim memory for use when reading multiple tags
770 for (int n = 0; n < 12; n++)
771 data[n] = new char[MAXBUF];
773 /* Read the multiple-tag items (class tags, connect tags, etc)
774 * and call the callbacks associated with them. We have three
775 * callbacks for these, a 'start', 'item' and 'end' callback.
778 /* XXX - Make this use ConfValueInteger and so on */
779 for (int Index = 0; MultiValues[Index].tag; Index++)
781 MultiValues[Index].init_function(MultiValues[Index].tag);
783 int number_of_tags = ConfValueEnum(this->config_data, MultiValues[Index].tag);
785 for (int tagnum = 0; tagnum < number_of_tags; tagnum++)
787 for (int valuenum = 0; MultiValues[Index].items[valuenum]; valuenum++)
789 ConfValue(this->config_data, MultiValues[Index].tag, MultiValues[Index].items[valuenum], tagnum, data[valuenum], MAXBUF);
791 switch (MultiValues[Index].datatype[valuenum])
794 ptr[valuenum] = data[valuenum];
797 r_i[valuenum] = atoi(data[valuenum]);
798 ptr[valuenum] = &r_i[valuenum];
801 r_i[valuenum] = ((*data[valuenum] == tolower('y')) || (*data[valuenum] == tolower('t')) || (*data[valuenum] == '1'));
802 ptr[valuenum] = &r_i[valuenum];
808 MultiValues[Index].validation_function(MultiValues[Index].tag, (char**)MultiValues[Index].items, ptr, MultiValues[Index].datatype);
811 MultiValues[Index].finish_function(MultiValues[Index].tag);
814 /* Free any memory we claimed
816 for (int n = 0; n < 12; n++)
819 // write once here, to try it out and make sure its ok
820 WritePID(Config->PID);
822 log(DEFAULT,"Done reading configuration file, InspIRCd is now starting.");
824 /* If we're rehashing, let's load any new modules, and unload old ones
828 ServerInstance->stats->BoundPortCount = BindPorts(false);
830 if (!removed_modules.empty())
831 for (std::vector<std::string>::iterator removing = removed_modules.begin(); removing != removed_modules.end(); removing++)
833 if (ServerInstance->UnloadModule(removing->c_str()))
835 WriteOpers("*** REHASH UNLOADED MODULE: %s",removing->c_str());
838 WriteServ(user->fd,"973 %s %s :Module %s successfully unloaded.",user->nick, removing->c_str(), removing->c_str());
845 WriteServ(user->fd,"972 %s %s :Failed to unload module %s: %s",user->nick, removing->c_str(), removing->c_str(), ServerInstance->ModuleError());
849 if (!added_modules.empty())
850 for (std::vector<std::string>::iterator adding = added_modules.begin(); adding != added_modules.end(); adding++)
852 if (ServerInstance->LoadModule(adding->c_str()))
854 WriteOpers("*** REHASH LOADED MODULE: %s",adding->c_str());
857 WriteServ(user->fd,"975 %s %s :Module %s successfully loaded.",user->nick, adding->c_str(), adding->c_str());
864 WriteServ(user->fd,"974 %s %s :Failed to load module %s: %s",user->nick, adding->c_str(), adding->c_str(), ServerInstance->ModuleError());
868 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());
872 void Exit(int status)
874 if (Config->log_file)
875 fclose(Config->log_file);
876 send_error("Server shutdown.");
880 void Killed(int status)
882 if (Config->log_file)
883 fclose(Config->log_file);
884 send_error("Server terminated.");
888 char* CleanFilename(char* name)
890 char* p = name + strlen(name);
891 while ((p != name) && (*p != '/')) p--;
892 return (p != name ? ++p : p);
896 void Rehash(int status)
898 WriteOpers("Rehashing config file %s due to SIGHUP",CleanFilename(CONFIG_FILE));
899 fclose(Config->log_file);
901 Config->Read(false,NULL);
902 FOREACH_MOD(I_OnRehash,OnRehash(""));
909 printf("\033[1;32mInspire Internet Relay Chat Server, compiled %s at %s\n",__DATE__,__TIME__);
910 printf("(C) ChatSpike Development team.\033[0m\n\n");
911 printf("Developers:\t\t\033[1;32mBrain, FrostyCoolSlug, w00t, Om\033[0m\n");
912 printf("Others:\t\t\t\033[1;32mSee /INFO Output\033[0m\n");
913 printf("Name concept:\t\t\033[1;32mLord_Zathras\033[0m\n\n");
916 void WritePID(const std::string &filename)
918 ofstream outfile(filename.c_str());
919 if (outfile.is_open())
926 printf("Failed to write PID-file '%s', exiting.\n",filename.c_str());
927 log(DEFAULT,"Failed to write PID-file '%s', exiting.",filename.c_str());
934 signal (SIGALRM, SIG_IGN);
935 signal (SIGHUP, Rehash);
936 signal (SIGPIPE, SIG_IGN);
937 signal (SIGTERM, Exit);
938 signal (SIGSEGV, Error);
945 if ((childpid = fork ()) < 0)
947 else if (childpid > 0)
949 /* We wait a few seconds here, so that the shell prompt doesnt come back over the output */
955 printf("InspIRCd Process ID: \033[1;32m%lu\033[0m\n",(unsigned long)getpid());
958 if (getrlimit(RLIMIT_CORE, &rl) == -1)
960 log(DEFAULT,"Failed to getrlimit()!");
965 rl.rlim_cur = rl.rlim_max;
966 if (setrlimit(RLIMIT_CORE, &rl) == -1)
967 log(DEFAULT,"setrlimit() failed, cannot increase coredump size.");
974 /* Make Sure Modules Are Avaliable!
975 * (BugFix By Craig.. See? I do work! :p)
976 * Modified by brain, requires const char*
977 * to work with other API functions
981 bool FileExists (const char* file)
984 if ((input = fopen (file, "r")) == NULL)
995 bool ServerConfig::LoadConf(ConfigDataHash &target, const char* filename, std::ostringstream &errorstream)
997 std::ifstream conf(filename);
1010 /* Check if the file open failed first */
1013 errorstream << "LoadConf: Couldn't open config file: " << filename << std::endl;
1017 /* Fix the chmod of the file to restrict it to the current user and group */
1018 chmod(filename,0600);
1020 for (unsigned int t = 0; t < include_stack.size(); t++)
1022 if (std::string(filename) == include_stack[t])
1024 errorstream << "File " << filename << " is included recursively (looped inclusion)." << std::endl;
1029 /* It's not already included, add it to the list of files we've loaded */
1030 include_stack.push_back(filename);
1032 /* Start reading characters... */
1036 * Here we try and get individual tags on separate lines,
1037 * this would be so easy if we just made people format
1038 * their config files like that, but they don't so...
1039 * We check for a '<' and then know the line is over when
1040 * we get a '>' not inside quotes. If we find two '<' and
1041 * no '>' then die with an error.
1044 if((ch == '#') && !in_quote)
1070 errorstream << "Got another opening < when the first one wasn't closed: " << filename << ":" << linenumber << std::endl;
1078 errorstream << "We're in a quote but outside a tag, interesting. " << filename << ":" << linenumber << std::endl;
1083 // errorstream << "Opening new config tag on line " << linenumber << std::endl;
1094 // errorstream << "Closing quote in config tag on line " << linenumber << std::endl;
1099 // errorstream << "Opening quote in config tag on line " << linenumber << std::endl;
1107 errorstream << "Found a (closing) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1111 errorstream << "Found a (opening) \" outside a tag: " << filename << ":" << linenumber << std::endl;
1121 // errorstream << "Closing config tag on line " << linenumber << std::endl;
1125 * If this finds an <include> then ParseLine can simply call
1126 * LoadConf() and load the included config into the same ConfigDataHash
1129 if(!this->ParseLine(target, line, linenumber, errorstream))
1136 errorstream << "Got a closing > when we weren't inside a tag: " << filename << ":" << linenumber << std::endl;
1146 bool ServerConfig::LoadConf(ConfigDataHash &target, const std::string &filename, std::ostringstream &errorstream)
1148 return this->LoadConf(target, filename.c_str(), errorstream);
1151 bool ServerConfig::ParseLine(ConfigDataHash &target, std::string &line, long linenumber, std::ostringstream &errorstream)
1153 std::string tagname;
1154 std::string current_key;
1155 std::string current_value;
1161 got_name = got_key = in_quote = false;
1163 // std::cout << "ParseLine(data, '" << line << "', " << linenumber << ", stream)" << std::endl;
1165 for(std::string::iterator c = line.begin(); c != line.end(); c++)
1169 /* We don't know the tag name yet. */
1180 /* We got to a space, we should have the tagname now. */
1181 if(tagname.length())
1189 /* We have the tag name */
1192 /* We're still reading the key name */
1202 /* We got an '=', end of the key name. */
1208 /* We have the key name, now we're looking for quotes and the value */
1213 /* We're not already in a quote. */
1218 /* Leaving quotes, we have the value */
1219 results.push_back(KeyVal(current_key, current_value));
1220 std::cout << "<" << tagname << ":" << current_key << "> " << current_value << std::endl;
1224 if((tagname == "include") && (current_key == "file"))
1226 if(!this->DoInclude(target, current_value, errorstream))
1230 current_key.clear();
1231 current_value.clear();
1238 current_value += *c;
1245 /* Finished parsing the tag, add it to the config hash */
1246 target.insert(std::pair<std::string, KeyValList > (tagname, results));
1251 bool ServerConfig::DoInclude(ConfigDataHash &target, const std::string &file, std::ostringstream &errorstream)
1253 std::string confpath;
1254 std::string newfile;
1255 std::string::size_type pos;
1257 confpath = CONFIG_FILE;
1260 for (std::string::iterator c = newfile.begin(); c != newfile.end(); c++)
1270 if((pos = confpath.find("/inspircd.conf")) != std::string::npos)
1272 /* Leaves us with just the path */
1273 newfile = confpath.substr(0, pos) + std::string("/") + newfile;
1277 errorstream << "Couldn't get config path from: " << confpath << std::endl;
1282 return LoadConf(target, newfile, errorstream);
1285 bool ServerConfig::ConfValue(ConfigDataHash &target, const char* tag, const char* var, int index, char* result, int length)
1288 bool r = ConfValue(target, std::string(tag), std::string(var), index, value);
1289 strlcpy(result, value.c_str(), length);
1293 bool ServerConfig::ConfValue(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, std::string &result)
1295 ConfigDataHash::size_type pos = index;
1296 if((pos >= 0) && (pos < target.count(tag)))
1298 ConfigDataHash::const_iterator iter = target.find(tag);
1300 for(int i = 0; i < index; i++)
1303 for(KeyValList::const_iterator j = iter->second.begin(); j != iter->second.end(); j++)
1314 log(DEBUG, "ConfValue got an out-of-range index %d", pos);
1320 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const char* tag, const char* var, int index, int &result)
1322 return ConfValueInteger(target, std::string(tag), std::string(var), index, result);
1325 bool ServerConfig::ConfValueInteger(ConfigDataHash &target, const std::string &tag, const std::string &var, int index, int &result)
1328 std::istringstream stream;
1329 bool r = ConfValue(target, tag, var, index, value);
1331 if(!(stream >> result))
1336 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const char* tag, const char* var, int index)
1338 return ConfValueBool(target, std::string(tag), std::string(var), index);
1341 bool ServerConfig::ConfValueBool(ConfigDataHash &target, const std::string &tag, const std::string &var, int index)
1344 if(!ConfValue(target, tag, var, index, result))
1347 return ((result == "yes") || (result == "true") || (result == "1"));
1350 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const char* tag)
1352 return ConfValueEnum(target, std::string(tag));
1355 int ServerConfig::ConfValueEnum(ConfigDataHash &target, const std::string &tag)
1357 return target.count(tag);
1360 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const char* tag, int index)
1365 int ServerConfig::ConfVarEnum(ConfigDataHash &target, const std::string &tag, int index)
1367 ConfigDataHash::size_type pos = index;
1369 if((pos >= 0) && (pos < target.count(tag)))
1371 ConfigDataHash::const_iterator iter = target.find(tag);
1373 for(int i = 0; i < index; i++)
1376 return iter->second.size();
1380 log(DEBUG, "ConfVarEnum got an out-of-range index %d", pos);
1386 /** This will bind a socket to a port. It works for UDP/TCP.
1387 * If a hostname is given to bind to, the function will first
1388 * attempt to resolve the hostname, then bind to the IP the
1389 * hostname resolves to. This is a blocking lookup blocking for
1390 * a maximum of one second before it times out, using the DNS
1391 * server specified in the configuration file.
1393 bool BindSocket(int sockfd, struct sockaddr_in client, struct sockaddr_in server, int port, char* addr)
1395 memset(&server,0,sizeof(server));
1396 struct in_addr addy;
1397 bool resolved = false;
1398 char resolved_addr[128];
1403 if (*addr && !inet_aton(addr,&addy))
1405 /* If they gave a hostname, bind to the IP it resolves to */
1406 if (CleanAndResolve(resolved_addr, addr, true))
1408 inet_aton(resolved_addr,&addy);
1409 log(DEFAULT,"Resolved binding '%s' -> '%s'",addr,resolved_addr);
1410 server.sin_addr = addy;
1415 log(DEFAULT,"WARNING: Could not resolve '%s' to an IP for binding to on port %d",addr,port);
1419 server.sin_family = AF_INET;
1424 server.sin_addr.s_addr = htonl(INADDR_ANY);
1428 server.sin_addr = addy;
1431 server.sin_port = htons(port);
1432 if (bind(sockfd,(struct sockaddr*)&server,sizeof(server)) < 0)
1438 log(DEBUG,"Bound port %s:%d",*addr ? addr : "*",port);
1439 if (listen(sockfd, Config->MaxConn) == -1)
1441 log(DEFAULT,"ERROR in listen(): %s",strerror(errno));
1446 NonBlocking(sockfd);
1453 // Open a TCP Socket
1458 struct linger linger = { 0 };
1460 if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
1462 log(DEFAULT,"Error creating TCP socket: %s",strerror(errno));
1467 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
1468 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
1470 linger.l_linger = 1;
1471 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, &linger,sizeof(linger));
1476 bool HasPort(int port, char* addr)
1478 for (int count = 0; count < ServerInstance->stats->BoundPortCount; count++)
1480 if ((port == Config->ports[count]) && (!strcasecmp(Config->addrs[count],addr)))
1488 int BindPorts(bool bail)
1490 char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
1491 sockaddr_in client,server;
1492 int clientportcount = 0;
1493 int BoundPortCount = 0;
1497 int InitialPortCount = ServerInstance->stats->BoundPortCount;
1498 log(DEBUG,"Initial port count: %d",InitialPortCount);
1500 for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "bind"); count++)
1502 Config->ConfValue(Config->config_data, "bind", "port", count, configToken, MAXBUF);
1503 Config->ConfValue(Config->config_data, "bind", "address", count, Addr, MAXBUF);
1504 Config->ConfValue(Config->config_data, "bind", "type", count, Type, MAXBUF);
1506 if (((!*Type) || (!strcmp(Type,"clients"))) && (!HasPort(atoi(configToken),Addr)))
1508 // modules handle server bind types now
1509 Config->ports[clientportcount+InitialPortCount] = atoi(configToken);
1513 strlcpy(Config->addrs[clientportcount+InitialPortCount],Addr,256);
1515 log(DEBUG,"NEW binding %s:%s [%s] from config",Addr,configToken, Type);
1518 int PortCount = clientportcount;
1521 for (int count = InitialPortCount; count < InitialPortCount + PortCount; count++)
1523 if ((openSockfd[count] = OpenTCPSocket()) == ERROR)
1525 log(DEBUG,"Bad fd %d binding port [%s:%d]",openSockfd[count],Config->addrs[count],Config->ports[count]);
1528 if (!BindSocket(openSockfd[count],client,server,Config->ports[count],Config->addrs[count]))
1530 log(DEFAULT,"Failed to bind port [%s:%d]: %s",Config->addrs[count],Config->ports[count],strerror(errno));
1534 /* Associate the new open port with a slot in the socket engine */
1535 ServerInstance->SE->AddFd(openSockfd[count],true,X_LISTEN);
1539 return InitialPortCount + BoundPortCount;
1543 log(DEBUG,"There is nothing new to bind!");
1545 return InitialPortCount;
1548 for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "bind"); count++)
1550 Config->ConfValue(Config->config_data, "bind", "port", count, configToken, MAXBUF);
1551 Config->ConfValue(Config->config_data, "bind", "address", count, Addr, MAXBUF);
1552 Config->ConfValue(Config->config_data, "bind", "type", count, Type, MAXBUF);
1554 if ((!*Type) || (!strcmp(Type,"clients")))
1556 // modules handle server bind types now
1557 Config->ports[clientportcount] = atoi(configToken);
1559 // If the client put bind "*", this is an unrealism.
1560 // We don't actually support this as documented, but
1561 // i got fed up of people trying it, so now it converts
1562 // it to an empty string meaning the same 'bind to all'.
1566 strlcpy(Config->addrs[clientportcount],Addr,256);
1568 log(DEBUG,"Binding %s:%s [%s] from config",Addr,configToken, Type);
1572 int PortCount = clientportcount;
1574 for (int count = 0; count < PortCount; count++)
1576 if ((openSockfd[BoundPortCount] = OpenTCPSocket()) == ERROR)
1578 log(DEBUG,"Bad fd %d binding port [%s:%d]",openSockfd[BoundPortCount],Config->addrs[count],Config->ports[count]);
1582 if (!BindSocket(openSockfd[BoundPortCount],client,server,Config->ports[count],Config->addrs[count]))
1584 log(DEFAULT,"Failed to bind port [%s:%d]: %s",Config->addrs[count],Config->ports[count],strerror(errno));
1588 /* well we at least bound to one socket so we'll continue */
1593 /* if we didn't bind to anything then abort */
1594 if (!BoundPortCount)
1596 log(DEFAULT,"No ports bound, bailing!");
1597 printf("\nERROR: Could not bind any of %d ports! Please check your configuration.\n\n", PortCount);
1601 return BoundPortCount;